使用esp32接入大模型(http请求)
本示例适用于所有乐鑫的esp32模组及开发板。使用串口通信和http协议。实现简单的和大模型对话要求。
话不多说直接上代码
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define DEBUG 1
// 替换为你的Wi-Fi网络凭据
#define WLAN_SSID "N/A"
#define WLAN_PASSWD "********"
// 响应超时时间,单位为毫秒.返回文字长度大则需要更长的时间
#define TIMEOUT_MS 30000
const char *TAG = "ESP_QWEN";
void DBG(const char *tag, const String message)
{
#ifdef DEBUG
Serial.printf("%s: %s\r\n", tag, message.c_str());
#endif
return;
}
// 替换为你的API密钥
const char *apiKey = "YourApiKey"; // API密钥
const char *apiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // API接口URL
// 发送请求到API
String getGPTAnswer(String inputText)
{
HTTPClient http;
http.setTimeout(TIMEOUT_MS); // 设置超时时间
http.begin(apiUrl);
http.addHeader("Content-Type", "application/json"); // 表示请求体为JSON格式
String token_key = String("Bearer ") + apiKey;
http.addHeader("Authorization", token_key);
// 调整payload以匹配Qwen API的要求
String payload = "{\"model\":\"qwen-plus\",\"messages\":[{\"role\": \"system\",\"content\": \"You are a helpful assistant.\"},{\"role\": \"user\",\"content\": \"" + inputText + "\"}]}";
int httpResponseCode = http.POST(payload);
if (httpResponseCode == 200)
{
String response = http.getString();
http.end();
DBG(TAG, "response:" + response);
// 解析JSON响应
DynamicJsonDocument jsonDoc(1024);
DeserializationError error = deserializeJson(jsonDoc, response);
if (error)
{
Serial.println("Failed to parse JSON response");
return "<error>";
}
String outputText = jsonDoc["choices"][0]["message"]["content"];
return outputText;
}
else
{
http.end();
Serial.printf("Error %i \n", httpResponseCode);
return "<error>";
}
}
void setup()
{
// 初始化串口
Serial.begin(115200);
// 连接到Wi-Fi网络
WiFi.mode(WIFI_STA);
WiFi.begin(WLAN_SSID, WLAN_PASSWD);
Serial.print("Connecting to WiFi ..");
int i = 0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(1000);
if (i++ > 10)
{
Serial.println("WiFi connect timeout");
ESP.restart();
}
}
Serial.print("\ngot IP:");
Serial.println(WiFi.localIP());
Serial.println("向qwen提问:");
}
void loop()
{
if (Serial.available())
{
String inputText = Serial.readStringUntil('\n');
inputText.trim();
Serial.println("Input: " + inputText);
String answer = getGPTAnswer(inputText);
Serial.println("Answer: " + answer);
Serial.println("向qwen提问:");
}
}
使用方法:首先需要连上本地WiFi,定义自己的WiFi ssid 和密码
定义debug函数,使用条件编译方便去除调试信息
随后需要设置超时时间,apikey和网址
在连上网后每当检测到串口输入:
将输入的字符串放入到预制的HTTP请求内容中。
首先通知服务器当前请求为json格式
注意请求头部需要加入Bearer 和apikey
Authorization用于通知服务器本次请求使用key来授权
将请求发送到服务器
等待服务器响应:
本示例不使用WebSocket,所以大模型输出的字符量越大,等待的延时就越长。
建议随实际使用调整缓冲区大小以及超时时间。
注意本示例的请求会消耗免费token数,不要频繁使用。
收到响应后会解析回复的json语句,解析出content并输出
如此循环往复。
如需使用其他大模型,更改网址,ApiKey,请求格式即可。十分简单!