Skip to main content
XRouter 支持兼容接口的流式响应。客户端会收到 Server-Sent Events 或对应 SDK 封装后的增量事件。
不同上游模型返回的增量字段和最终 usage 信息可能存在差异。生产环境建议按目标模型实际返回内容做兼容处理。

Chat Completions

在请求体中设置 stream: true
Terminal
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
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 启用流式响应。
Terminal
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
Terminal
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。" }
    ]
  }'

排查建议

先用非流式请求验证同一个模型和 Key 是否可用。非流式成功后,再确认客户端是否正确处理 SSE 事件。
不同上游和不同接口格式对流式 usage 的返回策略不同。不要把最终 usage 字段作为业务成功的唯一判断条件。
检查中间代理是否禁用了流式传输、缓冲了响应,或设置了过短的超时时间。