中间件与工具
langchain-anthropic 提供两种使用 Claude 原生工具的方式:
- 中间件(本页):生产就绪的实现,内置执行、状态管理和安全策略
- 工具(通过
bind_tools):底层构建块,你提供自己的执行逻辑
何时使用哪个
功能对比
示例:中间件与工具对比
示例:中间件与工具对比
使用中间件(交钥匙方案):使用工具(自带执行逻辑):
提示词缓存
通过在 Anthropic 服务器上缓存静态或重复的提示词内容来降低成本和延迟 (like system prompts, tool definitions, and conversation history) on Anthropic’s servers. This middleware implements a conversational caching strategy that places explicit cache breakpoints on the system message, tool definitions, and the most recent user message, allowing the entire conversation history to be cached and reused in subsequent API calls. 提示词缓存适用于以下场景:- 具有在请求之间不变的长静态系统提示词的应用
- 具有在多次调用中保持不变的大量工具定义的智能体
- 在多轮对话中重复使用早期消息历史的对话
- 降低 API 成本和延迟至关重要的高流量部署
了解更多关于 Anthropic prompt caching strategies and limitations.
AnthropicPromptCachingMiddleware
配置选项
配置选项
string
default:"ephemeral"
Cache type. Only
'ephemeral' is currently supported.string
default:"5m"
Time to live for cached content. Valid values:
'5m' or '1h'number
default:"0"
Minimum number of messages before caching starts
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:
- 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
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 工具
使用本地命令执行来执行 Claude 的原生bash_20250124 工具。
bash 工具中间件适用于以下场景:
- 使用 Claude 的内置 bash 工具进行本地执行
- 利用 Claude 优化的 bash 工具接口
- 需要与 Anthropic 模型保持持久 shell 会话的智能体
此中间件封装了
ShellToolMiddleware 并将其暴露为 Claude 的原生 bash 工具。ClaudeBashToolMiddleware
配置选项
配置选项
ClaudeBashToolMiddleware accepts all parameters from ShellToolMiddleware, including:str | Path | None
Base directory for the shell session
tuple[str, ...] | list[str] | str | None
Commands to run when the session starts
BaseExecutionPolicy | None
Execution policy (
HostExecutionPolicy, DockerExecutionPolicy, or CodexSandboxExecutionPolicy)tuple[RedactionRule, ...] | list[RedactionRule] | None
Rules for sanitizing command output
完整示例
完整示例
文本编辑器
提供 Claude 的文本编辑器工具(text_editor_20250728)用于文件创建和编辑。
文本编辑器中间件适用于以下场景:
- 基于文件的智能体工作流
- 代码编辑和重构任务
- 多文件项目工作
- 需要持久文件存储的智能体
提供两种变体:基于状态的(文件在 LangGraph 状态中)和基于文件系统的(文件在磁盘上)。
State-based text editor
Filesystem-based text editor
view- 查看文件内容或列出目录create- 创建新文件str_replace- 替换文件中的字符串insert- 在指定行号插入文本delete- 删除文件rename- 重命名/移动文件
配置选项
配置选项
StateClaudeTextEditorMiddleware (state-based)Sequence[str] | None
Optional list of allowed path prefixes. If specified, only paths starting with these prefixes are allowed.
FilesystemClaudeTextEditorMiddleware (filesystem-based)str
required
Root directory for file operations
list[str] | None
Optional list of allowed virtual path prefixes (default:
["/"])int
default:"10"
Maximum file size in MB
完整示例:基于状态的文本编辑器
完整示例:基于状态的文本编辑器
完整示例:基于文件系统的文本编辑器
完整示例:基于文件系统的文本编辑器
记忆
提供 Claude 的记忆工具(memory_20250818)用于跨对话轮次的持久化智能体记忆。
记忆中间件适用于以下场景:
- 长时间运行的智能体对话
- 跨中断保持上下文
- 任务进度追踪
- 持久化智能体状态管理
Claude 的记忆工具使用
/memories 目录,并自动注入系统提示词,鼓励智能体检查和更新记忆。StateClaudeMemoryMiddleware, FilesystemClaudeMemoryMiddleware
State-based memory
Filesystem-based memory
配置选项
配置选项
StateClaudeMemoryMiddleware (state-based)Sequence[str] | None
Optional list of allowed path prefixes. Defaults to
["/memories"].str
System prompt to inject. Defaults to Anthropic’s recommended memory prompt that encourages the agent to check and update memory.
FilesystemClaudeMemoryMiddleware (filesystem-based)str
required
Root directory for file operations
list[str] | None
Optional list of allowed virtual path prefixes. Defaults to
["/memories"].int
default:"10"
Maximum file size in MB
str
System prompt to inject
完整示例:基于状态的记忆
完整示例:基于状态的记忆
The agent will automatically:
- Check
/memoriesdirectory at start - Record progress and thoughts during execution
- Update memory files as work progresses
完整示例:基于文件系统的记忆
完整示例:基于文件系统的记忆
The agent will automatically:
- Check
/memoriesdirectory at start - Record progress and thoughts during execution
- Update memory files as work progresses
文件搜索
为存储在 LangGraph 状态中的文件提供 Glob 和 Grep 搜索工具。 文件搜索中间件适用于以下场景:- 搜索基于状态的虚拟文件系统
- 与文本编辑器和记忆工具配合使用
- 按模式查找文件
- 使用正则表达式搜索内容
StateFileSearchMiddleware
配置选项
配置选项
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.
完整示例:搜索记忆文件
完整示例:搜索记忆文件
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

