端点
POST /v1/messages
Claude 全系列的唯一推荐入口,请求与响应格式和 Anthropic Messages API 一致,完整支持 prompt cache、thinking、工具调用与流式输出。以 OpenAI 兼容格式调用 Claude 会丢失这些能力,调用 Claude 请使用本端点。
请求
请求头
| 请求头 | 取值 | 说明 |
|---|---|---|
x-api-key | sk-xxxxxx | 鉴权。也可以改用 Authorization: Bearer sk-xxxxxx |
anthropic-version | 2023-06-01 | 可省略,省略时自动补默认值 |
content-type | application/json |
最小请求体:
json
{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "用一句话介绍你自己"}
]
}参数
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | Claude 模型 ID,完整列表见 GET /v1/models |
max_tokens | integer | 是 | 最大输出 token 数 |
messages | array | 是 | 对话消息。role 为 user 或 assistant,content 为文本字符串或内容块数组,与 Anthropic 官方格式一致 |
system | string 或数组 | 否 | 系统提示词 |
stream | boolean | 否 | 设为 true 时以 SSE 流式返回,默认 false |
其余字段(temperature、tools、thinking、内容块中的 cache_control 等)按 Anthropic Messages API 格式透传,用法以 Anthropic 官方文档为准。
响应
非流式返回 message 对象:
json
{
"id": "msg_01KxDE...",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-5",
"content": [{"type": "text", "text": "我是 Claude……"}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 159, "output_tokens": 34}
}| 字段 | 说明 |
|---|---|
id | 消息 ID |
type | 固定为 message |
role | 固定为 assistant |
model | 实际响应的模型 ID |
content | 内容块数组,文本回复在 type 为 text 的块的 text 字段里 |
stop_reason | 停止原因,如 end_turn |
usage | 本次请求的 input_tokens 与 output_tokens |
stream 为 true 时响应为 text/event-stream,事件序列:message_start → content_block_start → 多个 content_block_delta → content_block_stop → message_delta → message_stop。
示例
基础请求
bash
curl https://caapi.top/v1/messages \
-H "x-api-key: sk-xxxxxx" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "用一句话介绍你自己"}
]
}'流式请求
bash
curl https://caapi.top/v1/messages \
-H "x-api-key: sk-xxxxxx" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"stream": true,
"messages": [{"role": "user", "content": "写一首五言绝句"}]
}'Python SDK
python
from anthropic import Anthropic
client = Anthropic(
api_key="sk-xxxxxx",
base_url="https://caapi.top",
)
resp = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "你好"}],
)
print(resp.content[0].text)错误
错误响应统一为 error 对象加顶层 trace_id,排查问题时请提供 trace_id。
| HTTP 状态 | error.type | 触发条件 |
|---|---|---|
| 401 | missing_auth_credential | 请求没有带 x-api-key 或 Authorization: Bearer |
| 401 | invalid_api_key | x-api-key 里的 Key 不正确或不完整 |
| 401 | invalid_bearer_token | Authorization: Bearer 里的 Key 不正确或不完整 |
响应示例(缺少鉴权):
json
{
"error": {
"message": "Missing auth credential. Provide x-api-key: sk-* or Authorization: Bearer <token>.",
"type": "missing_auth_credential",
"code": 401,
"details": null
},
"trace_id": "4c9530c5-2bcc-472d-9c73-e07262bbbdb9"
}