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

# 创建聊天补全

> 使用消息、流式输出、工具、视觉与 JSON 输出生成兼容 OpenAI 的 Chat Completion。

根据有序消息列表创建模型响应。对于已有 OpenAI SDK 与消息式应用，本端点具有最广泛的兼容性。

## 端点

```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
POST https://api.yelu.ai/v1/chat/completions
```

## 请求头

<ParamField header="Authorization" type="string" required>格式为 `Bearer $YELU_API_KEY`。</ParamField>
<ParamField header="Content-Type" type="string" required>必须为 `application/json`。</ParamField>

## 请求体

<ParamField body="model" type="string" required>[模型列表](/zh/api-reference/models)返回的模型 ID。</ParamField>
<ParamField body="messages" type="array" required>有序对话消息。每项包含 `role` 与 `content`；多模态模型也可接受内容数组。</ParamField>
<ParamField body="temperature" type="number" default="1">采样温度，范围 `0` 到 `2`。通常只调整 `temperature` 或 `top_p` 其中一个。</ParamField>
<ParamField body="top_p" type="number" default="1">核采样概率，范围 `0` 到 `1`。</ParamField>
<ParamField body="max_completion_tokens" type="integer">允许生成的最大 Token 数。</ParamField>
<ParamField body="stream" type="boolean" default="false">设为 `true` 时返回 SSE 增量 Chunk。</ParamField>
<ParamField body="stream_options" type="object">流式选项；兼容模型可通过 `include_usage` 请求最终用量 Chunk。</ParamField>
<ParamField body="stop" type="string | string[]">遇到指定序列时停止生成。</ParamField>
<ParamField body="presence_penalty" type="number" default="0">范围 `-2` 到 `2`，按 Token 是否出现调整重复倾向。</ParamField>
<ParamField body="frequency_penalty" type="number" default="0">范围 `-2` 到 `2`，按 Token 出现频率调整重复倾向。</ParamField>
<ParamField body="tools" type="array">模型可以请求的函数定义。执行前必须校验参数。</ParamField>
<ParamField body="tool_choice" type="string | object">`none`、`auto`、`required` 或指定函数。</ParamField>
<ParamField body="response_format" type="object">在兼容模型上请求 JSON Object 或 JSON Schema。</ParamField>
<ParamField body="reasoning_effort" type="string">兼容推理模型支持 `low`、`medium` 或 `high`。</ParamField>
<ParamField body="user" type="string">稳定且不包含敏感信息的最终用户标识。</ParamField>

## 响应

<ResponseField name="id" type="string" required>补全请求唯一 ID。</ResponseField>
<ResponseField name="object" type="string" required>非流式为 `chat.completion`，流式 Chunk 为 `chat.completion.chunk`。</ResponseField>
<ResponseField name="created" type="integer" required>创建时间的 Unix 时间戳。</ResponseField>
<ResponseField name="model" type="string" required>实际生成响应的模型。</ResponseField>
<ResponseField name="choices" type="array" required>候选结果，包含 `index`、助手 `message` 和 `finish_reason`。</ResponseField>
<ResponseField name="usage" type="object">Token 用量，通常包含 `prompt_tokens`、`completion_tokens` 与 `total_tokens`。</ResponseField>

<RequestExample>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl https://api.yelu.ai/v1/chat/completions \
    -H "Authorization: Bearer $YELU_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model":"gpt-4o-mini",
      "messages":[
        {"role":"system","content":"你是一名简洁的技术编辑。"},
        {"role":"user","content":"改写：API 应以可预测的方式失败。"}
      ],
      "temperature":0.2,
      "max_completion_tokens":80
    }'
  ```

  ```javascript JavaScript (Fetch) theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await fetch('https://api.yelu.ai/v1/chat/completions', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.YELU_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [
        { role: 'system', content: '你是一名简洁的技术编辑。' },
        { role: 'user', content: '改写：API 应以可预测的方式失败。' },
      ],
      temperature: 0.2,
      max_completion_tokens: 80,
    }),
  });
  if (!response.ok) throw new Error(await response.text());
  console.log((await response.json()).choices[0].message.content);
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import os
  import requests

  response = requests.post(
      "https://api.yelu.ai/v1/chat/completions",
      headers={"Authorization": f"Bearer {os.environ['YELU_API_KEY']}"},
      json={
          "model": "gpt-4o-mini",
          "messages": [
              {"role": "system", "content": "你是一名简洁的技术编辑。"},
              {"role": "user", "content": "改写：API 应以可预测的方式失败。"},
          ],
          "temperature": 0.2,
          "max_completion_tokens": 80,
      },
      timeout=60,
  )
  response.raise_for_status()
  print(response.json()["choices"][0]["message"]["content"])
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "id":"chatcmpl_01JYELU8D1",
    "object":"chat.completion",
    "created":1783900800,
    "model":"gpt-4o-mini",
    "choices":[{"index":0,"message":{"role":"assistant","content":"API 应返回一致且定义明确的错误。"},"finish_reason":"stop"}],
    "usage":{"prompt_tokens":29,"completion_tokens":10,"total_tokens":39}
  }
  ```

  ```json 400 theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {"error":{"message":"The model field is required.","type":"invalid_request_error","param":"model","code":"missing_required_parameter"}}
  ```
</ResponseExample>

## 错误码

| 状态码         | 类型或 Code                | 含义                 |
| ----------- | ----------------------- | ------------------ |
| `400`       | `invalid_request_error` | 消息、字段、JSON 或模型能力无效 |
| `401`       | `authentication_error`  | Key 缺失或无效          |
| `403`       | `permission_denied`     | 无权使用模型或操作          |
| `404`       | `model_not_found`       | 模型不可用，应刷新模型列表      |
| `413`       | `request_too_large`     | 上下文或请求体过大          |
| `429`       | `rate_limit_error`      | 达到请求限制             |
| `500`–`504` | `server_error`          | 网关或上游临时失败          |

<CardGroup cols={2}>
  <Card title="流式输出" icon="activity" href="/zh/guides/streaming">安全解析 SSE Chunk。</Card>
  <Card title="函数调用" icon="wrench" href="/zh/guides/function-calling">把聊天模型连接到应用工具。</Card>
</CardGroup>
