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

# 流式输出

> 通过 SSE 实现逐 Token 实时响应流

流式输出将补全结果以增量事件（chunks）序列的形式逐步推送，而不是等待完整响应。

要启用流式输出，设置 `stream: true`：

```bash theme={null}
curl https://api.eztokens.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $EZTOKENS_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "messages": [{"role": "user", "content": "Tell me a story."}],
    "stream": true
  }'
```

## 流式响应格式

每个 chunk 是一个以 `data: ` 为前缀的 JSON 对象：

```text theme={null}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: [DONE]
```

## SDK 用法

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from openai import OpenAI

    client = OpenAI(
        api_key="EZTOKENS_API_KEY",
        base_url="https://api.eztokens.ai/v1"
    )

    stream = client.chat.completions.create(
        model="gpt-4.1",
        messages=[{"role": "user", "content": "Tell me a story."}],
        stream=True
    )

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

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from "openai";

    const client = new OpenAI({
      apiKey: "EZTOKENS_API_KEY",
      baseURL: "https://api.eztokens.ai/v1",
    });

    const stream = await client.chat.completions.create({
      model: "gpt-4.1",
      messages: [{ role: "user", content: "Tell me a story." }],
      stream: true,
    });

    for await (const chunk of stream) {
      process.stdout.write(chunk.choices[0]?.delta?.content || "");
    }
    ```
  </Tab>
</Tabs>

<Note>
  流式行为取决于所选模型的能力。当服务器发送 `data: [DONE]` 或连接关闭时，流结束。
</Note>
