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

# 建立聊天補全

> 為聊天訊息建立補全

## 請求本文

<ParamField body="model" type="string" required>
  要使用的模型 ID。可用選項請參閱 [Models](https://tokenlab.sh/zh-TW/models)。
</ParamField>

<ParamField body="messages" type="array" required>
  組成對話的一系列訊息。

  每個訊息物件包含：

  * `role` (string): `system`, `user`, 或 `assistant`
  * `content` (string | array): 訊息內容

  當 `content` 為陣列時，TokenLab 支援相容模型的結構化多模態區塊：

  * text: `{ "type": "text", "text": "..." }`
  * 圖片: `{ "type": "image_url", "image_url": { "url": "https://..." } }`
  * 影片: `{ "type": "video_url", "video_url": { "url": "https://..." } }`
  * 音訊: `{ "type": "audio_url", "audio_url": { "url": "https://..." } }`

  對於多模態生產流量，建議使用公開的 `https` URL。TokenLab 會將這些媒體區塊轉換為路由至實體模型所需的供應商專屬請求格式。
</ParamField>

<ParamField body="temperature" type="number" default="1">
  介於 0 到 2 的取樣溫度。較高的值會使輸出更具隨機性。
</ParamField>

<ParamField body="max_tokens" type="integer">
  要生成的最大 token 數量。
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  若為 true，部分訊息差異將會以 SSE 事件發送。
</ParamField>

<ParamField body="stream_options" type="object">
  串流選項。設定 `include_usage: true` 以在串流分片中接收 token 使用資訊。
</ParamField>

<ParamField body="top_p" type="number" default="1">
  Nucleus 取樣參數。建議調整此參數或 `temperature`，而非兩者同時調整。
</ParamField>

<ParamField body="frequency_penalty" type="number" default="0">
  數值介於 -2.0 到 2.0。正值會懲罰重複出現的 token。
</ParamField>

<ParamField body="presence_penalty" type="number" default="0">
  數值介於 -2.0 到 2.0。正值會懲罰已出現在文字中的 token。
</ParamField>

<ParamField body="stop" type="string | array">
  最多 4 個序列，API 在遇到這些序列時會停止生成 token。
</ParamField>

<ParamField body="tools" type="array">
  模型可能會呼叫的一組工具（函式呼叫）。
</ParamField>

<ParamField body="tool_choice" type="string | object">
  控制模型如何使用工具。選項：`auto`、`none`、`required`，或指定的工具物件。
</ParamField>

<ParamField body="parallel_tool_calls" type="boolean" default="true">
  是否啟用平行函式呼叫。設為 false 則依序呼叫函式。
</ParamField>

<ParamField body="max_completion_tokens" type="integer">
  補全的最大 token 數量。為 `max_tokens` 的替代方案，對於較新的具推理能力的模型族群較有用。
</ParamField>

<ParamField body="reasoning_effort" type="string">
  針對具推理能力模型的推理努力等級。選項：`low`、`medium`、`high`。
</ParamField>

<ParamField body="seed" type="integer">
  用於確定性取樣的隨機種子。
</ParamField>

<ParamField body="n" type="integer" default="1">
  要生成的補全數量（1-128）。
</ParamField>

<ParamField body="logprobs" type="boolean">
  是否回傳對數機率（log probabilities）。
</ParamField>

<ParamField body="top_logprobs" type="integer">
  要回傳的前 N 個對數機率（0-20）。需要 `logprobs: true`。
</ParamField>

<ParamField body="top_k" type="integer">
  Top-K 取樣參數（適用於 Anthropic/Gemini 模型）。
</ParamField>

<ParamField body="response_format" type="object">
  回應格式規格。使用 `{"type": "json_object"}` 以啟用 JSON 模式。將 `{"type": "json_schema", "json_schema": {...}}` 視為依據所選模型與路由行為的最佳努力路徑。
</ParamField>

<ParamField body="logit_bias" type="object">
  修改指定 token 出現機率的偏好。將 token ID（以字串）對映到 -100 到 100 的偏差值。
</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="array">
  補全選項清單。

  每個選項包含：

  * `index` (integer): 選項的索引
  * `message` (object): 生成的訊息
  * `finish_reason` (string): 模型停止的原因（`stop`、`length`、`tool_calls`）
</ResponseField>

<ResponseField name="usage" type="object">
  token 使用統計。

  * `prompt_tokens` (integer): prompt 中的 token 數
  * `completion_tokens` (integer): 補全中的 token 數
  * `total_tokens` (integer): 使用的總 token 數
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.tokenlab.sh/v1/chat/completions" \
    -H "Authorization: Bearer sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-4o",
      "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
      ],
      "temperature": 0.7,
      "max_tokens": 1000
    }'
  ```

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

  client = OpenAI(
      api_key="sk-your-api-key",
      base_url="https://api.tokenlab.sh/v1"
  )

  response = client.chat.completions.create(
      model="gpt-4o",
      messages=[
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"}
      ],
      temperature=0.7,
      max_tokens=1000
  )

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

  ```javascript JavaScript theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
    apiKey: 'sk-your-api-key',
    baseURL: 'https://api.tokenlab.sh/v1'
  });

  const response = await client.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      { role: 'user', content: 'Hello!' }
    ],
    temperature: 0.7,
    max_tokens: 1000
  });

  console.log(response.choices[0].message.content);
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init('https://api.tokenlab.sh/v1/chat/completions');

  curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => [
          'Content-Type: application/json',
          'Authorization: Bearer sk-your-api-key'
      ],
      CURLOPT_POSTFIELDS => json_encode([
          'model' => 'gpt-4o',
          'messages' => [
              ['role' => 'system', 'content' => 'You are a helpful assistant.'],
              ['role' => 'user', 'content' => 'Hello!']
          ],
          'temperature' => 0.7,
          'max_tokens' => 1000
      ])
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($response, true);
  echo $data['choices'][0]['message']['content'];
  ```
</RequestExample>

## 多模態範例

```json theme={null}
{
  "model": "gemini-2.5-pro",
  "messages": [
    {
      "role": "user",
      "content": [
        { "type": "text", "text": "Describe this video briefly." },
        { "type": "video_url", "video_url": { "url": "https://example.com/demo.mp4" } }
      ]
    }
  ],
  "max_tokens": 64
}
```

<ResponseExample>
  ```json Response theme={null}
  {
    "id": "chatcmpl-abc123",
    "object": "chat.completion",
    "created": 1706000000,
    "model": "gpt-4o",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "Hello! How can I help you today?"
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 20,
      "completion_tokens": 9,
      "total_tokens": 29
    }
  }
  ```
</ResponseExample>
