# Anthropic 兼容接口

https://modelportal.ai/docs/api-anthropic?lang=zh

基础地址 `https://modelportal.ai`，鉴权 `x-api-key: YOUR_API_KEY` 或 `Authorization: Bearer YOUR_API_KEY`，请求头还要带 `anthropic-version`（如 `2023-06-01`）。请求与响应格式与 Anthropic Messages API 一致。旧地址 `/anthropic/*` 返回 410 `request.endpoint_moved`。

## POST /v1/messages

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `model` | string | 是 | 模型 ID 或别名，可以是目录里任意文本模型 |
| `max_tokens` | integer | 是 | 最大输出 |
| `messages` | array | 是 | 对话消息，支持文本、图片、`tool_use`、`tool_result` 和 thinking 块 |
| `system` | string 或 array | 否 | 系统提示，内容块可带 `cache_control` |
| `stream` | boolean | 否 | 为 `true` 时以 SSE 返回，事件与官方一致，以 `message_stop` 结束 |
| `thinking` | object | 否 | 推理控制，见[推理控制](/docs/reasoning) |
| `tools`、`tool_choice` | — | 否 | 工具调用 |
| `temperature`、`top_p`、`top_k` | number | 否 | 采样参数 |
| `metadata.user_id` | string | 否 | 当作会话标识用于会话亲和，转发前删除 |

路由偏好用请求头 `X-ModelPortal-Provider-Preferences` 传。`anthropic-beta` 请求头会转发给上游。

```json
{
  "id": "msg_...",
  "type": "message",
  "role": "assistant",
  "model": "MODEL_ID",
  "content": [{"type": "text", "text": "你好！"}],
  "stop_reason": "end_turn",
  "usage": {"input_tokens": 9, "output_tokens": 4, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cost": 0.000013},
  "provider": "PROVIDER_ID",
  "attempts": [{"provider": "PROVIDER_ID", "endpoint": "ENDPOINT_ID", "status": 200, "cost": 0.000013}]
}
```

`usage` 是计费用量：`input_tokens` 不含缓存，缓存写入与读取分列，`output_tokens` 含推理。`usage.cost` 是这次的扣费（USD），`provider`、`attempts` 是承接的供应商和每次尝试；流式时这三项写在 `message_delta` 事件里。响应头见[接口概览](/docs/api-overview)。

## POST /v1/messages/count_tokens

计算输入 token 数，不计费、不预留余额。字段同 `/v1/messages`，只需要 `model` 和 `messages`。

## GET /v1/models

带 `anthropic-version` 请求头时，按 Anthropic 格式返回这把密钥能调用的模型。

## 错误

错误体为 `{"type": "error", "error": {"type", "message"}}`，没有机器可读的错误码：

| HTTP | `error.type` | 对应的平台错误码 |
| --- | --- | --- |
| 400 | `invalid_request_error` | `invalid_request`、`unsupported_parameter` |
| 401 | `authentication_error` | `invalid_api_key`、`key_inactive` |
| 402 | `billing_error` | `insufficient_balance`、`budget_exceeded` |
| 403 | `permission_error` | `key_restricted`、`request_blocked`、`region_restricted`、`verification_required` |
| 404 / 410 | `not_found_error` | `model_not_found`、`model_retired`、`request.endpoint_moved` |
| 422 | `invalid_request_error` | `no_eligible_endpoint`，`error.excluded` 列出排除原因 |
| 429 | `rate_limit_error` | `rate_limited`、`capacity_exhausted` |
| 502 | `api_error` | `upstream_failed` |

响应头 `x-should-retry` 为 `true`（429 与 5xx）时可以退避重试。完整错误码见[常见错误](/docs/errors)。
