Skip to content

流式响应处理 ​

SSE 流式输出


概述 ​

流式响应允许在模型生成内容时实时接收输出,提供更好的用户体验。

下方代码演示 OpenAI Chat Completions 的文本流,不是所有厂商通用的事件解析器。模型和渠道须支持对应协议:

协议事件与内容解析重点
Chat Completionsdata: 中的 choices[].delta、结束标记 [DONE]文本与 tool_calls 增量分别累积;纯用量块可能没有 choices
Responsesresponse.output_text.delta、工具参数增量、完成或失败事件按事件类型和输出项 ID 处理,不读取 choices
Anthropic Messagesmessage_start、content_block_start/delta/stop、message_delta/stop按块索引累积文本、工具 partial_json、思考与签名;保留完整块用于续接
Gemini GenerateContent:streamGenerateContent?alt=sse 的候选内容块读取 candidates[].content.parts[],保留函数块、媒体和 thoughtSignature

SSE 的一个事件可能跨越多个网络数据块,必须先按事件边界缓冲,再解析 JSON。工具参数增量不是每次都能独立解析的完整 JSON。原生协议入口见文本调用和 Gemini 指南;双向语音使用实时接口。

示例使用 ABU_API_KEY 环境变量,模型 ID 请替换为当前分组可用型号。

Python 实现 ​

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["ABU_API_KEY"],
    base_url="https://api.abuai.chat/v1"
)

stream = client.chat.completions.create(
    model="gpt-5.2-instant",
    messages=[{"role": "user", "content": "写一篇文章"}],
    stream=True
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Node.js 实现 ​

javascript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.ABU_API_KEY,
  baseURL: 'https://api.abuai.chat/v1'
});

const stream = await client.chat.completions.create({
  model: 'gpt-5.2-instant',
  messages: [{ role: 'user', content: '写一篇文章' }],
  stream: true
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content || '';
  process.stdout.write(content);
}

cURL 实现 ​

bash
curl https://api.abuai.chat/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -d '{
    "model": "gpt-5.2-instant",
    "messages": [{"role": "user", "content": "Hello"}],
    "stream": true
  }' \
  --no-buffer

浏览器与后端 ​

平台 Key 由自己的后端保管。浏览器请求经过身份与权限校验的业务接口,由后端使用 SDK 消费上游流,再转发约定格式的内容事件。不要把平台 Key 放进浏览器请求头。

若业务后端原样转发 Chat Completions SSE,浏览器可使用下面的解析方式。/api/chat-stream 是你需要实现的业务接口,不是平台现有路由;它应返回 SSE,并处理鉴权、限流和上游错误。

javascript
async function readChatStream(prompt, onText, signal) {
  const response = await fetch('/api/chat-stream', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ prompt }),
    signal
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  if (!response.body) throw new Error('响应没有可读流');

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let pending = '';
  let eventLines = [];
  let completed = false;

  function acceptLine(line) {
    if (line !== '') {
      eventLines.push(line);
      return;
    }
    const data = eventLines
      .filter(line => line.startsWith('data:'))
      .map(line => line.slice(5).replace(/^ /, ''))
      .join('\n');
    eventLines = [];
    if (!data) return; // 心跳、注释等不含 data 的事件
    if (data === '[DONE]') {
      completed = true;
      return;
    }
    const event = JSON.parse(data);
    if (event.error) throw new Error(event.error.message || '流式请求失败');
    const text = event.choices?.[0]?.delta?.content;
    if (text) onText(text);
  }

  try {
    while (!completed) {
      const { done, value } = await reader.read();
      pending += done ? decoder.decode() : decoder.decode(value, { stream: true });
      let newline;
      while ((newline = pending.indexOf('\n')) !== -1) {
        const line = pending.slice(0, newline).replace(/\r$/, '');
        pending = pending.slice(newline + 1);
        acceptLine(line);
        if (completed) break;
      }
      if (done) break;
    }
    if (!completed) throw new Error('流提前结束,请核对已有输出与调用记录');
  } finally {
    await reader.cancel().catch(() => {});
    reader.releaseLock();
  }
}

该示例只显示 Chat Completions 文本增量;工具调用需按索引累积参数,Responses、Messages 和 Gemini 按各自事件协议处理。UTF-8 解码器和未完成行会跨网络块保留,不能对每次 reader.read() 的结果直接独立 JSON.parse。

SSE 数据格式 ​

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-5.2-instant","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-5.2-instant","choices":[{"index":0,"delta":{"content":" World"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-5.2-instant","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

错误处理 ​

python
try:
    stream = client.chat.completions.create(
        model="gpt-5.2-instant",
        messages=[{"role": "user", "content": "Hello"}],
        stream=True
    )
    
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="")
            
except Exception as e:
    print(f"Stream error: {e}")

最佳实践 ​

  1. 超时设置: 流式请求建议设置较长的超时时间
  2. 中断处理: 保留已有输出,明确提示流是否完成;重新请求可能重复生成和计费,不视为自动续传
  3. 缓冲处理: 适当缓冲输出,避免频繁 DOM 更新
  4. 取消请求: 提供取消流式请求的能力

AbuAI - 让 AI 触手可及