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

# POST /chat/completions

> OpenAI Chat Completions 兼容层 —— 每个模型都套同一种 OpenAI 形状请求。

OpenAI 原生协议。逐字讲 Chat Completions，所以任何为 Chat Completions API
构建的客户端（OpenAI Python / Node SDK、LangChain 默认、LlamaIndex 等）都能
不改代码直接用 —— 把 base URL 指向 `https://llm.bytespike.ai/v1`、换 key
即可。非 GPT 模型（Claude、Gemini、DeepSeek、Doubao）在底下被翻译。

## 何时使用

以下情况选这个端点：

* **作为 `openai` SDK 调用的直接替换**（`OpenAI(base_url=…, api_key=…)`）
* **OpenAI 独有的特性** 比如 `response_format: {"type": "json_schema"}` 或 `logprobs`
* **硬编码 OpenAI 形状的框架**

工具调用直接用 OpenAI 的 `tool_calls` 形状。要在 Claude 上用 prompt caching，建议改用 [`/v1/messages`](./claude-messages) —— OpenAI 形状装不下 `cache_control`。

## 请求

```bash theme={null}
curl https://llm.bytespike.ai/v1/chat/completions \
  -H "Authorization: Bearer $BYTESPIKE_API_KEY" \
  -H "content-type: application/json" \
  -d '{
    "model": "gpt-5-4",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Summarize the first chapter of Moby Dick."}
    ],
    "max_tokens": 1024
  }'
```

### 请求头

| Header          | 是否必填 | 说明                                                     |
| --------------- | ---- | ------------------------------------------------------ |
| `Authorization` | 是    | `Bearer sk-byts-…`。（也接受 `x-api-key`，与 `/messages` 对称。） |
| `content-type`  | 是    | `application/json`。                                    |

### Body

