TokenLab

核心指南

串流 (Streaming)

在模型輸出產生時即時顯示

概覽

串流 (Streaming) 會以小型事件的形式傳遞模型輸出,而無需等待完整答案。若模型在 accepted_request_formats 中列出了 openai_responses,請使用 Responses 串流;若您的 SDK 或應用程式已預期使用 Chat Completions 串流,則請維持使用該方式。

Responses 串流

curl https://api.tokenlab.sh/v1/responses \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.6-terra",
    "input": "Write a short poem.",
    "stream": true
  }'

Responses SSE 保留了已記錄的事件名稱、順序與欄位。在第一個事件到達後,若串流中斷,則視為不完整,且不會自動重新啟動。

Responses WebSocket

連接至 wss://api.tokenlab.sh/v1/responses 並發送 response.create 事件。WebSocket 回應皆為串流形式,且不支援 background 或 response.cancel。帶有 generate: false 的 response.create 會回傳一個 ID,該 ID 可在不產生模型輸出或產生模型費用的情況下繼續使用。

每個連線一次處理一個活動回應,最長持續 60 分鐘。事件包含一個回應範圍內的 sequence_number。名為 error 的串流事件使用扁平化的事件物件;連線與協定失敗則使用巢狀的 error 物件。

Chat Completions 串流

如果您的框架仍預期從 /v1/chat/completions 接收 SSE 區塊,這同樣適用:

import os
from openai import OpenAI

with OpenAI(
    api_key=os.environ["TOKENLAB_API_KEY"],
    base_url="https://api.tokenlab.sh/v1",
    timeout=30.0,
    max_retries=0,
) as client:
    finish_reason = None
    with client.chat.completions.create(
        model="gpt-5.6-terra",
        messages=[{"role": "user", "content": "Write a short poem."}],
        stream=True,
        stream_options={"include_usage": True},
    ) as stream:
        for chunk in stream:
            if not chunk.choices:
                continue
            choice = chunk.choices[0]
            if choice.delta.content:
                print(choice.delta.content, end="", flush=True)
            if choice.finish_reason:
                finish_reason = choice.finish_reason
    if finish_reason != "stop":
        raise RuntimeError(f"Stream ended without a complete text answer: {finish_reason}")

Messages 串流

使用 "stream": true 呼叫 POST /v1/messages 會回傳 Anthropic Messages SSE 事件。僅在收到 message_stop 事件後才視串流為完成;若串流提早結束,則視為不完整。

Gemini 串流

POST /v1beta/models/{model}:streamGenerateContent?alt=sse 會回傳 Gemini 區塊。事件可能僅包含中繼資料,中間事件可能會省略 finishReason,且串流可能會在沒有 Chat Completions [DONE] 標記的情況下自然結束。

串流結束條件

典型的完成條件:

  • Responses API 串流的 response.completed
  • Messages 串流的 message_stop
  • Chat Completions 串流的 finish_reason: "stop"
  • 達到 Token 限制時的 finish_reason: "length"
  • 當模型想要使用工具時的工具/函式呼叫事件

Web 應用程式模式

在您的伺服器上執行 SDK 串流消費者。瀏覽器應呼叫您自己的已驗證後端;請將 TokenLab 金鑰保留在伺服器環境中。將文字增量 (deltas) 轉發至瀏覽器,並在使用者停止或中斷連線時取消上游串流。請使用 SDK 來解析 SSE 事件:一個網路區塊不一定是一個完整的事件。

妥善處理串流

本頁內容