OpenAI库的流式输出模式
发布时间:2026/10/20 8:22:34 锦皓数字建站

可以设定结果输出为stream模式流式输出获得更好的使用体验开启流式输出主要就2步在client.chat.completions.create()调用模型的时候设定参数:streamTruefor循环response对象并在循环内输出内容from openaiimportOpenAI from openai.types.chat.chat_completionimportChatCompletion# 获取client对象OpenAI类对象clientOpenAI(base_urlhttps://llm-w51hypeilnm3yxpr.cn-beijing.maas.aliyuncs.com/compatible-mode/v1,)# 调用模型response:ChatCompletionclient.chat.completions.create(modelqwen3.8-27b, messages[{role:system,content:你是一个python专家},{role:assistant,content:好的我是编程专家},{role:user,content:输出1-10数字用python代码}], streamTrue)forchunkinresponse:ifnot chunk.choices:continueprint(chunk.choices[0].delta.content,end,flushTrue)
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。