Skip to main content
Build custom middleware by implementing hooks that run at specific points in the agent execution flow.

Hooks

Middleware provides two styles of hooks to intercept agent execution:

Node-style hooks

Run sequentially at specific execution points.

Wrap-style hooks

Run around each model or tool call.

Node-style hooks

Run sequentially at specific execution points. Use for logging, validation, and state updates. Choose the hooks your middleware needs. You can choose between node-style hooks and wrap-style hooks. Node-style hooks run at specific execution points:
HookWhen it runs
before_agentBefore agent starts (once per invocation)
before_modelBefore each model call
after_modelAfter each model response
after_agentAfter agent completes (once per invocation)
Wrap-style hooks run around each call, giving you control over execution:
HookWhen it runs
wrap_model_callAround each model call
wrap_tool_callAround each tool call
Example:

Wrap-style hooks

Intercept execution and control when the handler is called. Use for retries, caching, and transformation. You decide if the handler is called zero times (short-circuit), once (normal flow), or multiple times (retry logic). Available hooks:
  • wrap_model_call - Around each model call
  • wrap_tool_call - Around each tool call
Example:

State updates

Both node-style and wrap-style hooks can update agent state. The mechanism differs:
  • Node-style hooks (before_agent, before_model, after_model, after_agent): Return a dict directly. The dict is applied to the agent state using the graph’s reducers.
  • Wrap-style hooks (wrap_model_call, wrap_tool_call): For model calls, return ExtendedModelResponse with a Command to inject state updates alongside the model response. For tool calls, return a Command directly. Use these when you need to track or update state based on logic that runs during the model or tool call, such as summarization trigger points, usage metadata, or custom fields calculated from the request or response.

Node-style hooks

Return a dict from a node-style hook to merge updates into agent state. The dict keys map to state fields.

Wrap-style hooks

Return a ExtendedModelResponse with a Command from wrap_model_call to inject state updates from the model call layer:
The Command flows through the graph’s reducers, so updates are applied correctly and messages are additive rather than replacing existing state.

Composition with multiple middleware

When multiple middleware layers return ExtendedModelResponse, their commands compose:
  • Commands are applied through reducers: Each Command becomes a separate state update. For messages, this means they are additive.
  • Outer wins on conflicts: For non-reducer state fields, commands are applied inner-first, then outer. The outermost middleware’s value takes precedence on conflicting keys.
  • Retry-safe: If the outer middleware implements logic that can result in multiple calls to handler() again (for example, retry logic), commands from earlier calls are discarded.

Create middleware

You can create middleware in two ways:

Decorator-based middleware

Quick and simple for single-hook middleware. Use decorators to wrap individual functions.

Class-based middleware

More powerful for complex middleware with multiple hooks or configuration.

Decorator-based middleware

Quick and simple for single-hook middleware. Use decorators to wrap individual functions. Available decorators: Node-style: Wrap-style: Convenience: Example:
When to use decorators:
  • Single hook needed
  • No complex configuration
  • Quick prototyping

Class-based middleware

More powerful for complex middleware with multiple hooks or configuration. Use classes when you need to define both sync and async implementations for the same hook, or when you want to combine multiple hooks in a single middleware. python An AgentMiddleware subclass can declare three class attributes that the agent factory picks up at compile time:
  • state_schema — extend the agent state with custom fields. See Custom state schema.
  • tools — register additional tools that ship with the middleware (e.g., write_todos on the to-do list middleware).
  • transformers — register scope-aware stream transformer factories. See Custom stream transformers. :::
Example:
When to use classes:
  • Defining both sync and async implementations for the same hook
  • Multiple hooks needed in a single middleware
  • Complex configuration required (e.g., configurable thresholds, custom models)
  • Reuse across projects with init-time configuration
:::

Custom state schema

If your middleware needs to track state across hooks, middleware can extend the agent’s state with custom properties. This enables middleware to:
  • Track state across execution: Maintain counters, flags, or other values that persist throughout the agent’s execution lifecycle
  • Share data between hooks: Pass information from before_model to after_model or between different middleware instances
  • Implement cross-cutting concerns: Add functionality like rate limiting, usage tracking, user context, or audit logging without modifying the core agent logic
  • Make conditional decisions: Use accumulated state to determine whether to continue execution, jump to different nodes, or modify behavior dynamically

