Middleware Types
The framework provides three middleware types:Agent Middleware
Intercepts
agent.run() calls. Use for request validation, session management, and result transformation.Chat Middleware
Intercepts chat client requests. Use for prompt engineering, message filtering, and response caching.
Function Middleware
Intercepts tool/function invocations. Use for argument validation, result caching, and execution logging.
How Middleware Works
Middleware forms a pipeline where each middleware can:- Inspect the incoming request (context object)
- Modify the request before it reaches the next layer
- Call the next middleware via
call_next() - Inspect/modify the response after execution
- Short-circuit execution by not calling
call_next()
Agent Middleware
- Python
- .NET
Class-Based Middleware
Function-Based Middleware
Context Properties
AgentContext provides:agent- The agent instancemessages- Input messagessession- Agent session (if provided)options- Runtime options dictstream- Whether streaming is enabledresult- Agent response (available aftercall_next())metadata- Shared metadata dict for cross-middleware communicationkwargs- Additional keyword arguments
Function Middleware
- Python
- .NET
Class-Based Function Middleware
Function-Based Function Middleware
Context Properties
FunctionInvocationContext provides:function- The FunctionTool being invokedarguments- Validated function argumentsresult- Function result (available aftercall_next())metadata- Shared metadata dictkwargs- Runtime keyword arguments
Chat Middleware
- Python
- .NET
Class-Based Chat Middleware
Function-Based Chat Middleware
Context Properties
ChatContext provides:client- The chat client instancemessages- Messages being sentoptions- Chat options dictstream- Whether streaming is enabledresult- Chat response (available aftercall_next())metadata- Shared metadata dictkwargs- Runtime keyword arguments
Middleware Composition
- Python
- .NET
Middleware can be registered at agent creation or per-run:
Advanced Patterns
Short-Circuiting Execution
- Python
- .NET
Shared State Between Middleware
- Python
- .NET
Conditional Middleware
- Python
- .NET
Example: Complete Middleware Stack
- Python
- .NET
Best Practices
Middleware Design Tips
- Single Responsibility: Each middleware should do one thing well
- Order Matters: Security/auth middleware should run first
- Performance: Keep middleware lightweight; avoid heavy computation
- Error Handling: Handle exceptions gracefully, don’t break the pipeline
- Metadata: Use
context.metadatafor cross-middleware communication - Idempotency: Middleware should be safe to run multiple times
Next Steps
Observability
Monitor middleware execution with OpenTelemetry
Sessions
Manage state across middleware invocations
Tools
Learn about function middleware for tools
Agents
Understand agent middleware integration