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

# 流式响应

> 通过 Server-Sent Events 流式接收 Yelu 模型输出，并在 Curl、JavaScript 与 Python 中安全解析。

流式响应会在模型生成内容时立即发送增量数据，从而降低首 Token 延迟。Yelu 的 Chat Completions 与 Responses 使用 Server-Sent Events（SSE）。

## 开启流式输出

设置 `stream: true`。Chat Completions 的每个 `data:` 行包含 `chat.completion.chunk`，最终以 `data: [DONE]` 结束。

<CodeGroup>
  ```bash Curl theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -N https://api.yelu.ai/v1/chat/completions \
    -H "Authorization: Bearer $YELU_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"写一首四行的 API 小诗。"}],"stream":true,"stream_options":{"include_usage":true}}'
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await fetch('https://api.yelu.ai/v1/chat/completions', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.YELU_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: '写一首四行的 API 小诗。' }],
      stream: true,
      stream_options: { include_usage: true },
    }),
  });
  if (!response.ok || !response.body) throw new Error(await response.text());

  const decoder = new TextDecoder();
  let buffer = '';
  for await (const chunk of response.body) {
    buffer += decoder.decode(chunk, { stream: true });
    const lines = buffer.split('\n');
    buffer = lines.pop() ?? '';
    for (const line of lines) {
      if (!line.startsWith('data: ')) continue;
      const payload = line.slice(6).trim();
      if (payload === '[DONE]') continue;
      process.stdout.write(JSON.parse(payload).choices?.[0]?.delta?.content ?? '');
    }
  }
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import json
  import os
  import requests

  with requests.post(
      "https://api.yelu.ai/v1/chat/completions",
      headers={"Authorization": f"Bearer {os.environ['YELU_API_KEY']}"},
      json={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "写一首四行的 API 小诗。"}], "stream": True},
      stream=True,
      timeout=(10, 120),
  ) as response:
      response.raise_for_status()
      for line in response.iter_lines(decode_unicode=True):
          if not line or not line.startswith("data: "):
              continue
          payload = line[6:].strip()
          if payload == "[DONE]":
              break
          print(json.loads(payload).get("choices", [{}])[0].get("delta", {}).get("content", ""), end="", flush=True)
  ```
</CodeGroup>

## 解析规则

* 网络 Chunk 不一定与 SSE 行对齐；必须缓冲到完整换行。
* 忽略空行与不使用的 SSE 字段。
* 按顺序拼接文本 Delta。
* Tool Call 的名称和参数可能跨多个 Delta，应完整累积后再解析 JSON。
* 使用流式 UTF-8 Decoder，避免拆坏多字节字符。
* 收到终止 Event 前，响应都应视为不完整。
* 用户离开或不再需要输出时应取消请求。

## Responses API

Responses API 返回带 `type` 的 Event，而不是 Chat Completion Chunk。按类型处理文本 Delta，对未知 Event 保持忽略以获得前向兼容性，并在需要时保存最终 Response 或 Usage Event。

<Warning>HTTP `200` 仅表示流已建立。流内仍可能出现错误，也可能在终止 Event 前断开。只有产品明确支持时才保留部分结果。</Warning>

生产环境应配置连接、空闲读取与总超时；关闭代理缓冲；限制最大输出；记录首 Token 延迟、总耗时、Finish Reason 和完整状态。
