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)
相关推荐
StevenSurpass1 小时前
打印业务彻底解耦:FastPrintAgent 统一 JSON 模型 + FastReport 引擎的设计与落地
mqtt·http·中间件·打印·fastreport
captain3764 小时前
网络原理(7)-NAT(Network Address Translation)
java·网络·网络协议·java-ee
西索斯coding4 小时前
GPT-5.6-Luna 接入 Cline 教程:base_url 配置、max_tokens 上限与 ZDR 请求头写法
大数据·人工智能·gpt·ai
爱研究的小梁4 小时前
异构链路科普:5G/4G、卫星、专网、WiFi、光纤,如何聚合工作?
网络·网络协议·udp·信息与通信
梦想平凡5 小时前
情怀棋牌源代码焕新记录(一):全新国风UI与原版工程梳理
java·服务器·数据库·websocket·网络协议·cocos2d
K成长日志6 小时前
DALI-2协议简介
网络·网络协议·智能楼宇·智能照明·智能建筑·dali
Shota Kishi14 小时前
Solana Shreds 的 UDP 直投架构:Shredstream UDP Forwarding 的设计与实现
网络协议·架构·udp·区块链·solana
玄芯散人1 天前
【筑基·055】TCP vs UDP:可靠和快速的取舍
网络协议·tcpdump
小此方1 天前
Linux网络(十二):HTTP短连接与长连接:从Connection机制到Cookie、Session,彻底理解HTTP的无状态
服务器·网络·http
whyfail1 天前
开发平替实录:ZCode + 火山 Coding Plan + GLM-5.3-Flash,打不过 GPT-5.6-Sol,但只差一口气的成本
gpt·codex·glm·智谱·zcode