ChatAnthropic
本 Notebook 快速介绍了如何开始使用 Anthropic 的 聊天模型。如需了解 ChatAnthropic 所有功能和配置的详细文档,请前往 API 参考。
Anthropic 提供多种聊天模型。您可以在 Anthropic 文档 中找到有关其最新模型以及成本、上下文窗口和支持的输入类型的相关信息。
请注意,可以通过 AWS Bedrock 和 Google VertexAI 访问某些 Anthropic 模型。请参阅 ChatBedrock 和 ChatVertexAI 集成,通过这些服务使用 Anthropic 模型。
概述
集成详情
| 类 | 包 | 本地 | 可序列化 | JS 支持 | 包下载次数 | 包最新版本 |
|---|---|---|---|---|---|---|
| ChatAnthropic | langchain-anthropic | ❌ | beta | ✅ |
模型功能
| 工具调用 | 结构化输出 | JSON 模式 | 图像输入 | 音频输入 | 视频输入 | Token 级流式传输 | 原生异步 | Token 用量跟踪 | Logprobs |
|---|---|---|---|---|---|---|---|---|---|
| ✅ | ✅ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ |
设置
如需访问 Anthropic 模型,您需要创建一个 Anthropic 账户,获取 API 密钥,并安装 langchain-anthropic 集成包。
凭证
前往 https://console.anthropic.com/ 注册 Anthropic 并生成 API 密钥。完成此操作后,设置 ANTHROPIC_API_KEY 环境变量:
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 API 密钥:
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
安装
LangChain Anthropic 集成位于 langchain-anthropic 包中:
%pip install -qU langchain-anthropic
langchain-anthropic>=0.3.13实例化
现在我们可以实例化我们的模型对象并生成聊天补全:
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
model="claude-3-5-sonnet-20240620",
temperature=0,
max_tokens=1024,
timeout=None,
max_retries=2,
# other params...
)
调用
messages = [
(
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
),
("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
AIMessage(content="J'adore la programmation.", response_metadata={'id': 'msg_018Nnu76krRPq8HvgKLW4F8T', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 29, 'output_tokens': 11}}, id='run-57e9295f-db8a-48dc-9619-babd2bedd891-0', usage_metadata={'input_tokens': 29, 'output_tokens': 11, 'total_tokens': 40})
print(ai_msg.content)
J'adore la programmation.
链式调用
我们可以像这样将模型与提示模板链接起来:
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
),
("human", "{input}"),
]
)
chain = prompt | llm
chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love programming.",
}
)
AIMessage(content="Here's the German translation:\n\nIch liebe Programmieren.", response_metadata={'id': 'msg_01GhkRtQZUkA5Ge9hqmD8HGY', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 23, 'output_tokens': 18}}, id='run-da5906b4-b200-4e08-b81a-64d4453643b6-0', usage_metadata={'input_tokens': 23, 'output_tokens': 18, 'total_tokens': 41})
内容块
来自单个 Anthropic AI 消息的内容可以是单个字符串或内容块列表。例如,当 Anthropic 模型调用工具时,工具调用是消息内容的一部分(同时也会在标准化的 AIMessage.tool_calls 中暴露):
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")
llm_with_tools = llm.bind_tools([GetWeather])
ai_msg = llm_with_tools.invoke("Which city is hotter today: LA or NY?")
ai_msg.content
[{'text': "To answer this question, we'll need to check the current weather in both Los Angeles (LA) and New York (NY). I'll use the GetWeather function to retrieve this information for both cities.",
'type': 'text'},
{'id': 'toolu_01Ddzj5PkuZkrjF4tafzu54A',
'input': {'location': 'Los Angeles, CA'},
'name': 'GetWeather',
'type': 'tool_use'},
{'id': 'toolu_012kz4qHZQqD4qg8sFPeKqpP',
'input': {'location': 'New York, NY'},
'name': 'GetWeather',
'type': 'tool_use'}]
ai_msg.tool_calls
[{'name': 'GetWeather',
'args': {'location': 'Los Angeles, CA'},
'id': 'toolu_01Ddzj5PkuZkrjF4tafzu54A'},
{'name': 'GetWeather',
'args': {'location': 'New York, NY'},
'id': 'toolu_012kz4qHZQqD4qg8sFPeKqpP'}]
多模态
Claude 支持将图像和 PDF 作为内容块输入,这两种格式都支持 Anthropic 的原生格式(请参阅有关 Vision 和 PDF 支持 的文档),以及 LangChain 的 标准格式。
Files API
Claude 还通过其托管的 Files API 支持与文件的交互。请参阅下面的示例。
Files API 还可用于将文件上传到容器,供 Claude 的内置代码执行工具使用。有关详细信息,请参阅下面的 代码执行 部分。
图片
# Upload image
import anthropic
client = anthropic.Anthropic()
file = client.beta.files.upload(
# Supports image/jpeg, image/png, image/gif, image/webp
file=("image.png", open("/path/to/image.png", "rb"), "image/png"),
)
image_file_id = file.id
# Run inference
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
model="claude-sonnet-4-20250514",
betas=["files-api-2025-04-14"],
)
input_message = {
"role": "user",
"content": [
{
"type": "text",
"text": "Describe this image.",
},
{
"type": "image",
"source": {
"type": "file",
"file_id": image_file_id,
},
},
],
}
llm.invoke([input_message])
PDF 文件
# Upload document
import anthropic
client = anthropic.Anthropic()
file = client.beta.files.upload(
file=("document.pdf", open("/path/to/document.pdf", "rb"), "application/pdf"),
)
pdf_file_id = file.id
# Run inference
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
model="claude-sonnet-4-20250514",
betas=["files-api-2025-04-14"],
)
input_message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe this document."},
{"type": "document", "source": {"type": "file", "file_id": pdf_file_id}}
],
}
llm.invoke([input_message])
扩展思考
Claude 3.7 Sonnet 支持一项 扩展思考 功能,该功能将输出导致其最终答案的逐步推理过程。
要使用它,请在初始化 ChatAnthropic 时指定 thinking 参数。它也可以在调用期间作 为关键字参数传递。
您需要指定一个 token 预算来使用此功能。请参阅下面的使用示例:
import json
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
model="claude-3-7-sonnet-latest",
max_tokens=5000,
thinking={"type": "enabled", "budget_tokens": 2000},
)
response = llm.invoke("What is the cube root of 50.653?")
print(json.dumps(response.content, indent=2))
[
{
"signature": "ErUBCkYIARgCIkCx7bIPj35jGPHpoVOB2y5hvPF8MN4lVK75CYGftmVNlI4axz2+bBbSexofWsN1O/prwNv8yPXnIXQmwT6zrJsKEgwJzvks0yVRZtaGBScaDOm9xcpOxbuhku1zViIw9WDgil/KZL8DsqWrhVpC6TzM0RQNCcsHcmgmyxbgG9g8PR0eJGLxCcGoEw8zMQu1Kh1hQ1/03hZ2JCOgigpByR9aNPTwwpl64fQUe6WwIw==",
"thinking": "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.",
"type": "thinking"
},
{
"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.",
"type": "text"
}
]