Docs

创建消息

POST/v1/messages

使用 Anthropic Messages API 格式创建消息

本页目录
  1. 请求头
  2. 请求体
  3. 响应
  4. 请求示例
  5. 响应示例
  6. 错误响应示例
  7. 图片输入示例
  8. 扩展思考示例

此端点提供原生的 Anthropic Messages API 兼容性。对于具备扩展思考等功能的 Claude 模型,请使用此接口。

/v1/messages 和 /v1/messages/count_tokens 仍属于 chat 协议族下的兼容端点。

请求头

请求头 Authorization

类型:string

必填:否

Bearer token 形式:Bearer sk-your-api-key。Authorization 与 x-api-key 二选一即可。

请求头 x-api-key

类型:string

必填:否

Anthropic 风格的 API Key 请求头。当客户端需要 Anthropic 请求头时,用它替代 Authorization。

请求头 anthropic-version

类型:string

必填:否

Anthropic API 版本。客户端通常发送 2023-06-01。网关不校验该头。

请求体

参数 model

类型:string

位置:body

必填:是

Claude 模型 ID(例如 claude-sonnet-4-6 或 claude-opus-4-6)。

参数 messages

类型:array

位置:body

必填:是

包含 role 和 content 的消息对象数组。

对于支持视觉能力的 Claude 模型,content 可以是纯字符串,也可以是内容块数组。传图片时请使用结构化内容块,而不是把图片 URL 或 Base64 直接写进纯文本里。

内容块示例:

  • 文本块:{ "type": "text", "text": "请描述这张图片" }
  • URL 图片块:{ "type": "image", "source": { "type": "url", "url": "https://example.com/image.jpg" } }
  • Base64 图片块:{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "iVBORw0KGgoAAA..." } }

参数 max_tokens

类型:integer

位置:body

必填:是

要生成的最大 token 数。

参数 system

类型:string

位置:body

System prompt(与 messages 数组分开)。

参数 temperature

类型:number

位置:body

采样温度(0-1)。

参数 stream

类型:boolean

位置:body

启用流式响应。

参数 thinking

类型:object

位置:body

支持该能力的 Claude 模型的扩展思考配置。

  • type(string):设为 "enabled" 以启用
  • budget_tokens(integer):用于思考的 token 预算

参数 tools

类型:array

位置:body

模型可用的工具。

参数 tool_choice

类型:object

位置:body

模型应如何使用工具。可选值:auto、any、tool(特定工具)。

参数 top_p

类型:number

位置:body

Nucleus sampling 参数。请只使用 temperature 或 top_p 其中之一。

参数 top_k

类型:integer

位置:body

每个 token 仅从前 K 个选项中进行采样。

参数 stop_sequences

类型:array

位置:body

自定义停止序列,当命中时模型将停止生成。

参数 metadata

类型:object

位置:body

附加到请求中的元数据,用于跟踪目的。

响应

响应字段 id

类型:string

唯一的消息标识符。

响应字段 type

类型:string

始终为 message。

响应字段 role

类型:string

始终为 assistant。

响应字段 content

类型:array

内容块数组(text、thinking、tool_use)。

响应字段 model

类型:string

使用的模型。

响应字段 stop_reason

类型:string

生成停止的原因(end_turn、max_tokens、tool_use)。

响应字段 usage

类型:object

token 使用情况,包含 input_tokens 和 output_tokens。

请求示例

curl -X POST "https://api.anypath.dev/v1/messages" \
  -H "x-api-key: sk-your-api-key" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "max_tokens": 1024,
    "system": "You are a helpful assistant.",
    "messages": [
      {"role": "user", "content": "Hello, Claude!"}
    ]
  }'
from anthropic import Anthropic

client = Anthropic(
    api_key="sk-your-api-key",
    base_url="https://api.anypath.dev"
)

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system="You are a helpful assistant.",
    messages=[
        {"role": "user", "content": "Hello, Claude!"}
    ]
)

print(message.content[0].text)
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: 'sk-your-api-key',
  baseURL: 'https://api.anypath.dev'
});

const message = await client.messages.create({
  model: 'claude-sonnet-4-6',
  max_tokens: 1024,
  system: 'You are a helpful assistant.',
  messages: [
    { role: 'user', content: 'Hello, Claude!' }
  ]
});

console.log(message.content[0].text);
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    payload := map[string]interface{}{
        "model":      "claude-sonnet-4-6",
        "max_tokens": 1024,
        "system":     "You are a helpful assistant.",
        "messages": []map[string]string{
            {"role": "user", "content": "Hello, Claude!"},
        },
    }

    jsonData, _ := json.Marshal(payload)
    req, _ := http.NewRequest("POST", "https://api.anypath.dev/v1/messages", bytes.NewBuffer(jsonData))
    req.Header.Set("x-api-key", "sk-your-api-key")
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}
<?php
$payload = [
    'model' => 'claude-sonnet-4-6',
    'max_tokens' => 1024,
    'system' => 'You are a helpful assistant.',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, Claude!']
    ]
];

$ch = curl_init('https://api.anypath.dev/v1/messages');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'x-api-key: sk-your-api-key',
        'anthropic-version: 2023-06-01',
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode($payload)
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo $data['content'][0]['text'];

响应示例

{
  "id": "msg_abc123",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello! How can I help you today?"
    }
  ],
  "model": "claude-sonnet-4-6",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 15,
    "output_tokens": 10
  }
}

错误响应示例

Anthropic 形态的错误响应同样使用标准 error 结构:

{
  "error": {
    "message": "API key spending limit exceeded.",
    "type": "spending_limit_exceeded",
    "code": "spending_limit_exceeded"
  }
}
{
  "error": {
    "message": "Rate limit exceeded. Please retry after the period indicated in the Retry-After header.",
    "type": "rate_limit_exceeded",
    "code": "rate_limit_exceeded"
  }
}

图片输入示例

对于支持视觉能力的 Claude 模型,请将图片放在 messages[].content 中,作为结构化图片内容块传入。

{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "请描述这张图片。"
        },
        {
          "type": "image",
          "source": {
            "type": "url",
            "url": "https://example.com/demo.jpg"
          }
        }
      ]
    }
  ]
}
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "请描述这张图片。"
        },
        {
          "type": "image",
          "source": {
            "type": "base64",
            "media_type": "image/jpeg",
            "data": "/9j/4AAQSkZJRgABAQ..."
          }
        }
      ]
    }
  ]
}

扩展思考示例

message = client.messages.create(
    model="claude-opus-4-6",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 10000
    },
    messages=[{"role": "user", "content": "Solve this math problem..."}]
)

for block in message.content:
    if block.type == "thinking":
        print(f"Thinking: {block.thinking}")
    elif block.type == "text":
        print(f"Response: {block.text}")