第 5 章 / 共 21 章約 1 分鐘

5. 對話補全 Chat Completions#

POST /v1/chat/completions — 最核心的介面,相容 OpenAI Chat Completions。

請求參數#

參數類型必填說明
modelstring是模型名,如 gpt-4o、claude-3-5-sonnet-20241022
messagesarray是訊息陣列,每項含 role(system/user/assistant)與 content
streamboolean否是否串流回傳,預設 false
temperaturenumber否取樣溫度,越高越隨機
max_tokensinteger否生成的最大 token 數

其他 OpenAI 標準參數(top_p、presence_penalty 等)會透傳給上游模型。

非串流請求#

cURL
curl http://183.240.79.21:52099/v1/chat/completions \
  -H "Authorization: Bearer sk-你的YiTuoToken-Key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      { "role": "system", "content": "你是一个乐于助人的助手。" },
      { "role": "user", "content": "你好,请介绍一下你自己" }
    ],
    "temperature": 0.7
  }'

串流請求(SSE)#

請求內文加上 "stream": true,回應以 Server-Sent Events 逐塊回傳,每塊為一個 chat.completion.chunk,最後以 data: [DONE] 結束。

cURL
curl http://183.240.79.21:52099/v1/chat/completions \
  -H "Authorization: Bearer sk-你的YiTuoToken-Key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [{ "role": "user", "content": "写一首关于秋天的短诗" }],
    "stream": true
  }'

多輪對話#

把歷史訊息依次放進 messages 陣列即可維持上下文:

JSON
{
  "model": "gpt-4o",
  "messages": [
    { "role": "user", "content": "推荐一部科幻电影" },
    { "role": "assistant", "content": "推荐《星际穿越》。" },
    { "role": "user", "content": "它的导演是谁?" }
  ]
}