APIQIKAPIQIK
文档导航
用户指南

流式响应

通过 stream=true 逐块读取增量内容,并正确处理结束、取消和断线。

设置 stream: true 后,服务端在生成过程中持续返回增量数据,用户无需等待完整答案即可看到内容。

Python 示例

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["APIQIK_API_KEY"],
    base_url="https://api.dimleap.cn/v1",
)

stream = client.chat.completions.create(
    model="glm-5.1",
    messages=[
        {"role": "user", "content": "用三点说明智能路由的价值。"}
    ],
    stream=True,
)

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

print()

Node.js 示例

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.APIQIK_API_KEY,
  baseURL: "https://api.dimleap.cn/v1",
});

const stream = await client.chat.completions.create({
  model: "glm-5.1",
  messages: [
    { role: "user", content: "用三点说明智能路由的价值。" },
  ],
  stream: true,
});

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

原始 HTTP

curl -N https://api.dimleap.cn/v1/chat/completions \
  -H "Authorization: Bearer $APIQIK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "glm-5.1",
    "messages": [{"role": "user", "content": "写一段产品介绍"}],
    "stream": true
  }'

实现要点

  • 流式内容位于 choices[0].delta.content,不是 message.content。
  • 并非每个数据块都有文本,工具调用、角色信息或统计数据也可能独立出现。
  • 前端应对短时间高频更新做合并渲染,避免每个字符触发一次昂贵重绘。
  • 用户点击停止时,应同时取消浏览器请求和后端到 Dimleap 的连接。
  • 连接中断后无法假定能从原位置无缝继续;重试时要防止重复展示内容。