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

# 流式输出

> 让文本模型边生成边返回

流式输出适合聊天窗口、长文本生成、AI Coding 和需要降低首字等待时间的产品体验。开启后，服务端会通过 SSE 逐段返回增量内容。

## 开启方式

在 Chat Completions 请求里设置：

```json theme={null}
{
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}
```

`stream_options.include_usage` 会尽量在流结束前返回用量信息；如果上游或网络中断没有返回完整 usage，响应里可能拿不到最终 usage，最终计费以平台账单记录为准。

<Note>示例模型使用 `gpt-5.4`。实际接入时，请以控制台可用模型和模型详情为准。</Note>

## 基本请求

<CodeGroup>
  ```bash cURL theme={null}
  curl -N https://tapapi.ai/v1/chat/completions \
    -H "Authorization: Bearer sk-xxx" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5.4",
      "stream": true,
      "stream_options": {"include_usage": true},
      "messages": [
        {"role": "user", "content": "写一段 100 字的产品介绍"}
      ]
    }'
  ```

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

  client = OpenAI(api_key="sk-xxx", base_url="https://tapapi.ai/v1")

  stream = client.chat.completions.create(
      model="gpt-5.4",
      stream=True,
      stream_options={"include_usage": True},
      messages=[{"role": "user", "content": "写一段 100 字的产品介绍"}],
  )

  for chunk in stream:
      if not chunk.choices:
          continue

      delta = chunk.choices[0].delta
      text = getattr(delta, "content", None)
      if text:
          print(text, end="", flush=True)
  ```

  ```javascript Node.js theme={null}
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: "sk-xxx",
    baseURL: "https://tapapi.ai/v1",
  });

  const stream = await client.chat.completions.create({
    model: "gpt-5.4",
    stream: true,
    stream_options: { include_usage: true },
    messages: [{ role: "user", content: "写一段 100 字的产品介绍" }],
  });

  for await (const chunk of stream) {
    const text = chunk.choices[0]?.delta?.content;
    if (text) process.stdout.write(text);
  }
  ```
</CodeGroup>

## 读取方式

非流式返回里，文本在：

```text theme={null}
choices[0].message.content
```

流式返回里，每个增量 chunk 通常读取：

```text theme={null}
choices[0].delta.content
```

生产解析时要跳过空内容、ping/keep-alive 和没有普通文本 delta 的 chunk。最后会收到结束事件。不同 SDK 对底层 SSE 的封装略有不同，建议优先使用 SDK 的 async iterator 或 for-loop。

底层事件流通常是：

```text theme={null}
data: {...}
data: {...}
data: [DONE]
```

## 什么时候开启

| 场景              | 建议                |
| --------------- | ----------------- |
| 聊天产品            | 默认开启，降低等待感        |
| AI Coding / 长文本 | 开启，方便边生成边显示       |
| 批处理脚本           | 可以关闭，便于统一解析结果     |
| JSON 提取         | 通常先关闭，等结构稳定后再考虑流式 |

## 上线注意

* 前端不要直接持有 Tapapi API Key
* 后端要支持客户端取消生成
* 记录 `X-Oneapi-Request-Id`、模型名、耗时和最终用量
* 网络断开时，最终 `usage` 可能拿不到，需要有容错
* 504、524 或前端超时后，不要盲目立刻补跑，先查业务状态和账单
* 超时和重试策略见 [超时处理](/production/timeouts)
