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)
相关推荐
moonless02225 小时前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
量子位1 天前
GPT-5编程专用版发布!独立连续编程7小时,简单任务提速10倍,VS Code就能用
gpt·chatgpt
FPGA_Linuxer1 天前
FPGA 40 DAC线缆和光模块带光纤实现40G UDP差异
网络协议·fpga开发·udp
real 11 天前
传输层协议UDP
网络·网络协议·udp
ftpeak2 天前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
hsjkdhs2 天前
网络编程之UDP广播与粘包问题
网络·网络协议·udp
yzx9910132 天前
接口协议全解析:从HTTP到gRPC,如何选择适合你的通信方案?
网络·人工智能·网络协议·flask·pygame
板鸭〈小号〉2 天前
UDP-Server(3)chat聊天室
网络·网络协议·udp
Code_流苏2 天前
AI热点周报(9.7~9.13):阿里Qwen3-Next震撼发布、Claude 增强记忆与服务抖动、OpenAI 聚焦模型规范化...
人工智能·gpt·ai·openai·claude·qwen3-next·架构创新
weixin_456904272 天前
使用HTTPS 服务在浏览器端使用摄像头的方式解析
网络协议·http·https