Chat Completions

使用 OpenAI 相容的 Chat Completions 端點,以訊息為基礎生成文字。

POST https://getrouter.ai/v1/chat/completions

基本請求

curl https://getrouter.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MODEL_ID",
    "messages": [
      {"role": "system", "content": "請清楚且簡潔地回答。"},
      {"role": "user", "content": "什麼是 API 閘道?"}
    ]
  }'

非串流回應的生成內容位於:

choices[0].message.content

如果模型有回報 token 用量,會傳回在 usage 物件中。

Python

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://getrouter.ai/v1",
)

response = client.chat.completions.create(
    model="MODEL_ID",
    messages=[
        {"role": "system", "content": "請清楚且簡潔地回答。"},
        {"role": "user", "content": "什麼是 API 閘道?"},
    ],
)

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

Node.js / TypeScript

import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: 'YOUR_API_KEY',
  baseURL: 'https://getrouter.ai/v1',
})

const response = await client.chat.completions.create({
  model: 'MODEL_ID',
  messages: [
    { role: 'system', content: '請清楚且簡潔地回答。' },
    { role: 'user', content: '什麼是 API 閘道?' },
  ],
})

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

訊息角色

API 結構描述支援下列角色:

角色用途
system高階行為或上下文
developer適用於支援此角色之模型的開發者指示
user終端使用者輸入
assistant助理先前的輸出
tool工具呼叫傳回的結果

常用請求欄位

欄位說明
model必填的模型 ID
messages必填且依序排列的對話訊息
stream設為 true 時傳回增量區塊
temperature所選模型支援的取樣控制
top_p核取樣控制
max_tokens相容模型可生成的 token 數量上限
max_completion_tokens相容模型使用的完成內容上限
tools適用於支援工具呼叫之模型的工具定義
tool_choice控制工具選擇
response_format相容模型的結構化回應設定
reasoning_effort相容推理模型可使用 lowmediumhigh

除非所選模型支援,否則請勿傳送選填欄位。

多模態輸入

訊息內容結構描述支援具有類型的內容部分,例如文字、圖片 URL、輸入音訊、檔案及影片 URL。可用性取決於模型。

圖片輸入範例:

{
  "model": "MODEL_ID",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "描述這張圖像。"},
        {
          "type": "image_url",
          "image_url": {"url": "https://example.com/image.jpg"}
        }
      ]
    }
  ]
}

工具呼叫

當相容模型傳回 tool_calls 時,請在應用程式中執行要求的函式,並附加一則含有相符 tool_call_idtool 訊息。工具支援與實際行為取決於模型。

串流

stream 設為 true,並從每個區塊的 choices[0].delta.content 讀取文字。完整範例請參閱串流

錯誤

  • 400 — 請求欄位無效或值不受支援
  • 401 — 缺少 API 金鑰或金鑰無效
  • 429 — 速率限制、配額或容量限制
  • 模型錯誤 — 模型 ID 不正確或端點不相符

後續步驟