Python实现调用GPT-4o大模型接口

Python原生POST请求实现流式输出和非流式输出两种形式
import json
import re

import requests

url = "https://api.xi-ai.cn/v1/chat/completions"  # 替换为目标URL
data = {
    "model": "gpt-4o",
    "messages": [
        {
            "role": "user",
            "content": '''
            golang实现客服系统
            '''
        },
    ]
}
headers = {
    "Authorization": "Bearer sk-GEkBBUEHN2xxx01cBf4b5bAcs9cD6Fc15Ef03301",
}
response = requests.post(url, json=data, headers=headers, timeout=600)
json_data = response.json()
print(json_data)
aiReply = ""
if "choices" in json_data:
    aiReply = json_data["choices"][0]["message"]["content"]
print(aiReply)
import json
import requests

url = "https://api.xi-ai.cn/v1/chat/completions"  # 替换为目标URL
data = {
    "stream": True,
    "model": "gpt-4o",
    "messages": [
        {
            "role": "user",
            "content": "golang实现客服系统"
        },
    ]
}
headers = {
    "Authorization": "Bearer sk-uXADzlDtsss7d44Cb9a604934ssss6Ef751",
}

# 使用 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:
            break
        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)

 

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容