
ESP32S3接入deepseek大模型实现串口问答
ESP32S3接入deepseek大模型
·
1.准备:
esp32s3板子,wifi,deepseek api(需要充钱,1块钱即可)
2.编译环境:
Aeduino IDE v2.3.4
ESP32 board v3.1.1
3.deepseek创建API key获取api密钥
4.代码修改
修改为你的wifi和deepseek api密钥,修改完即可直接烧录
5.运行结果
提了问题之后回答有的慢,貌似还没有记忆功能。。。待完善。。。
6.源代码
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h> // 用于解析 JSON
// 替换为你的WiFi名称和密码
const char* ssid = "wifi名称";
const char* password = "wifi密码";
// DeepSeek API的URL
const char* deepseekUrl = "https://api.deepseek.com/v1/chat/completions";
// API密钥
const char* apiKey = "修改为你的api密钥";
// 超时时间(毫秒)
const unsigned long timeout = 30000; // 30秒
// 全局变量用于存储串口输入
String userInput = "";
void setup()
{
Serial.begin(115200);
// 连接WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// 提示用户输入问题
Serial.println("Enter your question:");
}
void loop()
{
// 检查串口是否有输入
if (Serial.available())
{
userInput = Serial.readStringUntil('\n'); // 读取用户输入
userInput.trim(); // 去除多余的空格和换行符
if (userInput.length() > 0)
{
Serial.println("Sending question to DeepSeek: " + userInput);
String response = sendDeepSeekRequest(userInput); // 调用请求函数
Serial.println("DeepSeek Response: " + response);
Serial.println("Enter your next question:");
}
}
}
// 发送请求到DeepSeek并返回回复内容
String sendDeepSeekRequest(String prompt)
{
WiFiClientSecure client;
HTTPClient http;
// 忽略证书验证(仅用于测试,生产环境不推荐)
client.setInsecure();
// 设置超时时间
http.setTimeout(timeout);
// 开始HTTP请求
if (http.begin(client, deepseekUrl))
{
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + apiKey);
// 构建请求体
String requestBody = "{
\"model\": \"deepseek-chat\",
\"messages\": [{
\"role\": \"user\", \"content\": \"" + prompt + "\"}]}";
// 发送POST请求
int httpResponseCode = http.POST(requestBody);
// 检查响应码
if (httpResponseCode > 0)
{
Serial.printf("HTTP Response code: %d\n", httpResponseCode);
// 获取响应内容
String response = http.getString();
http.end(); // 结束请求
// 解析 JSON 并提取回复内容或错误信息
return parseDeepSeekResponse(response, httpResponseCode);
}
else
{
Serial.printf("Error on sending POST: %s\n", http.errorToString(httpResponseCode).c_str());
http.end(); // 结束请求
return "Error: " + String(http.errorToString(httpResponseCode));
}
}
else
{
Serial.println("Failed to connect to DeepSeek API");
return "Error: Connection failed";
}
}
// 解析 DeepSeek 的 JSON 响应并提取回复内容或错误信息
String parseDeepSeekResponse(String jsonResponse, int httpResponseCode)
{
// 使用 ArduinoJson 解析 JSON
StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, jsonResponse);
if (error)
{
Serial.print("JSON parsing failed: ");
Serial.println(error.c_str());
return "Error: Failed to parse JSON";
}
// 检查是否是错误响应
if (httpResponseCode != 200)
{
const char* errorMessage = doc["error"]["message"];
if (errorMessage)
{
return "Error: " + String(errorMessage);
}
else
{
return "Error: Unknown error occurred";
}
}
// 提取回复内容
const char* content = doc["choices"][0]["message"]["content"];
if (content)
{
return String(content);
}
else
{
return "Error: No content found in response";
}
}
更多推荐
所有评论(0)