Custom stream transformers

Middleware-registered transformers require langchain>=1.3.2.
Middleware can register stream transformer factories that project events from the live agent stream onto typed extension channels. This is useful for surfacing counters, side-channel artifacts, partial outputs, or wire-level redaction without coupling to the framework’s built-in projections. At compile time, middleware-registered factories merge with anything the caller passes directly to the agent factory. The final ordering rules keep the built-in ToolCallTransformer in front and let caller-supplied entries land last. Set the transformers class attribute to a tuple of factory callables. Each factory has the shape Callable[[tuple[str, ...]], StreamTransformer] and is invoked as factory(scope), where scope is the mini-mux scope tuple (() for the root, non-empty for subgraphs); returning a fresh transformer per call keeps each subgraph isolated.
See Register transformers on middleware for the full ordering rules and the PII redaction example.

Execution order

When using multiple middleware, understand how they execute:
Before hooks run in order:
  1. middleware1.before_agent()
  2. middleware2.before_agent()
  3. middleware3.before_agent()
Agent loop starts
  1. middleware1.before_model()
  2. middleware2.before_model()
  3. middleware3.before_model()
Wrap hooks nest like function calls:
  1. middleware1.wrap_model_call()middleware2.wrap_model_call()middleware3.wrap_model_call() → model
After hooks run in reverse order:
  1. middleware3.after_model()
  2. middleware2.after_model()
  3. middleware1.after_model()
Agent loop ends
  1. middleware3.after_agent()
  2. middleware2.after_agent()
  3. middleware1.after_agent()
Key rules:
  • before_* hooks: First to last
  • after_* hooks: Last to first (reverse)
  • wrap_* hooks: Nested (first middleware wraps all others)

Agent jumps

To exit early from middleware, return a dictionary with jump_to: Available jump targets:
  • 'end': Jump to the end of the agent execution (or the first after_agent hook)
  • 'tools': Jump to the tools node
  • 'model': Jump to the model node (or the first before_model hook)

Best practices

  1. Keep middleware focused - each should do one thing well
  2. Handle errors gracefully - don’t let middleware errors crash the agent
  3. Use appropriate hook types:
    • Node-style for sequential logic (logging, validation)
    • Wrap-style for control flow (retry, fallback, caching)
  4. Clearly document any custom state properties
  5. Unit test middleware independently before integrating
  6. Consider execution order - place critical middleware first in the list
  7. Use built-in middleware when possible

Examples

Dynamic prompt

Dynamically modify the system prompt at runtime to inject context, user-specific instructions, or other information before each model call. This is one of the most common middleware use cases. Use the system_message field on ModelRequest to read and modify the system prompt. It contains a SystemMessage object (even if the agent was created with a string system_prompt).
  • ModelRequest.system_message is always a SystemMessage object, even if the agent was created with system_prompt="string"
  • Use SystemMessage.content_blocks to access content as a list of blocks, regardless of whether the original content was a string or list
  • When modifying system messages, use content_blocks and append new blocks to preserve existing structure
  • You can pass SystemMessage objects directly to create_agent’s system_prompt parameter for advanced use cases like cache control

Dynamic model selection

Dynamically selecting tools

Select relevant tools at runtime to improve performance and accuracy. This section covers filtering pre-registered tools. For registering tools that are discovered at runtime (e.g., from MCP servers), see Runtime tool registration. Benefits:
  • Shorter prompts - Reduce complexity by exposing only relevant tools
  • Better accuracy - Models choose correctly from fewer options
  • Permission control - Dynamically filter tools based on user access

Tool call monitoring

Prompt caching (Anthropic)

When working with Anthropic models, use structured content blocks with cache control directives to cache large system prompts:
Notes:
  • ModelRequest.system_message is always a SystemMessage object, even if the agent was created with system_prompt="string"
  • Use SystemMessage.content_blocks to access content as a list of blocks, regardless of whether the original content was a string or list
  • When modifying system messages, use content_blocks and append new blocks to preserve existing structure
  • You can pass SystemMessage objects directly to create_agent’s system_prompt parameter for advanced use cases like cache control
:::

Additional resources