Skip to main content

Documentation Index

Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

专为 Anthropic 的 Claude 模型设计的中间件。了解更多关于中间件的信息。
中间件描述
提示词缓存通过缓存重复的提示词前缀来降低成本
Bash tool使用本地命令执行 Claude 的原生 bash 工具
Text editor提供 Claude 的文本编辑器工具用于文件编辑
Memory提供 Claude 的记忆工具用于持久化智能体记忆
File search基于状态的文件系统搜索工具

中间件与工具

langchain-anthropic 提供两种使用 Claude 原生工具的方式:
  • 中间件(本页):生产就绪的实现,内置执行、状态管理和安全策略
  • 工具(通过 bind_tools):底层构建块,你提供自己的执行逻辑

何时使用哪个

使用场景推荐原因
生产环境中使用 bash 的智能体中间件持久会话、Docker 隔离、输出脱敏
基于状态的文件编辑中间件内置 LangGraph 状态持久化
文件系统文件编辑中间件写入磁盘并验证路径
自定义执行逻辑工具完全控制执行过程
快速原型工具更简单,自带回调
使用 bind_tools 的非智能体用法工具中间件需要 create_agent

功能对比

功能中间件工具
create_agent 配合使用
bind_tools 配合使用
内置状态管理
自定义执行回调
使用中间件(交钥匙方案):
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import ClaudeBashToolMiddleware
from langchain.agents import create_agent
from langchain.agents.middleware import DockerExecutionPolicy

# Production-ready with Docker isolation, session management, etc.
agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    middleware=[
        ClaudeBashToolMiddleware(
            workspace_root="/workspace",
            execution_policy=DockerExecutionPolicy(image="python:3.11"),
            startup_commands=["pip install pandas"],
        ),
    ],
)
使用工具(自带执行逻辑):
import subprocess

from anthropic.types.beta import BetaToolBash20250124Param
from langchain_anthropic import ChatAnthropic
from langchain.agents import create_agent
from langchain.tools import tool

tool_spec = BetaToolBash20250124Param(
    name="bash",
    type="bash_20250124",
    strict=True,
)

@tool(extras={"provider_tool_definition": tool_spec})
def bash(*, command: str, restart: bool = False, **kw):
    """Execute a bash command."""
    if restart:
        return "Bash session restarted"
    try:
        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=30,
        )
        return result.stdout + result.stderr
    except Exception as e:
        return f"Error: {e}"


agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[bash],
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "List files in this directory"}]}
)
print(result["messages"][-1].content)

提示词缓存

通过在 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 成本和延迟至关重要的高流量部署
对于更简单的用例,你也可以使用 automatic caching 在调用时传递 cache_control 而无需中间件。 当你需要对系统提示词和工具定义的缓存断点进行显式控制时,建议使用中间件。
了解更多关于 Anthropic prompt caching strategies and limitations.
API reference: AnthropicPromptCachingMiddleware
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import AnthropicPromptCachingMiddleware
from langchain.agents import create_agent

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    system_prompt="<Your long system prompt here>",
    middleware=[AnthropicPromptCachingMiddleware(ttl="5m")],
)
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.
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import AnthropicPromptCachingMiddleware
from langchain.agents import create_agent
from langchain.messages import HumanMessage
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import MemorySaver


LONG_PROMPT = """
Please be a helpful assistant.

<Lots more context ...>
"""

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    system_prompt=LONG_PROMPT,
    middleware=[AnthropicPromptCachingMiddleware(ttl="5m")],
    checkpointer=MemorySaver(),  # Persists conversation history
)

# Use a thread_id to maintain conversation state
config: RunnableConfig = {"configurable": {"thread_id": "user-123"}}

# First invocation: Creates cache with system prompt, tools, and "Hi, my name is Bob"
agent.invoke({"messages": [HumanMessage("Hi, my name is Bob")]}, config=config)

# Second invocation: Reuses cached system prompt, tools, and previous messages
# The checkpointer maintains conversation history, so the agent remembers "Bob"
result = agent.invoke({"messages": [HumanMessage("What's my name?")]}, config=config)
print(result["messages"][-1].content)
Your name is Bob! You told me that when you introduced yourself at the start of our conversation.

Bash 工具

使用本地命令执行来执行 Claude 的原生 bash_20250124 工具。 bash 工具中间件适用于以下场景:
  • 使用 Claude 的内置 bash 工具进行本地执行
  • 利用 Claude 优化的 bash 工具接口
  • 需要与 Anthropic 模型保持持久 shell 会话的智能体
此中间件封装了 ShellToolMiddleware 并将其暴露为 Claude 的原生 bash 工具。
API reference: ClaudeBashToolMiddleware
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import ClaudeBashToolMiddleware
from langchain.agents import create_agent

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        ClaudeBashToolMiddleware(
            workspace_root="/workspace",
        ),
    ],
)
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.
import tempfile

from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import ClaudeBashToolMiddleware
from langchain.agents import create_agent
from langchain.agents.middleware import DockerExecutionPolicy

# Create a temporary workspace directory for this demo.
# In production, use a persistent directory path.
workspace = tempfile.mkdtemp(prefix="agent-workspace-")

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        ClaudeBashToolMiddleware(
            workspace_root=workspace,
            startup_commands=["echo 'Session initialized'"],
            execution_policy=DockerExecutionPolicy(
                image="python:3.11-slim",
            ),
        ),
    ],
)

# Claude can now use its native bash tool
result = agent.invoke(
    {"messages": [{"role": "user", "content": "What version of Python is installed?"}]}
)
print(result["messages"][-1].content)
Python 3.11.14 is installed.

文本编辑器

提供 Claude 的文本编辑器工具(text_editor_20250728)用于文件创建和编辑。 文本编辑器中间件适用于以下场景:
  • 基于文件的智能体工作流
  • 代码编辑和重构任务
  • 多文件项目工作
  • 需要持久文件存储的智能体
提供两种变体:基于状态的(文件在 LangGraph 状态中)和基于文件系统的(文件在磁盘上)。
API references:
State-based text editor
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import StateClaudeTextEditorMiddleware
from langchain.agents import create_agent

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[StateClaudeTextEditorMiddleware()],
)
Filesystem-based text editor
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import FilesystemClaudeTextEditorMiddleware
from langchain.agents import create_agent

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        FilesystemClaudeTextEditorMiddleware(
            root_path="/workspace",
        ),
    ],
)
Claude 的文本编辑器工具支持以下命令:
  • view - 查看文件内容或列出目录
  • create - 创建新文件
  • str_replace - 替换文件中的字符串
  • insert - 在指定行号插入文本
  • delete - 删除文件
  • rename - 重命名/移动文件
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
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import StateClaudeTextEditorMiddleware
from langchain.agents import create_agent
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import MemorySaver


agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        StateClaudeTextEditorMiddleware(
            allowed_path_prefixes=["/project"],
        ),
    ],
    checkpointer=MemorySaver(),
)

# Use a thread_id to persist state across invocations
config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

# Claude can now create and edit files (stored in LangGraph state)
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Create a file at /project/hello.py with a simple hello world program"}]},
    config=config,
)
print(result["messages"][-1].content)
I've created a simple "Hello, World!" program at `/project/hello.py`. The program uses Python's `print()` function to display "Hello, World!" to the console when executed.
import tempfile

from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import FilesystemClaudeTextEditorMiddleware
from langchain.agents import create_agent


# Create a temporary workspace directory for this demo.
# In production, use a persistent directory path.
workspace = tempfile.mkdtemp(prefix="editor-workspace-")

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        FilesystemClaudeTextEditorMiddleware(
            root_path=workspace,
            allowed_prefixes=["/src"],
            max_file_size_mb=10,
        ),
    ],
)

# Claude can now create and edit files (stored on disk)
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Create a file at /src/hello.py with a simple hello world program"}]}
)
print(result["messages"][-1].content)
I've created a simple "Hello, World!" program at `/src/hello.py`. The program uses Python's `print()` function to display "Hello, World!" to the console when executed.

记忆

提供 Claude 的记忆工具(memory_20250818)用于跨对话轮次的持久化智能体记忆。 记忆中间件适用于以下场景:
  • 长时间运行的智能体对话
  • 跨中断保持上下文
  • 任务进度追踪
  • 持久化智能体状态管理
Claude 的记忆工具使用 /memories 目录,并自动注入系统提示词,鼓励智能体检查和更新记忆。
API reference: StateClaudeMemoryMiddleware, FilesystemClaudeMemoryMiddleware
State-based memory
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import StateClaudeMemoryMiddleware
from langchain.agents import create_agent

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[StateClaudeMemoryMiddleware()],
)
Filesystem-based memory
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import FilesystemClaudeMemoryMiddleware
from langchain.agents import create_agent

agent_fs = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        FilesystemClaudeMemoryMiddleware(
            root_path="/workspace",
        ),
    ],
)
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
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import StateClaudeMemoryMiddleware
from langchain.agents import create_agent
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import MemorySaver


agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[StateClaudeMemoryMiddleware()],
    checkpointer=MemorySaver(),
)

# Use a thread_id to persist state across invocations
config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

