跳转至

Anthropic Messages API

请求格式

1
2
3
4
5
6
7
8
9
const response = await anthropic.messages.create({
  model: "claude-haiku-4-5-20251001",
  max_tokens: 4096,
  system: "You are a helpful assistant.",
  messages: [
    { role: "user", content: "Hello" }
  ],
  tools: [...]  // 可选:工具定义列表
});

响应格式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{
  id: "msg_abc123",
  type: "message",
  role: "assistant",
  content: [
    { type: "text", text: "Hello! How can I help?" }
  ],
  stop_reason: "end_turn",  // "end_turn" | "tool_use" | "max_tokens"
  usage: {
    input_tokens: 12,
    output_tokens: 23
  }
}

当 LLM 想使用工具时

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{
  role: "assistant",
  content: [
    { type: "text", text: "I'll read that file." },
    {
      type: "tool_use",
      id: "toolu_abc123",
      name: "read_file",
      input: { path: "./hello.js" }
    }
  ],
  stop_reason: "tool_use"
}

返回工具结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Harness 构造的消息(不是用户发的)
{
  role: "user",
  content: [
    {
      type: "tool_result",
      tool_use_id: "toolu_abc123",
      content: "console.log('hello');"
    }
  ]
}

参考链接