| 字段                  | 类型                  | 是否必填 | 说明                                                                           |
| ------------------- | ------------------- | ---- | ---------------------------------------------------------------------------- |
| `model`             | string              | 是    | 模型 slug。目录中任意模型 —— 见 [跨模型路由](#cross-model-routing)。                          |
| `messages`          | array               | 是    | 对话历史。Role：`system`、`user`、`assistant`、`tool`。                                |
| `max_tokens`        | integer             | 否    | 响应长度硬上限。默认值因模型而异。                                                            |
| `temperature`       | number              | 否    | 默认 1.0。                                                                      |
| `top_p`             | number              | 否    | Nucleus sampling。                                                            |
| `n`                 | integer             | 否    | 返回几个生成。默认 1。                                                                 |
| `stream`            | boolean             | 否    | server-sent events。见 [流式](#streaming)。                                       |
| `stop`              | string \| string\[] | 否    | 自定义 stop token。                                                              |
| `presence_penalty`  | number              | 否    | -2.0 到 2.0。                                                                  |
| `frequency_penalty` | number              | 否    | -2.0 到 2.0。                                                                  |
| `response_format`   | object              | 否    | `{"type": "json_object"}` / `{"type": "json_schema", "json_schema": {...}}`。 |
| `tools`             | array               | 否    | Function / 工具定义（见 [工具调用](#tool-calling)）。                                    |
| `tool_choice`       | string \| object    | 否    | `"none"` / `"auto"` / `{"type": "function", "function": {"name": "…"}}`。     |
| `seed`              | integer             | 否    | 确定性采样（best-effort）。                                                          |
| `user`              | string              | 否    | 稳定的终端用户 id —— 转发给模型 + 我方记录用于追溯滥用。                                            |

## 响应

```json theme={null}
{
  "id": "chatcmpl-9aBc…",
  "object": "chat.completion",
  "created": 1716393600,
  "model": "gpt-5-4",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Ishmael, the narrator, signs onto a whaling ship..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 23,
    "completion_tokens": 87,
    "total_tokens": 110
  }
}
```

### 响应字段

| 字段                             | 类型             | 说明                                             |
| ------------------------------ | -------------- | ---------------------------------------------- |
| `id`                           | string         | 服务端生成的 id，前缀 `chatcmpl-`。                      |
| `choices[].message.role`       | string         | 非错误响应恒为 `"assistant"`。                         |
| `choices[].message.content`    | string \| null | 模型发工具调用而非文本时为 `null`。                          |
| `choices[].message.tool_calls` | array          | 模型想调用工具时返回。                                    |
| `choices[].finish_reason`      | string         | `stop`、`length`、`tool_calls`、`content_filter`。 |
| `usage.prompt_tokens`          | integer        | 输入计费 token 数。                                  |
| `usage.completion_tokens`      | integer        | 输出计费 token 数。                                  |
| `usage.total_tokens`           | integer        | 总和。                                            |

### 计费类请求头

与其他端点一致的信封：

```
X-RateLimit-Limit: 50.00
X-RateLimit-Remaining: 42.18
X-RateLimit-Reset: 1716705600
X-Quota-Remaining-Credits: 192.40
```

详见 [API 参考总览](/zh/api-reference/overview#conventions)。

## 流式 \[#streaming]

设 `"stream": true`。响应是 SSE，`data: {json}` 行加结尾 `data: [DONE]`：

```
data: {"id":"chatcmpl-…","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-…","choices":[{"index":0,"delta":{"content":"Ishmael"},"finish_reason":null}]}

…

data: {"id":"chatcmpl-…","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
```

设了 `stream_options: {"include_usage": true}` 时，token 用量会在最后一个非 `[DONE]` 帧里返回。

## 工具调用 \[#tool-calling]

工具遵循 OpenAI 的 `function` 形状。两次请求轮转：

### 第一轮 —— 提供工具

```json theme={null}
{
  "model": "gpt-5-4",
  "messages": [
    {"role": "user", "content": "What's the weather in Tokyo?"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string"}
          },
          "required": ["city"]
        }
      }
    }
  ]
}
```

响应：

```json theme={null}
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"Tokyo\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}
```

注意 `arguments` 是 **JSON 字符串** 而不是对象 —— 这是 OpenAI 的约定。

### 第二轮 —— 回传工具结果

```json theme={null}
{
  "model": "gpt-5-4",
  "messages": [
    {"role": "user", "content": "What's the weather in Tokyo?"},
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_abc",
          "type": "function",
          "function": {"name": "get_weather", "arguments": "{\"city\":\"Tokyo\"}"}
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "call_abc",
      "content": "18°C, partly cloudy"
    }
  ],
  "tools": [ /* same schema */ ]
}
```

## 视觉（image\_url 内容）

通过 `image_url` 内容块发送图像。data URL 和 HTTPS URL 都行；网关把字节直接转发给支持视觉的模型（GPT-5-x、Claude Sonnet/Opus 4.x、Gemini、Doubao Vision）。

```json theme={null}
{
  "model": "gpt-5-4",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "What's in this image?"},
        {
          "type": "image_url",
          "image_url": {
            "url": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
          }
        }
      ]
    }
  ]
}
```

支持该字段的模型上，`detail`（`"low"` / `"high"` / `"auto"`）会被尊重。

## 跨模型路由 \[#cross-model-routing]

本端点的 `model` 字段接受 **任意** ByteSpike 目录模型 —— 网关透明地把 OpenAI 形状翻译成各模型的原生协议：

```json theme={null}
{"model": "gpt-5-4", "messages": [...]}
{"model": "claude-sonnet-4-6", "messages": [...]}
{"model": "gemini-3-5-flash", "messages": [...]}
{"model": "deepseek-v4-pro", "messages": [...]}
{"model": "kimi-k2-6", "messages": [...]}
```

注意：

* `response_format: {"type": "json_schema"}` 需要模型原生支持结构化输出（GPT 4.x+、部分 Gemini Pro 变体）。其他模型会返回 400 `unsupported_feature`。
* `seed` 是 best-effort；跨模型的确定性无法保证。
* `tool_calls.arguments` 不论用哪个模型，恒返回 JSON 字符串 —— 哪怕 Claude 模型内部返回的是结构化 input。

完整目录：[`GET /v1/models`](../utility/v1-models)。按模型计价：[bytespike.ai/pricing](https://bytespike.ai/pricing)。

## 速率限制和配额头

| Header                           | 说明                         |
| -------------------------------- | -------------------------- |
| `x-ratelimit-limit-requests`     | 你的 tier 的 requests/min 上限。 |
| `x-ratelimit-remaining-requests` | 当前窗口内剩余。                   |
| `x-ratelimit-reset-requests`     | 桶充满还需多少秒。                  |
| `x-ratelimit-limit-tokens`       | tokens/min 上限。             |
| `x-ratelimit-remaining-tokens`   | 当前窗口剩余 token 数。            |

## 错误

所有非 2xx 响应 **免费** —— 失败不计费。Body 形状与 OpenAI 的错误信封一致：

```json theme={null}
{
  "error": {
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "message": "You exceeded your current requests-per-minute budget.",
    "param": null
  }
}
```

| Status | `error.type`                                        | 触发                                                                                 |
| ------ | --------------------------------------------------- | ---------------------------------------------------------------------------------- |
| 400    | `invalid_request_error`                             | Body 校验失败。message 指出字段。                                                            |
| 400    | `invalid_request_error`（code `unsupported_model`）   | model slug 不在范围或已下线。                                                               |
| 400    | `invalid_request_error`（code `unsupported_feature`） | 例如对非结构化输出模型用 `response_format: json_schema`。                                       |
| 401    | `authentication_error`                              | key 缺失 / 已撤销。                                                                      |
| 402    | `insufficient_credits`                              | 钱包用尽 —— 去 [console.bytespike.ai/billing](https://console.bytespike.ai/billing) 充值。 |
| 403    | `permission_error`                                  | 范围拒绝、IP 未在白名单、模型受限。                                                                |
| 404    | `not_found_error`                                   | 路径打错或未知 model id。                                                                  |
| 429    | `rate_limit_error`                                  | tier 速率限制。按 `x-ratelimit-reset-*` 退避。                                              |
| 5xx    | `api_error` / `overloaded_error`                    | 上游 provider 问题。免费 + 自动重试信封。                                                        |

## SDK 示例

OpenAI Python SDK，把 base URL 换掉：

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["BYTESPIKE_API_KEY"],
    base_url="https://llm.bytespike.ai/v1",
)

r = client.chat.completions.create(
    model="claude-sonnet-4-6",   # Claude through the OpenAI shape
    messages=[{"role": "user", "content": "Hello!"}],
)
print(r.choices[0].message.content)
```

不需要 fork SDK —— 我方就是用上游 `openai` 包做的测试。
