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)
相关推荐
迎仔32 分钟前
计算机网络分层模型通俗指南 (OSI vs TCP/IP)
网络协议·tcp/ip·计算机网络
迎仔39 分钟前
HTTPS 原理与配置参数通俗指南
redis·网络协议·https
欧洵.1 小时前
HTTP协议详解Fiddler的安装与使用
网络·网络协议·http
runner365.git1 小时前
语言接入大模型,websocket还是webrtc?
websocket·网络协议·webrtc
煤炭里de黑猫1 小时前
# TCP/IP 协议栈深度解析:从体系架构到现代应用优化
网络协议·tcp/ip·架构
头发还没掉光光1 小时前
解决TCP粘包问题,使用C++实现TCP通信的自定义协议设计
linux·网络·c++·网络协议·tcp/ip
青火coding2 小时前
ai时代下的RPC传输——StreamObserver
qt·网络协议·microsoft·rpc
Tandy12356_12 小时前
手写TCP/IP协议栈——HTTP协议实现(完结篇)
c语言·网络·网络协议·tcp/ip·计算机网络·http
yangSnowy12 小时前
webSocket 通信详解
网络·websocket·网络协议
丁总学Java12 小时前
微信小程序上传揭秘:http://tmp 临时文件是如何“飞”到后端的?
http·微信小程序·小程序