回到首页 返回首页
回到顶部 回到顶部
返回上一页 返回上一页

【FireBeetle 2 ESP32 P4 开发套件】AI 智能体对话 简单

头像 无垠的广袤 2025.08.14 24 0

 

本文介绍了 DFRobot FireBeetle 2 ESP32 P4 开发套件通过 API 接入 AI 模型实现与智能体对话的项目设计。

 

项目介绍

 

一般流程:流程图、代码、对话演示;

更换 AI 模型:结合小智开发者平台提供的云雾 API 解决方案,实现 AI 模型的快速切换与测试;

 

项目方案

 

包括流程图、工程代码、效果演示等。

 

流程图

 

flowchart_gpt_talk.jpg

 

工程代码

 

运行 Thonny IDE 软件,配置解释器和设备端口,新建文件并添加如下代码

 

import network
import time
import urequests
import ujson
import micropython
import select
import sys
from machine import reset

# ====== 配置部分 ======
SSID = 'xxx'
PASSWORD = 'xxx'
API_URL = "https://api.siliconflow.cn/v1/chat/completions"
API_KEY = "sk-fzvjpoldzvxxxvdrvrjiadercddliahbfyohdrnfnnaedjmt"  # 替换为实际API密钥

# ====== 系统状态 ======
class SystemStatus:
    WIFI_CONNECTED = 1
    WIFI_DISCONNECTED = 0

# ====== WiFi连接 ======
def connect_wifi(max_retries=3):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    
    retry_count = 0
    while retry_count < max_retries:
        if not wlan.isconnected():
            print(f"尝试连接WiFi {SSID}... (尝试 {retry_count + 1}/{max_retries})")
            wlan.connect(SSID, PASSWORD)
            
            timeout = 20
            while not wlan.isconnected() and timeout > 0:
                print(".", end="")
                time.sleep(1)
                timeout -= 1
            
            if wlan.isconnected():
                print("\nWiFi连接成功!")
                print("IP地址:", wlan.ifconfig()[0])
                return SystemStatus.WIFI_CONNECTED
        
        retry_count += 1
        if retry_count < max_retries:
            print("\n连接失败,5秒后重试...")
            time.sleep(5)
    
    print("\nWiFi连接失败,请检查配置后重启设备")
    return SystemStatus.WIFI_DISCONNECTED

# ====== API请求处理 ======
def chat_with_ai(prompt):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "Qwen/Qwen3-8B",
        "messages": [
            {"role": "system", "content": "你是我的AI助手小智,你必须用中文回答且字数不超过85个"},
            {"role": "user", "content": prompt}
        ],
    }
    
    try:
        response = urequests.post(
            API_URL,
            headers=headers,
            data=ujson.dumps(payload).encode('utf-8'),
            timeout=10
        )
        
        if response.status_code == 200:
            json_resp = response.json()
            return json_resp['choices'][0]['message']['content']
        else:
            return f"错误: API返回状态码 {response.status_code}"
            
    except Exception as e:
        return f"请求出错: {str(e)}"
    finally:
        if 'response' in locals():
            response.close()

# ====== 主循环 ======
def main_loop():
    print("\n=== 小智AI助手已就绪 ===")
    print("输入您的问题后按回车,输入'退出'结束对话\n")
    
    micropython.kbd_intr(-1)  # 禁用键盘中断
    
    while True:
        # 检查WiFi连接
        wlan = network.WLAN(network.STA_IF)
        if not wlan.isconnected():
            print("\nWiFi连接断开,尝试重新连接...")
            if connect_wifi() == SystemStatus.WIFI_DISCONNECTED:
                print("无法恢复WiFi连接,系统将在5秒后重启...")
                time.sleep(5)
                reset()
        
        # 检查用户输入
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            user_input = sys.stdin.readline().strip()
            
            if user_input.lower() in ['退出', 'exit', 'quit']:
                print("\n对话结束,再见!")
                break
                
            if user_input:
                print("\n您:", user_input)
                print("小智正在思考...")
                
                start_time = time.time()
                response = chat_with_ai(user_input)
                response_time = time.time() - start_time
                
                print(f"小智 (响应时间: {response_time:.1f}s):", response)
                print("\n继续输入或输入'退出'结束对话:")

# ====== 系统启动 ======
print("=== 系统启动中 ===")
if connect_wifi() == SystemStatus.WIFI_CONNECTED:
    try:
        main_loop()
    except KeyboardInterrupt:
        print("\n用户中断,系统退出")
    except Exception as e:
        print(f"系统错误: {e}, 即将重启...")
        time.sleep(3)
        reset()
else:
    print("系统将在5秒后重启...")
    time.sleep(5)
    reset()

 

修改配置信息,包括 WiFi 名称和密码、API Key、URL、模型名称等;

保存代码,运行程序;

输入问题并回车,实现对话;

输入 exit 退出程序。

 

效果演示

 

通过对话测试 AI 模型的接入效果。

 

你是谁

 

ai_talk_who.png

 

你在哪

 

ai_talk_where.jpg

 

讲个笑话

 

ai_talk_funny.jpg

 

micropython

 

ai_talk_micropython.jpg

 

薛定谔方程

 

ai_ask_schrodinger.jpg

 

麦克斯韦方程

 

ai_ask_maxwell.jpg

 

关机

 

ai_talk_shut.jpg

 

更换模型

 

进入 小智 API 首页 的文档页面;

进入 发出请求 标签页,获取聊天智能体 URL https://aifuture.pw/v1/chat/completions ;

进入 中转站基本介绍 - API 快速开始指南 页面;

 

xiaozhi-api.jpg

 

根据教程和提示完成 注册

进入 API令牌 标签页,选择 添加令牌 ;

 

yunwu-api.jpg

 

点击查看,复制 API Key .

 

代码

 

# ------------------------------------------------------------------------------
#  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://yunwu.ai/v1/chat/completions"
API_KEY       = "sk-3sIrxxK0xxOJcIxx9Okfxx0xxqhfa31xxxxJsOdCxx5f1Txx"

# ------------------------------------------------------------------------------
#  CONSTANTS
# ------------------------------------------------------------------------------
class SystemStatus:
    WIFI_CONNECTED    = 1
    WIFI_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 = 20
            while not sta.isconnected() and timeout:
                print(".", end="")
                time.sleep(1)
                timeout -= 1

            if sta.isconnected():
                print("\nWi-Fi connected successfully!")
                print("IP address:", sta.ifconfig()[0])
                return SystemStatus.WIFI_CONNECTED

        if 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":       "gpt-3.5-turbo",
        "messages":    [{"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 . Type 'exit' or 'quit' to leave.\n")

    micropython.kbd_intr(-1)  # disable Ctrl-C

    while True:
        # Re-establish Wi-Fi if lost
        sta = 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 check
        if 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!")
                break

            if user_input:
                print("\nYou:", user_input)
                print("Thinking...")

                t0 = time.time()
                reply = chat_with_ai(user_input)
                elapsed = time.time() - t0

                print(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 退出程序。

 

测试效果

 

who are you

 

ai_chat_who.jpg

 

feeling

 

ai_ask_feelings.jpg

 

weather

 

ai_chat_weather.jpg

 

总结

 

本文介绍了 DFRobot FireBeetle 2 ESP32 P4 开发套件通过 API 接入 AI 模型,实现与 AI 智能体对话的项目设计。包括项目介绍、项目方案、流程图、工程代码、效果演示、模型切换等,为该开发板在人工智能和边缘 AI 领域的应用提供了参考。

评论

user-avatar