跳至主要內容
GetAPI
繁體中文
選單

GetAPI.ONE

串流接收 GetAPI.ONE Responses

消費 Server-Sent Events 流,只追加文字增量,並將 completed、failed 與 incomplete 作為不同的終止結果處理。

選擇相容路徑

  • 使用目前目錄中明確宣告 Responses 端點的模型。
  • 將 API 金鑰儲存在可信伺服器端或本地程序中。
  • 預先決定呼叫方如何顯示部分文字以及如何從中斷中恢復。
text
POST https://www.getapi.one/v1/responses
Accept: text/event-stream
Authorization: Bearer $GETAPI_ONE_API_KEY

讀取事件生命週期

  1. 透過伺服器端 SDK 或 HTTP 用戶端傳送 stream=true,首次受控請求停用自動重試。
  2. 僅將 response.output_text.delta 的 payload 追加到可見文字。
  3. 在 response.completed 時停止,並保留應用所需的最終回應後設資料。
  4. 將 response.failed 與 response.incomplete 作為非成功結果展示,不要把部分文字標成已完成。
  5. 將 error 事件、傳輸異常、完成前 EOF 或本地取消視為非成功,並關閉流。
python
import os
from openai import OpenAI

terminal_event = None
try:
    with OpenAI(
        api_key=os.environ["GETAPI_ONE_API_KEY"],
        base_url="https://www.getapi.one/v1",
        timeout=30.0,
        max_retries=0,
    ) as client:
        with client.responses.create(
            model="<RESPONSES_MODEL_ID_FROM_CURRENT_CATALOG>",
            input="Give three concise deployment checks.",
            stream=True,
        ) as stream:
            for event in stream:
                if event.type == "response.output_text.delta":
                    print(event.delta, end="", flush=True)
                elif event.type == "response.completed":
                    terminal_event = event.type
                    print("\ncompleted")
                    break
                elif event.type in {"response.failed", "response.incomplete", "error"}:
                    terminal_event = event.type
                    raise RuntimeError(f"stream ended with {event.type}: {event}")
except KeyboardInterrupt:
    raise SystemExit("cancelled locally; the stream and client were closed")

if terminal_event != "response.completed":
    raise RuntimeError("stream ended before response.completed")

將事件對映到介面狀態

事件應用動作
response.output_text.delta追加 event.delta,不要替換已渲染文字。
response.completed標記成功並關閉載入狀態。
response.failed展示結構化錯誤與安全重試入口。
response.incomplete保留部分輸出並明確標記未完成,同時檢查 incomplete details。

驗證預期結果

  • 文字逐步出現且沒有重複增量。
  • 僅在終止事件或傳輸錯誤後結束載入。
  • 連線中斷時絕不顯示虛假的成功狀態。

處理傳輸與協議錯誤

  • 若沒有事件到達,檢查準確的 /v1/responses 路徑、stream=true、代理緩衝與模型端點宣告。
  • 若輸出重複,只追加每個 delta 一次,不要同時混用 SDK 累積結果與原始事件。
  • 僅在無可見副作用前重試,或使用應用層冪等機制;斷連並不能證明上游請求未執行。

在伺服器端處理串流呼叫

text
Browser → your authenticated backend → GetAPI.ONE
                 server-held key only

下一步