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

# Create a chat completion

发送请求以获取给定聊天对话的模型响应。支持流式和非流式模式。兼容 OpenAI Chat Completions API 格式。

## 认证

<ParamField header="Authorization" type="string" required>
  Bearer 令牌。在 Authorization 请求头中使用您的 API 密钥作为 Bearer 令牌。

  格式：`Bearer <SUNRA_KEY>`
</ParamField>

## 请求

此端点接受一个 JSON 对象。

<ParamField body="messages" type="object[]" required>
  对话的消息列表。

  <Expandable title="属性">
    <ParamField body="role" type="string" required>
      消息作者的角色。支持的值：`system`、`user`、`assistant`、`tool`。
    </ParamField>

    <ParamField body="content" type="string | object[]" required>
      消息的内容。可以是字符串或多模态输入的内容部分数组。
    </ParamField>

    <ParamField body="name" type="string">
      参与者的可选名称。为模型提供信息以区分相同角色的不同参与者。
    </ParamField>

    <ParamField body="tool_calls" type="object[]">
      模型生成的工具调用，例如函数调用。仅出现在 `assistant` 消息中。
    </ParamField>

    <ParamField body="tool_call_id" type="string">
      此消息所响应的工具调用。仅出现在 `tool` 消息中。
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="model" type="string" required>
  用于补全的模型。在 [sunra.ai/models](https://sunra.ai/models) 浏览可用模型。
</ParamField>

<ParamField body="provider" type="object">
  可选的 Provider 路由偏好。省略时使用自动路由。支持的字段和 Provider 查询方式见 [Provider 路由](/zh-Hans/llm/provider-routing)。
</ParamField>

<ParamField body="stream" type="boolean" default={false}>
  如果设置为 `true`，将以服务器发送事件（SSE）的方式发送部分消息增量。流式请求受空闲超时与生命周期上限约束，见[输出上限与流生命周期](/zh-Hans/llm/limits#流生命周期)。
</ParamField>

<ParamField body="max_completion_tokens" type="integer">
  补全中生成的最大令牌数，取代 `max_tokens` 成为推荐参数。在不支持该字段的 provider 上，网关会把它翻译为 `max_tokens`；两者同时传入时取较小者。见[输出上限](/zh-Hans/llm/limits)。
</ParamField>

<ParamField body="max_tokens" type="integer">
  补全中生成的最大令牌数。输入令牌和生成令牌的总长度受模型上下文长度的限制。超过模型自身输出上限的值会返回 `400`，而不会被静默削平。
</ParamField>

<ParamField body="temperature" type="number" default={1}>
  采样温度，介于 0 到 2 之间。较高的值（如 0.8）使输出更随机，较低的值（如 0.2）使其更集中和确定性。
</ParamField>

<ParamField body="top_p" type="number" default={1}>
  核采样参数（0-1）。温度采样的替代方案，模型会考虑具有 top\_p 概率质量的令牌。
</ParamField>

<ParamField body="frequency_penalty" type="number" default={0}>
  介于 -2.0 和 2.0 之间的数字。正值会根据新令牌在文本中的现有频率进行惩罚，降低模型逐字重复相同内容的可能性。
</ParamField>

<ParamField body="presence_penalty" type="number" default={0}>
  介于 -2.0 和 2.0 之间的数字。正值会根据新令牌是否出现在文本中进行惩罚，增加模型谈论新话题的可能性。
</ParamField>

<ParamField body="stop" type="string | string[]">
  最多 4 个序列，API 将在这些序列处停止生成更多令牌。
</ParamField>

<ParamField body="n" type="integer" default={1}>
  为每条输入消息生成多少个聊天补全选择。
</ParamField>

<ParamField body="logprobs" type="boolean" default={false}>
  是否返回输出令牌的对数概率。如果为 true，则返回消息内容中每个输出令牌的对数概率。
</ParamField>

<ParamField body="top_logprobs" type="integer">
  一个介于 0 到 20 之间的整数，指定在每个令牌位置返回最可能的令牌数量。使用此参数时，`logprobs` 必须设置为 `true`。
</ParamField>

<ParamField body="response_format" type="object">
  指定模型必须输出的格式的对象。

  <Expandable title="属性">
    <ParamField body="type" type="string" required>
      响应格式的类型。支持的值：`text`、`json_object`、`json_schema`。
    </ParamField>

    <ParamField body="json_schema" type="object">
      JSON Schema 对象。当类型为 `json_schema` 时必填。
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="seed" type="integer">
  如果指定，系统将尽最大努力进行确定性采样，使得具有相同种子和参数的重复请求应返回相同的结果。
</ParamField>

<ParamField body="tools" type="object[]">
  模型可以调用的工具列表。目前仅支持函数作为工具。

  <Expandable title="属性">
    <ParamField body="type" type="string" required>
      工具的类型。目前仅支持 `function`。
    </ParamField>

    <ParamField body="function" type="object" required>
      函数定义。

      <Expandable title="属性">
        <ParamField body="name" type="string" required>
          要调用的函数名称。
        </ParamField>

        <ParamField body="description" type="string">
          函数功能的描述。
        </ParamField>

        <ParamField body="parameters" type="object">
          函数接受的参数，以 JSON Schema 对象描述。
        </ParamField>

        <ParamField body="strict" type="boolean" default={false}>
          是否启用严格的 schema 遵循。
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="tool_choice" type="string | object">
  控制模型调用哪个（如果有的话）工具。`none` 表示模型不会调用任何工具。`auto` 表示模型可以在生成消息或调用工具之间选择。`required` 表示模型必须调用一个或多个工具。也可以通过 `{"type": "function", "function": {"name": "my_function"}}` 指定特定函数。
</ParamField>

<ParamField body="parallel_tool_calls" type="boolean" default={true}>
  是否在工具使用期间启用并行函数调用。
</ParamField>

<ParamField body="user" type="string">
  代表您的最终用户的唯一标识符，可帮助监控和检测滥用行为。
</ParamField>

## 响应

成功的聊天补全响应。

<ResponseField name="id" type="string">
  聊天补全的唯一标识符。
</ResponseField>

<ResponseField name="object" type="string">
  对象类型。始终为 `chat.completion`。
</ResponseField>

<ResponseField name="created" type="integer">
  聊天补全创建时的 Unix 时间戳（秒）。
</ResponseField>

<ResponseField name="model" type="string">
  用于聊天补全的模型。
</ResponseField>

<ResponseField name="choices" type="object[]">
  聊天补全选择列表。如果 `n` 大于 1，则可以有多个选择。

  <Expandable title="属性">
    <ResponseField name="index" type="integer">
      选择在列表中的索引。
    </ResponseField>

    <ResponseField name="message" type="object">
      模型生成的聊天补全消息。

      <Expandable title="属性">
        <ResponseField name="role" type="string">
          此消息作者的角色。始终为 `assistant`。
        </ResponseField>

        <ResponseField name="content" type="string | null">
          消息的内容。
        </ResponseField>

        <ResponseField name="tool_calls" type="object[]">
          模型生成的工具调用，例如函数调用。

          <Expandable title="属性">
            <ResponseField name="id" type="string">
              工具调用的 ID。
            </ResponseField>

            <ResponseField name="type" type="string">
              工具的类型。目前仅支持 `function`。
            </ResponseField>

            <ResponseField name="function" type="object">
              模型调用的函数。

              <Expandable title="属性">
                <ResponseField name="name" type="string">
                  要调用的函数名称。
                </ResponseField>

                <ResponseField name="arguments" type="string">
                  调用函数的参数，由模型以 JSON 格式生成。
                </ResponseField>
              </Expandable>
            </ResponseField>
          </Expandable>
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="finish_reason" type="string">
      模型停止生成令牌的原因。可以是 `stop`、`length`、`tool_calls` 或 `content_filter`。
    </ResponseField>

    <ResponseField name="logprobs" type="object | null">
      该选择的对数概率信息。
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usage" type="object">
  补全请求的使用统计。

  <Expandable title="属性">
    <ResponseField name="prompt_tokens" type="integer">
      提示中的令牌数。
    </ResponseField>

    <ResponseField name="completion_tokens" type="integer">
      生成的补全中的令牌数。
    </ResponseField>

    <ResponseField name="total_tokens" type="integer">
      请求中使用的总令牌数（提示 + 补全）。
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="system_fingerprint" type="string | null">
  此指纹表示模型运行的后端配置。可与 `seed` 参数一起使用，以了解后端何时发生了更改。
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api-llm.sunra.ai/v1/chat/completions \
    -H "Authorization: Bearer <SUNRA_KEY>" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "google/gemini-2.5-flash",
      "messages": [
        {
          "role": "system",
          "content": "You are a helpful assistant."
        },
        {
          "role": "user",
          "content": "What is the capital of France?"
        }
      ]
    }'
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api-llm.sunra.ai/v1/chat/completions",
      headers={
          "Authorization": "Bearer <SUNRA_KEY>",
          "Content-Type": "application/json"
      },
      json={
          "model": "google/gemini-2.5-flash",
          "messages": [
              {"role": "system", "content": "You are a helpful assistant."},
              {"role": "user", "content": "What is the capital of France?"}
          ]
      }
  )
  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api-llm.sunra.ai/v1/chat/completions", {
    method: "POST",
    headers: {
      "Authorization": "Bearer <SUNRA_KEY>",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      model: "google/gemini-2.5-flash",
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "What is the capital of France?" }
      ]
    })
  });
  const data = await response.json();
  console.log(data);
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "chatcmpl-abc123",
    "object": "chat.completion",
    "created": 1677652288,
    "model": "google/gemini-2.5-flash",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "The capital of France is Paris."
        },
        "finish_reason": "stop",
        "logprobs": null
      }
    ],
    "system_fingerprint": "fp_44709d6fcb",
    "usage": {
      "prompt_tokens": 25,
      "completion_tokens": 8,
      "total_tokens": 33
    }
  }
  ```
</ResponseExample>
