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 小时前
C/C++ Linux网络编程15 - 网络层IP协议
linux·网络·c++·网络协议·tcp/ip·计算机网络·网络层
CodeByV5 小时前
【网络】UDP 协议深度解析:从五元组标识到缓冲区
网络·网络协议·udp
车载测试工程师6 小时前
CAPL学习-AVB交互层-概述
网络协议·tcp/ip·以太网·capl·canoe
鲸鱼电台分台8 小时前
工业应用通信协议:IEC104
网络协议
百***07459 小时前
GPT-5.2与Gemini 3.0 Pro技术选型指南:核心能力对比+第三方API接入全攻略
gpt
无敌最俊朗@10 小时前
WebSocket与Webhook:实时通信技术对比
网络·websocket·网络协议
百***243710 小时前
GPT5.1 vs Claude-Opus-4.5 全维度对比及快速接入实战
大数据·人工智能·gpt
2301_7737303112 小时前
系统编程—IPC进程间通信
网络·网络协议
Neolnfra12 小时前
渗透测试标准化流程
开发语言·安全·web安全·http·网络安全·https·系统安全
fiveym13 小时前
Apache HTTP 服务搭建全攻略
网络协议·http·apache