Provider-agnostic middleware
The following middleware work with any LLM provider:Summarization
Automatically summarize conversation history when approaching token limits, preserving recent messages while compressing older context. Summarization is useful for the following:- Long-running conversations that exceed context windows.
- Multi-turn dialogues with extensive history.
- Applications where preserving full conversation context matters.
SummarizationMiddleware
Configuration options
Configuration options
'openai:gpt-4o-mini') or a BaseChatModel instance. See init_chat_model for more information.- A single condition dict (all properties must be met - AND logic)
- A list of condition dicts (any condition must be met - OR logic)
fraction(float): Fraction of model’s context size (0-1)tokens(int): Absolute token countmessages(int): Message count
fraction(float): Fraction of model’s context size to keep (0-1)tokens(int): Absolute token count to keepmessages(int): Number of recent messages to keep
{messages} placeholder where conversation history will be inserted.trigger: {"tokens": value} instead. Token threshold for triggering summarization.keep: {"messages": value} instead. Recent messages to preserve.Full example
Full example
- Single condition object (all properties must be met - AND logic)
- Array of conditions (any condition must be met - OR logic)
- Each condition can use
fraction(of model’s context size),tokens(absolute count), ormessages(message count)
fraction- Fraction of model’s context size to keeptokens- Absolute token count to keepmessages- Number of recent messages to keep
Human-in-the-loop
Pause agent execution for human approval, editing, or rejection of tool calls before they execute. Human-in-the-loop is useful for the following:- High-stakes operations requiring human approval (e.g. database writes, financial transactions).
- Compliance workflows where human oversight is mandatory.
- Long-running conversations where human feedback guides the agent.
HumanInTheLoopMiddleware
Model call limit
Limit the number of model calls to prevent infinite loops or excessive costs. Model call limit is useful for the following:- Preventing runaway agents from making too many API calls.
- Enforcing cost controls on production deployments.
- Testing agent behavior within specific call budgets.
ModelCallLimitMiddleware
Configuration options
Configuration options
Tool call limit
Control agent execution by limiting the number of tool calls, either globally across all tools or for specific tools. Tool call limits are useful for the following:- Preventing excessive calls to expensive external APIs.
- Limiting web searches or database queries.
- Enforcing rate limits on specific tool usage.
- Protecting against runaway agent loops.
ToolCallLimitMiddleware
Configuration options
Configuration options
None means no thread limit.None means no run limit.Note: At least one of thread_limit or run_limit must be specified.'continue'(default) - Block exceeded tool calls with error messages, let other tools and the model continue. The model decides when to end based on the error messages.'error'- Raise aToolCallLimitExceededErrorexception, stopping execution immediately'end'- Stop execution immediately with aToolMessageand AI message for the exceeded tool call. Only works when limiting a single tool; raisesNotImplementedErrorif other tools have pending calls.
Full example
Full example
- Thread limit - Max calls across all runs in a conversation (requires checkpointer)
- Run limit - Max calls per single invocation (resets each turn)
'continue'(default) - Block exceeded calls with error messages, agent continues'error'- Raise exception immediately'end'- Stop with ToolMessage + AI message (single-tool scenarios only)
Model fallback
Automatically fallback to alternative models when the primary model fails. Model fallback is useful for the following:- Building resilient agents that handle model outages.
- Cost optimization by falling back to cheaper models.
- Provider redundancy across OpenAI, Anthropic, etc.
ModelFallbackMiddleware
Configuration options
Configuration options
PII detection
Detect and handle Personally Identifiable Information (PII) in conversations using configurable strategies. PII detection is useful for the following:- Healthcare and financial applications with compliance requirements.
- Customer service agents that need to sanitize logs.
- Any application handling sensitive user data.
PIIMiddleware
Custom PII types
You can create custom PII types by providing adetector parameter. This allows you to detect patterns specific to your use case beyond the built-in types.
Three ways to create custom detectors:
- Regex pattern string - Simple pattern matching
- Custom function - Complex detection logic with validation
text, start, and end keys:
Configuration options
Configuration options
email, credit_card, ip, mac_address, url) or a custom type name.'block'- Raise exception when detected'redact'- Replace with[REDACTED_TYPE]'mask'- Partially mask (e.g.,****-****-****-1234)'hash'- Replace with deterministic hash
To-do list
Equip agents with task planning and tracking capabilities for complex multi-step tasks. To-do lists are useful for the following:- Complex multi-step tasks requiring coordination across multiple tools.
- Long-running operations where progress visibility is important.
write_todos tool and system prompts to guide effective task planning.TodoListMiddleware
Configuration options
Configuration options
LLM tool selector
Use an LLM to intelligently select relevant tools before calling the main model. LLM tool selectors are useful for the following:- Agents with many tools (10+) where most aren’t relevant per query.
- Reducing token usage by filtering irrelevant tools.
- Improving model focus and accuracy.
LLMToolSelectorMiddleware
Configuration options
Configuration options
'openai:gpt-4o-mini') or a BaseChatModel instance. See init_chat_model for more information.Defaults to the agent’s main model.Tool retry
Automatically retry failed tool calls with configurable exponential backoff. Tool retry is useful for the following:- Handling transient failures in external API calls.
- Improving reliability of network-dependent tools.
- Building resilient agents that gracefully handle temporary errors.
ToolRetryMiddleware
Configuration options
Configuration options
None, applies to all tools.True if it should be retried.'return_message'- Return aToolMessagewith error details (allows LLM to handle failure)'raise'- Re-raise the exception (stops agent execution)- Custom callable - Function that takes the exception and returns a string for the
ToolMessagecontent
initial_delay * (backoff_factor ** retry_number) seconds. Set to 0.0 for constant delay.±25%) to delay to avoid thundering herdFull example
Full example
max_retries- Number of retry attempts (default: 2)backoff_factor- Multiplier for exponential backoff (default: 2.0)initial_delay- Starting delay in seconds (default: 1.0)max_delay- Cap on delay growth (default: 60.0)jitter- Add random variation (default: True)
on_failure='return_message'- Return error messageon_failure='raise'- Re-raise exception- Custom function - Function returning error message
LLM tool emulator
Emulate tool execution using an LLM for testing purposes, replacing actual tool calls with AI-generated responses. LLM tool emulators are useful for the following:- Testing agent behavior without executing real tools.
- Developing agents when external tools are unavailable or expensive.
- Prototyping agent workflows before implementing actual tools.
LLMToolEmulator
Configuration options
Configuration options
None (default), ALL tools will be emulated. If empty list [], no tools will be emulated. If array with tool names/instances, only those tools will be emulated.'anthropic:claude-sonnet-4-5-20250929') or a BaseChatModel instance. Defaults to the agent’s model if not specified. See init_chat_model for more information.Full example
Full example
Context editing
Manage conversation context by clearing older tool call outputs when token limits are reached, while preserving recent results. This helps keep context windows manageable in long conversations with many tool calls. Context editing is useful for the following:- Long conversations with many tool calls that exceed token limits
- Reducing token costs by removing older tool outputs that are no longer relevant
- Maintaining only the most recent N tool results in context
ContextEditingMiddleware, ClearToolUsesEdit
Configuration options
Configuration options
ContextEdit strategies to apply'approximate' or 'model'ClearToolUsesEdit options:True, tool call arguments are replaced with empty objects.Full example
Full example
ClearToolUsesEdit, which clears older tool results while preserving recent ones.How it works:- Monitor token count in conversation
- When threshold is reached, clear older tool outputs
- Keep most recent N tool results
- Optionally preserve tool call arguments for context
Shell tool
Expose a persistent shell session to agents for command execution. Shell tool middleware is useful for the following:- Agents that need to execute system commands
- Development and deployment automation tasks
- Testing and validation workflows
- File system operations and script execution
ShellToolMiddleware]
Configuration options
Configuration options
HostExecutionPolicy- Full host access (default); best for trusted environments where the agent already runs inside a container or VMDockerExecutionPolicy- Launches a separate Docker container for each agent run, providing harder isolationCodexSandboxExecutionPolicy- Reuses the Codex CLI sandbox for additional syscall/filesystem restrictions
/bin/bash.Full example
Full example
HostExecutionPolicy(default) - Native execution with full host accessDockerExecutionPolicy- Isolated Docker container executionCodexSandboxExecutionPolicy- Sandboxed execution via Codex CLI
File search
Provide Glob and Grep search tools over filesystem files. File search middleware is useful for the following:- Code exploration and analysis
- Finding files by name patterns
- Searching code content with regex
- Large codebases where file discovery is needed
FilesystemFileSearchMiddleware]
Configuration options
Configuration options
Full example
Full example
- Supports patterns like
**/*.py,src/**/*.ts - Returns matching file paths sorted by modification time
- Full regex syntax support
- Filter by file patterns with
includeparameter - Three output modes:
files_with_matches,content,count
Provider-specific middleware
These middleware are optimized for specific LLM providers.Anthropic
Middleware specifically designed for Anthropic’s Claude models.Prompt caching
Reduce costs and latency by caching static or repetitive prompt content (like system prompts, tool definitions, and conversation history) on Anthropic’s servers. This middleware implements a conversational caching strategy that places cache breakpoints after the most recent message, allowing the entire conversation history (including the latest user message) to be cached and reused in subsequent API calls. Prompt caching is useful for the following:- Applications with long, static system prompts that don’t change between requests
- Agents with many tool definitions that remain constant across invocations
- Conversations where early message history is reused across multiple turns
- High-volume deployments where reducing API costs and latency is critical
AnthropicPromptCachingMiddleware
Configuration options
Configuration options
'ephemeral' is currently supported.'5m' or '1h''ignore', 'warn', or 'raise'Full example
Full example
- First request: System prompt, tools, and the user message “Hi, my name is Bob” are sent to the API and cached
- Second request: The cached content (system prompt, tools, and first message) is retrieved from cache. Only the new message “What’s my name?” needs to be processed, plus the model’s response from the first request
- This pattern continues for each turn, with each request reusing the cached conversation history
Bash tool
Execute Claude’s nativebash_20250124 tool with local command execution. The bash tool middleware is useful for the following:
- Using Claude’s built-in bash tool with local execution
- Leveraging Claude’s optimized bash tool interface
- Agents that need persistent shell sessions with Anthropic models
ShellToolMiddleware and exposes it as Claude’s native bash tool.ClaudeBashToolMiddleware]
Configuration options
Configuration options
ClaudeBashToolMiddleware accepts all parameters from @[ShellToolMiddleware], including:HostExecutionPolicy, DockerExecutionPolicy, or CodexSandboxExecutionPolicy)Full example
Full example
Text editor
Provide Claude’s text editor tool (text_editor_20250728) for file creation and editing. The text editor middleware is useful for the following:
- File-based agent workflows
- Code editing and refactoring tasks
- Multi-file project work
- Agents that need persistent file storage
StateClaudeTextEditorMiddleware], @[FilesystemClaudeTextEditorMiddleware]
Configuration options
Configuration options
StateClaudeTextEditorMiddleware] (state-based)FilesystemClaudeTextEditorMiddleware] (filesystem-based)["/"])Full example
Full example
view- View file contents or list directorycreate- Create a new filestr_replace- Replace string in fileinsert- Insert text at line numberdelete- Delete a filerename- Rename/move a file
Memory
Provide Claude’s memory tool (memory_20250818) for persistent agent memory across conversation turns. The memory middleware is useful for the following:
- Long-running agent conversations
- Maintaining context across interruptions
- Task progress tracking
- Persistent agent state management
/memories directory and automatically injects a system prompt encouraging the agent to check and update memory.StateClaudeMemoryMiddleware], @[FilesystemClaudeMemoryMiddleware]
Configuration options
Configuration options
StateClaudeMemoryMiddleware] (state-based)["/memories"].FilesystemClaudeMemoryMiddleware] (filesystem-based)["/memories"].Full example
Full example
File search
Provide Glob and Grep search tools for files stored in LangGraph state. File search middleware is useful for the following:- Searching through state-based virtual file systems
- Works with text editor and memory tools
- Finding files by patterns
- Content search with regex
StateFileSearchMiddleware]
Configuration options
Configuration options
"text_editor_files" for text editor files or "memory_files" for memory files.Full example
Full example
OpenAI
Middleware specifically designed for OpenAI models.Content moderation
Moderate agent traffic (user input, model output, and tool results) using OpenAI’s moderation endpoint to detect and handle unsafe content. Content moderation is useful for the following:- Applications requiring content safety and compliance
- Filtering harmful, hateful, or inappropriate content
- Customer-facing agents that need safety guardrails
- Meeting platform moderation requirements
OpenAIModerationMiddleware]
Configuration options
Configuration options
'omni-moderation-latest', 'omni-moderation-2024-09-26', 'text-moderation-latest', 'text-moderation-stable''end'- End agent execution immediately with a violation message'error'- RaiseOpenAIModerationErrorexception'replace'- Replace the flagged content with the violation message and continue
{categories}- Comma-separated list of flagged categories{category_scores}- JSON string of category scores{original_content}- The original flagged content
"I'm sorry, but I can't comply with that request. It was flagged for {categories}."Full example
Full example
check_input- User messages before model callcheck_output- AI messages after model callcheck_tool_results- Tool outputs before model call
'end'(default) - Stop execution with violation message'error'- Raise exception for application handling'replace'- Replace flagged content and continue