跳转到主要内容
Anthropic Claude 是一款非常强大的 AI 对话系统,只要输入提示词,就能在短短几秒内生成流畅自然的回复。Claude Messages API 是 Anthropic 官方原生的 API 格式,与 OpenAI 兼容格式(Chat Completion)不同,它采用 Anthropic 自有的请求和响应结构,能够更好地利用 Claude 的独特能力,如多模态内容输入、工具调用、深度思考(Extended Thinking)等高级特性。 本文档主要介绍 Claude Messages API 操作的使用流程,利用它我们可以使用与 Anthropic 官方一致的原生接口来调用 Claude 的对话功能。

申请流程

要使用 Claude Messages API,首先可以到 Claude Messages API 页面点击「Acquire」按钮,获取请求所需要的凭证: 如果你尚未登录或注册,会自动跳转到登录页面邀请您来注册和登录,登录注册之后会自动返回当前页面。 在首次申请时会有免费额度赠送,可以免费使用该 API。

基本使用

Claude Messages API 的请求路径为 /v1/messages,与 Anthropic 官方 API 保持一致。我们至少需要提供三个必填参数:
  • model:选择使用的 Claude 模型,如 claude-opus-4-20250514claude-sonnet-4-20250514 等。
  • messages:输入的消息数组,每条消息包含 role(角色)和 content(内容),其中 role 支持 userassistant
  • max_tokens:最大输出 token 数,用于限制单次回复的长度。
常用可选参数:
  • system:系统提示词,用于设定模型的行为和角色。
  • temperature:生成随机性,0-1 之间,值越大回复越发散。
  • stream:是否使用流式响应,设为 true 可实现逐字返回效果。
  • stop_sequences:自定义停止序列,模型遇到这些文本时会停止生成。
  • top_p:核采样参数,与 temperature 配合控制生成的随机性。
  • top_k:仅从概率最高的 K 个选项中采样。
  • tools:工具定义,用于让模型调用外部函数。
  • tool_choice:控制模型如何使用提供的工具。

cURL 示例

curl -X POST 'https://api.acedata.cloud/v1/messages' \
  -H 'accept: application/json' \
  -H 'authorization: Bearer {token}' \
  -H 'content-type: application/json' \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": "Hello, Claude"
      }
    ]
  }'

Python 示例

import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
        {"role": "user", "content": "Hello, Claude"}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
调用之后,返回结果如下:
{
  "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hi! My name is Claude. How can I help you today?"
    }
  ],
  "model": "claude-sonnet-4-20250514",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 12,
    "output_tokens": 15
  }
}
返回结果字段说明:
  • id:本次消息的唯一标识符。
  • type:始终为 message
  • role:始终为 assistant
  • content:回复内容数组,每个元素包含 type(如 text)和对应的内容。
  • model:处理请求的模型名称。
  • stop_reason:停止原因,可能的值包括 end_turn(正常结束)、max_tokens(达到最大长度)、stop_sequence(遇到停止序列)、tool_use(工具调用)。
  • stop_sequence:如果因自定义停止序列而停止,显示匹配的停止序列文本。
  • usage:token 使用统计,包含 input_tokens(输入 token 数)和 output_tokens(输出 token 数)。

系统提示词

Claude Messages API 支持通过 system 字段设定系统提示词,用于定义模型的行为、角色和上下文。

Python 示例

import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "system": "你是一位专业的中文翻译助手,请将用户输入的英文翻译成中文。",
    "messages": [
        {"role": "user", "content": "The quick brown fox jumps over the lazy dog."}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
通过设置 system 提示词,可以精确地控制 Claude 的角色和行为方式。

流式响应

该接口也支持流式响应,将 stream 参数设为 true 即可获得逐步返回的效果,非常适合在网页中实现逐字显示。

Python 示例

import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "stream": True,
    "messages": [
        {"role": "user", "content": "Hello, Claude"}
    ]
}

response = requests.post(url, json=payload, headers=headers, stream=True)
for line in response.iter_lines():
    if line:
        print(line.decode("utf-8"))
流式响应以 Server-Sent Events (SSE) 格式返回,每行以 event:data: 为前缀。流式事件类型包括:
  • message_start:消息开始,包含消息的基本信息和模型名称。
  • content_block_start:内容块开始。
  • content_block_delta:内容块增量更新,包含新生成的文本片段。
  • content_block_stop:内容块结束。
  • message_delta:消息级别的增量更新,包含 stop_reason 和最终的 usage 信息。
  • message_stop:消息结束。
