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)
相关推荐
W.A委员会41 分钟前
常见网络攻击
网络·http·网络安全
TechWayfarer1 小时前
攻防对抗:利用IP段归属查询工具快速封禁攻击源——3步联动防火墙(附脚本)
python·网络协议·tcp/ip·安全
xixixi777775 小时前
从Mythos到GPT-5.4-Cyber:AI安全竞赛的“双轨”分化与防御新范式
网络·gpt·安全·机器学习·架构·大模型·claude
科技牛牛6 小时前
IP定位误差导致封号_深度解析
网络·网络协议·tcp/ip
思麟呀6 小时前
应用层协议HTTP
linux·服务器·网络·c++·网络协议·http
Aaron_Chou3137 小时前
如何在Trae中配置Claude,gpt-5.4,deepseek等大模型的中转API
人工智能·gpt·claude·deepseek·cline·trae
2501_948114247 小时前
2026旗舰模型四强争霸:GPT-5.4、Claude Opus 4.6、Gemini 3.1 Pro与Grok 4.20深度横评
人工智能·gpt·ai·谷歌
SiYuanFeng7 小时前
一展使用gpt-5-mini和gemini-3.1-flash-image-preview-0.5k的运行demo代码
linux·python·gpt
come112348 小时前
最新的 gpt 5.4 和 claude 4.7 模型为什么更好用
人工智能·gpt
pengyi8710159 小时前
共享IP使用基础注意事项,从源头降低关联风险
网络·网络协议·tcp/ip·安全·http