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

# 流式响应

> 在 XRouter 的 OpenAI 兼容和 Anthropic Messages 接口中启用流式响应。

XRouter 支持兼容接口的流式响应。客户端会收到 Server-Sent Events 或对应 SDK 封装后的增量事件。

<Info>
  不同上游模型返回的增量字段和最终 usage 信息可能存在差异。生产环境建议按目标模型实际返回内容做兼容处理。
</Info>

## Chat Completions

在请求体中设置 `stream: true`。

```bash Terminal theme={null}
curl "https://api.xrouter.dev/v1/chat/completions" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "your-model-id",
    "stream": true,
    "messages": [
      { "role": "user", "content": "请用三句话介绍 XRouter。" }
    ]
  }'
```

Python SDK 示例：

```python Python theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="https://api.xrouter.dev/v1",
    api_key="sk-your-api-key",
)

stream = client.chat.completions.create(
    model="your-model-id",
    stream=True,
    messages=[
        {"role": "user", "content": "请用三句话介绍 XRouter。"}
    ],
)

for event in stream:
    delta = event.choices[0].delta.content
    if delta:
        print(delta, end="")
```

## Responses API

Responses API 同样通过 `stream: true` 启用流式响应。

```bash Terminal theme={null}
curl "https://api.xrouter.dev/v1/responses" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "your-model-id",
    "stream": true,
    "input": "请用三句话介绍 XRouter。"
  }'
```

## Anthropic Messages

Anthropic Messages 格式也使用 `stream: true`。

```bash Terminal theme={null}
curl "https://api.xrouter.dev/v1/messages" \
  -H "x-api-key: sk-your-api-key" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "your-claude-model-id",
    "max_tokens": 512,
    "stream": true,
    "messages": [
      { "role": "user", "content": "请用三句话介绍 XRouter。" }
    ]
  }'
```

## 排查建议

<AccordionGroup>
  <Accordion title="客户端一直等待，没有输出">
    先用非流式请求验证同一个模型和 Key 是否可用。非流式成功后，再确认客户端是否正确处理 SSE 事件。
  </Accordion>

  <Accordion title="流式请求没有 usage">
    不同上游和不同接口格式对流式 usage 的返回策略不同。不要把最终 usage 字段作为业务成功的唯一判断条件。
  </Accordion>

  <Accordion title="代理或网关中断流式响应">
    检查中间代理是否禁用了流式传输、缓冲了响应，或设置了过短的超时时间。
  </Accordion>
</AccordionGroup>
