> ## Documentation Index
> Fetch the complete documentation index at: https://docs-vip.apigo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude 结构化输出示例

> Claude 结构化输出与 JSON mode 最佳实践示例。

## 推荐 endpoint

* [Claude /v1/messages](/api-reference/endpoints/claude/text)

## 最小请求

```json theme={null}
{
  "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 示例

```bash theme={null}
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 示例

```python theme={null}
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 示例

```js theme={null}
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”