输出效果如下:
event: message_start
data: {"type":"message_start","message":{"id":"msg_01XFDUDYJgAACzvnptvVoYEL","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-20250514","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":0}}}

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":"Hi"}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"! My name is"}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" Claude. How can I help you today?"}}

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"}
可以看到,流式响应中 content_block_delta 事件包含了逐步生成的文本内容,通过拼接所有 text_delta 即可获得完整回复。

JavaScript 示例

const options = {
  method: "POST",
  headers: {
    accept: "application/json",
    authorization: "Bearer {token}",
    "content-type": "application/json",
  },
  body: JSON.stringify({
    model: "claude-sonnet-4-20250514",
    max_tokens: 1024,
    stream: true,
    messages: [{ role: "user", content: "Hello, Claude" }],
  }),
};

const response = await fetch("https://api.acedata.cloud/v1/messages", options);
const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  console.log(decoder.decode(value));
}

多轮对话

如果您想要对接多轮对话功能,需要在 messages 数组中交替排列 userassistant 角色的消息,将之前的对话历史一并传入。

Python 示例

import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
        {"role": "user", "content": "Hello, my name is Alice."},
        {"role": "assistant", "content": "Hello Alice! Nice to meet you. How can I help you today?"},
        {"role": "user", "content": "What is my name?"}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
返回结果如下:
{
  "id": "msg_01Y1wfQmd89g968TVbFu57Yc",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Your name is Alice, as you just told me!"
    }
  ],
  "model": "claude-sonnet-4-20250514",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 40,
    "output_tokens": 14
  }
}
通过在 messages 中传递完整的对话历史,Claude 可以结合上下文进行准确的回答。

深度思考模型

Claude 支持 Extended Thinking(深度思考)功能,可以让模型在回复之前先进行内部推理,提升处理复杂问题的准确性。使用该功能时需要传入 thinking 参数。

Python 示例

import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 16000,
    "thinking": {
        "type": "enabled",
        "budget_tokens": 10000
    },
    "messages": [
        {"role": "user", "content": "What is the sine of 30 degrees? Show your reasoning."}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
返回结果如下:
{
  "id": "msg_018J4YaRoGHtbsTVb4Vvz7oH",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "The user is asking for the sine of 30 degrees. This is a basic trigonometry question.\n\nIn a 30-60-90 triangle, the sides are in the ratio 1:√3:2.\n\nFor a 30° angle:\n- The opposite side is 1\n- The hypotenuse is 2\n- So sin(30°) = opposite/hypotenuse = 1/2 = 0.5"
    },
    {
      "type": "text",
      "text": "The sine of 30 degrees is **1/2** or **0.5**.\n\nThis is one of the fundamental trigonometric values. In a 30-60-90 triangle, the sides are in the ratio 1:√3:2, where the side opposite to the 30° angle has length 1 and the hypotenuse has length 2, giving us sin(30°) = 1/2."
    }
  ],
  "model": "claude-sonnet-4-20250514",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 28,
    "output_tokens": 239
  }
}
可以看到,content 数组中包含了两个内容块:
  • type: "thinking":模型的内部思考过程,展示了推理步骤。
  • type: "text":最终的回答结果。
注意事项:
  • 使用 thinking 时,max_tokens 需要大于 budget_tokens,因为 budget_tokens 是分配给思考过程的 token 预算。
  • budget_tokens 越大,模型进行更深入推理的空间越大,适合处理复杂问题。

视觉模型

Claude 支持多模态输入,可以同时处理文本和图像。在 Messages API 中,通过将 content 设为数组格式,并传入图像内容块即可使用视觉能力。

使用 Base64 编码图像

import base64
import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

# 读取并编码图片
with open("image.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode("utf-8")

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/png",
                        "data": image_data
                    }
                },
                {
                    "type": "text",
                    "text": "What's in this image?"
                }
            ]
        }
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())

使用 URL 图像

import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://cdn.acedata.cloud/ueugot.png"
                    }
                },
                {
                    "type": "text",
                    "text": "What's in this image?"
                }
            ]
        }
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())

cURL 示例

