Skip to main content
Middleware provides a powerful way to intercept and modify the behavior of agents, chat clients, and function calls. Use middleware for logging, authentication, caching, error handling, and more.

Types of Middleware

The Agent Framework supports three types of middleware:

Agent Middleware

Intercepts agent run() calls:

Chat Middleware

Intercepts chat client get_response() calls:

Function Middleware

Intercepts tool/function executions:

Creating Middleware

Class-Based Middleware

Inherit from the appropriate base class:

Function-Based Middleware

Use type hints to indicate middleware type:

Decorator-Based Middleware

Use decorators to explicitly mark middleware type:

Using Middleware

Agent-Level Middleware

Apply middleware to all agent runs:

Run-Level Middleware

Apply middleware to a specific run:

Middleware Order

Middleware executes in the order specified:

Middleware Context

AgentContext

ChatContext

FunctionInvocationContext

Advanced Patterns

Modifying Inputs

Modifying Outputs

Short-Circuiting Execution

Return a result without calling the agent:

Middleware Termination

Explicitly terminate execution:

Exception Handling

Shared State Between Middleware

Session Behavior Middleware

Runtime Context Delegation

Combining Middleware Types

Best Practices

Each middleware should have a single, well-defined responsibility. This makes them easier to test and compose.
Prefer using call_next() and only modify context.result when you need to override behavior.
When context.stream is True, be aware that the result will be an async iterable:
  • Use Agent Middleware for high-level agent behavior (auth, routing)
  • Use Chat Middleware for model interaction (caching, retries)
  • Use Function Middleware for tool execution (logging, validation)
The order matters. Place authentication/authorization middleware before others:

API Reference

AgentMiddleware Base Class

ChatMiddleware Base Class

FunctionMiddleware Base Class

Examples

Authentication Middleware

Rate Limiting Middleware

  • Agents - Using middleware with agents
  • Tools - Function middleware for tools
  • Workflows - Middleware in workflows