跳轉到主要內容

概覽

串流可讓您在輸出生成的同時接收部分內容,從而改善感知延遲與使用者體驗。 對於新的 OpenAI 風格整合,建議優先使用 Responses streaming。如果您的框架仍在使用 Chat Completions streaming,LemonData 也支援該相容路徑。

建議:Responses Streaming

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

Chat Completions Streaming

如果您的框架仍預期從 /v1/chat/completions 接收 SSE 區塊,這同樣可行:
stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a short poem"}],
    stream=True
)

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

串流結束條件

典型的完成條件:
  • Responses API streams 的 response.completed
  • Chat Completions streams 的 finish_reason: "stop"
  • 當達到 token 限制時的 finish_reason: "length"
  • 當模型想要使用工具時的 tool/function call 事件

Web App 模式

async function streamChat(message) {
  const response = await fetch('https://api.lemondata.cc/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: message }],
      stream: true
    })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    const lines = chunk.split('\\n').filter(line => line.startsWith('data: '));

    for (const line of lines) {
      const data = line.slice(6);
      if (data === '[DONE]') return;
      const parsed = JSON.parse(data);
      const content = parsed.choices?.[0]?.delta?.content;
      if (content) {
        document.getElementById('output').textContent += content;
      }
    }
  }
}

最佳實務

如果您的 SDK 或應用程式已支援,請使用 /v1/responses。將 /v1/chat/completions streaming 保留給以相容性為導向的整合。
在 delta 區塊到達時立即將其附加到 UI 或終端機,而不是等待完整回應。
將網路中斷與上游連線中斷視為正常的失敗模式,並在長時間執行的工作階段中謹慎地重新連線。