赞
踩
目录
因为网上用micropython接入百度大模型的资料太少了,就自己查了百度api文档改了一个
一、如何获取百度模型API
这东西网上有很多,我就不过多赘述
我参考的是这篇(就因为他是用arduino写的所以才有这篇文章)
https://vor2345.blog.csdn.net/article/details/135372118
1.Thonny(新手推荐)
2.烧录好最新micropython固件的esp32开发板(防止固件中有的库没有)
3.有Wifi
micropython代码是根据百度官方给的python代码改的
- import network
- import requests
- import json
- #替换你自己的应用API Key、应用Secret Key
- url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]"
- #填入你的问题
- "content": "现在几点了?"
- #填入你的WiFi信息
- wlan.connect('WiFi名称', 'WiFi密码')
- import network
- import requests
- import json
-
- def get_access_token():
- #使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
- url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]"
- payload = json.dumps("")
- headers = {
- 'Content-Type': 'application/json',
- 'Accept': 'application/json'
- }
-
- response = requests.request("POST", url, headers=headers, data=payload)
- return response.json().get("access_token")
-
- def main():
- #与大模型进行对话
- url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-0205?access_token=" + get_access_token()
-
- payload = json.dumps({
- "messages": [
- {
- "role": "user",
- "content": "为现在几点了?" #填入你的问题
- }
- ]
- })
- headers = {
- 'Content-Type': 'application/json'
- }
-
- response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
- print(response.text)
- answer = response.json().get("result")
- print(answer)
-
-
-
- if __name__ == '__main__':
- #连接WiFi
- wlan = network.WLAN(network.STA_IF)
- wlan.active(True)
- wlan.connect('WiFi名称', 'WiFi密码')#填入你的WiFi
- while not wlan.isconnected():
- pass
- print(wlan.ifconfig())
- main()
上面的代码每次运行都会进行一次taken请求,会拖慢运行速度。所以可以每月请求一次接口taken,再将taken直接填入,如下:
- import network
- import requests
- import json
-
- def main():
- #与大模型进行对话
- url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-0205?access_token=[你获取的接口taken]"
-
- payload = json.dumps({
- "messages": [
- {
- "role": "user",
- "content": "为现在几点了?" #填入你的问题
- }
- ]
- })
- headers = {
- 'Content-Type': 'application/json'
- }
-
- response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
- print(response.text)
- answer = response.json().get("result")
- print(answer)
-
- if __name__ == '__main__':
- main()
这样就可以通过micropython调用百度千帆大模型了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。