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

# ChatAnthropic 集成

> 使用 LangChain Python 集成 ChatAnthropic 对话模型

您可以在 [Claude](https://platform.claude.com/docs/en/about-claude/models/overview) 文档中找到 Anthropic 最新模型的信息、成本、上下文窗口以及支持的输入类型。

> [!TIP]
>
> **API 参考**
>
> 查看所有功能和配置选项的详细文档，请前往 @\[`ChatAnthropic` API 参考。

> [!NOTE]
>
> **AWS Bedrock 和 Gemini 企业智能体平台**
>
> 请注意，某些 Anthropic 模型也可以通过 AWS Bedrock 和 Gemini 企业智能体平台访问。查看 [`ChatBedrock`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/bedrock/) 和 [`ChatVertexAI`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/google_vertex_ai) 集成，以通过这些服务使用 Anthropic 模型。
>
> 对于 AWS Bedrock 上的 Anthropic 模型（与 `ChatAnthropic` 相同的 API），请使用 `langchain-aws` 的 [`ChatAnthropicBedrock`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/bedrock#chatanthropicbedrock)。

## 概述

### 集成细节

| 类 | 包 | 可序列化 | 支持 JS/TS | 下载量 | 最新版本 |
| :- | :- | :-: | :-: | :-: | :-: |
| @\[`ChatAnthropic`] | @\[`langchain-anthropic`] | beta | ✅ [(npm)](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/chat/anthropic.md) | [![Downloads per month](https://static.pepy.tech/badge/langchain-anthropic/month)](https://pypi.org/project/langchain-anthropic/) | [![PyPI - Latest version](https://img.shields.io/pypi/v/langchain-anthropic?style=flat-square\&label=%20\&color=orange)](https://pypi.org/project/langchain-anthropic/) |

### 模型特性

| [工具调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) | [结构化输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output.md) | [图像输入](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态) | 音频输入 | 视频输入 | [Token级流式输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/streaming.md) | 原生异步 | [Token使用量](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#token-使用) | [Logprobs](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#对数概率) |
| :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ |

## 安装

要访问 Anthropic (Claude) 模型，您需要安装 `langchain-anthropic` 集成包并获取一个 [Claude](https://platform.claude.com/docs/en/get-started#prerequisites) API 密钥。

### 安装

```bash pip theme={null}
pip install -U langchain-anthropic
```

```bash uv theme={null}
uv add langchain-anthropic
```

### 凭证

前往 [Claude 控制台](https://console.anthropic.com) 注册并生成一个 Claude API 密钥。完成此操作后，设置 `ANTHROPIC_API_KEY` 环境变量：

```python theme={null}
import getpass
import os

if "ANTHROPIC_API_KEY" not in os.environ:
    os.environ["ANTHROPIC_API_KEY"] = getpass.getpass("Enter your Anthropic API key: ")
```

要启用模型调用的自动跟踪，设置您的 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```python theme={null}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 实例化

现在我们可以实例化我们的模型对象并生成对话补全：

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-haiku-4-5-20251001",
    # temperature=,
    # max_tokens=,
    # timeout=,
    # max_retries=,
    # ...
)
```

有关所有可用的实例化参数的详细信息，请参阅 @\[`ChatAnthropic`] API 参考。

> [!NOTE]
>
> **推理地域**
>
> 要控制模型推理运行的位置（[数据驻留](https://platform.claude.com/docs/en/build-with-claude/data-residency)），在创建 @\[`ChatAnthropic`] 时传递 `inference_geo`。有关支持值，请参阅 Anthropic 文档。

## 采样参数

较新的 Claude 模型会拒绝非默认的采样参数。在 `claude-opus-5`、`claude-fable-5`、`claude-opus-4-8`、`claude-opus-4-7` 或 `claude-sonnet-5` 上将 `temperature`、`top_p` 或 `top_k` 设置为非默认值会返回 400 错误：

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(model="claude-opus-5", temperature=0)
model.invoke("Hello!")
# anthropic.BadRequestError: Error code: 400 -
# {'type': 'error', 'error': {'type': 'invalid_request_error',
#  'message': '`temperature` is deprecated for this model.'}}
```

模型支持情况：

| 模型 | `temperature` / `top_p` / `top_k` |
| - | - |
| `claude-opus-5`、`claude-fable-5`、`claude-opus-4-8`、`claude-opus-4-7`、`claude-sonnet-5` | 拒绝非默认值 (400)。省略参数，或仅传递默认值（例如，`temperature=1`）。 |
| `claude-opus-4-6`、`claude-sonnet-4-6`、`claude-haiku-4-5` 及更早版本 | 被接受 |

> [!WARNING]
>
> **升级模型字符串？**
>
> 按 `ChatAnthropic(model=..., temperature=0)` 编写的代码在升级到上述较新模型时会失效。请移除采样参数，而不是调整其值。在这些模型上，应通过提示词来控制输出风格。详情请参阅 [Anthropic 迁移指南](https://platform.claude.com/docs/en/about-claude/models/migration-guide)。

## 调用

> [accordion] 调用
>
> ```python theme={null}
> messages = [
>     (
>         "system",
>         "You are a helpful translator. Translate the user sentence to French.",
>     ),
>     (
>         "human",
>         "I love programming.",
>     ),
> ]
> ai_msg = model.invoke(messages)
> ```
>
> ```python theme={null}
> print(ai_msg.text)
> ```
>
> ```text theme={null}
> J'adore la programmation.
> ```

> [accordion] 流式输出
>
> ```python theme={null}
> stream = model.stream_events(messages, version="v3")
> for token in stream.text:
>     print(token, end="", flush=True)
> ```
>
> ```text theme={null}
> J'aime la programmation.
> ```
>
> 要从流中聚合完整消息：
>
> ```python theme={null}
> stream = model.stream_events(messages, version="v3")
> full_message = stream.output
> ```
>
> ```python theme={null}
> AIMessage(content="J'aime la programmation.", id="run-b34faef0-882f-4869-a19c-ed2b856e6361")
> ```

> [accordion] 异步
>
> ```python theme={null}
> ai_msg = await model.ainvoke(messages)
>
> # stream
> stream = await model.astream_events(messages, version="v3")
> async for token in stream.text:
>     print(token, end="", flush=True)
>
> # batch
> await model.abatch([messages])
> ```
>
> ```python theme={null}
> AIMessage(
>     content="J'aime la programmation.",
>     response_metadata={
>         "id": "msg_01Trik66aiQ9Z1higrD5XFx3",
>         "model": "claude-sonnet-4-6",
>         "stop_reason": "end_turn",
>         "stop_sequence": None,
>         "usage": {"input_tokens": 25, "output_tokens": 11},
>     },
>     id="run-5886ac5f-3c2e-49f5-8a44-b1e92808c929-0",
>     usage_metadata={
>         "input_tokens": 25,
>         "output_tokens": 11,
>         "total_tokens": 36,
>     },
> )
> ```

了解更多关于支持的调用方法，请参阅我们的 [模型](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#调用) 指南。

## 内容块

在使用工具时，[扩展思考](#扩展思考)和其他功能，来自单个 Anthropic @\[`AIMessage`] 的内容可以是单个字符串，也可以是 Anthropic 内容块的列表。

例如，当 Anthropic 模型调用工具时，工具调用是消息内容的一部分（同时也会在标准化的 @\[`AIMessage.tool_calls`] 中暴露）：

```python theme={null}
from langchain_anthropic import ChatAnthropic
from typing_extensions import Annotated

model = ChatAnthropic(model="claude-haiku-4-5-20251001")


def get_weather(
    location: Annotated[str, ..., "Location as city and state."]
) -> str:
    """Get the weather at a location."""
    return "It's sunny."


model_with_tools = model.bind_tools([get_weather])
response = model_with_tools.invoke("Which city is hotter today: LA or NY?")
response.content
```

```python theme={null}
[{'text': "I'll help you compare the temperatures of Los Angeles and New York by checking their current weather. I'll retrieve the weather for both cities.",
  'type': 'text'},
 {'id': 'toolu_01CkMaXrgmsNjTso7so94RJq',
  'input': {'location': 'Los Angeles, CA'},
  'name': 'get_weather',
  'type': 'tool_use'},
 {'id': 'toolu_01SKaTBk9wHjsBTw5mrPVSQf',
  'input': {'location': 'New York, NY'},
  'name': 'get_weather',
  'type': 'tool_use'}]
```

使用 `content_blocks` 将以 LangChain 的标准格式渲染内容，该格式在跨其他模型提供者时保持一致。了解更多关于 [内容块](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#标准内容块) 的信息。

```python theme={null}
response.content_blocks
```

您还可以使用 `tool_calls` 属性以标准格式访问特定的工具调用：

```python theme={null}
response.tool_calls
```

```python theme={null}
[{'name': 'GetWeather',
  'args': {'location': 'Los Angeles, CA'},
  'id': 'toolu_01Ddzj5PkuZkrjF4tafzu54A'},
 {'name': 'GetWeather',
  'args': {'location': 'New York, NY'},
  'id': 'toolu_012kz4qHZQqD4qg8sFPeKqpP'}]
```

## 工具

Anthropic 的工具使用功能允许您定义 Claude 在对话期间可以调用的外部函数。这支持动态信息检索、计算以及与外部系统的交互。

有关如何将工具绑定到您的模型实例的详细信息，请参见 @\[`ChatAnthropic.bind_tools`]。

> [!NOTE]
>
> 有关 Claude 的内置工具（代码执行、网络浏览、文件 API 等）的信息，请参阅 [内置工具](#内置工具)。

```python theme={null}
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    '''Get the current weather in a given location'''

    location: str = Field(description="The city and state, e.g. San Francisco, CA")


class GetPopulation(BaseModel):
    '''Get the current population in a given location'''

    location: str = Field(description="The city and state, e.g. San Francisco, CA")


model_with_tools = model.bind_tools([GetWeather, GetPopulation]) # [!code highlight]
ai_msg = model_with_tools.invoke("Which city is hotter today and which is bigger: LA or NY?")
ai_msg.tool_calls
```

```python theme={null}
[
    {
        "name": "GetWeather",
        "args": {"location": "Los Angeles, CA"},
        "id": "toolu_01KzpPEAgzura7hpBqwHbWdo",
    },
    {
        "name": "GetWeather",
        "args": {"location": "New York, NY"},
        "id": "toolu_01JtgbVGVJbiSwtZk3Uycezx",
    },
    {
        "name": "GetPopulation",
        "args": {"location": "Los Angeles, CA"},
        "id": "toolu_01429aygngesudV9nTbCKGuw",
    },
    {
        "name": "GetPopulation",
        "args": {"location": "New York, NY"},
        "id": "toolu_01JPktyd44tVMeBcPPnFSEJG",
    },
]
```

### 严格工具使用

> [!NOTE]
>
> 严格工具使用需要 `langchain-anthropic>=1.1.0`。有关受支持的模型，请参阅 [Claude 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use)。

Anthropic 支持选择加入 [严格遵循工具调用模式](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)。这通过约束解码确保工具名称和参数经过验证并正确类型化。

在没有严格模式的情况下，Claude 有时可能会生成无效的工具输入，从而破坏您的应用程序：

* **类型不匹配**：`passengers: "2"` 而不是 `passengers: 2`
* **缺少必需字段**：遗漏您的函数期望的字段
* **无效的枚举值**：超出允许范围的值
* **模式违规**：嵌套对象不符合预期结构

严格工具使用保证符合模式的工具调用：

* 工具输入严格遵循您的 `input_schema`
* 保证字段类型和必需字段
* 消除对格式错误输入的错误处理
* 使用的工具 `name` 始终来自提供的工具

| 使用严格工具使用 | 使用标准工具调用 |
| - | - |
| 构建可靠性至关重要的智能体工作流 | 简单的单轮工具调用 |
| 具有许多参数或嵌套对象的工具 | 原型设计和实验 |
| 需要特定类型的功能（例如，`int` vs `str`） | |

要启用严格工具使用，请在调用 @\[`bind_tools`]\[ChatAnthropic.bind\_tools] 时指定 `strict=True`。

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(model="claude-sonnet-4-6")

def get_weather(location: str) -> str:
    """Get the weather at a location."""
    return "It's sunny."

model_with_tools = model.bind_tools([get_weather], strict=True)  # [!code highlight]
```

> [accordion] 示例：类型安全的预订系统
>
> 考虑一个 `passengers` 必须是整数的预订系统：
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
> from typing import Literal
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> def book_flight(
>     destination: str,
>     departure_date: str,
>     passengers: int, # [!code highlight]
>     cabin_class: Literal["economy", "business", "first"]
> ) -> str:
>     """Book a flight to a destination.
>
>     Args:
>         destination: The destination city
>         departure_date: Date in YYYY-MM-DD format
>         passengers: Number of passengers (must be an integer)
>         cabin_class: The cabin class for the flight
>     """
>     return f"Booked {passengers} passengers to {destination}"
>
> model_with_tools = model.bind_tools(
>     [book_flight],
>     strict=True, # [!code highlight]
>     tool_choice="any",
> )
> response = model_with_tools.invoke("Book 2 passengers to Tokyo, business class, 2025-01-15")
>
> # With strict=True, passengers is guaranteed to be int, not "2" or "two"
> print(response.tool_calls[0]["args"]["passengers"])
> ```
>
> ```text theme={null}
> 2
> ```

严格工具使用有一些 JSON 模式限制需要注意。有关更多详细信息，请参阅 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations)。

如果您的工具模式使用不受支持的功能，您将收到 400 错误。在这种情况下，请简化模式或使用标准（非严格）工具调用。

### 输入示例

对于复杂的工具，您可以提供使用示例以帮助 Claude 正确理解如何使用它们。这是通过在工具的 `extras` 参数中设置 `input_examples` 实现的。

```python theme={null}
from langchain_anthropic import ChatAnthropic
from langchain.tools import tool

@tool(
    extras={ # [!code highlight]
        "input_examples": [ # [!code highlight]
            { # [!code highlight]
                "query": "weather report", # [!code highlight]
                "location": "San Francisco", # [!code highlight]
                "format": "detailed" # [!code highlight]
            }, # [!code highlight]
            { # [!code highlight]
                "query": "temperature", # [!code highlight]
                "location": "New York", # [!code highlight]
                "format": "brief" # [!code highlight]
            } # [!code highlight]
        ] # [!code highlight]
    } # [!code highlight]
)
def search_weather_data(query: str, location: str, format: str = "brief") -> str:
    """Search weather database with specific query and format preferences.

    Args:
        query: The type of weather information to retrieve
        location: City or region to search
        format: Output format, either 'brief' or 'detailed'
    """
    return f"{format.title()} {query} for {location}: Data found"

model = ChatAnthropic(model="claude-sonnet-4-6")
model_with_tools = model.bind_tools([search_weather_data])

response = model_with_tools.invoke(
    "Get me a detailed weather report for Seattle"
)
```

`extras` 参数还支持：

* `defer_loading` (bool): 按需加载工具，用于 [工具搜索](#工具搜索) 或 [会话中期的工具变更](#对话中更改工具)
* `cache_control` (dict): 为该工具启用 [提示词缓存](#缓存工具)
* `eager_input_streaming` (bool): 为该工具启用 [细粒度工具流式输出](#细粒度工具流式输出)

### 细粒度工具流式输出

Anthropic 支持 [细粒度工具流式输出](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming)，在流式传输具有大参数的工具调用时可以减少延迟。

细粒度流式输出在参数数据可用时立即发送，而不是在传输前缓存整个参数值。对于大型工具参数，这可以将初始延迟从 15 秒减少到约 3 秒。

> [!WARNING]
>
> 细粒度流式输出可能会返回无效或部分 JSON 输入，特别是如果响应在完成前就到达 `max_tokens` 时。为不完整的 JSON 数据实现适当的错误处理。

要为应增量流式传输工具参数的工具启用细粒度工具流式输出，请在工具上设置 `extras={"eager_input_streaming": True}`。该值会通过工具定义传递给 Anthropic API。

```python theme={null}
from langchain_anthropic import ChatAnthropic
from langchain.tools import tool

model = ChatAnthropic(model="claude-sonnet-4-6")

@tool(extras={"eager_input_streaming": True})
def write_document(title: str, content: str) -> str:
    """Write a document with the given title and content."""
    return f"Document '{title}' written successfully"

model_with_tools = model.bind_tools([write_document])

# Stream tool calls with reduced latency
for chunk in model_with_tools.stream(
    "Write a detailed technical document about the benefits of streaming APIs"
):
    print(chunk.content)
```

流式数据以 `input_json_delta` 块的形式到达 `chunk.content`。您可以累积这些块来构建完整的工具参数：

```python theme={null}
import json

from langchain_anthropic import ChatAnthropic
from langchain.tools import tool

model = ChatAnthropic(model="claude-sonnet-4-6")

@tool(extras={"eager_input_streaming": True})
def write_document(title: str, content: str) -> str:
    """Write a document with the given title and content."""
    return f"Document '{title}' written successfully"

model_with_tools = model.bind_tools([write_document])

accumulated_json = ""

for chunk in model_with_tools.stream("Write a document about AI"):
    for block in chunk.content:
        if isinstance(block, dict) and block.get("type") == "input_json_delta":
            accumulated_json += block.get("partial_json", "")
            try:
                # Try to parse accumulated JSON
                parsed = json.loads(accumulated_json)
                print(f"Complete args: {parsed}")
            except json.JSONDecodeError:
                # JSON is still incomplete, continue accumulating
                pass
```

```text theme={null}
Complete args: {'title': 'Artificial Intelligence: An Overview', 'content': '# Artificial Intelligence: An Overview...
```

### 程序化工具调用

> [!NOTE]
>
> 程序化工具调用需要 `langchain-anthropic>=1.3.0`。请参阅 [Claude 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) 了解支持的模型。

工具可以配置为从 Claude 的 [代码执行](#代码执行) 环境中可调用，在涉及大数据处理或多工具工作流的环境中可以减少延迟和 Token 消耗。

有关详细信息，请参阅 Claude 的 [程序化工具调用指南](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling)。要使用此功能：

* 在您的工具集中包含 [代码执行](#代码执行) 内置工具
* 在您希望程序化调用的工具上指定 `extras={"allowed_callers": ["code_execution_20250825"]}`

下方提供了包含 [`create_agent`](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/agents) 的完整示例。

> [!TIP]
>
> 您可以在初始化时指定 `reuse_last_container` 以自动重用先前模型响应的代码执行容器。

```python theme={null}
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_anthropic import ChatAnthropic


@tool(extras={"allowed_callers": ["code_execution_20250825"]}) # [!code highlight]
def get_weather(location: str) -> str:
    """Get the weather at a location."""
    return "It's sunny."

tools = [
    {"type": "code_execution_20250825", "name": "code_execution"}, # [!code highlight]
    get_weather,
]

model = ChatAnthropic(
    model="claude-sonnet-4-6",
    reuse_last_container=True,  # [!code highlight]
)

agent = create_agent(model, tools=tools)

input_query = {
    "role": "user",
    "content": "What's the weather in Boston?",
}

result = agent.invoke({"messages": [input_query]})
```

## 多模态

Claude 支持图像和 PDF 输入作为内容块，既支持 Anthropic 的原生格式（参见文档中关于 [vision](https://platform.claude.com/docs/en/build-with-claude/vision) 和 [PDF 支持](https://platform.claude.com/docs/en/build-with-claude/pdf-support) 的说明），也支持 LangChain 的 [标准格式](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态)。

### 支持的输入方法

| 方法 | 图像 | PDF |
| - | :-: | :-: |
| Base64 内联数据 | ✅ | ✅ |
| HTTP/HTTPS URL | ✅ | ✅ |
| [文件 API](https://platform.claude.com/docs/en/build-with-claude/files) | ✅ | ✅ |

> [!TIP]
>
> 文件 API 也可以用于将文件上传到容器中，以配合 Claude 的内置代码执行工具使用。详情请参阅 [代码执行](#代码执行) 部分。

### 图像输入

使用 @\[`HumanMessage`] 并以列表内容格式提供文本和图像输入。

```python URL theme={null}
from langchain_anthropic import ChatAnthropic
from langchain.messages import HumanMessage

model = ChatAnthropic(model="claude-sonnet-4-6")

message = HumanMessage(
    content=[
        {"type": "text", "text": "Describe the image at the URL."},
        {
            "type": "image",
            "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
        },
    ]
)
response = model.invoke([message])
```

```python Base64 encoded theme={null}
import base64
import httpx
from langchain_anthropic import ChatAnthropic
from langchain.messages import HumanMessage

model = ChatAnthropic(model="claude-sonnet-4-6")

image_url = "https://picsum.photos/id/237/200/300"
image_data = base64.b64encode(httpx.get(image_url, follow_redirects=True).content).decode("utf-8")

message = HumanMessage(
    content=[
        {"type": "text", "text": "Describe the image."},
        { # [!code highlight]
            "type": "image", # [!code highlight]
            "base64": image_data, # [!code highlight]
            "mime_type": "image/jpeg", # [!code highlight]
        }, # [!code highlight]
    ]
)
response = model.invoke([message])
```

```python Files API theme={null}
import anthropic
from langchain_anthropic import ChatAnthropic
from langchain.messages import HumanMessage

client = anthropic.Anthropic()
file = client.beta.files.upload(
    file=("image.png", open("/path/to/image.png", "rb"), "image/png"),
)

model = ChatAnthropic(
    model="claude-sonnet-4-6",
    betas=["files-api-2025-04-14"], # [!code highlight]
)

message = HumanMessage(
    content=[
        {"type": "text", "text": "Describe this image."},
        {
            "type": "image",
            "file_id": file.id, # [!code highlight]
        },
    ]
)
response = model.invoke([message])
```

### PDF 输入

提供文本和 PDF 文件输入。

```python URL theme={null}
from langchain_anthropic import ChatAnthropic
from langchain.messages import HumanMessage

model = ChatAnthropic(model="claude-sonnet-4-6")

message = HumanMessage(
    content=[
        {"type": "text", "text": "Summarize this document."},
        {
            "type": "file",
            "url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
            "mime_type": "application/pdf",
        },
    ]
)
response = model.invoke([message])
```

```python Base64 encoded theme={null}
import base64
import httpx
from langchain_anthropic import ChatAnthropic
from langchain.messages import HumanMessage

model = ChatAnthropic(model="claude-sonnet-4-6")

pdf_url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
pdf_data = base64.b64encode(httpx.get(pdf_url).content).decode("utf-8")

message = HumanMessage(
    content=[
        {"type": "text", "text": "Summarize this document."},
        {
            "type": "file",
            "base64": pdf_data, # [!code highlight]
            "mime_type": "application/pdf", # [!code highlight]
        },
    ]
)
response = model.invoke([message])
```

```python Files API theme={null}
import anthropic
from langchain_anthropic import ChatAnthropic
from langchain.messages import HumanMessage

client = anthropic.Anthropic()
file = client.beta.files.upload(
    file=("document.pdf", open("/path/to/document.pdf", "rb"), "application/pdf"),
)

model = ChatAnthropic(
    model="claude-sonnet-4-6",
    betas=["files-api-2025-04-14"], # [!code highlight]
)

message = HumanMessage(
    content=[
        {"type": "text", "text": "Summarize this document."},
        {
            "type": "file",
            "file_id": file.id, # [!code highlight]
        },
    ]
)
response = model.invoke([message])
```

## 扩展思考

某些 Claude 模型支持 [扩展思考](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) 功能，该功能会输出其最终答案所依据的逐步推理过程。

在 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#supported-models) 中查看兼容的模型。

要使用扩展思考，在初始化 @\[`ChatAnthropic`] 时指定 `thinking` 参数。如有需要，它也可以在调用过程中作为参数传递。

对于 Claude Sonnet 及更早版本模型，需要指定一个 Token 预算。对于 Claude Opus 4.6+，可以使用自适应思考功能，该功能会自动确定预算。

```python With token budget theme={null}
import json
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-sonnet-4-6",
    max_tokens=5000,
    thinking={"type": "enabled", "budget_tokens": 2000}, # [!code highlight]
)

response = model.invoke("What is the cube root of 50.653?")
print(json.dumps(response.content_blocks, indent=2))
```

```python Adaptive (Opus 4.6+) theme={null}
import json
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-opus-4-8",
    max_tokens=5000,
    thinking={"type": "adaptive"}, # [!code highlight]
)

response = model.invoke("What is the cube root of 50.653?")
print(json.dumps(response.content_blocks, indent=2))
```

```python Invocation param theme={null}
import json
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(model="claude-sonnet-4-6")

response = model.invoke(
    "What is the cube root of 50.653?",
    max_tokens=5000,
    thinking={"type": "enabled", "budget_tokens": 2000} # [!code highlight]
)
print(json.dumps(response.content_blocks, indent=2))
```

```json theme={null}
[
  {
    "type": "reasoning",
    "reasoning": "To find the cube root of 50.653, I need to find the value of $x$ such that $x^3 = 50.653$.\n\nI can try to estimate this first. \n$3^3 = 27$\n$4^3 = 64$\n\nSo the cube root of 50.653 will be somewhere between 3 and 4, but closer to 4.\n\nLet me try to compute this more precisely. I can use the cube root function:\n\ncube root of 50.653 = 50.653^(1/3)\n\nLet me calculate this:\n50.653^(1/3) \u2248 3.6998\n\nLet me verify:\n3.6998^3 \u2248 50.6533\n\nThat's very close to 50.653, so I'm confident that the cube root of 50.653 is approximately 3.6998.\n\nActually, let me compute this more precisely:\n50.653^(1/3) \u2248 3.69981\n\nLet me verify once more:\n3.69981^3 \u2248 50.652998\n\nThat's extremely close to 50.653, so I'll say that the cube root of 50.653 is approximately 3.69981.",
    "extras": {"signature": "ErUBCkYIBxgCIkB0UjV..."}
  },
  {
    "type": "text",
    "text": "The cube root of 50.653 is approximately 3.6998.\n\nTo verify: 3.6998\u00b3 = 50.6530, which is very close to our original number.",
  }
]
```

> [!WARNING]
>
> Claude 消息 API 在处理 Claude Sonnet 3.7 和 Claude 4 模型的思考方式上有所不同。
>
> 更多信息请参考 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#differences-in-thinking-across-model-versions)。

## 努力程度

某些 Claude 模型支持一个 [努力程度](https://platform.claude.com/docs/en/build-with-claude/effort) 功能，该功能控制 Claude 在响应时使用的 Token 数量。这对于在响应质量、延迟和成本之间取得平衡非常有用。

> [!NOTE]
>
> **模型支持**
>
> 努力程度通常在 Claude Opus 4.6 和 Claude Opus 4.5 上可用。`max` 努力程度级别仅在 Claude Opus 4.6 上受支持。`xhigh` 努力程度级别在 Claude Opus 4.7 上受支持。Anthropic 可能会随着时间的推移添加或调整模型支持——请使用 [Claude 努力程度文档](https://platform.claude.com/docs/en/build-with-claude/effort) 作为事实来源。

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-opus-4-5-20251101",
    effort="medium",  # Options: "max", "xhigh", "high", "medium", "low" [!code highlight]
)

response = model.invoke("Analyze the trade-offs between microservices and monolithic architectures")
```

> [!NOTE]
>
> 将 `effort` 设置为 `"high"` 与完全省略该参数的行为完全相同。

`effort` 是标准 [`reasoning_effort`](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models#推理) 参数的别名，在构建和调用时都适用。如果两者都设置，`effort` 会优先。

> [!NOTE]
>
> `reasoning_effort` 需要 `langchain-anthropic>=1.5.3`。

```python theme={null}
model = ChatAnthropic(model="claude-opus-4-6")
response = model.invoke(
    "Analyze the trade-offs between microservices and monolithic architectures",
    reasoning_effort="high",
)
```

请参阅 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/effort)，了解何时使用不同的努力程度级别以及受支持的模型。

## 任务预算

Claude Opus 4.7 及更高版本支持 [任务预算](https://platform.claude.com/docs/en/build-with-claude/task-budgets)，这是针对智能体循环（思考、工具调用、工具结果和最终输出）的建议性 Token 目标。模型会看到正在运行的倒计时，并利用它来优先处理工作并优雅地完成。与 `max_tokens` 不同，任务预算不是硬性上限。

> [!NOTE]
>
> 任务预算需要 `langchain-anthropic>=1.4.1`，目前处于 Beta 测试阶段。

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-opus-4-8",
    output_config={  # [!code highlight]
        "effort": "high",  # [!code highlight]
        "task_budget": {"type": "tokens", "total": 128_000},  # [!code highlight]
    },  # [!code highlight]
)
```

## 引用

Anthropic 支持一个 [引用](https://platform.claude.com/docs/en/build-with-claude/citations) 功能，允许 Claude 根据用户提供的源文档将其上下文附加到答案中。

当 [文档](https://platform.claude.com/docs/en/build-with-claude/citations#document-types) 或 `search_result` 内容块包含 `"citations": {"enabled": True}` 时，Claude 可能会在其响应中生成引用。

### 简单示例

在这个示例中，我们传递了一个 [纯文本文档](https://platform.claude.com/docs/en/build-with-claude/citations#plain-text-documents)。在后台，Claude [自动分块](https://platform.claude.com/docs/en/build-with-claude/citations#plain-text-documents) 输入文本为句子，这些句子用于生成引用。

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(model="claude-haiku-4-5-20251001")

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "document",
                "source": {
                    "type": "text",
                    "media_type": "text/plain",
                    "data": "The grass is green. The sky is blue.",
                },
                "title": "My Document",
                "context": "This is a trustworthy document.",
                "citations": {"enabled": True},
            },
            {"type": "text", "text": "What color is the grass and sky?"},
        ],
    }
]
response = model.invoke(messages)
response.content
```

```python theme={null}
[{'text': 'Based on the document, ', 'type': 'text'},
 {'text': 'the grass is green',
  'type': 'text',
  'citations': [{'type': 'char_location',
    'cited_text': 'The grass is green. ',
    'document_index': 0,
    'document_title': 'My Document',
    'start_char_index': 0,
    'end_char_index': 20}]},
 {'text': ', and ', 'type': 'text'},
 {'text': 'the sky is blue',
  'type': 'text',
  'citations': [{'type': 'char_location',
    'cited_text': 'The sky is blue.',
    'document_index': 0,
    'document_title': 'My Document',
    'start_char_index': 20,
    'end_char_index': 36}]},
 {'text': '.', 'type': 'text'}]
```

### 在工具结果中（智能体 RAG）

Claude 支持一个 [搜索结果](https://platform.claude.com/docs/en/build-with-claude/search-results) 内容块，表示对知识库或其他自定义源的查询的可引用结果。这些内容块可以以顶部行（如上述示例）和工具结果内的形式传递给 Claude。这允许 Claude 使用工具调用的结果来引用其响应的元素。

为了在工具调用响应中传递搜索结果，定义一个返回 `search_result` 内容块列表的工具，这些内容块以 Anthropic 的原生格式返回。例如：

```python theme={null}
def retrieval_tool(query: str) -> list[dict]:
    """Access my knowledge base."""

    # Run a search (e.g., with a LangChain vector store)
    results = vector_store.similarity_search(query=query, k=2)

    # Package results into search_result blocks
    return [
        {
            "type": "search_result",
            # Customize fields as desired, using document metadata or otherwise
            "title": "My Document Title",
            "source": "Source description or provenance",
            "citations": {"enabled": True},
            "content": [{"type": "text", "text": doc.page_content}],
        }
        for doc in results
    ]
```

> [accordion] End to end example with LangGraph
>
> 这里我们展示了一个端到端的示例，其中我们将样本文档填充到 LangChain [向量存储](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores.md) 中，并给 Claude 配备了一个查询这些文档的工具。
>
> 此工具接受一个搜索查询和一个 `category` 字符串字面量，但任何有效的工具签名都可以使用。
>
> 此示例需要 `langchain-openai` 和 `numpy` 已安装：
>
> ```bash theme={null}
> pip install langchain-openai numpy
> ```
>
> ```python theme={null}
> from typing import Literal
>
> from langchain.chat_models import init_chat_model
> from langchain.embeddings import init_embeddings
> from langchain_core.documents import Document
> from langchain_core.vectorstores import InMemoryVectorStore
> from langgraph.checkpoint.memory import InMemorySaver
> from langchain.agents import create_agent
>
>
> # Set up vector store
> # Ensure you set your OPENAI_API_KEY environment variable
> embeddings = init_embeddings("openai:text-embedding-3-small")
> vector_store = InMemoryVectorStore(embeddings)
>
> document_1 = Document(
>     id="1",
>     page_content=(
>         "To request vacation days, submit a leave request form through the "
>         "HR portal. Approval will be sent by email."
>     ),
>     metadata={
>         "category": "HR Policy",
>         "doc_title": "Leave Policy",
>         "provenance": "Leave Policy - page 1",
>     },
> )
> document_2 = Document(
>     id="2",
>     page_content="Managers will review vacation requests within 3 business days.",
>     metadata={
>         "category": "HR Policy",
>         "doc_title": "Leave Policy",
>         "provenance": "Leave Policy - page 2",
>     },
> )
> document_3 = Document(
>     id="3",
>     page_content=(
>         "Employees with over 6 months tenure are eligible for 20 paid vacation days "
>         "per year."
>     ),
>     metadata={
>         "category": "Benefits Policy",
>         "doc_title": "Benefits Guide 2025",
>         "provenance": "Benefits Policy - page 1",
>     },
> )
>
> documents = [document_1, document_2, document_3]
> vector_store.add_documents(documents=documents)
>
>
> # Define tool
> async def retrieval_tool(
>     query: str, category: Literal["HR Policy", "Benefits Policy"]
> ) -> list[dict]:
>     """Access my knowledge base."""
>
>     def _filter_function(doc: Document) -> bool:
>         return doc.metadata.get("category") == category
>
>     results = vector_store.similarity_search(
>         query=query, k=2, filter=_filter_function
>     )
>
>     return [
>         {
>             "type": "search_result",
>             "title": doc.metadata["doc_title"],
>             "source": doc.metadata["provenance"],
>             "citations": {"enabled": True},
>             "content": [{"type": "text", "text": doc.page_content}],
>         }
>         for doc in results
>     ]
>
>
>
> # Create agent
> model = init_chat_model("claude-haiku-4-5-20251001")
>
> checkpointer = InMemorySaver()
> agent = create_agent(model, [retrieval_tool], checkpointer=checkpointer)
>
>
> # Invoke on a query
> config = {"configurable": {"thread_id": "session_1"}}
>
> input_message = {
>     "role": "user",
>     "content": "How do I request vacation days?",
> }
> stream = await agent.astream_events(
>     {"messages": [input_message]},
>     config,
>     version="v3",
> )
> async for snapshot in stream.values:
>     snapshot["messages"][-1].pretty_print()
> ```

### 与文本分割器一起使用

Anthropic 还允许您使用 [自定义文档](https://platform.claude.com/docs/en/build-with-claude/citations#custom-content-documents) 类型指定自己的分割。LangChain [文本分割器](https://langchain-docs-zh.mintlify.site/langchain/oss/integrations/splitters.md) 可以用于生成此目的的具有意义的分割。参见以下示例，其中我们分割了 LangChain `README.md`（一个 markdown 文档），并将其作为上下文传递给 Claude：

此示例需要 @\[`langchain-text-splitters`] 已安装：

```bash theme={null}
pip install langchain-text-splitters
```

```python expandable theme={null}
import requests
from langchain_anthropic import ChatAnthropic
from langchain_text_splitters import MarkdownTextSplitter


def format_to_anthropic_documents(documents: list[str]):
    return {
        "type": "document",
        "source": {
            "type": "content",
            "content": [{"type": "text", "text": document} for document in documents],
        },
        "citations": {"enabled": True},
    }


# Pull readme
get_response = requests.get(
    "https://raw.githubusercontent.com/langchain-ai/langchain/master/README.md"
)
readme = get_response.text

# Split into chunks
splitter = MarkdownTextSplitter(
    chunk_overlap=0,
    chunk_size=50,
)
documents = splitter.split_text(readme)

# Construct message
message = {
    "role": "user",
    "content": [
        format_to_anthropic_documents(documents),
        {"type": "text", "text": "Give me a link to LangChain's tutorials."},
    ],
}

# Query model
model = ChatAnthropic(model="claude-haiku-4-5-20251001")
response = model.invoke([message])
```

## 提示词缓存

Anthropic 支持 [缓存](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 您的提示词中的元素，包括消息、工具定义、工具结果、图像和文档。这允许您重用大型文档、指令、[少量样本文档](https://docs.langchain.com/langsmith/create-few-shot-evaluators) 和其他数据，以减少延迟和成本。

在直接模型调用中启用提示词缓存有两种方法：

* **[自动缓存](#自动缓存)**：在调用时传递 `cache_control`（`model.invoke(..., cache_control=...)`）。这是提供者/API 级别的缓存：Anthropic API 将缓存断点应用于最后一个可缓存块，并在对话增长时将其向前移动。
* **[显式缓存断点](#显式缓存断点)**：将 `cache_control` 直接放置在单个内容块上，以实现对缓存内容进行细粒度、直接断点控制。

> [!WARNING]
>
> 仅某些 Claude 模型支持提示词缓存。有关详细信息，请参阅 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#supported-models)。

> [!NOTE]
>
> 对于 LangChain 智能体，如果您希望 LangChain 优化稳定的系统提示词和工具内容，请优先使用 [`AnthropicPromptCachingMiddleware`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/anthropic#提示词缓存)。中间件是 LangChain 智能体/容器的优化，与下面显示的调用级 `cache_control` 不同，后者镜像 Anthropic API 的行为。

### 自动缓存

> [!NOTE]
>
> 自动缓存需要 `langchain-anthropic>=1.4.0`。

将 `cache_control` 作为调用参数传递，可自动缓存所有内容，包括最后一个可缓存块。对于具有相同前缀的后续请求，将自动重用缓存内容。随着对话的增长，缓存断点会向前移动，因此无需管理单个 `cache_control` 标记。

```python theme={null}
from langchain_anthropic import ChatAnthropic
import requests

model = ChatAnthropic(model="claude-sonnet-4-5")

# Pull LangChain readme
get_response = requests.get(
    "https://raw.githubusercontent.com/langchain-ai/langchain/b476fdb54aa6e6f5f0b24a68c2f4a94e43b369f9/README.md"
)
readme = get_response.text

messages = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "You are a technology expert.",
            },
            {
                "type": "text",
                "text": f"{readme}"
            },
        ],
    },
    {
        "role": "user",
        "content": "What's LangChain, according to its README?",
    },
]

response = model.invoke(
    messages,
    cache_control={"type": "ephemeral"},  # [!code highlight]
)

usage = response.usage_metadata["input_token_details"]
print(f"Usage:\n{usage}")

```

对于1小时缓存，指定 `ttl` 字段：

```python theme={null}
response = model.invoke(
    messages,
    cache_control={"type": "ephemeral", "ttl": "1h"},  # [!code highlight]
)
```

### 显式缓存断点

为了实现细粒度控制，请用 `cache_control` 标记单个内容块。当您需要缓存以不同频率变化的多个部分时，这很有用。

#### 消息

```python expandable theme={null}
import requests
from langchain_anthropic import ChatAnthropic


model = ChatAnthropic(model="claude-sonnet-4-5")

# Pull LangChain readme
get_response = requests.get(
    "https://raw.githubusercontent.com/langchain-ai/langchain/b476fdb54aa6e6f5f0b24a68c2f4a94e43b369f9/README.md"
)
readme = get_response.text

messages = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "You are a technology expert.",
            },
            {
                "type": "text",
                "text": f"{readme}",
                "cache_control": {"type": "ephemeral"},  # [!code highlight]
            },
        ],
    },
    {
        "role": "user",
        "content": "What's LangChain, according to its README?",
    },
]

response_1 = model.invoke(messages)
response_2 = model.invoke(messages)

usage_1 = response_1.usage_metadata["input_token_details"]
usage_2 = response_2.usage_metadata["input_token_details"]

print(f"First invocation:\n{usage_1}")
print(f"\nSecond:\n{usage_2}")
```

```python theme={null}
First invocation:
{'cache_read': 0, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 1569, 'ephemeral_1h_input_tokens': 0}

Second:
{'cache_read': 1569, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}
```

> [!TIP]
>
> **1小时缓存**
>
> 缓存有效期默认为5分钟。若需更长的缓存，请在 `cache_control` 字段中指定 `"ttl": "1h"`。1小时缓存写入费用是基础输入 Token 价格的2倍（5分钟缓存为1.25倍）。
>
> > [accordion] 示例
> >
> > ```python theme={null}
> > model = ChatAnthropic(model="claude-sonnet-4-6")
> >
> > messages = [
> >     {
> >         "role": "user",
> >         "content": [
> >             {
> >                 "type": "text",
> >                 "text": f"{long_text}",
> >                 "cache_control": {"type": "ephemeral", "ttl": "1h"}, # [!code highlight]
> >             },
> >         ],
> >     }
> > ]
> > ```
> >
> > 缓存 Token 数量的详细信息将包含在响应的 @\[`InputTokenDetails`] 的 @\[`usage_metadata`]\[UsageMetadata] 中：
> >
> > ```python theme={null}
> > response = model.invoke(messages)
> > response.usage_metadata
> > ```
> >
> > ```json theme={null}
> > {
> >     "input_tokens": 1500,
> >     "output_tokens": 200,
> >     "total_tokens": 1700,
> >     "input_token_details": {
> >         "cache_read": 0,
> >         "cache_creation": 1000,
> >         "ephemeral_1h_input_tokens": 750,
> >         "ephemeral_5m_input_tokens": 250,
> >     }
> > }
> > ```

#### 缓存工具

```python expandable theme={null}
import requests

from langchain_anthropic import ChatAnthropic
from langchain.tools import tool


# For demonstration purposes, we artificially expand the
# tool description using the LangChain README text.
get_response = requests.get(
    "https://raw.githubusercontent.com/langchain-ai/langchain/master/README.md"
)
readme = get_response.text
description = (
    "Get the weather at a location. "
    f"By the way, check out this readme: {readme}"
)


@tool(description=description, extras={"cache_control": {"type": "ephemeral"}})  # [!code highlight]
def get_weather(location: str) -> str:
    return "It's sunny."


model = ChatAnthropic(model="claude-sonnet-4-6")
model_with_tools = model.bind_tools([get_weather])
query = "What's the weather in San Francisco?"

response_1 = model_with_tools.invoke(query)
response_2 = model_with_tools.invoke(query)

usage_1 = response_1.usage_metadata["input_token_details"]
usage_2 = response_2.usage_metadata["input_token_details"]

print(f"First invocation:\n{usage_1}")
print(f"\nSecond:\n{usage_2}")
```

```python theme={null}
First invocation:
{'cache_read': 0, 'cache_creation': 1809}

Second:
{'cache_read': 1809, 'cache_creation': 0}
```

#### 对话应用中的增量缓存

提示词缓存可用于 [多轮对话](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#continuing-a-multi-turn-conversation) 以维持早期消息的上下文，而无需冗余处理。

我们可以通过用 `cache_control` 标记最终消息来启用增量缓存。Claude 将自动为后续消息使用之前缓存的最长前缀。

下面，我们实现了一个包含此功能的简单聊天机器人。我们遵循 LangChain 的 [聊天机器人教程](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/quickstart.md)，但添加了一个自定义的 [reducer](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/graph-api.md#归约器)，该 reducer 会自动将每个用户消息中的最后一个内容块标记为 `cache_control`：

> [accordion] Chatbot with incremental prompt caching
>
> ```python expandable theme={null}
> import requests
> from langchain_anthropic import ChatAnthropic
> from langgraph.checkpoint.memory import MemorySaver
> from langgraph.graph import START, StateGraph, add_messages
> from typing_extensions import Annotated, TypedDict
>
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> # Pull LangChain readme
> get_response = requests.get(
>     "https://raw.githubusercontent.com/langchain-ai/langchain/master/README.md"
> )
> readme = get_response.text
>
>
> def messages_reducer(left: list, right: list) -> list:
>     # Update last user message
>     for i in range(len(right) - 1, -1, -1):
>         if right[i].type == "human":
>             right[i].content[-1]["cache_control"] = {"type": "ephemeral"}
>             break
>
>     return add_messages(left, right)
>
>
> class State(TypedDict):
>     messages: Annotated[list, messages_reducer]
>
>
> workflow = StateGraph(state_schema=State)
>
>
> # Define the function that calls the model
> def call_model(state: State):
>     response = model.invoke(state["messages"])
>     return {"messages": [response]}
>
>
> # Define the (single) node in the graph
> workflow.add_edge(START, "model")
> workflow.add_node("model", call_model)
>
> # Add memory
> memory = MemorySaver()
> app = workflow.compile(checkpointer=memory)
> ```
>
> ```python theme={null}
> from langchain.messages import HumanMessage
>
> config = {"configurable": {"thread_id": "abc123"}}
>
> query = "Hi! I'm Bob."
>
> input_message = HumanMessage([{"type": "text", "text": query}])
> output = app.invoke({"messages": [input_message]}, config)
> output["messages"][-1].pretty_print()
> print(f"\n{output['messages'][-1].usage_metadata['input_token_details']}")
> ```
>
> ```python theme={null}
> ================================== Ai Message ==================================
>
> Hello, Bob! It's nice to meet you. How are you doing today? Is there something I can help you with?
>
> {'cache_read': 0, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}
> ```
>
> ```python theme={null}
> query = f"Check out this readme: {readme}"
>
> input_message = HumanMessage([{"type": "text", "text": query}])
> output = app.invoke({"messages": [input_message]}, config)
> output["messages"][-1].pretty_print()
> print(f"\n{output['messages'][-1].usage_metadata['input_token_details']}")
> ```
>
> ```text theme={null}
> ================================== Ai Message ==================================
>
> I can see you've shared the README from the LangChain GitHub repository. This is the documentation for LangChain, which is a popular framework for building applications powered by Large Language Models (LLMs). Here's a summary of what the README contains:
>
> LangChain is:
> - A framework for developing LLM-powered applications
> - Helps chain together components and integrations to simplify AI application development
> - Provides a standard interface for models, embeddings, vector stores, etc.
>
> Key features/benefits:
> - Real-time data augmentation (connect LLMs to diverse data sources)
> - Model interoperability (swap models easily as needed)
> - Large ecosystem of integrations
>
> The LangChain ecosystem includes:
> - LangSmith - For evaluations and observability
> - LangGraph - For building complex agents with customizable architecture
> - LangSmith - For deployment and scaling of agents
>
> The README also mentions installation instructions (`pip install -U langchain`) and links to various resources including tutorials, how-to guides, conceptual guides, and API references.
>
> Is there anything specific about LangChain you'd like to know more about, Bob?
>
> {'cache_read': 0, 'cache_creation': 1846, 'ephemeral_5m_input_tokens': 1846, 'ephemeral_1h_input_tokens': 0}
> ```
>
> ```python theme={null}
> query = "What was my name again?"
>
> input_message = HumanMessage([{"type": "text", "text": query}])
> output = app.invoke({"messages": [input_message]}, config)
> output["messages"][-1].pretty_print()
> print(f"\n{output['messages'][-1].usage_metadata['input_token_details']}")
> ```
>
> ```text theme={null}
> ================================== Ai Message ==================================
>
> Your name is Bob. You introduced yourself at the beginning of our conversation.
>
> {'cache_read': 1846, 'cache_creation': 278, 'ephemeral_5m_input_tokens': 278, 'ephemeral_1h_input_tokens': 0}
> ```
>
> 在 [LangSmith 跟踪](https://smith.langchain.com/public/4d0584d8-5f9e-4b91-8704-93ba2ccf416a/r) 中，切换 "原始输出" 将显示发送给对话模型的精确消息，包括 `cache_control` 键。

## Token 计数

在将消息发送到模型之前，您可以使用 @\[`get_num_tokens_from_messages()`]\[ChatAnthropic.get\_num\_tokens\_from\_messages] 对消息中的 Token 进行计数。这使用了 Anthropic 官方的 [Token 计数 API](https://platform.claude.com/docs/en/build-with-claude/token-counting)。

> [accordion] 消息 Token 计数
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
> from langchain.messages import HumanMessage, SystemMessage
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> messages = [
>     SystemMessage(content="You are a scientist"),
>     HumanMessage(content="Hello, Claude"),
> ]
>
> token_count = model.get_num_tokens_from_messages(messages)
> print(token_count)
> ```
>
> ```text theme={null}
> 14
> ```

> [accordion] 工具 Token 计数
>
> 您也可以在使用工具时进行 Token 计数：
>
> ```python theme={null}
> from langchain.tools import tool
>
> @tool(parse_docstring=True)
> def get_weather(location: str) -> str:
>     """Get the current weather in a given location
>
>     Args:
>         location: The city and state, e.g. San Francisco, CA
>     """
>     return "Sunny"
>
> messages = [
>     HumanMessage(content="What's the weather like in San Francisco?"),
> ]
>
> token_count = model.get_num_tokens_from_messages(messages, tools=[get_weather])
> print(token_count)
> ```
>
> ```text theme={null}
> 586
> ```

## 对话中系统消息

> [!NOTE]
>
> 对话中系统消息需要 `langchain-anthropic>=1.7.3`。

支持的 Claude 模型接受 [对话中系统消息](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages)。其指令从该点开始生效。添加一条消息不会改变之前的回合，因此不会使 [提示词缓存](#提示词缓存)失效。

一个以 @\[`SystemMessage`] 开头的消息始终放在顶层 `system` 字段中。`ChatAnthropic` 在满足以下两个条件时，会在对话中自己的位置发送一个稍后的 `SystemMessage`：

* 模型支持对话中系统消息。[Claude 文档](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages)列出了哪些模型支持。
* 消息紧随人类或工具消息之后，且是最后一条消息或后跟 AI 消息。

否则，`ChatAnthropic` 将消息移入顶层 `system` 字段并附带警告，该消息适用于整个对话。如果顶层系统消息已填满该字段，`ChatAnthropic` 会引发 `ValueError`。

```python theme={null}
from langchain.messages import AIMessage, HumanMessage, SystemMessage
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(model="claude-opus-5-5")

response = model.invoke(
    [
        SystemMessage("You are a travel assistant."),
        HumanMessage("Suggest a day trip from Lisbon."),
        AIMessage("Sintra is a good choice: palaces, gardens, and a short train ride."),
        HumanMessage("How do I get there?"),
        SystemMessage("The user has switched to the mobile app. Keep answers under 50 words."),  # [!code highlight]
    ]
)
```

有关措辞指导和完善的放置规则，请参阅 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages)。

### 对话中更改工具

> [!NOTE]
>
> 对话中工具更改需要 `langchain-anthropic>=1.7.4`。

对话中 `SystemMessage` 还可以添加或删除 Anthropic 的 [`tool_addition` 和 `tool_removal`](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#mid-conversation-tool-changes) 内容块。编辑请求中的 `tools` 会使整个对话的提示词缓存失效。这些块不会改变 `tools`，因此缓存的 prefix 仍然匹配。

上述 [放置和模型规则](#对话中系统消息) 适用。当 `ChatAnthropic` 无法在适当位置发送消息时，它会带有警告地丢弃工具更改块。

`ChatAnthropic` 添加了所需的 beta 头部，因此您无需设置 `betas`。

要在对话中途添加工具，使用 `extras={"defer_loading": True}` 绑定它，以便 Claude 最初看不到它。然后在 `tool_addition` 块中按名称引用它：

```python theme={null}
from langchain.messages import HumanMessage, SystemMessage
from langchain.tools import tool
from langchain_anthropic import ChatAnthropic


@tool
def get_time() -> str:
    """Get the current time."""
    return "12:00"


@tool(extras={"defer_loading": True})  # [!code highlight]
def get_weather(location: str) -> str:
    """Get the current weather for a location."""
    return f"It's sunny in {location}."


model = ChatAnthropic(model="claude-opus-5-5")
model_with_tools = model.bind_tools([get_time, get_weather])

response = model_with_tools.invoke(
    [
        HumanMessage("What's the weather in San Francisco?"),
        SystemMessage(
            [
                {  # [!code highlight]
                    "type": "tool_addition",  # [!code highlight]
                    "tool": {"type": "tool_reference", "name": "get_weather"},  # [!code highlight]
                },  # [!code highlight]
            ]
        ),
    ]
)
```

API 会拒绝所有工具都被延迟的请求，因此至少绑定一个未使用 `defer_loading` 的工具。

要撤回工具，在 `tool_removal` 块中引用它。稍后的 `tool_addition` 可以再次提供它。

```python theme={null}
SystemMessage(
    [
        {
            "type": "tool_removal",
            "tool": {"type": "tool_reference", "name": "get_weather"},
        },
    ]
)
```

要添加您最初未绑定的工具，[使用 `tool_definition` 内联定义](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#define-tools-in-a-message-beta)。内联定义处于 beta 版本，仅在 Claude API 上可用。

```python theme={null}
from langchain.messages import HumanMessage, SystemMessage
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(model="claude-opus-5-5")

response = model.invoke(
    [
        HumanMessage("How many orders did we get yesterday?"),
        SystemMessage(
            [
                {
                    "type": "tool_addition",
                    "tool": {
                        "type": "tool_definition",  # [!code highlight]
                        "definition": {  # [!code highlight]
                            "name": "db_query",
                            "description": "Run a read-only SQL query against the analytics database.",
                            "input_schema": {
                                "type": "object",
                                "properties": {"sql": {"type": "string"}},
                                "required": ["sql"],
                            },
                        },
                    },
                },
            ]
        ),
    ]
)
```

您也可以将这些块包裹在 `non_standard` 块中，这就是 `content_blocks` 返回它们的方式。`ChatAnthropic` 对这两种形式发送相同的请求。

## 上下文管理

Anthropic 支持上下文管理功能，可自动管理模型的上下文窗口以优化性能和成本。

请参阅 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/context-editing) 了解更多详细信息和配置选项。

### 清除工具使用

将工具结果从上下文中清除以减少 Token 使用，同时保留对话流程。

> [!NOTE]
>
> **上下文管理自 `langchain-anthropic>=0.3.21` 起得到支持**
>
> 您必须指定 `context-management-2025-06-27` beta 标头才能将上下文管理应用于您的模型调用。

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-sonnet-4-6",
    betas=["context-management-2025-06-27"], # [!code highlight]
    context_management={"edits": [{"type": "clear_tool_uses_20250919"}]}, # [!code highlight]
)
model_with_tools = model.bind_tools([{"type": "web_search_20260209", "name": "web_search"}])
response = model_with_tools.invoke("Search for recent developments in AI")
```

### 自动压缩

Claude Opus 4.6 及更高版本支持自动 [服务器端压缩](https://platform.claude.com/docs/en/build-with-claude/compaction)，当上下文窗口接近其限制时，会智能地压缩对话历史。这允许更长的对话而无需手动上下文管理。

> [!NOTE]
>
> **自动压缩要求：**
>
> * Claude Opus 4.6 或更高版本
> * `langchain-anthropic>=1.3.0`
> * `compact-2026-01-12` beta 标头

```python theme={null}
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-opus-4-8",
    betas=["compact-2026-01-12"], # [!code highlight]
    max_tokens=4096,
    context_management={ # [!code highlight]
        "edits": [ # [!code highlight]
            { # [!code highlight]
                "type": "compact_20260112", # [!code highlight]
                "trigger": {"type": "input_tokens", "value": 50000}, # [!code highlight]
            } # [!code highlight]
        ] # [!code highlight]
    }, # [!code highlight]
)
```

请参阅 Anthropic 的文档了解 [触发配置](https://platform.claude.com/docs/en/build-with-claude/compaction#trigger-configuration) 的详细信息。

当触发压缩事件时，`ChatAnthropic` 将返回 [压缩块](https://platform.claude.com/docs/en/build-with-claude/compaction#working-with-compaction-blocks)，表示提示的状态。这些应在多轮应用程序中将消息历史传递回模型时保留。

## 结构化输出

> [!NOTE]
>
> 结构化输出需要 `langchain-anthropic>=1.1.0`。请参阅 [Claude 文档](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)以了解支持的模型。

Anthropic 支持一种原生的 [结构化输出功能](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)，该功能保证其响应符合给定的模式。

您可以在单独的模型调用中访问此功能，或通过指定 LangChain [智能体](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/agents.md)的 [响应格式](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output.md)来使用此功能。以下是一些示例。

> [accordion] Individual model calls
>
> 使用 [`with_structured_output`](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models#结构化输出) 方法生成结构化模型响应。指定 `method="json_schema"` 以启用 Anthropic 的原生结构化输出功能；否则，该方法默认使用函数调用。
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
> from pydantic import BaseModel, Field
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> class Movie(BaseModel):
>     """A movie with details."""
>     title: str = Field(description="The title of the movie")
>     year: int = Field(description="The year the movie was released")
>     director: str = Field(description="The director of the movie")
>     rating: float = Field(description="The movie's rating out of 10")
>
> model_with_structure = model.with_structured_output(Movie, method="json_schema")  # [!code highlight]
> response = model_with_structure.invoke("Provide details about the movie Inception")
> response
> ```
>
> ```python theme={null}
> Movie(title='Inception', year=2010, director='Christopher Nolan', rating=8.8)
> ```

> [accordion] Agent response format
>
> 使用 [`ProviderStrategy`](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output) 指定 `response_format` 以在生成最终响应时启用 Anthropic 的结构化输出功能。
>
> ```python theme={null}
> from langchain.agents import create_agent
> from langchain.agents.structured_output import ProviderStrategy
> from pydantic import BaseModel
>
> class Weather(BaseModel):
>     temperature: float
>     condition: str
>
> def weather_tool(location: str) -> str:
>     """Get the weather at a location."""
>     return "Sunny and 75 degrees F."
>
> agent = create_agent(
>     model="anthropic:claude-sonnet-4-5",
>     tools=[weather_tool],
>     response_format=ProviderStrategy(Weather),  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "What's the weather in SF?"}]
> })
>
> result["structured_response"]
> ```
>
> ```python theme={null}
> Weather(temperature=75.0, condition='Sunny')
> ```

## 内置工具

Anthropic 支持多种内置的客户端和服务器端 [工具](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md)。

服务器端工具（例如 [web search](#网络搜索)）会被传递给模型并由 Anthropic 执行。客户端工具（例如 [bash tool](#bash-工具)）需要您在应用程序中实现回调执行逻辑，并将结果返回给模型。

无论哪种情况，您都可以通过在模型实例上使用 @\[`bind_tools`]\[ChatAnthropic.bind\_tools] 来使您的聊天模型访问工具。

重要的是，客户端工具需要您实现执行逻辑。请参考下文的相关章节获取示例。

> [!NOTE]
>
> **中间件与工具**
>
> 对于客户端工具（例如 [bash](#bash-工具)、[text editor](#文本编辑器)、[memory](#记忆工具)），您可以选择使用 [middleware](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/anthropic.md)，它们提供生产就绪的实现，包含内置的执行、状态管理和安全策略。
>
> 当您需要一个即插即用的解决方案时，请使用中间件；当您需要自定义执行逻辑或直接使用 @\[`bind_tools`]\[ChatAnthropic.bind\_tools] 时，请使用工具（下文有详细说明）。

> [!NOTE]
>
> **Beta 工具**
>
> 如果将 Beta 工具绑定到您的聊天模型，LangChain 将会自动为您添加所需的 Beta 头部信息。

### Bash 工具

Claude 支持一个客户端的 [bash 工具](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool)，允许它在持久的 bash 会话中执行 shell 命令。这使其能够进行系统操作、脚本执行和命令行自动化。

> [!NOTE]
>
> **重要提示：你必须提供执行环境**
>
> LangChain 处理 API 集成（发送/接收工具调用），但 **你负责**：
>
> * 设置沙盒化的计算环境（Docker、VM 等）
> * 实现命令执行和输出捕获
> * 在智能体循环中将结果传回 Claude
>
> 请参阅 [Claude bash 工具文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) 获取实现指南。

> [!NOTE]
>
> **要求：**
>
> * Claude 4 模型或 Claude Sonnet 3.7

> [tab] Anthropic type
>
> ```python expandable theme={null}
> import subprocess
>
> from anthropic.types.beta import BetaToolBash20250124Param  # [!code highlight]
> from langchain_anthropic import ChatAnthropic
> from langchain.messages import HumanMessage, ToolMessage
> from langchain.tools import tool
>
> tool_spec = BetaToolBash20250124Param(  # [!code highlight]
>     name="bash",  # [!code highlight]
>     type="bash_20250124",  # [!code highlight]
> )  # [!code highlight]
>
>
> @tool(extras={"provider_tool_definition": tool_spec})  # [!code highlight]
> 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}"
>
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
> model_with_bash = model.bind_tools([bash]) # [!code highlight]
>
> # Initial request
> messages = [HumanMessage("List all files in the current directory")]
> response = model_with_bash.invoke(messages)
> print(response.content_blocks)
>
> # Tool execution loop
> while response.tool_calls:
>     # Execute each tool call
>     tool_messages = []
>     for tool_call in response.tool_calls:
>         result = bash.invoke(tool_call)
>         tool_messages.append(result)
>
>     # Continue conversation with tool results
>     messages = [*messages, response, *tool_messages]
>     response = model_with_bash.invoke(messages)
>     print(response.content_blocks)
> ```

> [tab] create\_agent
>
> ```python expandable theme={null}
> import subprocess
>
> from anthropic.types.beta import BetaToolBash20250124Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
> from langchain.tools import tool
>
> tool_spec = BetaToolBash20250124Param( # [!code highlight]
>     name="bash", # [!code highlight]
>     type="bash_20250124", # [!code highlight]
> ) # [!code highlight]
>
>
> @tool(extras={"provider_tool_definition": tool_spec}) # [!code highlight]
> def bash(*, command: str, restart: bool = False, **kw):
>     """Execute a bash command."""
>     if restart:
>         return "Bash session restarted"
>     result = subprocess.run(
>         command,
>         shell=True,
>         capture_output=True,
>         text=True,
>     )
>     return result.stdout + result.stderr
>
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-sonnet-4-6"),
>     tools=[bash],  # [!code highlight]
> )
>
> result = agent.invoke({"messages": [{"role": "user", "content": "List files"}]})
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> bash_tool = { # [!code highlight]
>     "type": "bash_20250124", # [!code highlight]
>     "name": "bash", # [!code highlight]
> } # [!code highlight]
>
> model_with_bash = model.bind_tools([bash_tool]) # [!code highlight]
> response = model_with_bash.invoke(
>     "List all Python files in the current directory"
> )
> # You must handle execution of the bash command in response.tool_calls via a tool execution loop
> ```
>
> 使用 @\[`create_agent`] 会自动处理工具执行循环。
>
> `response.tool_calls` 将包含 Claude 想要执行的 bash 命令。你必须在你环境中运行此命令并将结果传回。
>
> ```python theme={null}
> [{'type': 'text',
> 'text': "I'll list the Python files in the current directory for you."},
> {'type': 'tool_call',
> 'name': 'bash',
> 'args': {'command': 'ls -la *.py'},
> 'id': 'toolu_01ABC123...'}]
> ```

The bash 工具支持两个参数：

* `command`（必需）：要执行的 bash 命令
* `restart`（可选）：设置为 `true` 以重启 bash 会话

> [!TIP]
>
> 对于 "开箱即用" 的实现，可以考虑使用 [`ClaudeBashToolMiddleware`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/anthropic#bash-工具)，它提供持久会话、Docker 隔离、输出脱敏以及开/关命令。

### 代码执行

Claude 可以使用服务器端的 [代码执行工具](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) 在沙盒环境中执行代码。

> [!NOTE]
>
> 自 `langchain-anthropic>=1.0.3` 起支持 Anthropic 的 `2025-08-25` 代码执行工具。
>
> 自 `langchain-anthropic>=0.3.14` 起支持旧版 [`2025-05-22`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#upgrade-to-latest-tool-version) 工具。

> [!NOTE]
>
> 代码沙盒没有互联网访问权限，因此您只能使用环境中预安装的包。有关更多信息，请参阅 [Claude 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#networking-and-security)。

> [tab] Anthropic type
>
> ```python theme={null}
> from anthropic.types.beta import BetaCodeExecutionTool20250825Param # [!code highlight]
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(
>     model="claude-sonnet-4-6",
>     # (Optional) Enable the param below to automatically
>     # pass back in container IDs from previous response
>     reuse_last_container=True,
> )
>
> code_tool = BetaCodeExecutionTool20250825Param( # [!code highlight]
>     name="code_execution", # [!code highlight]
>     type="code_execution_20250825", # [!code highlight]
> ) # [!code highlight]
> model_with_tools = model.bind_tools([code_tool]) # [!code highlight]
>
> response = model_with_tools.invoke(
>     "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
> )
> ```

> [tab] create\_agent
>
> ```python theme={null}
> from anthropic.types.beta import BetaCodeExecutionTool20250825Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
>
> code_tool = BetaCodeExecutionTool20250825Param( # [!code highlight]
>     name="code_execution", # [!code highlight]
>     type="code_execution_20250825", # [!code highlight]
> ) # [!code highlight]
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-sonnet-4-6"),
>     tools=[code_tool],  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "Calculate mean and std of [1,2,3,4,5]"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(
>     model="claude-sonnet-4-6",
> )
>
> code_tool = {"type": "code_execution_20250825", "name": "code_execution"} # [!code highlight]
> model_with_tools = model.bind_tools([code_tool])
>
> response = model_with_tools.invoke(
>     "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
> )
> ```

> [accordion] Use with Files API
>
> 使用 Files API，Claude 可以编写代码以访问文件进行数据分析和其他用途。示例如下：
>
> ```python theme={null}
> import anthropic
> from anthropic.types.beta import BetaCodeExecutionTool20250825Param # [!code highlight]
> from langchain_anthropic import ChatAnthropic
>
>
> client = anthropic.Anthropic()
> file = client.beta.files.upload(
>     file=open("/path/to/sample_data.csv", "rb")
> )
> file_id = file.id
>
>
> # Run inference
> model = ChatAnthropic(
>     model="claude-sonnet-4-6",
> )
>
> code_tool = BetaCodeExecutionTool20250825Param( # [!code highlight]
>     name="code_execution", # [!code highlight]
>     type="code_execution_20250825", # [!code highlight]
> ) # [!code highlight]
> model_with_tools = model.bind_tools([code_tool])
>
> input_message = {
>     "role": "user",
>     "content": [
>         {
>             "type": "text",
>             "text": "Please plot these data and tell me what you see.",
>         },
>         {
>             "type": "container_upload",
>             "file_id": file_id,
>         },
>     ]
> }
> response = model_with_tools.invoke([input_message])
> ```
>
> 注意，Claude 可能会在代码执行过程中生成文件。您可以使用 Files API 访问这些文件：
>
> ```python theme={null}
> # Take all file outputs for demonstration purposes
> file_ids = []
> for block in response.content:
>     if block["type"] == "bash_code_execution_tool_result":
>         file_ids.extend(
>             content["file_id"]
>             for content in block.get("content", {}).get("content", [])
>             if "file_id" in content
>         )
>
> for i, file_id in enumerate(file_ids):
>     file_content = client.beta.files.download(file_id)
>     file_content.write_to_file(f"/path/to/file_{i}.png")
> ```
>
> > [!NOTE]
> >
> > **可用工具版本：**
> >
> > * `code_execution_20250522` (旧版)
> > * `code_execution_20250825` (推荐)

### 计算机使用

Claude 支持客户端 [计算机使用](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) 功能，允许它通过截图、鼠标控制和键盘输入与桌面环境交互。

> [!NOTE]
>
> **重要提示：您必须提供执行环境**
>
> LangChain 处理 API 集成（发送/接收工具调用），但 **您负责**：
>
> * 设置沙盒化计算环境（Linux 虚拟机、Docker 容器等）
> * 实现虚拟显示（例如，Xvfb）
> * 执行 Claude 的工具调用（截图、鼠标点击、键盘输入）
> * 在智能体循环中将结果传递回 Claude
>
> Anthropic 提供了一个 [参考实现](https://github.com/anthropics/anthropic-quickstarts/tree/main/computer-use-demo) 帮助您入门。

> [!NOTE]
>
> **要求：**
>
> * Claude Opus 4.5、Claude 4 或 Claude Sonnet 3.7

> [tab] Anthropic type
>
> ```python expandable theme={null}
> import base64
> from typing import Literal
>
> from anthropic.types.beta import BetaToolComputerUse20250124Param # [!code highlight]
> from langchain_anthropic import ChatAnthropic
> from langchain.messages import HumanMessage, ToolMessage
> from langchain.tools import tool
>
> DISPLAY_WIDTH = 1024
> DISPLAY_HEIGHT = 768
>
> tool_spec = BetaToolComputerUse20250124Param( # [!code highlight]
>     name="computer", # [!code highlight]
>     type="computer_20250124", # [!code highlight]
>     display_width_px=DISPLAY_WIDTH, # [!code highlight]
>     display_height_px=DISPLAY_HEIGHT, # [!code highlight]
>     display_number=1, # [!code highlight]
> ) # [!code highlight]
>
> @tool(extras={"provider_tool_definition": tool_spec}) # [!code highlight]
> def computer(
>     *,
>     action: Literal[
>         "key", "type", "mouse_move", "left_click", "left_click_drag",
>         "right_click", "middle_click", "double_click", "screenshot",
>         "cursor_position", "scroll"
>     ],
>     coordinate: list[int] | None = None,
>     text: str | None = None,
>     **kw
> ):
>     """Control the computer display."""
>     if action == "screenshot":
>         # Take screenshot and return base64-encoded image
>         # Implementation depends on your display setup (e.g., Xvfb, pyautogui)
>         return {"type": "image", "data": "base64_screenshot_data..."}
>     elif action == "left_click" and coordinate:
>         # Execute click at coordinate
>         return f"Clicked at {coordinate}"
>     elif action == "type" and text:
>         # Type text
>         return f"Typed: {text}"
>     # ... implement other actions
>     return f"Executed {action}"
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
> model_with_computer = model.bind_tools([computer]) # [!code highlight]
>
> # Initial request
> messages = [HumanMessage("Take a screenshot to see what's on the screen")]
> response = model_with_computer.invoke(messages)
> print(response.content_blocks)
>
> # Tool execution loop
> while response.tool_calls:
>     tool_messages = []
>     for tool_call in response.tool_calls:
>         result = computer.invoke(tool_call)
>         tool_messages.append(
>             ToolMessage(content=str(result), tool_call_id=tool_call["id"])
>         )
>
>     messages = [*messages, response, *tool_messages]
>     response = model_with_computer.invoke(messages)
>     print(response.content_blocks)
> ```

> [tab] create\_agent
>
> ```python expandable theme={null}
> from typing import Literal
>
> from anthropic.types.beta import BetaToolComputerUse20250124Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
> from langchain.tools import tool
>
> tool_spec = BetaToolComputerUse20250124Param( # [!code highlight]
>     name="computer", # [!code highlight]
>     type="computer_20250124", # [!code highlight]
>     display_width_px=1024, # [!code highlight]
>     display_height_px=768, # [!code highlight]
> ) # [!code highlight]
>
>
> @tool(extras={"provider_tool_definition": tool_spec}) # [!code highlight]
> def computer(
>     *,
>     action: Literal[
>         "key", "type", "mouse_move", "left_click", "left_click_drag",
>         "right_click", "middle_click", "double_click", "screenshot",
>         "cursor_position", "scroll"
>     ],
>     coordinate: list[int] | None = None,
>     text: str | None = None,
>     **kw
> ):
>     """Control the computer display."""
>     if action == "screenshot":
>         return {"type": "image", "data": "base64_screenshot_data..."}
>     elif action == "left_click" and coordinate:
>         return f"Clicked at {coordinate}"
>     elif action == "type" and text:
>         return f"Typed: {text}"
>     return f"Executed {action}"
>
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-sonnet-4-6"),
>     tools=[computer],  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "Take a screenshot"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> computer_tool = {
>     "type": "computer_20250124",
>     "name": "computer",
>     "display_width_px": 1024,
>     "display_height_px": 768,
>     "display_number": 1,
> }
>
> model_with_computer = model.bind_tools([computer_tool]) # [!code highlight]
> response = model_with_computer.invoke(
>     "Take a screenshot to see what's on the screen"
> )
> # You must handle execution of the computer actions in response.tool_calls via a tool execution loop
> ```
>
> 使用 @\[`create_agent`] 自动处理工具执行循环。
>
> `response.tool_calls` 将包含 Claude 希望执行的计算操作。您必须在环境中执行此操作并将结果返回。
>
> ```python theme={null}
> [{'type': 'text',
> 'text': "I'll take a screenshot to see what's currently on the screen."},
> {'type': 'tool_call',
> 'name': 'computer',
> 'args': {'action': 'screenshot'},
> 'id': 'toolu_01RNsqAE7dDZujELtacNeYv9'}]
> ```

> [!NOTE]
>
> **可用工具版本：**
>
> * `computer_20250124`（适用于 Claude 4 和 Claude Sonnet 3.7）
> * `computer_20251124`（适用于 Claude Opus 4.5）

### 远程 MCP

Claude 可以使用服务器端的 [MCP 连接器工具](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector)来处理模型生成的远程 MCP 服务器调用。

> [!NOTE]
>
> **远程 MCP 自 `langchain-anthropic>=0.3.14` 起得到支持**

> [tab] Anthropic type
>
> ```python theme={null}
> from anthropic.types.beta import BetaMCPToolsetParam # [!code highlight]
> from langchain_anthropic import ChatAnthropic
>
> mcp_servers = [
>     {
>         "type": "url",
>         "url": "https://docs.langchain.com/mcp",
>         "name": "LangChain Docs",
>     }
> ]
>
> model = ChatAnthropic(
>     model="claude-sonnet-4-6",
>     mcp_servers=mcp_servers, # [!code highlight]
> )
>
> mcp_tool = BetaMCPToolsetParam( # [!code highlight]
>     type="mcp_toolset", # [!code highlight]
>     mcp_server_name="LangChain Docs", # [!code highlight]
> ) # [!code highlight]
>
> response = model.invoke(
>     "What are LangChain content blocks?",
>     tools=[mcp_tool], # [!code highlight]
> )
> ```

> [tab] create\_agent
>
> ```python theme={null}
> from anthropic.types.beta import BetaMCPToolsetParam # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
>
> mcp_servers = [
>     {
>         "type": "url",
>         "url": "https://docs.langchain.com/mcp",
>         "name": "LangChain Docs",
>     }
> ]
>
> mcp_tool = BetaMCPToolsetParam( # [!code highlight]
>     type="mcp_toolset", # [!code highlight]
>     mcp_server_name="LangChain Docs", # [!code highlight]
> ) # [!code highlight]
>
> agent = create_agent(
>     model=ChatAnthropic(
>         model="claude-sonnet-4-6",
>         mcp_servers=mcp_servers,  # [!code highlight]
>     ),
>     tools=[mcp_tool],  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "What are LangChain content blocks?"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> mcp_servers = [
>     {
>         "type": "url",
>         "url": "https://docs.langchain.com/mcp",
>         "name": "LangChain Docs",
>         # "tool_configuration": {  # optional configuration
>         #     "enabled": True,
>         #     "allowed_tools": ["ask_question"],
>         # },
>         # "authorization_token": "PLACEHOLDER",  # optional authorization if needed
>     }
> ]
>
> model = ChatAnthropic(
>     model="claude-sonnet-4-6",
>     mcp_servers=mcp_servers, # [!code highlight]
> )
>
> response = model.invoke(
>     "What are LangChain content blocks?",
>     tools=[{"type": "mcp_toolset", "mcp_server_name": "LangChain Docs"}], # [!code highlight]
> )
> response.content_blocks
> ```

### 文本编辑器

Claude 支持一个客户端文本编辑器工具，可用于查看和修改本地文本文件。详情请参阅 [文本编辑器工具文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool)。

> [tab] Anthropic type
>
> ```python expandable theme={null}
> from typing import Literal
>
> from anthropic.types.beta import BetaToolTextEditor20250728Param # [!code highlight]
> from langchain_anthropic import ChatAnthropic
> from langchain.messages import HumanMessage, ToolMessage
> from langchain.tools import tool
>
> tool_spec = BetaToolTextEditor20250728Param( # [!code highlight]
>     name="str_replace_based_edit_tool", # [!code highlight]
>     type="text_editor_20250728", # [!code highlight]
> ) # [!code highlight]
>
> # Simple in-memory file storage for demonstration
> files: dict[str, str] = {
>     "/workspace/primes.py": "def is_prime(n):\n    if n < 2\n        return False\n    return True"
> }
>
> @tool(extras={"provider_tool_definition": tool_spec}) # [!code highlight]
> def str_replace_based_edit_tool(
>     *,
>     command: Literal["view", "create", "str_replace", "insert", "undo_edit"],
>     path: str,
>     file_text: str | None = None,
>     old_str: str | None = None,
>     new_str: str | None = None,
>     insert_line: int | None = None,
>     view_range: list[int] | None = None,
>     **kw
> ):
>     """View and edit text files."""
>     if command == "view":
>         if path not in files:
>             return f"Error: File {path} not found"
>         content = files[path]
>         if view_range:
>             lines = content.splitlines()
>             start, end = view_range[0] - 1, view_range[1]
>             return "\n".join(lines[start:end])
>         return content
>     elif command == "create":
>         files[path] = file_text or ""
>         return f"Created {path}"
>     elif command == "str_replace" and old_str is not None:
>         if path not in files:
>             return f"Error: File {path} not found"
>         files[path] = files[path].replace(old_str, new_str or "", 1)
>         return f"Replaced in {path}"
>     # ... implement other commands
>     return f"Executed {command} on {path}"
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
> model_with_tools = model.bind_tools([str_replace_based_edit_tool]) # [!code highlight]
>
> # Initial request
> messages = [HumanMessage("There's a syntax error in my primes.py file. Can you fix it?")]
> response = model_with_tools.invoke(messages)
> print(response.content_blocks)
>
> # Tool execution loop
> while response.tool_calls:
>     tool_messages = []
>     for tool_call in response.tool_calls:
>         result = str_replace_based_edit_tool.invoke(tool_call)
>         tool_messages.append(
>             ToolMessage(content=result, tool_call_id=tool_call["id"])
>         )
>
>     messages = [*messages, response, *tool_messages]
>     response = model_with_tools.invoke(messages)
>     print(response.content_blocks)
> ```

> [tab] create\_agent
>
> ```python expandable theme={null}
> from typing import Literal
>
> from anthropic.types.beta import BetaToolTextEditor20250728Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
> from langchain.tools import tool
>
> # Simple in-memory file storage
> files: dict[str, str] = {
>     "/workspace/primes.py": "def is_prime(n):\n    if n < 2\n        return False\n    return True"
> }
>
> tool_spec = BetaToolTextEditor20250728Param( # [!code highlight]
>     name="str_replace_based_edit_tool", # [!code highlight]
>     type="text_editor_20250728", # [!code highlight]
> ) # [!code highlight]
>
>
> @tool(extras={"provider_tool_definition": tool_spec}) # [!code highlight]
> def str_replace_based_edit_tool(
>     *,
>     command: Literal["view", "create", "str_replace", "insert", "undo_edit"],
>     path: str,
>     file_text: str | None = None,
>     old_str: str | None = None,
>     new_str: str | None = None,
>     **kw
> ):
>     """View and edit text files."""
>     if command == "view":
>         return files.get(path, f"Error: File {path} not found")
>     elif command == "create":
>         files[path] = file_text or ""
>         return f"Created {path}"
>     elif command == "str_replace" and old_str is not None:
>         if path not in files:
>             return f"Error: File {path} not found"
>         files[path] = files[path].replace(old_str, new_str or "", 1)
>         return f"Replaced in {path}"
>     return f"Executed {command} on {path}"
>
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-sonnet-4-6"),
>     tools=[str_replace_based_edit_tool],  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "Fix the syntax error in /workspace/primes.py"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> editor_tool = {"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"} # [!code highlight]
>
> model_with_tools = model.bind_tools([editor_tool]) # [!code highlight]
>
> response = model_with_tools.invoke(
>     "There's a syntax error in my primes.py file. Can you help me fix it?"
> )
> # You must handle execution of the text editor commands in response.tool_calls via a tool execution loop
> ```
>
> 使用 @\[`create_agent`] 可自动处理工具执行循环。
>
> ```python theme={null}
> [{'name': 'str_replace_based_edit_tool',
> 'args': {'command': 'view', 'path': '/root'},
> 'id': 'toolu_011BG5RbqnfBYkD8qQonS9k9',
> 'type': 'tool_call'}]
> ```

> [!NOTE]
>
> **可用工具版本：**
>
> * `text_editor_20250124` (遗留版)
> * `text_editor_20250728` (推荐版)

> [!TIP]
>
> 若要实现 "开箱即用" 的方案，建议使用 [`StateClaudeTextEditorMiddleware`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/anthropic#文本编辑器) 或 [`FilesystemClaudeTextEditorMiddleware`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/anthropic#文本编辑器)，它们提供 LangGraph 状态集成、文件系统持久化、路径验证及其他功能。

### 网络抓取

Claude 可以使用服务器端的 [网络抓取工具](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool) 从指定的网页和 PDF 文档中检索完整内容，并以其响应为引用进行支撑。

> [tab] Anthropic type
>
> ```python theme={null}
> from anthropic.types.beta import BetaWebFetchTool20250910Param # [!code highlight]
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(model="claude-haiku-4-5-20251001")
>
> fetch_tool = BetaWebFetchTool20250910Param( # [!code highlight]
>     name="web_fetch", # [!code highlight]
>     type="web_fetch_20250910", # [!code highlight]
>     max_uses=3, # [!code highlight]
> ) # [!code highlight]
>
> model_with_tools = model.bind_tools([fetch_tool]) # [!code highlight]
>
> response = model_with_tools.invoke(
>     "Please analyze the content at https://docs.langchain.com/"
> )
> ```

> [tab] create\_agent
>
> ```python theme={null}
> from anthropic.types.beta import BetaWebFetchTool20250910Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
>
> fetch_tool = BetaWebFetchTool20250910Param( # [!code highlight]
>     name="web_fetch", # [!code highlight]
>     type="web_fetch_20250910", # [!code highlight]
>     max_uses=3, # [!code highlight]
> ) # [!code highlight]
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-haiku-4-5-20251001"),
>     tools=[fetch_tool],  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "Analyze https://docs.langchain.com/"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(model="claude-haiku-4-5-20251001")
>
> fetch_tool = {"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 3} # [!code highlight]
>
> model_with_tools = model.bind_tools([fetch_tool]) # [!code highlight]
>
> response = model_with_tools.invoke(
>     "Please analyze the content at https://docs.langchain.com/"
> )
> ```

### 网络搜索

Claude 可以使用服务器端的 [网络搜索工具](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) 来执行搜索，并为其响应提供引用依据。

> [!NOTE]
>
> **网络搜索工具自 `langchain-anthropic>=0.3.13` 起得到支持**

> [tab] Anthropic type
>
> ```python theme={null}
> from anthropic.types import WebSearchTool20260209Param # [!code highlight]
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> search_tool = WebSearchTool20260209Param( # [!code highlight]
>     name="web_search", # [!code highlight]
>     type="web_search_20260209", # [!code highlight]
>     max_uses=3, # [!code highlight]
> ) # [!code highlight]
>
> model_with_tools = model.bind_tools([search_tool]) # [!code highlight]
>
> response = model_with_tools.invoke("How do I update a web app to TypeScript 5.5?")
> ```

> [tab] create\_agent
>
> ```python theme={null}
> from anthropic.types import WebSearchTool20260209Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
>
> search_tool = WebSearchTool20260209Param( # [!code highlight]
>     name="web_search", # [!code highlight]
>     type="web_search_20260209", # [!code highlight]
>     max_uses=3, # [!code highlight]
> ) # [!code highlight]
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-sonnet-4-6"),
>     tools=[search_tool],  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "How do I update a web app to TypeScript 5.5?"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> search_tool = {"type": "web_search_20260209", "name": "web_search", "max_uses": 3} # [!code highlight]
>
> model_with_tools = model.bind_tools([search_tool]) # [!code highlight]
>
> response = model_with_tools.invoke("How do I update a web app to TypeScript 5.5?")
> ```

### 记忆工具

Claude 支持一个记忆工具，用于在对话线程之间进行客户端存储和检索上下文。详情请参阅 [记忆工具文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool)。

> [!NOTE]
>
> **Anthropic 的内置记忆工具自 `langchain-anthropic>=0.3.21` 起得到支持**

> [tab] Anthropic type
>
> ```python expandable theme={null}
> from typing import Literal
>
> from anthropic.types.beta import BetaMemoryTool20250818Param  # [!code highlight]
> from langchain_anthropic import ChatAnthropic
> from langchain.messages import HumanMessage, ToolMessage
> from langchain.tools import tool
>
> tool_spec = BetaMemoryTool20250818Param(  # [!code highlight]
>     name="memory",  # [!code highlight]
>     type="memory_20250818",  # [!code highlight]
> )  # [!code highlight]
>
> # Simple in-memory storage for demonstration purposes
> memory_store: dict[str, str] = {
>     "/memories/interests": "User enjoys Python programming and hiking"
> }
>
>
> @tool(extras={"provider_tool_definition": tool_spec})  # [!code highlight]
> def memory(
>     *,
>     command: Literal["view", "create", "str_replace", "insert", "delete", "rename"],
>     path: str,
>     content: str | None = None,
>     old_str: str | None = None,
>     new_str: str | None = None,
>     insert_line: int | None = None,
>     new_path: str | None = None,
>     **kw,
> ):
>     """Manage persistent memory across conversations."""
>     if command == "view":
>         if path == "/memories":
>             # List all memories
>             return "\n".join(memory_store.keys()) or "No memories stored"
>         return memory_store.get(path, f"No memory at {path}")
>     elif command == "create":
>         memory_store[path] = content or ""
>         return f"Created memory at {path}"
>     elif command == "str_replace" and old_str is not None:
>         if path in memory_store:
>             memory_store[path] = memory_store[path].replace(old_str, new_str or "", 1)
>         return f"Updated {path}"
>     elif command == "delete":
>         memory_store.pop(path, None)
>         return f"Deleted {path}"
>     # ... implement other commands
>     return f"Executed {command} on {path}"
>
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
> model_with_tools = model.bind_tools([memory]) # [!code highlight]
>
> # Initial request
> messages = [HumanMessage("What are my interests?")]
> response = model_with_tools.invoke(messages)
> print(response.content_blocks)
>
> # Tool execution loop
> while response.tool_calls:
>     tool_messages = []
>     for tool_call in response.tool_calls:
>         result = memory.invoke(tool_call)
>         tool_messages.append(ToolMessage(content=result, tool_call_id=tool_call["id"]))
>
>     messages = [*messages, response, *tool_messages]
>     response = model_with_tools.invoke(messages)
>     print(response.content_blocks)
> ```
>
> ```python theme={null}
> [{'type': 'text',
> 'text': "I'll check my memory to see what information I have about your interests."},
> {'type': 'tool_call',
> 'name': 'memory',
> 'args': {'command': 'view', 'path': '/memories'},
> 'id': 'toolu_01XeP9sxx44rcZHFNqXSaKqh'}]
> ```

> [tab] create\_agent
>
> ```python expandable theme={null}
> from typing import Literal
>
> from anthropic.types.beta import BetaMemoryTool20250818Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
> from langchain.tools import tool
>
> # Simple in-memory storage
> memory_store: dict[str, str] = {
>     "/memories/interests": "User enjoys Python programming and hiking"
> }
>
> tool_spec = BetaMemoryTool20250818Param( # [!code highlight]
>     name="memory", # [!code highlight]
>     type="memory_20250818", # [!code highlight]
> ) # [!code highlight]
>
>
> @tool(extras={"provider_tool_definition": tool_spec}) # [!code highlight]
> def memory(
>     *,
>     command: Literal["view", "create", "str_replace", "insert", "delete", "rename"],
>     path: str,
>     content: str | None = None,
>     old_str: str | None = None,
>     new_str: str | None = None,
>     **kw
> ):
>     """Manage persistent memory across conversations."""
>     if command == "view":
>         if path == "/memories":
>             return "\n".join(memory_store.keys()) or "No memories stored"
>         return memory_store.get(path, f"No memory at {path}")
>     elif command == "create":
>         memory_store[path] = content or ""
>         return f"Created memory at {path}"
>     elif command == "str_replace" and old_str is not None:
>         if path in memory_store:
>             memory_store[path] = memory_store[path].replace(old_str, new_str or "", 1)
>         return f"Updated {path}"
>     elif command == "delete":
>         memory_store.pop(path, None)
>         return f"Deleted {path}"
>     return f"Executed {command} on {path}"
>
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-sonnet-4-6"),
>     tools=[memory],  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "What are my interests?"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```
>
> 使用 @\[`create_agent`] 可自动处理工具执行循环。

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
>
> model = ChatAnthropic(
>     model="claude-sonnet-4-6",
> )
> model_with_tools = model.bind_tools([{"type": "memory_20250818", "name": "memory"}]) # [!code highlight]
>
> response = model_with_tools.invoke("What are my interests?")
> response.content_blocks
> # You must handle execution of the memory commands in response.tool_calls via a tool execution loop
> ```
>
> ```python theme={null}
> [{'type': 'text',
> 'text': "I'll check my memory to see what information I have about your interests."},
> {'type': 'tool_call',
> 'name': 'memory',
> 'args': {'command': 'view', 'path': '/memories'},
> 'id': 'toolu_01XeP9sxx44rcZHFNqXSaKqh'}]
> ```

> [!TIP]
>
> 若要实现 "开箱即用" 的方案，建议使用 [`StateClaudeMemoryMiddleware`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/anthropic#记忆) 或 [`FilesystemClaudeMemoryMiddleware`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/anthropic#记忆)，它们提供 LangGraph 状态集成或文件系统持久化、自动系统提示词注入及其他功能。

### 工具搜索

Claude 支持服务器端的 [工具搜索](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) 功能，能够实现动态工具发现和加载。Claude 不需要将所有工具定义提前加载到上下文窗口中，而是可以搜索您的工具目录并仅加载所需的工具。

这在以下情况下很有用：

* 您的系统中有 10+ 个工具
* 工具定义消耗了大量的 Token
* 您在使用大型工具集时遇到工具选择准确性问题

有两种工具搜索变体：

* **正则表达式** (`tool_search_tool_regex_20251119`)：Claude 构建正则表达式来搜索工具
* **BM25** (`tool_search_tool_bm25_20251119`)：Claude 使用自然语言查询来搜索工具

使用 `extras` 参数来指定 `defer_loading` 在 LangChain 工具上：

> [tab] Anthropic type
>
> ```python expandable theme={null}
> from anthropic.types.beta import BetaToolSearchToolRegex20251119Param # [!code highlight]
> from langchain_anthropic import ChatAnthropic
> from langchain.tools import tool
>
> @tool(extras={"defer_loading": True}) # [!code highlight]
> def get_weather(location: str, unit: str = "fahrenheit") -> str:
>     """Get the current weather for a location.
>
>     Args:
>         location: City name
>         unit: Temperature unit (celsius or fahrenheit)
>     """
>     return f"Weather in {location}: Sunny"
>
> @tool(extras={"defer_loading": True}) # [!code highlight]
> def search_files(query: str) -> str:
>     """Search through files in the workspace.
>
>     Args:
>         query: Search query
>     """
>     return f"Found files matching '{query}'"
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> tool_search = BetaToolSearchToolRegex20251119Param( # [!code highlight]
>     name="tool_search_tool_regex", # [!code highlight]
>     type="tool_search_tool_regex_20251119", # [!code highlight]
> ) # [!code highlight]
>
> model_with_tools = model.bind_tools([
>     tool_search, # [!code highlight]
>     get_weather,
>     search_files,
> ])
> response = model_with_tools.invoke("What's the weather in San Francisco?")
> ```

> [tab] create\_agent
>
> ```python expandable theme={null}
> from anthropic.types.beta import BetaToolSearchToolRegex20251119Param # [!code highlight]
> from langchain.agents import create_agent
> from langchain_anthropic import ChatAnthropic
> from langchain.tools import tool
>
> tool_search = BetaToolSearchToolRegex20251119Param( # [!code highlight]
>     name="tool_search_tool_regex", # [!code highlight]
>     type="tool_search_tool_regex_20251119", # [!code highlight]
> ) # [!code highlight]
>
>
> @tool(extras={"defer_loading": True}) # [!code highlight]
> def get_weather(location: str, unit: str = "fahrenheit") -> str:
>     """Get the current weather for a location.
>
>     Args:
>         location: City name
>         unit: Temperature unit (celsius or fahrenheit)
>     """
>     return f"Weather in {location}: Sunny"
>
>
> @tool(extras={"defer_loading": True}) # [!code highlight]
> def search_files(query: str) -> str:
>     """Search through files in the workspace.
>
>     Args:
>         query: Search query
>     """
>     return f"Found files matching '{query}'"
>
>
> agent = create_agent(
>     model=ChatAnthropic(model="claude-sonnet-4-6"),
>     tools=[
>         tool_search,  # [!code highlight]
>         get_weather,
>         search_files,
>     ],
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]
> })
>
> for message in result["messages"]:
>     message.pretty_print()
> ```

> [tab] Dict
>
> ```python theme={null}
> from langchain_anthropic import ChatAnthropic
> from langchain.tools import tool
>
> @tool(extras={"defer_loading": True})  # [!code highlight]
> def get_weather(location: str, unit: str = "fahrenheit") -> str:
>     """Get the current weather for a location.
>
>     Args:
>         location: City name
>         unit: Temperature unit (celsius or fahrenheit)
>     """
>     return f"Weather in {location}: Sunny"
>
> @tool(extras={"defer_loading": True})  # [!code highlight]
> def search_files(query: str) -> str:
>     """Search through files in the workspace.
>
>     Args:
>         query: Search query
>     """
>     return f"Found files matching '{query}'"
>
> model = ChatAnthropic(model="claude-sonnet-4-6")
>
> model_with_tools = model.bind_tools([
>     {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}, # [!code highlight]
>     get_weather,
>     search_files,
> ])
> response = model_with_tools.invoke("What's the weather in San Francisco?")
> ```

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Model
    participant ToolSearch as Tool Search
    participant Tool as get_weather

    User->>Model: "What's the weather in San Francisco?"
    Model->>ToolSearch: tool_search_tool_regex(pattern="weather")
    ToolSearch-->>Model: tool_references: [get_weather]
    Model->>Tool: get_weather(location="San Francisco")
    Tool-->>Model: Weather result
    Model->>User: Response with weather info
```

**要点：**

* 只有当 Claude 通过搜索发现时，`defer_loading: True` 标记的工具才会被加载
* 将您 3-5 个最常用的工具作为非延迟加载，以获得最佳性能
* 两种变体都会搜索工具名称、描述、参数名称和参数描述

有关工具搜索的更多详细信息，包括与 MCP 服务器和客户端实现的配合使用，请参阅 [Claude 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。

如果您想提供延迟加载的工具而不是通过搜索，请 [在对话中更改工具](#对话中更改工具)。

## 响应元数据

```python theme={null}
ai_msg = model.invoke(messages)
ai_msg.response_metadata
```

```python theme={null}
{
    "id": "msg_013xU6FHEGEq76aP4RgFerVT",
    "model": "claude-sonnet-4-6",
    "stop_reason": "end_turn",
    "stop_sequence": None,
    "usage": {"input_tokens": 25, "output_tokens": 11},
}
```

## Token 使用元数据

```python theme={null}
ai_msg = model.invoke(messages)
ai_msg.usage_metadata
```

```python theme={null}
{"input_tokens": 25, "output_tokens": 11, "total_tokens": 36}
```

默认情况下，在流式输出时将包含包含 Token 使用信息的消息片段：

```python theme={null}
stream = model.stream_events(messages, version="v3")
full_message = stream.output
full_message.usage_metadata
```

```python theme={null}
{"input_tokens": 25, "output_tokens": 11, "total_tokens": 36}
```

可以通过在流式方法中设置 `stream_usage=False` 或在初始化 `ChatAnthropic` 时禁用这些功能。

## API 参考

有关所有功能和配置选项的详细文档，请访问 @\[`ChatAnthropic`] API 参考。

***

> 官方原文：[src/oss/python/integrations/chat/anthropic.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/chat/anthropic.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.