curl -X POST 'https://api.acedata.cloud/v1/messages' \
  -H 'accept: application/json' \
  -H 'authorization: Bearer {token}' \
  -H 'content-type: application/json' \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "image",
            "source": {
              "type": "url",
              "url": "https://cdn.acedata.cloud/ueugot.png"
            }
          },
          {
            "type": "text",
            "text": "What'\''s in this image?"
          }
        ]
      }
    ]
  }'
支持的图片格式包括:image/jpegimage/pngimage/gifimage/webp 返回结果示例:
{
  "id": "msg_01NCrxpZmV17bhQJJRQEFEb9",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "This image shows an API request configuration interface for what appears to be an AI chat completion service. The interface includes parameters for model selection, messages, stream mode, and max tokens settings."
    }
  ],
  "model": "claude-sonnet-4-20250514",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 1570,
    "output_tokens": 52
  }
}

工具调用(Tool Use)

Claude Messages API 原生支持工具调用功能,允许模型在需要时调用您预定义的工具/函数。

Python 示例

import requests

url = "https://api.acedata.cloud/v1/messages"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "tools": [
        {
            "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"
                    }
                },
                "required": ["location"]
            }
        }
    ],
    "messages": [
        {"role": "user", "content": "What's the weather like in San Francisco?"}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
当模型决定调用工具时,返回结果中 content 会包含 tool_use 类型的内容块:
{
  "id": "msg_01Aq9w938a90dw8q",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Let me check the weather in San Francisco for you."
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lgs",
      "name": "get_weather",
      "input": {
        "location": "San Francisco, CA"
      }
    }
  ],
  "model": "claude-sonnet-4-20250514",
  "stop_reason": "tool_use",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 120,
    "output_tokens": 68
  }
}
注意 stop_reasontool_use,表示模型需要调用工具。收到该结果后,您需要执行工具函数并将结果以 tool_result 的形式回传给模型:
payload = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "tools": [
        {
            "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"
                    }
                },
                "required": ["location"]
            }
        }
    ],
    "messages": [
        {"role": "user", "content": "What's the weather like in San Francisco?"},
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Let me check the weather in San Francisco for you."},
                {"type": "tool_use", "id": "toolu_01A09q90qw90lq917835lgs", "name": "get_weather", "input": {"location": "San Francisco, CA"}}
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01A09q90qw90lq917835lgs",
                    "content": "Sunny, 72°F"
                }
            ]
        }
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
模型会基于工具返回的结果,生成最终的自然语言回复。

与 Chat Completion API 的区别

Ace Data Cloud 同时提供两种 Claude API 格式,两者的主要区别如下:
特性Messages API (/v1/messages)Chat Completion API (/v1/chat/completions)
格式Anthropic 原生格式OpenAI 兼容格式
系统提示词独立的 system 字段通过 messagesrole: "system" 传递
响应结构content 数组(支持多种类型)choices 数组(包含 message
流式格式SSE 事件(多种事件类型)SSE data
深度思考原生 thinking 参数通过特殊模型名触发(如 -thinking 后缀)
工具调用原生 tools + input_schemaOpenAI 兼容的 functions 格式
Token 统计input_tokens / output_tokensprompt_tokens / completion_tokens
如果您的系统已经对接了 OpenAI 格式的 API,可以使用 Chat Completion API 来无缝切换。如果您需要使用 Claude 的全部原生能力,建议使用 Messages API。

错误处理

在调用 API 时,如果遇到错误,API 会返回相应的错误代码和信息。例如:
  • 400 token_mismatched:Bad request, possibly due to missing or invalid parameters.
  • 400 api_not_implemented:Bad request, possibly due to missing or invalid parameters.
  • 401 invalid_token:Unauthorized, invalid or missing authorization token.
  • 429 too_many_requests:Too many requests, you have exceeded the rate limit.
  • 500 api_error:Internal server error, something went wrong on the server.

错误响应示例

{
  "success": false,
  "error": {
    "code": "api_error",
    "message": "fetch failed"
  },
  "trace_id": "2cf86e86-22a4-46e1-ac2f-032c0f2a4e89"
}

结论

通过本文档,您已经了解了如何使用 Claude Messages API 以 Anthropic 原生格式调用 Claude 的对话功能。Messages API 支持基本对话、系统提示词、流式响应、多轮对话、深度思考、视觉理解和工具调用等丰富功能。如有任何问题,请随时联系我们的技术支持团队。