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

# 流式输出

在使用大模型生成结果的过程中，会遇到大模型要生成内容较多而导致生成时间较长的问题 —— 比如当您让大模型帮您生成一个 1000 字的文章，往往需要大模型输出 10 秒以上。在这个过程中，如果您没有给用户准备相应的反馈，则极有可能导致用户误以为系统故障 / 使用报错而离开当前界面。

因此，我们需要通过某些产品手段来优化产品体验，帮助用户感知到当前的进展情况和状态，以便于更好的将用户留在当前页面，等待执行结果。

在传统 API 当中，由于接口只能一次性返回，因此开发者需要在产品上放置 Loading 页面或骨架屏，以告知用户当前正在加载中。

但阶跃星辰的 [对话补全接口](https://platform.stepfun.com/docs/zh/api-reference/chat/chat-completion-create.md) 支持流式返回，您可以通过流式返回，实现类似于打字机特效的的效果，帮助用户在大模型生成过程中，直接查看内容。

![](https://mintcdn.com/stepfun/ivZhb9pOE5X12y-g/images/stream.gif?s=2892f635ae97e0bcc0494a5705d6fd14)

### 实现流式输出

开放平台的 Chat Completion 接口支持通过传入 stream=True，来开启流式输出内容， API 将会返回 SSE 请求内容，您可以通过解析 SSE 请求的返回结果，并将其渲染到 UI 上，来实现效果。

#### 代码示例

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
from openai import OpenAI

# 初始化 阶跃星辰 Client
STEPFUN_KEY = "YOUR_STEP_API_KEY"

client = OpenAI(base_url="https://api.stepfun.com/v1", api_key=STEPFUN_KEY)

# 调用补全接口进行补全

stream = client.chat.completions.create(
    model="step-5-preview",
    messages=[{"role": "user", "content": "全季酒店怎么样？"}],
    stream=True,
)

# 对流式返回的内容进行打印 / 渲染输出

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

```

### 注意事项

* 在使用流式输出时，虽然模型返回的速度较快，但依然有等待延迟，在此期间，您可以配合 Loading 引导用户等待，以帮助用户即时获得反馈。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.