> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenlab.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# 串流

> 實作即時串流回應

## 概覽

串流可讓您在輸出生成的同時接收部分內容，從而改善感知延遲與使用者體驗。

對於新的 OpenAI 風格整合，建議優先使用 **Responses streaming**。如果您的框架仍在使用 Chat Completions streaming，TokenLab 也支援該相容路徑。

## 建議：Responses Streaming

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.tokenlab.sh/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
    }'
  ```

  ```python Python theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="sk-your-api-key",
      base_url="https://api.tokenlab.sh/v1"
  )

  stream = client.responses.create(
      model="gpt-5.4",
      input="Write a short poem.",
      stream=True
  )

  for event in stream:
      if event.type == "response.output_text.delta":
          print(event.delta, end="", flush=True)
  ```

  ```javascript JavaScript theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
    apiKey: 'sk-your-api-key',
    baseURL: 'https://api.tokenlab.sh/v1'
  });

  const stream = await client.responses.create({
    model: 'gpt-5.4',
    input: 'Write a short poem.',
    stream: true
  });

  for await (const event of stream) {
    if (event.type === 'response.output_text.delta') {
      process.stdout.write(event.delta);
    }
  }
  ```
</CodeGroup>

## Chat Completions 串流

如果您的框架仍預期從 `/v1/chat/completions` 接收 SSE 區塊，這同樣可行：

```python theme={null}
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 模式

```javascript theme={null}
async function streamChat(message) {
  const response = await fetch('https://api.tokenlab.sh/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;
      }
    }
  }
}
```

## 最佳實務

<AccordionGroup>
  <Accordion title="新建專案優先使用 Responses streaming">
    如果您的 SDK 或應用程式已支援，請使用 `/v1/responses`。將 `/v1/chat/completions` streaming 保留給以相容性為導向的整合。
  </Accordion>

  <Accordion title="逐步刷新輸出">
    在 delta 區塊到達時立即將其附加到 UI 或終端機，而不是等待完整回應。
  </Accordion>

  <Accordion title="處理中斷連線與重試">
    將網路中斷與上游連線中斷視為正常的失敗模式，並在長時間執行的工作階段中謹慎地重新連線。
  </Accordion>
</AccordionGroup>
