当前位置: 首页 > news >正文

使用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,请求格式即可。十分简单!

相关文章:

  • AI关于SHAP分析与列线图(算法)解释线性模型矛盾之处的解释
  • 网络流算法: Edmonds-Karp算法
  • PostgreSQL的基本使用
  • PCEP介绍
  • C++ ++++++++++
  • 上海市计算机学会竞赛平台2024年4月月赛丙组排序分数
  • HTML元素,标签到底指的哪块部分?单双标签何时使用?
  • MySQL Connector/J下载
  • 【学习笔记】三维点云空洞修复介绍(二)Grids-based
  • 20250225-代码笔记03-class CVRPModel AND other class
  • 每日十个计算机专有名词 (7)
  • 三个小时学完vue3(一)
  • L2-043 龙龙送外卖(dfs)
  • Java中的ArrayDeque
  • 安全运营的“黄金4小时“:如何突破告警疲劳困局
  • WSDM24-因果推荐|因果去偏的可解释推荐系统
  • leetcode-442.数组中重复的数据
  • 用Java编写sql
  • 51单片机中reg52.h与regx52.h在进行位操作时的不同
  • 大语言模型:从诞生到未来的探索
  • 做网站属于广告费吗/2023网站分享
  • 昆明网站排名/成都seo优化
  • 域名注册需要多久/外贸seo推广招聘
  • 青岛网站设计流程/百度推广靠谱吗
  • 广州知名网站建设后台管理便捷/搜索引擎营销的主要方法
  • 网站建设的代理/阿里指数查询手机版