使用 Messages API
有效使用 Messages API 的实用模式和示例
Anthropic 提供两种使用 Claude 进行构建的方式,每种方式适用于不同的使用场景:
| Messages API | Claude Managed Agents | |
|---|---|---|
| 它是什么 | 直接的模型提示访问 | 预构建、可配置的智能体框架,运行在托管基础设施中 |
| 最适合 | 自定义智能体循环和细粒度控制 | 长时间运行的任务和异步工作 |
本指南涵盖使用 Messages API 的常见模式,包括基本请求、多轮对话、预填充技术和视觉功能。有关完整的 API 规范,请参阅 Messages API 参考。如需了解托管智能体框架,请参阅 Claude Managed Agents 概述。
基本请求和响应
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
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-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}在所有模型上,拒绝响应(stop_reason: "refusal")还会包含一个 stop_details 对象,用于标识触发拒绝的策略类别。有关字段参考和示例处理代码,请参阅处理停止原因。
多轮对话
Messages API 是无状态的,这意味着您始终需要将完整的对话历史发送给 API。您可以使用这种模式逐步构建对话。较早的对话轮次不一定需要真正来自 Claude。您可以使用合成的 assistant 消息。
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"},
],
)
print(message){
"id": "msg_018gCsTGsXkYJVqYPxTgDHBU",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Sure, I'd be happy to provide..."
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 30,
"output_tokens": 309
}
}消息中的 system 角色
在 Claude Fable 5.1、Claude Mythos 5.1、Claude Fable 5、Claude Mythos 5、Claude Opus 5.5、Claude Opus 4.8 和 Claude Opus 5 上,您可以在用户轮次之后包含 "role": "system" 的消息(需遵守放置规则),以便在对话进行中添加新的系统指令。system 消息不能作为 messages 中的第一个条目。对于从一开始就适用的指令,请使用顶层 system 字段。
对话中途的系统消息与顶层 system 字段具有相同的权威性,但由于它被追加到消息历史的末尾,因此不会使其之前的任何已缓存前缀失效。对于应从第一轮就适用的指令,请使用顶层 system 字段;对于仅在稍后才变得相关的指令,请使用对话中途的系统消息。
请参阅对话中途的系统消息获取完整指南,包括如何将其与 "prompt caching"(提示缓存)结合使用,详见提示缓存。
预填充 Claude 的响应
您可以在输入消息列表的最后一个位置预填充 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){
"id": "msg_01Q8Faay6S7QPTvEUUQARt7h",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "C"
}
],
"model": "claude-sonnet-4-5",
"stop_reason": "max_tokens",
"stop_sequence": null,
"usage": {
"input_tokens": 42,
"output_tokens": 1
}
}视觉
Claude 可以读取请求中的文本和图像。您可以使用 base64、url 或 file 源类型提供图像。file 源类型引用通过 Files API 上传的图像。支持的媒体类型为 image/jpeg、image/png、image/gif 和 image/webp。有关更多详细信息,请参阅视觉指南。
import base64
import httpx2
# 选项 1:Base64 编码的图像
image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
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)
# 选项 2:通过 URL 引用的图像
message_from_url = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://platform.claude.com/docs/images/vision-example.jpg",
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message_from_url){
"id": "msg_011CdKmWtV3oFx1C5yUbf5CY",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "This image is a beautiful minimalist/flat-design illustration of a sunset landscape. Here's what it contains:\n\n**Sky & Sun:**\n- A warm gradient sky transitioning from golden-yellow at the top to deep orange toward the horizon\n- A large pale yellow sun positioned in the upper-right area\n\n**Birds:**\n- Three small silhouetted birds flying in the upper-left portion of the sky, depicted as simple \"M\" or \"v\" shapes\n\n**Mountains:**\n- Multiple layered mountain peaks in purple and maroon tones\n- The mountains overlap to create depth, with varying shades of dusty purple and deep burgundy\n\n**Water:**\n- A dark purple body of water at the bottom of the image\n- A reflection of the sun shown as horizontal cream/peach colored lines in the center-bottom area\n\nThe overall style is clean, geometric, and uses a warm sunset color palette (oranges, yellows, purples, and maroons), giving it a peaceful, serene aesthetic typical of modern vector/flat design artwork."
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 1030,
"output_tokens": 350
}
}后续步骤
Was this page helpful?