Claude Platform Docs
  • 消息
  • 托管智能体
  • 管理

Search...
⌘K
第一步
Claude 简介快速入门
使用 Claude 构建
功能概览使用 Messages API停止原因与回退拒绝与回退回退额度
模型能力
扩展思考自适应思考努力程度任务预算(测试版)快速模式(研究预览)结构化输出引用流式传输消息批量处理搜索结果流式传输拒绝多语言支持嵌入
工具
概览工具使用的工作原理教程:构建使用工具的智能体定义工具处理工具调用并行工具使用工具运行器(SDK)严格工具使用工具使用与提示缓存服务器工具故障排除网页搜索工具网页抓取工具代码执行工具顾问工具记忆工具Bash 工具计算机使用工具文本编辑器工具
工具基础设施
工具参考管理工具上下文工具组合工具搜索编程式工具调用细粒度工具流式传输
上下文管理
上下文窗口压缩上下文编辑提示缓存对话中系统消息构建编排模式缓存诊断(测试版)令牌计数
处理文件
Files APIPDF 支持图像与视觉
技能
概览快速入门最佳实践企业技能API 中的技能
MCP
远程 MCP 服务器MCP 连接器
云平台上的 Claude
Amazon BedrockAmazon Bedrock(旧版)AWS 上的 Claude PlatformMicrosoft FoundryVertex AI

Log in
使用 Messages API
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Platform Docs

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Claude on AWS
  • Claude on Google Cloud

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
消息/使用 Claude 构建

使用 Messages API

有效使用 Messages API 的实用模式和示例

Anthropic 提供两种使用 Claude 进行构建的方式,每种方式适用于不同的使用场景:

Messages APIClaude Managed Agents
是什么直接访问模型提示功能预构建、可配置的智能体框架,运行在托管基础设施上
最适合自定义智能体循环和细粒度控制长时间运行的任务和异步工作
了解更多Messages API 文档Claude Managed Agents 文档

本指南涵盖使用 Messages API 的常见模式,包括基本请求、多轮对话、预填充技术和视觉功能。有关完整的 API 规范,请参阅 Messages API 参考。



此功能符合零数据保留(ZDR)的条件。当您的组织签订了 ZDR 协议时,通过此功能发送的数据在 API 响应返回后不会被存储。

基本请求和响应



Claude Opus 4.7 及更高版本的模型(包括 Claude Opus 4.8)不支持 temperature、top_p 和 top_k 采样参数。将它们设置为非默认值会返回 400 错误。请从请求负载中省略这些参数,改用提示来引导模型的行为。请参阅迁移指南。

message = anthropic.Anthropic().messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message)
Output
{
  "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
  }
}

在 Claude Opus 4.7 及更高版本的模型上,拒绝响应(stop_reason: "refusal")还包含一个 stop_details 对象,用于标识触发拒绝的策略类别。有关字段参考和示例处理代码,请参阅处理停止原因。

多轮对话

Messages API 是无状态的,这意味着您始终需要将完整的对话历史发送给 API。您可以使用此模式随时间构建对话。较早的对话轮次不一定需要实际来自 Claude。您可以使用合成的 assistant 消息。

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)
Output
{
  "id": "msg_018gCsTGsXkYJVqYPxTgDHBU",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Sure, I'd be happy to provide..."
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 30,
    "output_tokens": 309
  }
}

消息中的系统角色

在 Claude Opus 4.8 上,您可以在用户轮次之后包含带有 "role": "system" 的消息(需遵守放置规则),以便在对话中途添加新的系统指令。system 消息不能是 messages 中的第一个条目;对于从一开始就应用的指令,请使用顶层 system 字段。

对话中途的系统消息与顶层 system 字段具有相同的权威性,但由于它被附加到消息历史的末尾,因此不会使其之前的任何缓存前缀失效。对于应从第一轮就应用的指令,请使用顶层 system 字段;对于仅在稍后才相关的指令,请使用对话中途的系统消息。

请参阅对话中途的系统消息获取完整指南,包括如何将其与提示缓存结合使用。

预填充 Claude 的回复

您可以在输入消息列表的最后位置预填充 Claude 响应的一部分。这可用于塑造 Claude 的响应。下面的示例使用 "max_tokens": 1 从 Claude 获取单个多项选择答案。



Claude Fable 5、Claude Mythos 5、Claude Mythos Preview、Claude Opus 4.8、Claude Opus 4.7、Claude Opus 4.6 和 Claude Sonnet 4.6 不支持预填充。对这些模型使用预填充的请求会返回 400 错误。请在支持的模型上改用结构化输出,或使用系统提示指令。有关迁移模式,请参阅迁移指南。

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)
Output
{
  "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 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)

# 选项 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)
Output
{
  "id": "msg_01EcyWo6m4hyW8KHs2y2pei5",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "This image shows an ant, specifically a close-up view of an ant. The ant is shown in detail, with its distinct head, antennae, and legs clearly visible. The image is focused on capturing the intricate details and features of the ant, likely taken with a macro lens to get an extreme close-up perspective."
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 1551,
    "output_tokens": 71
  }
}

后续步骤

停止原因和回退

处理每个 stop_reason 值,并决定响应结束时应采取的操作。


Claude 的工具使用

为 Claude 提供工具,以便在 Messages API 中调用外部服务和 API。


计算机使用工具

使用 Messages API 控制桌面计算机环境。


结构化输出

从 Claude 获取有保证的、经过模式验证的 JSON 输出。

任务预算

使用 output_config.task_budget 在整个智能体循环中设置建议性令牌预算。

Was this page helpful?

  • 基本请求和响应
  • 多轮对话
  • 消息中的系统角色
  • 预填充 Claude 的回复
  • 视觉
  • 后续步骤