Source: https://wiki.niceai.dev/guide/api/anthropic-messages

# Anthropic Messages 接口

调用 Claude 原生接口时，请求 `POST https://api.niceai.dev/v1/messages`，请求头带上 `x-api-key` 和 `anthropic-version`，请求体必须包含 `model`、`max_tokens` 和 `messages`。使用 SDK 时 Base URL 只填 `https://api.niceai.dev`。

## 请求示例

**-group**

```bash [curl]
curl https://api.niceai.dev/v1/messages \
  -H "x-api-key: $NICEAI_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<模型名，见模型广场>",
    "max_tokens": 1024,
    "system": "你是一个简洁的助手。",
    "messages": [{"role": "user", "content": "你好"}]
  }'
```

```python [Python]
import os
import anthropic

client = anthropic.Anthropic(base_url="https://api.niceai.dev", api_key=os.environ["NICEAI_API_KEY"])

msg = client.messages.create(
    model="<模型名，见模型广场>",
    max_tokens=1024,
    system="你是一个简洁的助手。",
    messages=[{"role": "user", "content": "你好"}],
)
print(msg.content[0].text)
```

```ts [TypeScript]
import Anthropic from '@anthropic-ai/sdk'

const client = new Anthropic({ baseURL: 'https://api.niceai.dev', apiKey: process.env.NICEAI_API_KEY })

const msg = await client.messages.create({
  model: '<模型名，见模型广场>',
  max_tokens: 1024,
  system: '你是一个简洁的助手。',
  messages: [{ role: 'user', content: '你好' }],
})
console.log(msg.content)
```



## 请求头

| 请求头 | 说明 |
| --- | --- |
| `x-api-key` | NiceAI 密钥。Claude Code 用 `ANTHROPIC_AUTH_TOKEN` 时发送的是 `Authorization: Bearer`，两种写法都可以 |
| `anthropic-version` | 接口版本，目前填 `2023-06-01` |
| `anthropic-beta` | 可选，开启测试中的功能，是否可用取决于上游 |

## 常用参数

| 参数 | 说明 |
| --- | --- |
| `model` | 必填。模型名以 [模型广场](https://niceai.dev/model-plaza) 为准 |
| `max_tokens` | 必填。最大输出 token 数 |
| `messages` | 必填。`user` 与 `assistant` 交替的对话历史 |
| `system` | 系统提示词，放在顶层而不是 `messages` 里 |
| `stream` | 设为 `true` 时流式返回，见 [流式输出](https://wiki.niceai.dev/guide/api/streaming) |
| `tools` | 工具定义，见 [工具调用](https://wiki.niceai.dev/guide/api/tools) |
| `thinking` | 扩展思考，例如 `{"type": "enabled", "budget_tokens": 2048}`，需模型支持 |
| `cache_control` | 写在内容块上，开启提示词缓存，见 [提示词缓存是怎么省钱的](https://wiki.niceai.dev/guide/tech/prompt-caching) |

## 和 Chat Completions 的主要区别

| | Anthropic Messages | OpenAI Chat Completions |
| --- | --- | --- |
| 系统提示 | 顶层 `system` 字段 | `messages` 里 `role: system` |
| 输出上限 | `max_tokens` 必填 | 可选 |
| 回复内容 | `content` 是内容块数组 | `choices[0].message.content` 字符串 |
| 用量字段 | `usage.input_tokens` / `output_tokens`，另有缓存读写字段 | `usage.prompt_tokens` / `completion_tokens` |

## 常见问题

### 返回 404？

SDK 的 Base URL 不要加 `/v1`；直接用 curl 时完整路径才是 `/v1/messages`。

### 返回 401？

确认密钥分组为 Claude，并且只设置了一种鉴权方式。

### 返回 400 提示缺少 max_tokens？

Messages 接口必须传 `max_tokens`。

## 下一步

- [Anthropic SDK 接入](https://wiki.niceai.dev/guide/clients/anthropic-sdk)
- [Claude Code 接入](https://wiki.niceai.dev/guide/claude-code)
- [Claude Code 为什么输入 token 多](https://wiki.niceai.dev/guide/tech/claude-code-input-tokens)
