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

# 流式输出

> 逐段读取模型回答，减少等待首段内容的时间。

## Python 完整示例

先按 [SDK 文档](/sdk) 安装依赖，并设置 `API_KEY` 和 `MODEL` 环境变量。

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

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url="https://token.poryf.com/v1",
)
stream = client.chat.completions.create(
    model=os.environ["MODEL"],
    messages=[{"role": "user", "content": "你好"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices:
        text = chunk.choices[0].delta.content
        if text:
            print(text, end="", flush=True)
print()
```

## 与普通响应的区别

普通请求从 `message.content` 读取完整回答；流式请求从每一段的 `delta.content` 拼接回答。某些片段只有角色、结束标记或用量，不包含文本，应跳过空内容。

## 直接使用 HTTP

响应使用 SSE 分段传输，不能把整个响应当成一个 JSON 对象解析。使用 cURL 时添加 `-N` 禁用输出缓冲，并在请求体中设置 `"stream": true`。

## 中途断开

已经收到 HTTP 成功状态不代表流已正常结束。客户端应处理网络中断和错误事件。重新请求可能产生新的用量，不要无限自动重试。
