流式输出
把 stream 设为 true,模型会边生成边返回,以 SSE(Server-Sent Events)的形式逐段推送。长回复、长任务建议使用流式输出,能更早看到结果,也不容易因为长时间没有数据而被中间网络断开。
from openai import OpenAI
client = OpenAI(api_key="<你的 API Key>", base_url="https://api.tokenjoy.org/v1")
stream = client.chat.completions.create(
model="gpt-5",
messages=[{"role": "user", "content": "写一首关于秋天的短诗"}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)流式输出结束时,最后的数据块里带有本次请求的 token 用量。OpenAI 格式需要在请求中加上 stream_options: {"include_usage": true} 才会返回。