当前位置: 首页> 汽车> 维修 > 异步调用openai接口,流式响应

异步调用openai接口,流式响应

时间:2025/7/12 2:13:04来源:https://blog.csdn.net/zhilaizhiwang/article/details/141689822 浏览次数: 0次

服务端

import json
import uvicorn
from openai import AsyncOpenAI
from fastapi import FastAPI, Request,responsesclient = AsyncOpenAI(api_key="",base_url="https://open.bigmodel.cn/api/paas/v4/"
) 
MODEL = "glm-4-flash"
app = FastAPI()@app.route("/stream")
async def stream_endpoint(request: Request):async def response_stream():completion = client.chat.completions.create(model=MODEL,messages=[{"role": "system", "content": "你是一个聪明且富有创造力的小说作家"},{"role": "user", "content": "请你作为童话故事大王,写一篇短篇童话故事。"}],top_p=0.7,temperature=0.9,stream=True)partition = []async for chunk in await completion:partition.append(chunk.choices[0].delta.content)# 每次生成器产生数据时,发送到客户端# yield json.dumps(chunk.model_dump(), ensure_ascii=False) + "\n"yield ''.join(partition) + "\n"return responses.StreamingResponse(response_stream())if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8000)

调用方法

import requests
with requests.get('http://localhost:8000/stream', stream=True) as r:for line in r.iter_lines():if line:decoded_line = line.decode('utf-8')print(decoded_line)
关键字:异步调用openai接口,流式响应

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: