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)
相关推荐
Yefimov1 天前
DPDK:从网络协议栈的角度来观察微内核
后端·网络协议
IT_Octopus1 天前
https私人证书 PKIX path building failed 报错解决
java·spring boot·网络协议·https
艾菜籽1 天前
网络原理-HTTPS
网络·网络协议·https
摇滚侠1 天前
什么是 mesh 组网
网络协议
Arva .1 天前
HTTP Client
网络协议·http·lua
2301_772093562 天前
tuchuang_后端_前端_注册登录
数据库·后端·网络协议·mysql·wireshark
程序员三明治2 天前
HTTPS 真的牢不可破吗?—— 中间人攻击与安全机制解析
网络协议·安全·https
2501_915106322 天前
CDN 可以实现 HTTPS 吗?实战要点、部署模式与真机验证流程
网络协议·http·ios·小程序·https·uni-app·iphone
千里马-horse2 天前
HTTP、WebSocket、XMPP、CoAP、MQTT、DDS 六大协议在机器人通讯场景应用
mqtt·websocket·http·机器人·xmpp·coap·fastdds
安卓开发者2 天前
鸿蒙NEXT网络通信实战:使用HTTP协议进行网络请求
网络·http·harmonyos