> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Anthropic 中间件集成

> 使用 LangChain Python 与 Anthropic 中间件集成。

专为 Anthropic 的 Claude 模型设计的中间件。了解更多关于[中间件](/oss/python/langchain/middleware/overview)的信息。

| 中间件                 | 描述                          |
| ------------------- | --------------------------- |
| [提示缓存](#提示缓存)       | 通过缓存重复的提示前缀来降低成本            |
| [Bash 工具](#bash-工具) | 使用本地命令执行 Claude 的原生 bash 工具 |
| [文本编辑器](#文本编辑器)     | 提供 Claude 的文本编辑器工具用于文件编辑    |
| [记忆](#记忆)           | 提供 Claude 的记忆工具用于持久化代理记忆    |
| [文件搜索](#文件搜索)       | 用于基于状态的文件系统的搜索工具            |

## 中间件 vs 工具

`langchain-anthropic` 提供了两种使用 Claude 原生工具的方式：

* **中间件**（本页）：生产就绪的实现，内置执行、状态管理和安全策略
* **工具**（通过 [`bind_tools`](/oss/python/integrations/chat/anthropic#built-in-tools)）：底层构建块，您提供自己的执行逻辑

### 何时使用哪种方式

| 用例                                                                                                                     | 推荐方式 | 原因                                                                                                   |
| ---------------------------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------------------------------------------------- |
| 带有 bash 的生产代理                                                                                                          | 中间件  | 持久会话、Docker 隔离、输出脱敏                                                                                  |
| 基于状态的文件编辑                                                                                                              | 中间件  | 内置 LangGraph 状态持久化                                                                                   |
| 文件系统文件编辑                                                                                                               | 中间件  | 写入磁盘并进行路径验证                                                                                          |
| 自定义执行逻辑                                                                                                                | 工具   | 完全控制执行                                                                                               |
| 快速原型                                                                                                                   | 工具   | 更简单，自带回调                                                                                             |
| 不使用代理的 [`bind_tools`](https://reference.langchain.com/python/langchain-anthropic/chat_models/ChatAnthropic/bind_tools) | 工具   | 中间件需要 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) |

### 功能对比

| 功能                                                                                                                     | 中间件 |  工具 |
| ---------------------------------------------------------------------------------------------------------------------- | :-: | :-: |
| 与 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 配合使用                  |  ✅  |  ✅  |
| 与 [`bind_tools`](https://reference.langchain.com/python/langchain-anthropic/chat_models/ChatAnthropic/bind_tools) 配合使用 |  ❌  |  ✅  |
| 内置状态管理                                                                                                                 |  ✅  |  ❌  |
| 自定义执行回调                                                                                                                |  ❌  |  ✅  |

<Accordion title="示例：中间件 vs 工具对比">
  **使用中间件**（交钥匙解决方案）：

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_anthropic import ChatAnthropic
  from langchain_anthropic.middleware import ClaudeBashToolMiddleware
  from langchain.agents import create_agent
  from langchain.agents.middleware import DockerExecutionPolicy

  # 生产就绪，具有 Docker 隔离、会话管理等功能。
  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"],
          ),
      ],
  )
  ```

  **使用工具**（自带执行逻辑）：

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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):
      """执行 bash 命令。"""
      if restart:
          return "Bash 会话已重启"
      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"错误: {e}"


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

  result = agent.invoke(
      {"messages": [{"role": "user", "content": "列出此目录中的文件"}]}
  )
  print(result["messages"][-1].content)
  ```
</Accordion>

***

## 提示缓存

通过在 Anthropic 的服务器上缓存静态或重复的提示内容（如系统提示、工具定义和对话历史）来降低成本和延迟。此中间件实现了一种**对话缓存策略**，在系统消息、工具定义和最近的用户消息上放置显式缓存断点，允许整个对话历史在后续 API 调用中被缓存和重用。

提示缓存适用于以下情况：

* 具有长且静态的系统提示的应用程序，这些提示在请求之间不会改变
* 具有许多工具定义的代理，这些定义在调用之间保持不变
* 早期消息历史在多个轮次中被重用的对话
* 降低 API 成本和延迟至关重要的高流量部署

<Tip>
  对于更简单的用例，您也可以在调用时传递 `cache_control` 来使用[自动缓存](/oss/python/integrations/chat/anthropic#automatic-caching)，而无需中间件。当您需要显式控制系统提示和工具定义上的缓存断点时，建议使用中间件。
</Tip>

<Info>
  了解更多关于 [Anthropic 提示缓存](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-limitations)策略和限制的信息。
</Info>

**API 参考：** [`AnthropicPromptCachingMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/prompt_caching/AnthropicPromptCachingMiddleware)

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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="<在此处输入您的长系统提示>",
    middleware=[AnthropicPromptCachingMiddleware(ttl="5m")], # [!code highlight]
)
```

<Accordion title="配置选项">
  <ParamField body="type" type="string" default="ephemeral">
    缓存类型。目前仅支持 `'ephemeral'`。
  </ParamField>

  <ParamField body="ttl" type="string" default="5m">
    缓存内容的生存时间。有效值：`'5m'` 或 `'1h'`
  </ParamField>

  <ParamField body="min_messages_to_cache" type="number" default="0">
    开始缓存前的最小消息数
  </ParamField>

  <ParamField body="unsupported_model_behavior" type="string" default="warn">
    使用非 Anthropic 模型时的行为。选项：`'ignore'`、`'warn'` 或 `'raise'`
  </ParamField>
</Accordion>

<Accordion title="完整示例">
  中间件缓存每个请求中最新消息及之前的内容。在 TTL 窗口（5 分钟或 1 小时）内的后续请求中，之前看到的内容将从缓存中检索，而不是重新处理，从而显著降低成本和延迟。

  **工作原理：**

  1. 第一次请求：系统提示、工具和用户消息 *"Hi, my name is Bob"* 被发送到 API 并缓存
  2. 第二次请求：缓存的内容（系统提示、工具和第一条消息）从缓存中检索。只有新消息 *"What's my name?"* 需要处理，加上模型对第一次请求的响应
  3. 这种模式在每个轮次中继续，每个请求都重用缓存的对话历史

  <Note>
    提示缓存通过缓存令牌来降低 API 成本，但**不**提供对话记忆。要在调用之间持久化对话历史，请使用 [checkpointer](https://langchain-ai.github.io/langgraph/concepts/persistence/#checkpointer-libraries)（如 `MemorySaver`）。
  </Note>

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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 = """
  请成为一个有用的助手。

  <更多上下文 ...>
  """

  agent = create_agent(
      model=ChatAnthropic(model="claude-sonnet-4-6"),
      system_prompt=LONG_PROMPT,
      middleware=[AnthropicPromptCachingMiddleware(ttl="5m")], # [!code highlight]
      checkpointer=MemorySaver(),  # 持久化对话历史
  )

  # 使用 thread_id 来维护对话状态
  config: RunnableConfig = {"configurable": {"thread_id": "user-123"}}

  # 第一次调用：使用系统提示、工具和 "Hi, my name is Bob" 创建缓存
  agent.invoke({"messages": [HumanMessage("Hi, my name is Bob")]}, config=config)

  # 第二次调用：重用缓存的系统提示、工具和之前的消息
  # checkpointer 维护对话历史，因此代理记得 "Bob"
  result = agent.invoke({"messages": [HumanMessage("What's my name?")]}, config=config)
  print(result["messages"][-1].content)
  ```

  ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  你的名字是 Bob！你在我们对话开始时自我介绍时告诉过我。
  ```
</Accordion>

## Bash 工具

使用本地命令执行 Claude 的原生 `bash_20250124` 工具。

Bash 工具中间件适用于以下情况：

* 使用 Claude 内置的 bash 工具进行本地执行
* 利用 Claude 优化的 bash 工具接口
* 需要与 Anthropic 模型进行持久 shell 会话的代理

<Info>
  此中间件包装了 `ShellToolMiddleware` 并将其作为 Claude 的原生 bash 工具暴露。
</Info>

**API 参考：** [`ClaudeBashToolMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/bash/ClaudeBashToolMiddleware)

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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=[ # [!code highlight]
        ClaudeBashToolMiddleware( # [!code highlight]
            workspace_root="/workspace", # [!code highlight]
        ), # [!code highlight]
    ], # [!code highlight]
)
```

<Accordion title="配置选项">
  `ClaudeBashToolMiddleware` 接受 [`ShellToolMiddleware`](https://reference.langchain.com/python/langchain/agents/middleware/shell_tool/ShellToolMiddleware) 的所有参数，包括：

  <ParamField body="workspace_root" type="str | Path | None">
    shell 会话的基础目录
  </ParamField>

  <ParamField body="startup_commands" type="tuple[str, ...] | list[str] | str | None">
    会话启动时运行的命令
  </ParamField>

  <ParamField body="execution_policy" type="BaseExecutionPolicy | None">
    执行策略（`HostExecutionPolicy`、`DockerExecutionPolicy` 或 `CodexSandboxExecutionPolicy`）
  </ParamField>

  <ParamField body="redaction_rules" type="tuple[RedactionRule, ...] | list[RedactionRule] | None">
    用于清理命令输出的规则
  </ParamField>

  有关完整配置详情，请参阅 [Shell 工具](/oss/python/langchain/middleware/built-in#shell-tool)。
</Accordion>

<Accordion title="完整示例">
  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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

  # 为此演示创建一个临时工作区目录。
  # 在生产环境中，请使用持久目录路径。
  workspace = tempfile.mkdtemp(prefix="agent-workspace-")

  agent = create_agent(
      model=ChatAnthropic(model="claude-sonnet-4-6"),
      tools=[],
      middleware=[ # [!code highlight]
          ClaudeBashToolMiddleware( # [!code highlight]
              workspace_root=workspace, # [!code highlight]
              startup_commands=["echo '会话已初始化'"], # [!code highlight]
              execution_policy=DockerExecutionPolicy( # [!code highlight]
                  image="python:3.11-slim", # [!code highlight]
              ), # [!code highlight]
          ), # [!code highlight]
      ], # [!code highlight]
  )

  # Claude 现在可以使用其原生 bash 工具
  result = agent.invoke(
      {"messages": [{"role": "user", "content": "安装了哪个版本的 Python？"}]}
  )
  print(result["messages"][-1].content)
  ```

  ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  安装了 Python 3.11.14。
  ```
</Accordion>

## 文本编辑器

提供 Claude 的文本编辑器工具 (`text_editor_20250728`) 用于文件创建和编辑。

文本编辑器中间件适用于以下情况：

* 基于文件的代理工作流
* 代码编辑和重构任务
* 多文件项目工作
* 需要持久文件存储的代理

<Note>
  提供两种变体：**基于状态**（文件在 LangGraph 状态中）和**基于文件系统**（文件在磁盘上）。
</Note>

**API 参考：**

* [`StateClaudeTextEditorMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/StateClaudeTextEditorMiddleware)
* [`FilesystemClaudeTextEditorMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/FilesystemClaudeTextEditorMiddleware)

```python 基于状态的文本编辑器 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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()], # [!code highlight]
)
```

```python 基于文件系统的文本编辑器 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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=[ # [!code highlight]
        FilesystemClaudeTextEditorMiddleware( # [!code highlight]
            root_path="/workspace", # [!code highlight]
        ), # [!code highlight]
    ], # [!code highlight]
)
```

Claude 的文本编辑器工具支持以下命令：

* `view` - 查看文件内容或列出目录
* `create` - 创建新文件
* `str_replace` - 替换文件中的字符串
* `insert` - 在行号处插入文本
* `delete` - 删除文件
* `rename` - 重命名/移动文件

<Accordion title="配置选项">
  **[`StateClaudeTextEditorMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/StateClaudeTextEditorMiddleware)（基于状态）**

  <ParamField body="allowed_path_prefixes" type="Sequence[str] | None">
    可选的允许路径前缀列表。如果指定，则仅允许以这些前缀开头的路径。
  </ParamField>

  **[`FilesystemClaudeTextEditorMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/FilesystemClaudeTextEditorMiddleware)（基于文件系统）**

  <ParamField body="root_path" type="str" required>
    文件操作的根目录
  </ParamField>

  <ParamField body="allowed_prefixes" type="list[str] | None">
    可选的允许虚拟路径前缀列表（默认：`["/"]`）
  </ParamField>

  <ParamField body="max_file_size_mb" type="int" default="10">
    最大文件大小（MB）
  </ParamField>
</Accordion>

<AccordionGroup>
  <Accordion title="完整示例：基于状态的文本编辑器">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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( # [!code highlight]
                allowed_path_prefixes=["/project"], # [!code highlight]
            ), # [!code highlight]
        ],
        checkpointer=MemorySaver(),
    )

    # 使用 thread_id 在调用之间持久化状态
    config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

    # Claude 现在可以创建和编辑文件（存储在 LangGraph 状态中）
    result = agent.invoke(
        {"messages": [{"role": "user", "content": "在 /project/hello.py 创建一个简单的 hello world 程序"}]},
        config=config,
    )
    print(result["messages"][-1].content)
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    我已在 `/project/hello.py` 创建了一个简单的 "Hello, World!" 程序。该程序使用 Python 的 `print()` 函数在执行时向控制台显示 "Hello, World!"。
    ```
  </Accordion>

  <Accordion title="完整示例：基于文件系统的文本编辑器">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import tempfile

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


    # 为此演示创建一个临时工作区目录。
    # 在生产环境中，请使用持久目录路径。
    workspace = tempfile.mkdtemp(prefix="editor-workspace-")

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

    # Claude 现在可以创建和编辑文件（存储在磁盘上）
    result = agent.invoke(
        {"messages": [{"role": "user", "content": "在 /src/hello.py 创建一个简单的 hello world 程序"}]}
    )
    print(result["messages"][-1].content)
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    我已在 `/src/hello.py` 创建了一个简单的 "Hello, World!" 程序。该程序使用 Python 的 `print()` 函数在执行时向控制台显示 "Hello, World!"。
    ```
  </Accordion>
</AccordionGroup>

## 记忆

提供 Claude 的记忆工具 (`memory_20250818`) 用于跨对话轮次的持久化代理记忆。

记忆中间件适用于以下情况：

* 长时间运行的代理对话
* 在中断后维护上下文
* 任务进度跟踪
* 持久化代理状态管理

<Info>
  Claude 的记忆工具使用 `/memories` 目录，并自动注入系统提示，鼓励代理检查和更新记忆。
</Info>

**API 参考：** [`StateClaudeMemoryMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/StateClaudeMemoryMiddleware), [`FilesystemClaudeMemoryMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/FilesystemClaudeMemoryMiddleware)

```python 基于状态的记忆 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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()], # [!code highlight]
)
```

```python 基于文件系统的记忆 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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=[ # [!code highlight]
        FilesystemClaudeMemoryMiddleware( # [!code highlight]
            root_path="/workspace", # [!code highlight]
        ), # [!code highlight]
    ], # [!code highlight]
)
```

<Accordion title="配置选项">
  **[`StateClaudeMemoryMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/StateClaudeMemoryMiddleware)（基于状态）**

  <ParamField body="allowed_path_prefixes" type="Sequence[str] | None">
    可选的允许路径前缀列表。默认为 `["/memories"]`。
  </ParamField>

  <ParamField body="system_prompt" type="str">
    要注入的系统提示。默认为 Anthropic 推荐的记忆提示，鼓励代理检查和更新记忆。
  </ParamField>

  **[`FilesystemClaudeMemoryMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/anthropic_tools/FilesystemClaudeMemoryMiddleware)（基于文件系统）**

  <ParamField body="root_path" type="str" required>
    文件操作的根目录
  </ParamField>

  <ParamField body="allowed_prefixes" type="list[str] | None">
    可选的允许虚拟路径前缀列表。默认为 `["/memories"]`。
  </ParamField>

  <ParamField body="max_file_size_mb" type="int" default="10">
    最大文件大小（MB）
  </ParamField>

  <ParamField body="system_prompt" type="str">
    要注入的系统提示
  </ParamField>
</Accordion>

<AccordionGroup>
  <Accordion title="完整示例：基于状态的记忆">
    代理将自动：

    1. 启动时检查 `/memories` 目录
    2. 在执行过程中记录进度和想法
    3. 随着工作进展更新记忆文件

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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()], # [!code highlight]
        checkpointer=MemorySaver(),
    )

    # 使用 thread_id 在调用之间持久化状态
    config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

    # Claude 现在可以使用记忆来跟踪进度（存储在 LangGraph 状态中）
    result = agent.invoke(
        {"messages": [{"role": "user", "content": "记住我最喜欢的颜色是蓝色，然后确认你存储的内容。"}]},
        config=config,
    )
    print(result["messages"][-1].content)
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    完美！我已将您最喜欢的颜色 **蓝色** 存储在我的记忆系统中。该信息保存在我的用户偏好文件中，我可以在未来的对话中访问它。
    ```
  </Accordion>

  <Accordion title="完整示例：基于文件系统的记忆">
    代理将自动：

    1. 启动时检查 `/memories` 目录
    2. 在执行过程中记录进度和想法
    3. 随着工作进展更新记忆文件

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import tempfile

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


    # 为此演示创建一个临时工作区目录。
    # 在生产环境中，请使用持久目录路径。
    workspace = tempfile.mkdtemp(prefix="memory-workspace-")

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

    # Claude 现在可以使用记忆来跟踪进度（存储在磁盘上）
    result = agent.invoke(
        {"messages": [{"role": "user", "content": "记住我最喜欢的颜色是蓝色，然后确认你存储的内容。"}]}
    )
    print(result["messages"][-1].content)
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    完美！我已将您最喜欢的颜色 **蓝色** 存储在我的记忆系统中。该信息保存在我的用户偏好文件中，我可以在未来的对话中访问它。
    ```
  </Accordion>
</AccordionGroup>

## 文件搜索

提供 Glob 和 Grep 搜索工具，用于搜索存储在 LangGraph 状态中的文件。文件搜索中间件适用于以下情况：

* 搜索基于状态的虚拟文件系统
* 与文本编辑器和记忆工具配合使用
* 按模式查找文件
* 使用正则表达式进行内容搜索

**API 参考：** [`StateFileSearchMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/file_search/StateFileSearchMiddleware)

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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=[ # [!code highlight]
        StateClaudeTextEditorMiddleware(), # [!code highlight]
        StateFileSearchMiddleware(),  # 搜索文本编辑器文件 [!code highlight]
    ], # [!code highlight]
)
```

<Accordion title="配置选项">
  <ParamField body="state_key" type="str" default="text_editor_files">
    包含要搜索文件的状态键。对于文本编辑器文件使用 `"text_editor_files"`，对于记忆文件使用 `"memory_files"`。
  </ParamField>
</Accordion>

<AccordionGroup>
  <Accordion title="完整示例：搜索文本编辑器文件">
    中间件添加了 Glob 和 Grep 搜索工具，可与基于状态的文件配合使用。

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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"), # [!code highlight]
        ],
        checkpointer=MemorySaver(),
    )

    # 使用 thread_id 在调用之间持久化状态
    config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

    # 第一次调用：使用文本编辑器工具创建一些文件
    result = agent.invoke(
        {"messages": [HumanMessage("创建一个包含 main.py、utils/helpers.py 和 tests/test_main.py 的 Python 项目")]},
        config=config,
    )

    # 代理创建文件，这些文件存储在状态中
    print("创建的文件:", list(result["text_editor_files"].keys()))

    # 第二次调用：搜索我们刚刚创建的文件
    # 状态通过 checkpointer 自动持久化
    result = agent.invoke(
        {"messages": [HumanMessage("查找项目中的所有 Python 文件")]},
        config=config,
    )
    print(result["messages"][-1].content)
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    创建的文件: ['/project/main.py', '/project/utils/helpers.py', '/project/utils/__init__.py', '/project/tests/test_main.py', '/project/tests/__init__.py', '/project/README.md']
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    我在项目中找到了 5 个 Python 文件：

    1. `/project/main.py` - 主应用程序文件
    2. `/project/utils/__init__.py` - Utils 包初始化
    3. `/project/utils/helpers.py` - 辅助工具
    4. `/project/tests/__init__.py` - 测试包初始化
    5. `/project/tests/test_main.py` - 主测试文件

    您想查看其中任何一个文件的内容吗？
    ```
  </Accordion>

  <Accordion title="完整示例：搜索记忆文件">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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"), # [!code highlight]
        ],
        checkpointer=MemorySaver(),
    )

    # 使用 thread_id 在调用之间持久化状态
    config: RunnableConfig = {"configurable": {"thread_id": "my-session"}}

    # 第一次调用：记录一些记忆
    result = agent.invoke(
        {"messages": [HumanMessage("记住项目截止日期是 3 月 15 日，代码审查截止日期是 3 月 10 日")]},
        config=config,
    )

    # 代理创建记忆文件，这些文件存储在状态中
    print("创建的记忆文件:", list(result["memory_files"].keys()))

    # 第二次调用：搜索我们刚刚记录的记忆
    # 状态通过 checkpointer 自动持久化
    result = agent.invoke(
        {"messages": [HumanMessage("在我的记忆中搜索项目截止日期")]},
        config=config,
    )
    print(result["messages"][-1].content)
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    创建的记忆文件: ['/memories/project_info.md']
    ```

    ```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    我在我的记忆中找到了您的项目截止日期！这是我记录的内容：

    ## 重要截止日期
    - **代码审查截止日期：** 3 月 10 日
    - **项目截止日期：** 3 月 15 日

    ## 备注
    - 代码审查必须在最终项目截止日期前 5 天完成
    - 需要确保所有代码在 3 月 10 日前准备好进行审查

    关于这些截止日期，您有什么具体想了解或更新的吗？
    ```
  </Accordion>
</AccordionGroup>

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/middleware/anthropic.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
