本指南旨在为 Claude 提供使用 Claude API 的基础知识。它解释并举例说明了模型 ID/基本消息 API、工具使用、流式传输、扩展思考,仅此而已。
Smartest model: Claude Opus 4.8: claude-opus-4-8
Smart model: Claude Sonnet 4.6: claude-sonnet-4-6
For fast, cost-effective tasks: Claude Haiku 4.5: claude-haiku-4-5-20251001import anthropic
import os
message = anthropic.Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY")
).messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message){
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello!"
}
],
"model": "claude-opus-4-8",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}Messages API 是无状态的,这意味着您始终需要将完整的对话历史发送给 API。您可以使用此模式随时间逐步构建对话。较早的对话轮次不一定需要真正来自 Claude。您可以使用合成的 assistant 消息。
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"},
],
)
print(message)您可以在输入消息列表的最后一个位置预填 Claude 响应的一部分。这可用于引导 Claude 的响应。下面的示例使用 "max_tokens": 1 从 Claude 获取单个多选题答案。
message = anthropic.Anthropic().messages.create(
model="claude-sonnet-4-5",
max_tokens=1,
messages=[
{
"role": "user",
"content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
},
{"role": "assistant", "content": "The answer is ("},
],
)
print(message.content[0].text)Claude 可以在请求中读取文本和图像。图像支持 base64 和 url 两种源类型,以及 image/jpeg、image/png、image/gif 和 image/webp 媒体类型。
import anthropic
import base64
import httpx
# 选项 1:Base64 编码的图片
image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx.get(image_url).content).decode("utf-8")
message = anthropic.Anthropic().messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message.content[0].text)
# 选项 2:URL 引用的图片
message_from_url = anthropic.Anthropic().messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg",
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message_from_url.content[0].text)"Extended thinking"(扩展思考)有时可以帮助 Claude 处理非常困难的任务。在 Claude Opus 4.7 之前的模型上,启用扩展思考时必须将 temperature 设置为 1。
以下模型支持扩展思考:
claude-opus-4-7)claude-opus-4-6)claude-opus-4-5-20251101)claude-sonnet-4-6)claude-sonnet-4-5-20250929)claude-haiku-4-5-20251001)在 Claude Opus 4.8 和 Claude Opus 4.7 上,不支持手动扩展思考(带有 budget_tokens 值的 type: enabled),会返回 400 错误。请改用自适应思考(type: adaptive)。
当扩展思考开启时,Claude 会创建 thinking 内容块,在其中输出其内部推理。API 响应将包含 thinking 内容块,随后是 text 内容块。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
messages=[
{
"role": "user",
"content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
}
],
)
# 响应将包含摘要化的思考块和文本块
for block in response.content:
if block.type == "thinking":
print(f"\nThinking summary: {block.thinking}")
elif block.type == "text":
print(f"\nResponse: {block.text}")使用手动扩展思考(type: enabled)时,budget_tokens 参数决定了 Claude 在其内部推理过程中允许使用的最大令牌数。在 Claude 4 及更高版本的模型中,此限制适用于完整的思考令牌,而不是摘要输出。更大的预算可以通过对复杂问题进行更彻底的分析来提高响应质量。除非您使用交错思考,否则 budget_tokens 必须小于 max_tokens,以便 Claude 在思考完成后有空间编写其响应。
扩展思考可以与工具使用一起使用,使 Claude 能够对工具选择和结果处理进行推理。
重要限制:
tool_choice: {"type": "auto"}(默认)或 tool_choice: {"type": "none"}。thinking 块传回 API。import anthropic
client = anthropic.Anthropic()
weather_tool = {
"name": "get_weather",
"description": "Get the current weather for a location.",
"input_schema": {
"type": "object",
"properties": {"location": {"type": "string", "description": "The city name."}},
"required": ["location"],
},
}
weather_data = {"temperature": 72}
# 第一个请求 - Claude 返回思考内容和工具请求
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
)
# 提取思考块和工具使用块
thinking_block = next(
(block for block in response.content if block.type == "thinking"), None
)
tool_use_block = next(
(block for block in response.content if block.type == "tool_use"), None
)
# 第二个请求 - 包含思考块和工具结果
continuation = client.messages.create(
model="claude-opus-4-8",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[
{"role": "user", "content": "What's the weather in Paris?"},
# 请注意,thinking_block 和 tool_use_block 都被一并传入
{"role": "assistant", "content": [thinking_block, tool_use_block]},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_block.id,
"content": f"Current temperature: {weather_data['temperature']}°F",
}
],
},
],
)
for block in continuation.content:
if block.type == "text":
print(block.text)Claude 4 模型中的扩展思考与工具使用支持"interleaved thinking"(交错思考),这使 Claude 能够在工具调用之间进行思考。要在 Claude 4、4.5 和 Sonnet 4.6 模型上启用此功能,请在您的 API 请求中添加 beta 标头 interleaved-thinking-2025-05-14。
import anthropic
client = anthropic.Anthropic()
calculator_tool = {
"name": "calculator",
"description": "Perform arithmetic calculations.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The math expression to evaluate.",
}
},
"required": ["expression"],
},
}
database_tool = {
"name": "database_query",
"description": "Query the product database.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The database query."}
},
"required": ["query"],
},
}
response = client.beta.messages.create(
model="claude-sonnet-4-6",
max_tokens=16000,
thinking={"type": "enabled", "budget_tokens": 10000},
tools=[calculator_tool, database_tool],
messages=[
{
"role": "user",
"content": "What's the total revenue if we sold 150 units of product A at $50 each?",
}
],
betas=["interleaved-thinking-2025-05-14"],
)
for block in response.content:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "tool_use":
print(f"Tool call: {block.name}({block.input})")
elif block.type == "text":
print(f"Response: {block.text}")使用交错思考时(且仅限交错思考,不包括常规扩展思考),budget_tokens 可以超过 max_tokens 参数,因为在这种情况下 budget_tokens 代表一个助手轮次内所有思考块的总预算。
对于 Claude Opus 4.8、Claude Opus 4.7 和 Claude Opus 4.6,使用自适应思考(thinking: {type: "adaptive"})时会自动启用交错思考。无需 beta 标头。Sonnet 4.6 同时支持带有手动扩展思考的 interleaved-thinking-2025-05-14 beta 标头和自适应思考。
客户端工具在 API 请求的 tools 顶级参数中指定。每个工具定义包括:
| 参数 | 描述 |
|---|---|
name | 工具的名称。必须匹配正则表达式 ^[a-zA-Z0-9_-]{1,64}$。 |
description | 对工具功能、何时应使用以及其行为方式的详细纯文本描述。 |
input_schema | 一个 JSON Schema 对象,定义工具的预期参数。 |
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
}
},
"required": ["location"]
}
}提供极其详细的描述。 这是迄今为止影响工具性能最重要的因素。您的描述应解释有关工具的每个细节,包括:
考虑为复杂工具使用 input_examples。 对于具有嵌套对象、可选参数或格式敏感输入的工具,您可以使用 input_examples 字段(beta)提供具体示例。这有助于 Claude 理解预期的输入模式。有关详细信息,请参阅提供工具使用示例。
良好工具描述的示例:
{
"name": "get_stock_price",
"description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}您可以通过在 tool_choice 字段中指定工具来强制 Claude 使用特定工具:
tool_choice = {"type": "tool", "name": "get_weather"}使用 tool_choice 参数时,有四个可能的选项:
auto 允许 Claude 决定是否调用任何提供的工具(默认)。any 告诉 Claude 必须使用提供的工具之一。tool 强制 Claude 始终使用特定工具。none 阻止 Claude 使用任何工具。工具不一定需要是客户端函数。只要您希望模型返回遵循所提供 schema 的 JSON 输出,就可以使用工具。
使用工具时,Claude 通常会展示其"chain of thought"(思维链),即它用于分解问题并决定使用哪些工具的逐步推理。
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "<thinking>To answer this question, I will: 1. Use the get_weather tool to get the current weather in San Francisco. 2. Use the get_time tool to get the current time in the America/Los_Angeles timezone, which covers San Francisco, CA.</thinking>"
},
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": { "location": "San Francisco, CA" }
}
]
}默认情况下,Claude 可能会使用多个工具来回答用户查询。您可以通过设置 disable_parallel_tool_use=true 来禁用此行为。
响应将具有 tool_use 的 stop_reason,以及一个或多个包含以下内容的 tool_use 内容块:
id:此特定工具使用块的唯一标识符。name:正在使用的工具的名称。input:包含传递给工具的输入的对象。当您收到工具使用响应时,您应该:
tool_use 块中提取 name、id 和 input。tool_result 的新消息来继续对话:{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "15 degrees"
}
]
}max_tokens 停止原因如果 Claude 的响应在工具使用期间因达到 max_tokens 限制而被截断,请使用更高的 max_tokens 值重试请求。
pause_turn 停止原因使用网络搜索等服务器工具时,API 可能会返回 pause_turn 停止原因。通过在后续请求中按原样传回暂停的响应来继续对话。
如果工具本身在执行期间抛出错误,请使用 "is_error": true 返回错误消息:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "ConnectionError: the weather service API is not available (HTTP 500)",
"is_error": true
}
]
}如果 Claude 尝试使用的工具无效(例如缺少必需参数),请在工具定义中使用更详细的 description 值重试请求。
创建消息时,您可以设置 "stream": true,以使用"server-sent events"(服务器发送事件),即 SSE 增量流式传输响应。
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
model="claude-opus-4-8",
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)每个服务器发送事件都包含一个命名的事件类型和关联的 JSON 数据。每个流使用以下事件流程:
message_start:包含一个 content 为空的 Message 对象。content_block_start、一个或多个 content_block_delta 事件和 content_block_stop。message_delta 事件,指示对最终 Message 对象的顶级更改。message_stop 事件。警告: message_delta 事件的 usage 字段中显示的令牌计数是_累积的_。
{
"type": "content_block_delta",
"index": 0,
"delta": { "type": "text_delta", "text": "Hello frien" }
}对于 tool_use 内容块,增量是_部分 JSON 字符串_:
{"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}使用带流式传输的扩展思考时:
{
"type": "content_block_delta",
"index": 0,
"delta": {
"type": "thinking_delta",
"thinking": "Let me solve this step by step..."
}
}event: message_start
data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-8", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}
event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}
event: content_block_stop
data: {"type": "content_block_stop", "index": 0}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}
event: message_stop
data: {"type": "message_stop"}Was this page helpful?