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)
相关推荐
傻啦嘿哟4 小时前
2026代理IP服务商深度测评:8家主流厂商的“极限压力测试“全记录
网络协议·tcp/ip·压力测试
%小农4 小时前
在cursor中使用server
网络·网络协议·http
ivy159868377155 小时前
芯锦科技 HP9117 多协议USB Type-A快充识别芯片
网络·科技·网络协议·5g·信号处理·p2p
zzh940776 小时前
2026年ChatGPT镜像技术评测:GPT-5.4与Claude 3.5深度对比
gpt·chatgpt
西红市杰出青年6 小时前
MCP 的三种数据传输模式教程(stdio / SSE / Streamable HTTP)
网络·网络协议·http·ai
.select.6 小时前
HTTPS 如何优化?
网络协议·http·https
三三有猫9 小时前
HTTP、HTTPS和SOCKS代理怎么选?
网络协议·http·https
guoji77889 小时前
chatGPT5.4镜像如何重塑复杂问题解决范式:从对话助手到智能体执行者
大数据·人工智能·gpt·chatgpt
ofoxcoding10 小时前
GPT-5 API 完全指南:性能实测、成本测算与接入方案(2026)
gpt·ai
北京耐用通信11 小时前
工业级抗干扰!耐达讯自动化CC-Link IE转Modbus RTU网关,稳定运行,让数据不丢包
人工智能·科技·物联网·网络协议·自动化·信息与通信