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)
相关推荐
德迅云安全—珍珍33 分钟前
什么是udp攻击,为什么udp攻击难防御
网络·网络协议·udp
talenteddriver3 小时前
web: http请求(自用总结)
前端·网络协议·http
乾元4 小时前
AI 驱动的入侵检测与异常会话判别:从规则到行为分析前言:从“捕获敌人”到“守卫秩序”
运维·网络·人工智能·网络协议·安全
文弱书生6565 小时前
4-electronbot-USB协议前置知识
网络协议
LCG米6 小时前
车载以太网SOME/IP协议栈在TI TDA4VM平台上的实现与测试
网络·网络协议·tcp/ip
chalmers_157 小时前
将单个 WebSocket 客户端封装为实例
服务器·websocket·网络协议
ZeroNews内网穿透9 小时前
EasyNode 结合 ZeroNews,实现远程管理服务器
运维·服务器·网络协议·安全·http
IT 行者11 小时前
Spring Boot 4 升级指南:告别RestTemplate,拥抱现代HTTP客户端
spring boot·后端·http
老王熬夜敲代码11 小时前
TCP相关问题的解决
linux·网络·笔记·网络协议
YouEmbedded11 小时前
解码Qt HTTP+JSON实战(天气GET解析/百度AI POST封装)
qt·http·qjson