Skip to main content
Middleware specifically designed for Anthropic’s Claude models. Learn more about middleware.

Middleware vs tools

langchain-anthropic provides two ways to use Claude’s native tools:
  • Middleware (this page): Production-ready implementations with built-in execution, state management, and security policies
  • Tools (via bind_tools): Low-level building blocks where you provide your own execution logic

When to use which

Feature comparison

Using middleware (turnkey solution):
Using tools (bring your own execution):

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 directly marks stable agent content such as the system prompt and tool definitions, and passes cache_control through model_settings. The chat model and provider then handle the message-tail and provider-specific caching behavior, allowing the conversation history 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
For simpler use cases, you can also use automatic caching by passing cache_control at invocation time without middleware. The middleware is recommended when you need explicit control over cache breakpoints on system prompts and tool definitions.
Learn more about Anthropic prompt caching strategies and limitations.
API reference: AnthropicPromptCachingMiddleware
type
string
default:"ephemeral"
Cache type. Only 'ephemeral' is currently supported.
ttl
string
default:"5m"
Time to live for cached content. Valid values: '5m' or '1h'
min_messages_to_cache
number
default:"0"
Minimum number of messages before caching starts
unsupported_model_behavior
string
default:"warn"
Behavior when using non-Anthropic models. Options: 'ignore', 'warn', or 'raise'
The middleware caches content up to and including the latest message in each request. On subsequent requests within the TTL window (5 minutes or 1 hour), previously seen content is retrieved from cache rather than reprocessed, significantly reducing costs and latency.How it works:
  1. First request: System prompt, tools, and the user message “Hi, my name is Bob” are sent to the API and cached
  2. 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
  3. This pattern continues for each turn, with each request reusing the cached conversation history
Prompt caching reduces API costs by caching tokens, but does not provide conversation memory. To persist conversation history across invocations, use a checkpointer like MemorySaver.

Bash tool

Execute Claude’s native bash_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
This middleware wraps ShellToolMiddleware and exposes it as Claude’s native bash tool.
API reference: ClaudeBashToolMiddleware
ClaudeBashToolMiddleware accepts all parameters from ShellToolMiddleware, including:
workspace_root
str | Path | None
Base directory for the shell session
startup_commands
tuple[str, ...] | list[str] | str | None
Commands to run when the session starts
execution_policy
BaseExecutionPolicy | None
Execution policy (HostExecutionPolicy, DockerExecutionPolicy, or CodexSandboxExecutionPolicy)
redaction_rules
tuple[RedactionRule, ...] | list[RedactionRule] | None
Rules for sanitizing command output
See Shell tool for full configuration details.

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
Available in two variants: State-based (files in LangGraph state) and Filesystem-based (files on disk).
API references:
State-based text editor
Filesystem-based text editor
Claude’s text editor tool supports the following commands:
  • view - View file contents or list directory
  • create - Create a new file
  • str_replace - Replace string in file
  • insert - Insert text at line number
  • delete - Delete a file
  • rename - Rename/move a file
StateClaudeTextEditorMiddleware (state-based)
allowed_path_prefixes
Sequence[str] | None
Optional list of allowed path prefixes. If specified, only paths starting with these prefixes are allowed.
FilesystemClaudeTextEditorMiddleware (filesystem-based)
root_path
str
required
Root directory for file operations
allowed_prefixes
list[str] | None
Optional list of allowed virtual path prefixes (default: ["/"])
max_file_size_mb
int
default:"10"
Maximum file size in MB

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
Claude’s memory tool uses a /memories directory and automatically injects a system prompt encouraging the agent to check and update memory.
API reference: StateClaudeMemoryMiddleware, FilesystemClaudeMemoryMiddleware
State-based memory
Filesystem-based memory
StateClaudeMemoryMiddleware (state-based)
allowed_path_prefixes
Sequence[str] | None
Optional list of allowed path prefixes. Defaults to ["/memories"].
system_prompt
str
System prompt to inject. Defaults to Anthropic’s recommended memory prompt that encourages the agent to check and update memory.
FilesystemClaudeMemoryMiddleware (filesystem-based)
root_path
str
required
Root directory for file operations
allowed_prefixes
list[str] | None
Optional list of allowed virtual path prefixes. Defaults to ["/memories"].
max_file_size_mb
int
default:"10"
Maximum file size in MB
system_prompt
str
System prompt to inject
The agent will automatically:
  1. Check /memories directory at start
  2. Record progress and thoughts during execution
  3. Update memory files as work progresses
The agent will automatically:
  1. Check /memories directory at start
  2. Record progress and thoughts during execution
  3. Update memory files as work progresses
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
API reference: StateFileSearchMiddleware
state_key
str
default:"text_editor_files"
State key containing files to search. Use "text_editor_files" for text editor files or "memory_files" for memory files.
The middleware adds Glob and Grep search tools that work with state-based files.