ESP32本地大模型对话机器人制作教程
esp32ollama大语言模型
·
整体架构
在本地电脑部署好Ollama服务,安装qwen大模型和llama3.1大模型。
ESP32接入局域网,用户通过串口给esp32发送问题,esp32打包json后向ollama服务发送请求,ollama返回响应,esp32解析结果并通过串口打印出来。
运行效果
串口输入问题后,会打印出回答的结果。
完整代码
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "EzhanNet";
const char* password = "11111111";
const char* serverUrl = "http://192.168.0.121:9998/api/generate";
void sendPostRequest(const String& prompt) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverUrl);
http.addHeader("Content-Type", "application/json");
// 创建 JSON 数据
StaticJsonDocument<200> jsonDoc;
jsonDoc["model"] = "llama3.1";
jsonDoc["prompt"] = prompt;
jsonDoc["stream"] = false;
// 将 JSON 转换为字符串
String jsonString;
serializeJson(jsonDoc, jsonString);
// 发送 HTTP-POST 请求
int httpResponseCode = http.POST(jsonString);
// 检查响应代码
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Response code: " + String(httpResponseCode));
// 解析 JSON 响应
DynamicJsonDocument docJson(1024);
DeserializationError error = deserializeJson(docJson, response);
if (!error) {
const char* response_info = docJson["response"];
Serial.println("Ollama 回答: " + String(response_info));
} else {
Serial.println("解析 JSON 失败: " + String(error.c_str()));
}
} else {
Serial.println("发送 POST 时出错: " + String(httpResponseCode));
}
http.end();
} else {
Serial.println("WiFi 未连接");
}
}
void setup() {
Serial.begin(115200);
// 连接到 WiFi
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 10) {
delay(500);
Serial.println("连接到 WiFi...");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("已连接到 WiFi");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("连接 WiFi 失败");
}
}
void loop() {
if (Serial.available() > 0) {
String userInput = Serial.readStringUntil('\n'); // 读取串口输入直到换行
sendPostRequest(userInput); // 发送给 Ollama
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)