HTTP方式请求并处理GPT聊天补全接口的流式响应输出

python使用HTTP方式,调用OpenAI的聊天补全的流式响应接口,并处理数据

目的是,如果需要对接fastGPT等其他第三方,需要额外增加参数,或者其他开发语言调用时,不能使用官方的类库。需要自行封装请求方法,那么可以参考代码,增加参数或转成相应语言

bash 复制代码
import json
import requests

url = "https://代理域名/v1/chat/completions"  # 替换为目标URL
data = {
    "stream": True,
    "model": "gpt-3.5-turbo",
    "messages": [
        {
            "role": "user",
            "content": "你是谁"
        },
    ]
}
headers = {
    "Authorization": "Bearer key",
}

# 使用 with 语句确保请求完成后释放资源
with requests.post(url, json=data, headers=headers, timeout=60000, stream=True) as response:
    # print(response.headers)
    for chunk in response.iter_lines(chunk_size=None):
        mChunk = chunk.decode('utf-8')
        if "[DONE]" in mChunk:
            continue
        # print(mChunk)
        lines = mChunk.splitlines()
        for line in lines:
            respStr = line.strip().replace("data: ", "")
            respContent = ""
            try:
                respJson = json.loads(respStr)
                respContent = respJson["choices"][0]["delta"]["content"]
            except  Exception as e:
                respContent = ""
            print(respContent)
相关推荐
esmember3 小时前
电路研究9.2.6——合宙Air780EP中HTTP——HTTP GET 相关命令使用方法研究
网络·网络协议·http·at指令
weisian1516 小时前
消息队列篇--通信协议篇--STOMP(STOMP特点、格式及示例,WebSocket上使用STOMP,消息队列上使用STOMP等)
websocket·网络协议
追风赶月、9 小时前
【网络】传输层协议UDP
网络·网络协议·udp
pingfanren29 小时前
kimi,天工,gpt,deepseek效果对比
gpt
产品媛Gloria Deng9 小时前
分享| RL-GPT 框架通过慢agent和快agent结合提高AI解决复杂任务的能力-Arxiv
人工智能·gpt·ai·agent·ai智能体
霸王蟹9 小时前
http和https的区别?
网络·笔记·网络协议·学习·http·https
精通HelloWorld!9 小时前
使用HttpClient和HttpRequest发送HTTP请求
java·spring boot·网络协议·spring·http
杨江9 小时前
DB-GPT试用
gpt
泪不是Web妳而流10 小时前
BurpSuite抓包与HTTP基础
网络·经验分享·网络协议·安全·http·网络安全·学习方法
zhuyasen11 小时前
多维度详细比较 kratos、go-zero、goframe、sponge 框架
后端·http·微服务·rpc·golang