python接入百度智能云API实现ai对话

python接入百度智能云API实现ai对话

千帆大模型平台-百度智能云千帆

代码段:

import requests
import json

# 获取访问令牌的函数
def get_access_token():
    # 百度AI开放平台的API地址,用于获取access_token
    url = "个人url"

    # 将空字符串转换为JSON格式
    payload = json.dumps("")
    # 设置请求头,指定内容类型为JSON
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    # 发送POST请求到指定的URL,并获取响应
    response = requests.request("POST", url, headers=headers, data=payload)
    # 将响应体解析为JSON格式,并获取access_token
    return response.json().get("access_token")

def AI(user_input):
    # 获取用户输入
    # user_input = input("asking:")
    # 构造请求URL,包含访问令牌
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + get_access_token()

    # 构造请求体,包含用户输入和其他参数
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": user_input
            }
        ],
        "stream": False,
        "temperature": 0.9,
        "top_p": 0.7,
        "penalty_score": 1,
        "system": "猫娘",
        "max_output_tokens": 1000,
        "frequency_penalty": 0.1,
        "presence_penalty": 0.0,
    })
    # 设置请求头,指定内容类型为JSON
    headers = {
        'Content-Type': 'application/json'
    }

    # 发送POST请求到指定的URL,并获取响应
    response = requests.request("POST", url, headers=headers, data=payload)
    # 将响应体解析为Python字典
    response_data = response.json()
    # 检查响应中是否包含结果
    if 'result' in response_data:
        print(response_data['result'])
    else:
        print("没有返回结果或结果格式不正确。")

# 主函数
def main():
    AI("who")  # 提问,让她自我介绍

    user_input = input("可以向我提问任何问题~\n提问:")
    if user_input.lower() in ["不聊了", "再见", "没了"]:  # 增加退出词
        print("再见啦,拜拜~")
    else:
        AI(user_input)  # 循环提问

        while True:
            user_input = input("还有什么问题想问我喵:")
            if user_input.lower() in ["不聊了", "再见", "没了","拜拜"]:  # 增加退出词
                print("再见啦,拜拜~")
                break
            AI(user_input)  # 循环提问

# 程序入口
if __name__ == '__main__':
    main()

实现效果

image-20241204200403150

posted @ 2024-12-04 20:07  沁拒离  阅读(253)  评论(0)    收藏  举报