ChatGPT是一个非常热门的话题,而Python作为一门非常流行的编程语言,在本文中,我用Python和某平台的API编写一个简单的AI聊天APP。
import PySimpleGUI as sg
import requests
#在MiniMax开放平台体验中心鉴权信息页上获取group_id和api key
group_id = "请填写您的group_id"
api_key = "请填写您的api_key"
url = f'https://api.minimax.chat/v1/text/chatcompletion?GroupId={group_id}'
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
#prefix, user_name, bot_name = choose_prefix()
#tokens_to_generate可自行修改,范围为0-4096
request_body = {
"model":"abab5-chat",
"tokens_to_generate": 512,
'messages': []
}
sg.theme('BluePurple')
layout = [[sg.Text('输入你想要了解的内容:')],
[sg.Input(key='-IN-')],
[sg.Button('AI对话'), sg.Button('退出')],
[sg.Multiline(' ', key='_Multiline_', size=(48, 7), autoscroll=True)]]
window = sg.Window('AIChat APP', layout,icon='AI.ico')
#添加循环完成多轮交互
while True:
event, values = window.read()
# #print(event, values)
if event in (None, '退出'):
break
if event == 'AI对话':
# 下面的输入获取是基于python终端环境,请根据您的场景替换成对应的用户输入获取代码
line = values['-IN-']
# 将当次输入内容作为用户的一轮对话添加到messages
request_body['messages'].append({"sender_type": "USER", "text": line})
response = requests.post(url, headers=headers, json=request_body)
reply = response.json()['reply']
# print(f"reply: {reply}")
# 将当次的ai回复内容加入messages
request_body['messages'].append({"sender_type": "BOT", "text": reply})
# 获取AI Chat的回复
message = f"{reply}"
window.Element('_Multiline_').Update(message)
window.close()
用pyinstaller打包成exe文件。
打包后的exe文件
APP界面
#