> ## 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 令牌。

  Format: `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="stream" type="boolean" default={false}>
  如果設為 `true`，將以伺服器傳送事件（SSE）的方式傳送部分訊息增量。
</ParamField>

<ParamField body="max_tokens" type="integer">
  補全中生成的最大令牌數。輸入令牌和生成令牌的總長度受模型上下文長度的限制。
</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": "openai/gpt-4o",
      "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": "openai/gpt-4o",
          "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: "openai/gpt-4o",
      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": "openai/gpt-4o",
    "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>
