ChatECNU 边缘 AI 智能体对话
ChatECNU 边缘 AI 智能体对话
介绍了 ESP32 P4 通过 API 接入 ChatECNU 大模型应用平台,实现边缘 AI 部署与智能体对话的项目设计。
介绍
-
流程图、代码、对话演示;
-
结合 ChatECNU 开发者平台提供的 API 解决方案,实现 AI 模型的单片机板端调用以及快速对话测试;
API 获取详见:华东师范大学开发者平台 .
硬件
采用 DFRobot FireBeetle 2 ESP32-P4开发板 .
流程图
代码
-
烧录 ESP32 官方提供的 MicroPython 固件;
-
运行 Thonny IDE 软件,配置解释器和设备端口,新建文件并添加如下代码
# ------------------------------------------------------------------------------
# MicroPython AI Chat Agent
# ------------------------------------------------------------------------------
import network
import time
import urequests
import ujson
import micropython
import select
import sys
from machine import reset# ------------------------------------------------------------------------------
# CONFIGURATION
# ------------------------------------------------------------------------------
WIFI_SSID = "xxx"
WIFI_PASSWORD = "xxx"API_ENDPOINT = "https://chat.ecnu.edu.cn/open/api/v1/chat/completions"
API_KEY = "sk-4160d6151421480b83fa9f0c264a7xxx"# ------------------------------------------------------------------------------
# CONSTANTS
# ------------------------------------------------------------------------------
class SystemStatus:WIFI_CONNECTED = 1WIFI_DISCONNECTED = 0# ------------------------------------------------------------------------------
# Wi-Fi CONNECTION
# ------------------------------------------------------------------------------
def connect_wifi(max_retries: int = 3) -> int:sta = network.WLAN(network.STA_IF)sta.active(True)for attempt in range(1, max_retries + 1):if not sta.isconnected():print(f"Connecting to Wi-Fi '{WIFI_SSID}'... (attempt {attempt}/{max_retries})")sta.connect(WIFI_SSID, WIFI_PASSWORD)timeout = 20while not sta.isconnected() and timeout:print(".", end="")time.sleep(1)timeout -= 1if sta.isconnected():print("\nWi-Fi connected successfully!")print("IP address:", sta.ifconfig()[0])return SystemStatus.WIFI_CONNECTEDif attempt < max_retries:print("\nConnection failed, retrying in 5 s...")time.sleep(5)print("\nUnable to connect to Wi-Fi. Please check credentials.")return SystemStatus.WIFI_DISCONNECTED# ------------------------------------------------------------------------------
# AI CHAT HELPERS
# ------------------------------------------------------------------------------
def chat_with_ai(prompt: str) -> str:headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json"}payload = ujson.dumps({"model": "ecnu-plus","messages": [{'role': 'system', 'content': 'You are a helpful assistant.'},{"role": "user", "content": prompt}],"temperature": 0.7,"max_tokens": 200})try:resp = urequests.post(API_ENDPOINT,headers=headers,data=payload.encode("utf-8"),timeout=15)if resp.status_code == 200:data = resp.json()return data["choices"][0]["message"]["content"]else:return f"API error: HTTP {resp.status_code}\n{resp.text}"except Exception as e:return f"Request failed: {e}"finally:try:resp.close()except:pass# ------------------------------------------------------------------------------
# MAIN LOOP
# ------------------------------------------------------------------------------
def main_loop():print("\n=== AI Agent Ready ===")print("Type your question and press <Enter>. Type 'exit' or 'quit' to leave.\n")micropython.kbd_intr(-1) # disable Ctrl-Cwhile True:# Re-establish Wi-Fi if loststa = network.WLAN(network.STA_IF)if not sta.isconnected():print("\nWi-Fi lost, attempting to reconnect...")if connect_wifi() == SystemStatus.WIFI_DISCONNECTED:print("Cannot restore Wi-Fi. Rebooting in 5 s...")time.sleep(5)reset()# Non-blocking keyboard checkif sys.stdin in select.select([sys.stdin], [], [], 0)[0]:user_input = sys.stdin.readline().strip()if user_input.lower() in {"exit", "quit"}:print("\nGood-bye!")breakif user_input:print("\nYou:", user_input)print("Thinking...")t0 = time.time()reply = chat_with_ai(user_input)elapsed = time.time() - t0print(f"AI ({elapsed:.1f} s): {reply}")print("\nAsk another question or type 'exit' to leave.")# ------------------------------------------------------------------------------
# ENTRY POINT
# ------------------------------------------------------------------------------
print("=== Booting System ===")
if connect_wifi() == SystemStatus.WIFI_CONNECTED:try:main_loop()except KeyboardInterrupt:print("\nInterrupted by user — shutting down")except Exception as e:print(f"Fatal error: {e} — rebooting in 3 s...")time.sleep(3)reset()
else:print("Boot failed — rebooting in 5 s...")time.sleep(5)reset()
- 修改配置信息,包括 WiFi 名称和密码、API Key、URL、模型名称等;
- 保存代码,运行程序;
- 输入问题并回车,实现对话;
- 输入 exit 退出程序。
效果
对话演示
提问演示
拓展演示
总结
介绍了 ESP32 P4 通过 API 接入 ChatECNU 大模型应用平台,实现边缘 AI 部署与智能体对话的项目设计,为该模型在边缘 AI 领域的开发和应用提供了参考。