BLACK HOLE 丨 黑洞智能体
Docs

实战:流式解析思维链(Reasoning)与正文输出

COOKBOOK · STREAMING · 在 Web 前端或终端中实时区分渲染深度思考过程与最终回复并采集精确 Token 用量

完整展示如何在开启 stream: true 与 include_usage: true 的情况下,零缓冲实时渲染思考流与正文流,并在流结束时记录实际计费与缓存命中率。

TypeScript 与 Python 完整流式解析模板

传入 stream_options: { include_usage: true } 后,网关会在 data: [DONE] 前的最后一个数据块附带完整 usage 统计(含 cached_tokens 与 reasoning_tokens):

TypeScript

import OpenAI from 'openai'

const client = new OpenAI({
  baseURL: 'https://api.blackholeagent.cn/v1',
  apiKey: process.env.BLACKHOLE_API_KEY
})

const stream = await client.chat.completions.create({
  model: 'deepseek-v4-pro-0813',
  stream: true,
  stream_options: { include_usage: true },
  messages: [{ role: 'user', content: '设计一套支持幂等防重的订单扣款状态机表结构' }]
})

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta as { reasoning_content?: string; content?: string } | undefined
  if (delta?.reasoning_content) {
    process.stdout.write(delta.reasoning_content) // 渲染至折叠思考面板
  }
  if (delta?.content) {
    process.stdout.write(delta.content) // 渲染至主消息区
  }
  if (chunk.usage) {
    console.log('\nTokens 用量:', chunk.usage)
  }
}

Python

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="deepseek-v4-pro-0813",
    stream=True,
    stream_options={"include_usage": True},
    messages=[{"role": "user", "content": "设计一套支持幂等防重的订单扣款状态机表结构"}],
)

for chunk in stream:
    if chunk.choices:
        delta = chunk.choices[0].delta
        reasoning = getattr(delta, "reasoning_content", None)
        if reasoning:
            print(reasoning, end="", flush=True)
        if delta.content:
            print(delta.content, end="", flush=True)
    if chunk.usage:
        print("\nUsage:", chunk.usage)

On this page