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

# 建立對話請求 (OpenAI)

> 通用文字對話介面，支援 OpenAI 相容的大型語言模型生成對話回覆

## 簡介

通用文字對話介面，支援 OpenAI 相容的大型語言模型生成對話回覆。透過統一的 API 介面，您可以呼叫 OpenAI、Claude、DeepSeek、Grok、通義千問等多個主流大型模型。

## 認證

Bearer Token，如 `Bearer sk-xxxxxxxxxx`

## 請求參數

<ParamField body="model" type="string" required>
  模型識別碼，對應模型廣場。

  <Tip>
    mixroute 支援多種模型，完整模型列表見 [模型廣場](https://console.mixroute.ai/models)。
  </Tip>
</ParamField>

<ParamField body="messages" type="array" required>
  對話訊息列表，每個元素包含 `role`（user/system/assistant）和 `content`
</ParamField>

<ParamField body="temperature" type="number">
  隨機性控制，0-2，數值越高回覆越隨機
</ParamField>

<ParamField body="stream" type="boolean">
  是否啟用串流輸出，回傳 SSE 格式的分片資料
</ParamField>

<ParamField body="max_tokens" type="integer">
  最大生成 token 數，控制回覆長度
</ParamField>

<ParamField body="response_format" type="object">
  輸出格式，支援 `text` 或 `json_object` / `json_schema`
</ParamField>

<ParamField body="top_p" type="number">
  核採樣參數，0-1，替代 temperature 使用，數值越低採樣越保守
</ParamField>

<ParamField body="frequency_penalty" type="number">
  頻率懲罰，-2 到 2，正值根據已有頻率減少重複 token
</ParamField>

<ParamField body="presence_penalty" type="number">
  存在懲罰，-2 到 2，正值鼓勵討論新話題
</ParamField>

<ParamField body="stop" type="string | array">
  停止序列，遇到指定字串時停止生成
</ParamField>

<ParamField body="seed" type="integer">
  隨機種子，傳入相同 seed 可使生成結果盡量一致
</ParamField>

<ParamField body="user" type="string">
  最終用戶識別，用於監控和限流
</ParamField>

<ParamField body="n" type="integer">
  每個 prompt 生成的回覆候選數，預設為 1
</ParamField>

<ParamField body="logit_bias" type="object">
  詞元偏置，將 token ID 映射到偏置值（-100 到 100）
</ParamField>

<ParamField body="tools" type="array">
  工具定義列表，每個工具須包含 `type` 和 `function`
</ParamField>

<ParamField body="tool_choice" type="string">
  工具選擇策略：`"auto"` / `"none"` / `"required"`，或指定工具名
</ParamField>

## 基礎範例

<Tabs>
  <Tab title="非串流請求">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "messages": [
          {"role": "system", "content": "你是一個有用的助手"},
          {"role": "user", "content": "請用中文簡要介紹人工智慧"}
        ],
        "temperature": 0.7
      }'
    ```
  </Tab>

  <Tab title="串流請求（SSE）">
    ```bash theme={null}
    curl -N -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "doubao-seed-1-8-251228",
        "stream": true,
        "messages": [
          {"role": "system", "content": "你是一個有用的助手"},
          {"role": "user", "content": "請用中文簡要介紹人工智慧"}
        ]
      }'
    ```
  </Tab>

  <Tab title="Python 範例">
    ```python theme={null}
    from openai import OpenAI

    client = OpenAI(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.mixroute.ai/v1"
    )

    # 非串流
    completion = client.chat.completions.create(
        model="gpt-5.5",
        messages=[
            {"role": "system", "content": "你是一個有用的助手"},
            {"role": "user", "content": "請用中文簡要介紹人工智慧"}
        ],
        temperature=0.7
    )
    print(completion.choices[0].message.content)

    # 串流
    stream = client.chat.completions.create(
        model="doubao-seed-1-8-251228",
        messages=[
            {"role": "user", "content": "請用中文簡要介紹人工智慧"}
        ],
        stream=True
    )
    for chunk in stream:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="")
    ```
  </Tab>
</Tabs>

## 進階功能

<Tabs>
  <Tab title="工具呼叫">
    支援 OpenAI 相容的工具呼叫格式：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "messages": [
          {"role": "user", "content": "上海的天氣怎麼樣？"}
        ],
        "tools": [
          {
            "type": "function",
            "function": {
              "name": "get_weather",
              "description": "根據城市取得天氣資訊",
              "parameters": {
                "type": "object",
                "properties": {
                  "city": {"type": "string"}
                },
                "required": ["city"]
              }
            }
          }
        ],
        "tool_choice": "auto"
      }'
    ```
  </Tab>

  <Tab title="結構化輸出">
    使用 JSON Schema 約束模型輸出格式：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "response_format": {
          "type": "json_schema",
          "json_schema": {
            "name": "Answer",
            "schema": {
              "type": "object",
              "properties": {
                "summary": {"type": "string"}
              },
              "required": ["summary"]
            }
          }
        },
        "messages": [
          {"role": "user", "content": "回傳一個包含 summary 欄位的 JSON"}
        ]
      }'
    ```
  </Tab>

  <Tab title="思考能力">
    <Tabs>
      <Tab title="DeepSeek">
        DeepSeek 系列支援深度思考能力：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "deepseek-v4-pro",
            "messages": [
              {"role": "user", "content": "請分析這道數學題：如果 x^2 + 2x - 3 = 0，求 x 的值"}
            ],
            "temperature": 0.6
          }'
        ```

        回應將包含 `reasoning_content` 欄位展示思考過程。
      </Tab>

      <Tab title="通義千問">
        通義千問 Qwen 系列支援思考能力：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "qwen3.7-max",
            "messages": [
              {"role": "user", "content": "分析一下人工智慧的發展趨勢"}
            ],
            "enable_thinking": true
          }'
        ```
      </Tab>

      <Tab title="GPT-5.6">
        GPT-5.6 系列 (`gpt-5.6-sol` / `gpt-5.6-terra` / `gpt-5.6-luna`) 支援進階推理設定：

        * `reasoning.mode` — 執行模式：`"standard"`（預設）或 `"pro"`。Pro Mode 執行更多推理工作，提升困難任務可靠性
        * `reasoning.effort` — 推理強度：`none` / `low` / `medium` / `high` / `xhigh` / `max`（`max` 為新增檔位）

        ```shellscript theme={null}
        curl https://api.mixroute.ai/v1/responses \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk" \
          -d '{
            "model": "gpt-5.6-luna",
            "reasoning": {
              "mode": "pro",
        	"effort":"max"
            },
            "input": "Analyze the potential risks of this database migration plan."
          }'
        ```
      </Tab>

      <Tab title="Gemini">
        Gemini 2.0 Flash Thinking 支援思考能力：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "gemini-2.0-flash-thinking-exp",
            "messages": [
              {"role": "user", "content": "解釋量子計算的基本原理"}
            ]
          }'
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="通義千問擴展">
    通義千問支援額外的擴展參數：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "qwen3.7-max",
        "messages": [
          {"role": "user", "content": "你好"}
        ],
        "enable_search": true,
        "search_options": {
          "search_strategy": "standard",
          "forced_search": false
        }
      }'
    ```

    | 參數                               | 說明                    |
    | -------------------------------- | --------------------- |
    | `enable_search`                  | 啟用聯網搜尋                |
    | `search_options.search_strategy` | 搜尋策略：`standard`/`pro` |
    | `search_options.forced_search`   | 強制搜尋                  |
  </Tab>

  <Tab title="聯網搜尋">
    <Tabs>
      <Tab title="Claude 搜尋">
        Claude 模型支援聯網搜尋功能：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "claude-sonnet-5",
            "messages": [
              {"role": "user", "content": "今天有什麼重大新聞？"}
            ],
            "tools": [
              {
                "type": "web_search_20250305",
                "name": "web_search",
                "max_uses": 5
              }
            ]
          }'
        ```
      </Tab>

      <Tab title="Grok 搜尋">
        Grok 模型支援即時聯網搜尋：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "grok-3",
            "messages": [
              {"role": "user", "content": "最新的科技新聞有哪些？"}
            ],
            "search_parameters": {
              "mode": "auto",
              "return_citations": true
            }
          }'
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="GPT 檔案輸入">
    GPT 模型支援直接處理檔案內容：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "messages": [
          {
            "role": "user",
            "content": [
              {"type": "text", "text": "請分析這個文件的內容"},
              {
                "type": "file",
                "file": {
                  "url": "https://example.com/document.pdf"
                }
              }
            ]
          }
        ]
      }'
    ```

    支援的檔案類型包括 PDF、Word、Excel、圖片等。

    <Tip>
      模型檔案處理能力有一定差別，請留意選擇支援上傳檔案類型的模型。
    </Tip>
  </Tab>

  <Tab title="Grok 推理">
    Grok 模型支援增強推理能力：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "grok-3-mini",
        "messages": [
          {"role": "user", "content": "分析以下邏輯問題：如果所有A都是B，且所有B都是C，那麼..."}
        ],
        "reasoning_effort": "high"
      }'
    ```

    | reasoning\_effort | 說明        |
    | ----------------- | --------- |
    | `low`             | 快速回應，基礎推理 |
    | `medium`          | 平衡模式      |
    | `high`            | 深度推理，更精確  |
  </Tab>
</Tabs>

## 回應格式

<Tabs>
  <Tab title="非串流回應">
    ```json theme={null}
    {
      "id": "chatcmpl-xxx",
      "object": "chat.completion",
      "created": 1234567890,
      "model": "gpt-5.5",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "回覆內容..."
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 25,
        "completion_tokens": 100,
        "total_tokens": 125
      }
    }
    ```
  </Tab>

  <Tab title="串流回應">
    串流回應使用 Server-Sent Events (SSE) 格式：

    ```text theme={null}
    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-5.5","choices":[{"index":0,"delta":{"role":"assistant","content":"你"},"finish_reason":null}]}

    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-5.5","choices":[{"index":0,"delta":{"content":"好"},"finish_reason":null}]}

    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-5.5","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

    data: [DONE]
    ```

    每個 chunk 包含增量內容，最後以 `[DONE]` 結束。
  </Tab>
</Tabs>

## 錯誤處理

| 異常類型                | 觸發情境         |
| ------------------- | ------------ |
| AuthenticationError | API 金鑰無效或未授權 |
| NotFoundError       | 模型不存在或不被支援   |
| APIConnectionError  | 網路中斷或伺服器未回應  |
| RateLimitError      | 請求頻率超限       |

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.mixroute.ai/v1/chat/completions \
    --header 'Authorization: Bearer sk-xxxxxxxxxx' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-5.5",
      "messages": [
        {"role": "system", "content": "你是一個有用的助手"},
        {"role": "user", "content": "請用中文簡要介紹人工智慧"}
      ],
      "temperature": 0.7
    }'
  ```

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

  client = OpenAI(
      api_key="sk-xxxxxxxxxx",
      base_url="https://api.mixroute.ai/v1"
  )

  response = client.chat.completions.create(
      model="gpt-5.5",
      messages=[
          {"role": "system", "content": "你是一個有用的助手"},
          {"role": "user", "content": "請用中文簡要介紹人工智慧"}
      ],
      temperature=0.7
  )
  print(response.choices[0].message.content)
  ```

  ```javascript JavaScript theme={null}
  const OpenAI = require('openai');

  const client = new OpenAI({
    apiKey: 'sk-xxxxxxxxxx',
    baseURL: 'https://api.mixroute.ai/v1'
  });

  const response = await client.chat.completions.create({
    model: 'gpt-5.5',
    messages: [
      { role: 'system', content: '你是一個有用的助手' },
      { role: 'user', content: '請用中文簡要介紹人工智慧' }
    ],
    temperature: 0.7
  });
  console.log(response.choices[0].message.content);
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->post('https://api.mixroute.ai/v1/chat/completions', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx',
          'Content-Type' => 'application/json',
      ],
      'json' => [
          'model' => 'gpt-5.5',
          'messages' => [
              ['role' => 'system', 'content' => '你是一個有用的助手'],
              ['role' => 'user', 'content' => '請用中文簡要介紹人工智慧']
          ],
          'temperature' => 0.7
      ]
  ]);
  echo $response->getBody();
  ```

  ```go Go theme={null}
  package main

  import (
      "context"
      "fmt"
      openai "github.com/sashabaranov/go-openai"
  )

  func main() {
      config := openai.DefaultConfig("sk-xxxxxxxxxx")
      config.BaseURL = "https://api.mixroute.ai/v1"
      client := openai.NewClientWithConfig(config)

      resp, _ := client.CreateChatCompletion(
          context.Background(),
          openai.ChatCompletionRequest{
              Model: "gpt-5.5",
              Messages: []openai.ChatCompletionMessage{
                  {Role: "system", Content: "你是一個有用的助手"},
                  {Role: "user", Content: "請用中文簡要介紹人工智慧"},
              },
          },
      )
      fmt.Println(resp.Choices[0].Message.Content)
  }
  ```

  ```java Java theme={null}
  import com.theokanning.openai.OpenAiService;
  import com.theokanning.openai.completion.chat.*;

  OpenAiService service = new OpenAiService("sk-xxxxxxxxxx");
  ChatCompletionRequest request = ChatCompletionRequest.builder()
      .model("gpt-5.5")
      .messages(Arrays.asList(
          new ChatMessage("system", "你是一個有用的助手"),
          new ChatMessage("user", "請用中文簡要介紹人工智慧")
      ))
      .temperature(0.7)
      .build();
  ChatCompletionResult result = service.createChatCompletion(request);
  System.out.println(result.getChoices().get(0).getMessage().getContent());
  ```

  ```ruby Ruby theme={null}
  require 'openai'

  client = OpenAI::Client.new(
    access_token: 'sk-xxxxxxxxxx',
    uri_base: 'https://api.mixroute.ai/v1'
  )

  response = client.chat(
    parameters: {
      model: 'gpt-5.5',
      messages: [
        { role: 'system', content: '你是一個有用的助手' },
        { role: 'user', content: '請用中文簡要介紹人工智慧' }
      ],
      temperature: 0.7
    }
  )
  puts response.dig('choices', 0, 'message', 'content')
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "id": "chatcmpl-xxx",
    "object": "chat.completion",
    "created": 1234567890,
    "model": "gpt-5.5",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "人工智慧是研究、開發用於模擬、延伸和擴展人的智慧的理論、方法、技術及應用系統的一門新的技術科學..."
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 25,
      "completion_tokens": 100,
      "total_tokens": 125
    }
  }
  ```
</ResponseExample>
