LangChain v1.0Welcome to the new LangChain documentation! If you encounter any issues or have feedback, please open an issue so we can improve. Archived v0 documentation can be found here.See the release notes and migration guide for a complete list of changes and instructions on how to upgrade your code.


What can middleware do?
Monitor
Track agent behavior with logging, analytics, and debugging
Modify
Transform prompts, tool selection, and output formatting
Control
Add retries, fallbacks, and early termination logic
Enforce
Apply rate limits, guardrails, and PII detection
create_agent
]:
Built-in middleware
LangChain provides prebuilt middleware for common use cases:Summarization
Automatically summarize conversation history when approaching token limits.Perfect for:
- Long-running conversations that exceed context windows
- Multi-turn dialogues with extensive history
- Applications where preserving full conversation context matters
Configuration options
Configuration options
Model for generating summaries
Token threshold for triggering summarization
Recent messages to preserve
Custom token counting function. Defaults to character-based counting.
Custom prompt template. Uses built-in template if not specified.
Prefix for summary messages
Human-in-the-loop
Pause agent execution for human approval, editing, or rejection of tool calls before they execute.Perfect for:
- High-stakes operations requiring human approval (database writes, financial transactions)
- Compliance workflows where human oversight is mandatory
- Long running conversations where human feedback is used to guide the agent
Configuration options
Configuration options
Important: Human-in-the-loop middleware requires a checkpointer to maintain state across interruptions.See the human-in-the-loop documentation for complete examples and integration patterns.
Anthropic prompt caching
Reduce costs by caching repetitive prompt prefixes with Anthropic models.Perfect for:
- Applications with long, repeated system prompts
- Agents that reuse the same context across invocations
- Reducing API costs for high-volume deployments
Learn more about Anthropic Prompt Caching strategies and limitations.
Configuration options
Configuration options
Time to live for cached content. Valid values:
"5m"
or "1h"
Model call limit
Limit the number of model calls to prevent infinite loops or excessive costs.Perfect for:
- Preventing runaway agents from making too many API calls
- Enforcing cost controls on production deployments
- Testing agent behavior within specific call budgets
Configuration options
Configuration options
Tool call limit
Limit the number of tool calls to specific tools or all tools.Perfect for:
- Preventing excessive calls to expensive external APIs
- Limiting web searches or database queries
- Enforcing rate limits on specific tool usage
Configuration options
Configuration options
Specific tool to limit. If not provided, limits apply to all tools.
Maximum tool calls across all runs in a thread. Defaults to no limit.
Maximum tool calls per single invocation. Defaults to no limit.
Behavior when limit is reached. Options:
"end"
(graceful termination) or "error"
(throw exception)Model fallback
Automatically fallback to alternative models when the primary model fails.Perfect for:
- Building resilient agents that handle model outages
- Cost optimization by falling back to cheaper models
- Provider redundancy across OpenAI, Anthropic, etc.
Configuration options
Configuration options
The middleware accepts a variable number of string arguments representing fallback models in order:
One or more fallback model strings to try in order when the primary model fails
PII detection
Detect and handle Personally Identifiable Information in conversations.Perfect for:
- Healthcare and financial applications with compliance requirements
- Customer service agents that need to sanitize logs
- Any application handling sensitive user data
Configuration options
Configuration options
Type of PII to detect. Can be a built-in type (
email
, credit_card
, ip
, mac_address
, url
) or a custom type name.How to handle detected PII. Options:
"block"
- Throw error when detected"redact"
- Replace with[REDACTED_TYPE]
"mask"
- Partially mask (e.g.,****-****-****-1234
)"hash"
- Replace with deterministic hash
Custom detector regex pattern. If not provided, uses built-in detector for the PII type.
Check user messages before model call
Check AI messages after model call
Check tool result messages after execution
Planning
Add todo list management capabilities for complex multi-step tasks.This middleware automatically provides agents with a
write_todos
tool and system prompts to guide effective task planning.Configuration options
Configuration options
No configuration options available (uses defaults).
LLM tool selector
Use an LLM to intelligently select relevant tools before calling the main model.Perfect for:
- Agents with many tools (10+) where most aren’t relevant per query
- Reducing token usage by filtering irrelevant tools
- Improving model focus and accuracy
Configuration options
Configuration options
Context editing
Manage conversation context by trimming, summarizing, or clearing tool uses.Perfect for:
- Long conversations that need periodic context cleanup
- Removing failed tool attempts from context
- Custom context management strategies
Configuration options
Configuration options
Custom middleware
Build custom middleware by implementing hooks that run at specific points in the agent execution flow.Class-based middleware
Two hook styles
Node-style hooks
Run sequentially at specific execution points. Use for logging, validation, and state updates.
Wrap-style hooks
Intercept execution with full control over handler calls. Use for retries, caching, and transformation.
Node-style hooks
Run at specific points in the execution flow:beforeAgent
- Before agent starts (once per invocation)beforeModel
- Before each model callafterModel
- After each model responseafterAgent
- After agent completes (up to once per invocation)
Wrap-style hooks
Intercept execution and control when the handler is called:wrapModelCall
- Around each model callwrapToolCall
- Around each tool call
Custom state schema
Middleware can extend the agent’s state with custom properties. Define a custom state type and set it as thestate_schema
:
Context extension
Context properties are configuration values passed through the runnable config. Unlike state, context is read-only and typically used for configuration that doesn’t change during execution. Middleware can define context requirements that must be satisfied through the agent’s configuration:Execution order
When using multiple middleware, understanding execution order is important:Execution flow (click to expand)
Execution flow (click to expand)
Before hooks run in order:
middleware1.before_agent()
middleware2.before_agent()
middleware3.before_agent()
middleware1.before_model()
middleware2.before_model()
middleware3.before_model()
middleware1.wrap_model_call()
→middleware2.wrap_model_call()
→middleware3.wrap_model_call()
→ model
middleware3.after_model()
middleware2.after_model()
middleware1.after_model()
middleware3.after_agent()
middleware2.after_agent()
middleware1.after_agent()
before_*
hooks: First to lastafter_*
hooks: Last to first (reverse)wrap_*
hooks: Nested (first middleware wraps all others)
Agent jumps
To exit early from middleware, return a dictionary withjump_to
:
"end"
: Jump to the end of the agent execution"tools"
: Jump to the tools node"model"
: Jump to the model node (or the firstbefore_model
hook)
before_model
or after_model
, jumping to "model"
will cause all before_model
middleware to run again.
To enable jumping, decorate your hook with @hook_config(can_jump_to=[...])
:
Best practices
- Keep middleware focused - each should do one thing well
- Handle errors gracefully - don’t let middleware errors crash the agent
- Use appropriate hook types:
- Node-style for sequential logic (logging, validation)
- Wrap-style for control flow (retry, fallback, caching)
- Clearly document any custom state properties
- Unit test middleware independently before integrating
- Consider execution order - place critical middleware first in the list
- Use built-in middleware when possible, don’t reinvent the wheel :)
Examples
Dynamically selecting tools
Select relevant tools at runtime to improve performance and accuracy.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
Additional resources
- Middleware API reference - Complete guide to custom middleware
- Human-in-the-loop - Add human review for sensitive operations
- Testing agents - Strategies for testing safety mechanisms