HTTP方式请求并处理GPT聊天补全接口的流式响应输出

2024-01-03 02:27:46

python使用HTTP方式,调用OpenAI的聊天补全的流式响应接口,并处理数据
目的是,如果需要对接fastGPT等其他第三方,需要额外增加参数,或者其他开发语言调用时,不能使用官方的类库。需要自行封装请求方法,那么可以参考代码,增加参数或转成相应语言

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)

文章来源:https://blog.csdn.net/taoshihan/article/details/135351599
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。