程式(黃色部份需設定到您用的MQTT broker):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import os import json from phi.agent import Agent from phi.model.ollama import Ollama import paho.mqtt.client as mqtt import random MQTT_BROKER = os.getenv("MQTT_BROKER") MQTT_PORT = int(os.getenv("MQTT_PORT")) MQTT_USER = os.getenv("MQTT_USER") MQTT_PASSWORD = os.getenv("MQTT_PASSWORD") MQTT_TOPIC = "NFU/LED" client_id = f'python-mqtt-{random.randint(0, 1000)}' def control_led(action: bool): try: client = mqtt.Client(client_id) client.username_pw_set(MQTT_USER, MQTT_PASSWORD) client.connect(MQTT_BROKER, MQTT_PORT, 60) message = json.dumps({"action": "on" if action else "off"}) client.publish(MQTT_TOPIC, message) client.disconnect() return f"成功{'打開' if action else '關閉'} LED" except Exception as e: print(f"Debug - MQTT Error: {str(e)}") print(f"Debug - MQTT Settings: Broker={MQTT_BROKER}, Port={MQTT_PORT}") return f"LED 控制失敗: {str(e)}" led_agent = Agent( name="LED Control Agent", role="控制 LED 開關", instructions=[ "你是一個 LED 控制助手,負責解析用戶的開關燈指令。", "當用戶要求打開 LED 時,呼叫 control_led(True)", "當用戶要求關閉 LED 時,呼叫 control_led(False)", "對於不明確的指令,請詢問用戶具體需求" ], tools=[control_led], model=Ollama(id="llama3.2") ) def main(): print("智能助理已啟動!(輸入 'exit' 結束程式)") print("您可以:") print("1. 控制 LED 開關 (例如:'請打開 LED' 或 '關燈')") while True: user_input = input("\n請輸入指令: ").strip() if user_input.lower() == 'exit': print("程式已結束") break try: response = led_agent.run(user_input, stream=False) for message in response.messages: if message.role == "assistant" and message.content: print("\n助理回應:", message.content.strip()) except Exception as e: print(f"\n錯誤:{str(e)}") if __name__ == "__main__": main() |
執行結果:
智能助理已啟動!(輸入 'exit' 結束程式)
您可以:
1. 控制 LED 開關 (例如:'請打開 LED' 或 '關燈')
請輸入指令: 請打開 LED
助理回應: 您可以開始使用 LED 的功能了。
請輸入指令: 我要睡覺了
助理回應: LEDs 已經關閉,好night!
請輸入指令:
沒有留言:
張貼留言