跳转到主要内容

推荐 endpoint

最小请求

{
  "model": "claude-sonnet-4-20250514",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "从这段文本中提取订单号和金额,并且只返回 JSON:订单 A-1024,金额 99.5 美元。"
        }
      ]
    },
    {
      "role": "assistant",
      "content": [{ "type": "text", "text": "{" }]
    }
  ]
}

cURL 示例

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "从这段文本中提取订单号和金额,并且只返回 JSON:订单 A-1024,金额 99.5 美元。"
          }
        ]
      },
      {
        "role": "assistant",
        "content": [{ "type": "text", "text": "{" }]
      }
    ]
  }'

Python 示例

import json
from anthropic import Anthropic

client = Anthropic(api_key="<ANTHROPIC_API_KEY>")

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "从这段文本中提取订单号和金额,并且只返回 JSON:订单 A-1024,金额 99.5 美元。",
                }
            ],
        },
        {
            "role": "assistant",
            "content": [{"type": "text", "text": "{"}],
        },
    ],
)

payload = "{" + response.content[0].text
print(json.loads(payload))

Node.js 示例

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const response = await client.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "text",
          text: "从这段文本中提取订单号和金额,并且只返回 JSON:订单 A-1024,金额 99.5 美元。"
        }
      ]
    },
    {
      role: "assistant",
      content: [{ type: "text", text: "{" }]
    }
  ]
});

const payload = `{${response.content[0].text}`;
console.log(JSON.parse(payload));

最佳实践

  • 按 Anthropic 的 JSON mode 建议,明确写出目标结构
  • 需要高一致性时,用 assistant 预填充约束输出起手式
  • 复杂结构优先加 few-shot,而不是只写一句“返回 JSON”