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

# Create Chat Completion

> 使用 OpenAI 兼容的请求与响应格式调用聊天模型。

**Endpoint:** `POST /chat/completions`

大多数模型 API 集成都应使用这个接口。发送 `model` ID 和 `messages` 数组，YouRouter 会返回 OpenAI 兼容的 completion 响应。对于支持视觉能力的模型，这个接口也能在 `messages[].content` 中接收图片输入。

## 请求

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": "Reply with exactly: connected"
      }
    ]
  }'
```

## OpenAI SDK

<CodeGroup>
  ```python Python theme={null}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["YOUROUTER_API_KEY"],
      base_url="https://api.yourouter.ai/v1",
  )

  completion = client.chat.completions.create(
      model="gpt-4o",
      messages=[{"role": "user", "content": "Reply with exactly: connected"}],
  )

  print(completion.choices[0].message.content)
  ```

  ```javascript Node.js theme={null}
  import OpenAI from 'openai';

  const openai = new OpenAI({
    apiKey: process.env.YOUROUTER_API_KEY,
    baseURL: 'https://api.yourouter.ai/v1',
  });

  const completion = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: 'Reply with exactly: connected' }],
  });

  console.log(completion.choices[0].message.content);
  ```
</CodeGroup>

## 请求头

| Header          | 必填 | 说明                                                             |
| --------------- | -- | -------------------------------------------------------------- |
| `Authorization` | 是  | `Bearer <YOUROUTER_API_KEY>`                                   |
| `Content-Type`  | 是  | 使用 `application/json`。                                         |
| `vendor`        | 否  | 使用 `auto` 或省略代表自动路由。也可使用 `openai`、`anthropic`、`google` 等值固定上游。 |

## 请求体参数

<ResponseField name="model" type="string" required>
  要调用的模型 ID，例如 `gpt-4o`、`claude-sonnet-4-20250514` 或 `gemini-2.5-flash`。
</ResponseField>

<ResponseField name="messages" type="array" required>
  有序的对话消息数组。每条消息都包含 `role` 和 `content`。
</ResponseField>

<ResponseField name="stream" type="boolean" default="false">
  若为 true，则以 SSE 分片方式返回结果。
</ResponseField>

<ResponseField name="temperature" type="number">
  在模型支持时，用于控制输出随机性。
</ResponseField>

<ResponseField name="max_tokens" type="integer">
  在模型支持时，用于限制输出 token 数。
</ResponseField>

<ResponseField name="tools" type="array">
  对支持函数调用或工具调用的模型，传入工具定义。
</ResponseField>

## 多模态图片输入

对于支持视觉的模型，请把 `content` 设为块数组，并至少包含一个 `text` 块和一个 `image_url` 块。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Describe this image in one sentence."
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/image.jpg"
            }
          }
        ]
      }
    ]
  }'
```

对于私有图片，可以使用 base64 data URL：

```json theme={null}
{
  "type": "image_url",
  "image_url": {
    "url": "data:image/jpeg;base64,<BASE64_IMAGE>"
  }
}
```

### PDF 文件输入

如果目标模型和上游支持 OpenAI 兼容的文件内容块，可以在 `messages[].content` 中传入 PDF。`file_data` 应是 PDF 原始字节的 base64 编码内容。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "file",
            "file": {
              "filename": "document.pdf",
              "file_data": "<BASE64_PDF>"
            }
          },
          {
            "type": "text",
            "text": "Extract a summary and key conclusions from this PDF."
          }
        ]
      }
    ]
  }'
```

<Note>
  PDF 不是所有模型都支持。若你需要 Gemini 或 Claude 的原生 PDF 能力，请参考 [多模态指南](/zh/guides/multimodal) 中的 provider-native 示例。
</Note>

更多 Gemini 原生和 Claude 原生格式示例，请参考 [多模态指南](/zh/guides/multimodal)。

## 响应

成功响应遵循 OpenAI Chat Completions 结构。

```json theme={null}
{
  "id": "chatcmpl_example",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "connected"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 1,
    "total_tokens": 13
  }
}
```

助手文本通常位于：

```text theme={null}
choices[0].message.content
```

## 上游提供商路由

默认情况下为自动路由：

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}'
```

如果要固定上游提供商，可以发送 `vendor`：

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -H "vendor: openai" \
  -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}'
```

## 流式输出

把 `stream` 设为 `true` 后，可按 SSE 增量返回结果。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "stream": true,
    "messages": [
      {
        "role": "user",
        "content": "Explain model routing in two sentences."
      }
    ]
  }'
```

## 常见错误

| 状态码   | 原因             | 排查方向                             |
| ----- | -------------- | -------------------------------- |
| `400` | 请求体无效或参数不受支持   | 检查 `model`、`messages` 和 JSON 格式。 |
| `401` | API Key 缺失或无效  | 检查 `Authorization` 请求头。          |
| `429` | 命中上游提供商限流或并发限制 | 用退避方式重试，或改用自动路由。                 |
| `500` | 网关或上游提供商错误     | 安全重试，并保留请求 ID 以便支持排查。            |

模型 ID 和固定上游提供商的更多示例，请参考 [模型](/zh/model) 和 [路由指南](/zh/guides/router)。
