Middleware

Intercept agent requests and responses

Agents can use middleware to process requests and responses – for logging, validation, or transformation.

Diagram

Request Pipeline

📤 Input

🔧 Middleware

🤖 Agent

🔧 Middleware

📥 Output

Quick Start

  1. Simple Usage
    typescript
    import { Agent, Middleware } from 'praisonai';
    
    const logger: Middleware = async (ctx, next) => {
      console.log('Input:', ctx.input);
      await next();
      console.log('Output:', ctx.output);
    };
    
    const agent = new Agent({
      instructions: 'You are helpful',
      middleware: [logger]
    });
  2. With Configuration
    typescript
    const validate: Middleware = async (ctx, next) => {
      if (ctx.input.length > 1000) {
        throw new Error('Input too long');
      }
      await next();
    };

User Interaction Flow

Diagram
FilterAgentLoggerUserFilterAgentLoggerUserRequestLog + forwardResponseFilter + forward

Configuration Levels

typescript
// Level 1: Array - Middleware list
const agent = new Agent({
  middleware: [logger, validator]
});

// Level 2: Function - Simple middleware
const agent = new Agent({
  middleware: [
    async (ctx, next) => {
      console.log(ctx.input);
      await next();
    }
  ]
});

// Level 3: Instance - Full control
const agent = new Agent({
  middleware: [
    {
      name: 'logger',
      handler: loggerFn,
      order: 1
    },
    {
      name: 'cache',
      handler: cacheFn,
      order: 2
    }
  ]
});

Common Uses

Use CaseDescription
LoggingTrack all requests/responses
ValidationCheck inputs before processing
TransformationModify data in transit
CachingCache frequent responses

API Reference

HooksConfig

Hooks configuration (middleware pattern)


Best Practices

Keep middleware focused

Each middleware should do one thing well.

Order matters

Middleware runs in order – put validation first.

Always call next()

Forgetting next() breaks the chain.


Related