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)
相关推荐
esabby29 分钟前
253个原生IP + 40M独享回国带宽:香港站群服务器的硬核拆解
服务器·网络协议·tcp/ip
无糖可乐没有灵魂1 小时前
Security ❀ Https TLS抓包操作与解密配置
网络协议·http·https
treesforest1 小时前
随意装软件也会被恶意IP入侵电脑?
网络·网络协议·tcp/ip·网络安全·ip属地·查ip归属地
可爱系程序猿10 小时前
网络打印机地址正常却无法出纸:从 TCP/IP 端口到 Print Spooler 的排错步骤
网络·网络协议·tcp/ip
半亩码田13 小时前
AI周报 | DeepSeek-V4-Flash 正式版(7-31)、Wan2.6 全链路、GPT-5.6 降价 80%(上周 07.27-08.02)
人工智能·gpt
liulilittle15 小时前
UCP 控制协议 [简述]
网络·网络协议·计算机网络·udp·ip·通信
梦想的颜色16 小时前
2026 硬核横评:DeepSeek‑V4‑Flash VS OpenAI Codex (GPT‑5.6‑Codex) 代码模型全方位对比
gpt·codex·deepseek·ai 代码大模型·大模型 api 选型
Yan_chen66618 小时前
SSH(Secure Shell)安全外壳协议详解
运维·网络协议·ssh
RAOY的AI笔记20 小时前
# ChatGPT Plus 辅助分析 Python 异常堆栈:从日志脱敏到回归测试
gpt·chatgpt
GIR12320 小时前
研究更新:2026年网络协议分析工具发展前景与竞争格局报告(附市场占有率与产业链图谱)
网络·网络协议