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

# 流式输出

> 分别处理 Chat Completions 与 Responses 的 SSE 事件。

请求中设置 `stream: true`，响应通常为 `text/event-stream`。建议交给 SDK 解析；网络数据块不等于一个 SSE 事件，事件也可能跨多个数据块。

## 两种接口的区别

| 接口 | 增量文本 | 完成与异常 |
| - | - | - |
| Chat Completions | `choices[].delta.content` | 检查 `finish_reason`；通常以 `data: [DONE]` 结束 |
| Responses | `response.output_text.delta` 事件的 `delta` | `response.completed` 才表示完成；处理 `response.failed`、`response.incomplete`、`error` |

角色块、工具调用块或用量块可能不含文本；`choices` 也可能为空。Chat 的 `length` 表示达到生成限制，`tool_calls` 表示需要处理工具，并非完整自然语言回复。

HTTP 200 后仍可能出现事件级错误或网络中断。保留已收到的文字时应标记“不完整”，不要把 EOF 当作成功，也不要自动重放已开始的生成请求。

## Python：Chat Completions

按 [Python SDK](/zh/guides/python)安装依赖、设置环境变量；保存为 `stream-chat.py`，运行 `python stream-chat.py`。这是纯文本示例，只有 `finish_reason=stop` 视为完整输出。

```python theme={null}
import os
from openai import OpenAI, APIConnectionError, APIStatusError, APIError

with OpenAI(
    base_url=os.environ["API_BASE_URL"].rstrip("/"),
    api_key=os.environ["API_KEY"],
    timeout=60.0,
    max_retries=0,
) as client:
    finished = False
    try:
        with client.chat.completions.create(
            model=os.environ["API_MODEL"],
            messages=[{"role": "user", "content": "Say hello in one short sentence."}],
            stream=True,
        ) as stream:
            for chunk in stream:
                for choice in chunk.choices:
                    if choice.index != 0:
                        continue
                    print(choice.delta.content or "", end="", flush=True)
                    if choice.finish_reason is not None:
                        if choice.finish_reason != "stop":
                            raise SystemExit(f"\nText did not complete: {choice.finish_reason}")
                        finished = True
        if not finished:
            raise SystemExit("\nStream ended without a completion marker.")
        print()
    except APIStatusError as error:
        raise SystemExit(f"\nRequest failed (HTTP {error.status_code}).")
    except APIConnectionError:
        raise SystemExit("\nConnection failed; partial output may be incomplete.")
    except APIError:
        raise SystemExit("\nStream failed; partial output may be incomplete.")
```

## TypeScript：Responses

按 [TypeScript SDK](/zh/guides/typescript)安装依赖；保存为 `stream-responses.mts`，运行 `node stream-responses.mts`。选择支持 Responses 流式输出的模型。

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

const { API_BASE_URL, API_KEY, API_MODEL } = process.env;
if (!API_BASE_URL || !API_KEY || !API_MODEL) {
  throw new Error('Set API_BASE_URL, API_KEY, and API_MODEL first.');
}

const client = new OpenAI({
  baseURL: API_BASE_URL.replace(/\/+$/, ''),
  apiKey: API_KEY,
  timeout: 60_000,
  maxRetries: 0,
});

let completed = false;
try {
  const stream = await client.responses.create({
    model: API_MODEL,
    input: 'Say hello in one short sentence.',
    stream: true,
  });
  for await (const event of stream) {
    if (event.type === 'response.output_text.delta') {
      process.stdout.write(event.delta);
    } else if (event.type === 'response.completed') {
      completed = true;
    } else if (['error', 'response.failed', 'response.incomplete'].includes(event.type)) {
      throw new Error('Response did not complete.');
    }
  }
  if (!completed) throw new Error('Stream ended without a completion event.');
  process.stdout.write('\n');
} catch (error) {
  console.error(error instanceof OpenAI.APIError && error.status
    ? `\nRequest failed (HTTP ${error.status}).`
    : '\nStream failed or did not complete; partial output may be incomplete.');
  process.exitCode = 1;
}
```

## 部署与用量

如果文字一次性出现，检查网关或反向代理的响应缓冲设置和超时。取消客户端读取不保证上游停止执行。

Chat 的 `stream_options.include_usage` 需渠道支持；用量事件可能没有 `choices`。Responses 的用量通常在最终响应中。连接中断时可能拿不到最终用量，应结合控制台日志核对，不能把缺失用量视为零。

参考：[OpenAI 流式事件说明](https://developers.openai.com/api/docs/guides/streaming-responses)。

## 原生协议与流式工具

[Claude Messages](/zh/guides/native-claude)与 [Gemini generateContent](/zh/guides/native-gemini)提供独立的原生协议接入示例。需要组装工具参数分片并执行函数时，见 [Chat / Responses 流式工具调用](/zh/guides/streaming-tools)。

原生协议的可运行 SSE 与工具闭环见 [Claude](/zh/guides/native-claude-streaming)和 [Gemini](/zh/guides/native-gemini-streaming)，包含完成校验与签名保留。

[Read in English](/en/guides/streaming)


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