OneMux/文件中心/串流輸出

串流輸出

Server-Sent Events (SSE) 串流輸出會像打字機一樣逐字傳回 AI 回應,提升使用者體驗。本頁介紹如何啟用串流輸出、解析 SSE 資料區塊,以及處理串流連線。適用於聊天對話、內容生成等情境。

為什麼使用串流?

  • 大型語言模型回應較慢,使用者需要即時回饋
  • 類似 ChatGPT 的打字機效果
  • 提升使用者體驗

啟用串流輸出

在請求中設定 "stream": true

from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://api.onemux.net/v1"
)

response = client.chat.completions.create(
    model="gpt-6.1-sol",
    messages=[{"role": "user", "content": "寫一首詩"}],
    stream=True
)

for chunk in response:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

SSE 回應格式

串流回應使用 Server-Sent Events (SSE) 格式,每個資料區塊都以 data: 開頭:

data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"你"}}]}

data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"好"}}]}

data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"!"}}]}

data: [DONE]