文心千帆官网申请使用:点击
1、申请使用
2、使用并创建应用
Python调用
代码(GUI) 代码出处:点我
from tkinter import *
from tkinter import messagebox
import json
import requests
API_KEY = "API KEY内容"
SECRET_KEY = "Secret Key内容"
def main():
win = Tk()
win.geometry('600x500+0+0')
win.title('学霸小鼠研发团队-你问我答')
win.resizable(False, False)
win.config(background='light green')
Label(win, text='你问我答', font=('黑体', 20), bg='light green').pack()
Label(win, text='小鼠Bot(AI)', font=('宋体', 15), bg='light green').pack(pady=10)
e3 = Text(win, width=55, height=15, relief=FLAT, font=('宋体', 15))
scrollbary = Scrollbar(win, orient=VERTICAL) # 滚轮初始
scrollbary.pack(fill=Y, side=RIGHT)
e3.pack()
scrollbary.config(command=e3.yview)
e3.config(yscrollcommand=scrollbary.set)
e3.configure(state='disable')
# e3.configure(state='normal')
Label(win, text='提问区', font=('宋体', 15), bg='light green').pack(pady=5)
e5 = Text(win, width=66, height=2, relief=FLAT, font=('楷体', 10))
e5.place(x=15, y=420)
def question():
e3.configure(state='normal')
e3.delete('1.0', 'end')
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + get_access_token()
payload = json.dumps({
"messages": [
{
"role": "user",
"content": e5.get('1.0', 'end')
},
]
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
aso = response.text
result = json.loads(aso)
e3.insert('1.0', result['result'])
e3.configure(state='disable')
Button(win, text='提问', bg='blue', fg='white', width=10, height=1, relief=FLAT, command=question).place(x=485,
y=420)
Label(win, text='本产品由百度文心千帆的提供服务,作者:学霸小鼠研发团队(复杂问题可能会卡顿,属于正常现象,请耐心等待)',
font=('宋体', 8), bg='light green').pack(side='bottom')
win.mainloop()
def get_access_token():
"""
使用 AK,SK 生成鉴权签名(Access Token)
:return: access_token,或是None(如果错误)
"""
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
return str(requests.post(url, params=params).json().get("access_token"))
if __name__ == '__main__':
main()