# Claude can now use memory to track progress (stored in LangGraph state)
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Remember that my favorite color is blue, then confirm what you stored."}]},
    config=config,
)
print(result["messages"][-1].content)
Perfect! I've stored your favorite color as **blue** in my memory system. The information is saved in my user preferences file where I can access it in future conversations.
The agent will automatically:
  1. Check /memories directory at start
  2. Record progress and thoughts during execution
  3. Update memory files as work progresses
import tempfile

from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import FilesystemClaudeMemoryMiddleware
from langchain.agents import create_agent


# Create a temporary workspace directory for this demo.
# In production, use a persistent directory path.
workspace = tempfile.mkdtemp(prefix="memory-workspace-")

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        FilesystemClaudeMemoryMiddleware(
            root_path=workspace,
        ),
    ],
)

# Claude can now use memory to track progress (stored on disk)
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Remember that my favorite color is blue, then confirm what you stored."}]}
)
print(result["messages"][-1].content)
Perfect! I've stored your favorite color as **blue** in my memory system. The information is saved in my user preferences file where I can access it in future conversations.

文件搜索

为存储在 LangGraph 状态中的文件提供 Glob 和 Grep 搜索工具。 文件搜索中间件适用于以下场景:
  • 搜索基于状态的虚拟文件系统
  • 与文本编辑器和记忆工具配合使用
  • 按模式查找文件
  • 使用正则表达式搜索内容
API reference: StateFileSearchMiddleware
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import (
    StateClaudeTextEditorMiddleware,
    StateFileSearchMiddleware,
)
from langchain.agents import create_agent

agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        StateClaudeTextEditorMiddleware(),
        StateFileSearchMiddleware(),  # Search text editor files
    ],
)
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.
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import (
    StateClaudeTextEditorMiddleware,
    StateFileSearchMiddleware,
)
from langchain.agents import create_agent
from langchain.messages import HumanMessage
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import MemorySaver


agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        StateClaudeTextEditorMiddleware(),
        StateFileSearchMiddleware(state_key="text_editor_files"),
    ],
    checkpointer=MemorySaver(),
)

# Use a thread_id to persist state across invocations
config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

# First invocation: Create some files using the text editor tool
result = agent.invoke(
    {"messages": [HumanMessage("Create a Python project with main.py, utils/helpers.py, and tests/test_main.py")]},
    config=config,
)

# The agent creates files, which are stored in state
print("Files created:", list(result["text_editor_files"].keys()))

# Second invocation: Search the files we just created
# State is automatically persisted via the checkpointer
result = agent.invoke(
    {"messages": [HumanMessage("Find all Python files in the project")]},
    config=config,
)
print(result["messages"][-1].content)
Files created: ['/project/main.py', '/project/utils/helpers.py', '/project/utils/__init__.py', '/project/tests/test_main.py', '/project/tests/__init__.py', '/project/README.md']
I found 5 Python files in the project:

1. `/project/main.py` - Main application file
2. `/project/utils/__init__.py` - Utils package initialization
3. `/project/utils/helpers.py` - Helper utilities
4. `/project/tests/__init__.py` - Tests package initialization
5. `/project/tests/test_main.py` - Main test file

Would you like me to view the contents of any of these files?
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import (
    StateClaudeMemoryMiddleware,
    StateFileSearchMiddleware,
)
from langchain.agents import create_agent
from langchain.messages import HumanMessage
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import MemorySaver


agent = create_agent(
    model=ChatAnthropic(model="claude-sonnet-4-6"),
    tools=[],
    middleware=[
        StateClaudeMemoryMiddleware(),
        StateFileSearchMiddleware(state_key="memory_files"),
    ],
    checkpointer=MemorySaver(),
)

# Use a thread_id to persist state across invocations
config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

# First invocation: Record some memories
result = agent.invoke(
    {"messages": [HumanMessage("Remember that the project deadline is March 15th and code review deadline is March 10th")]},
    config=config,
)

# The agent creates memory files, which are stored in state
print("Memory files created:", list(result["memory_files"].keys()))

# Second invocation: Search the memories we just recorded
# State is automatically persisted via the checkpointer
result = agent.invoke(
    {"messages": [HumanMessage("Search my memories for project deadlines")]},
    config=config,
)
print(result["messages"][-1].content)
Memory files created: ['/memories/project_info.md']
I found your project deadlines in my memory! Here's what I have recorded:

## Important Deadlines
- **Code Review Deadline:** March 10th
- **Project Deadline:** March 15th

## Notes
- Code review must be completed 5 days before final project deadline
- Need to ensure all code is ready for review by March 10th

Is there anything specific about these deadlines you'd like to know or update?