Willkommen zur Projektseite Raspberry Pi Pico 2W & OpenAI-API. Hier dokumentieren wir Schritt für Schritt, wie aus einem kleinen Mikrocontroller ein leistungsfähiger KI-Chatbot mit ChatGPT wird.
Ziel dieses Projekts ist es, den Raspberry Pi Pico 2W so zu programmieren, dass er:
Im Folgenden findest Du das gesamte Programm. Trage Deine eigenen Zugangsdaten (WLAN-SSID, WLAN-Passwort und API-Key) ein.
import machine import network import requests import time # WLAN-Zugangsdaten wlanSSID = 'WLAN-Name' # <-- hier SSID eintragen wlanPW = 'WLAN-Passwort' # <-- hier Passwort eintragen network.country('DE') # OpenAI-API OPENAI_API_KEY = 'Dein API-KEY' # <-- hier API-Key einsetzen OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions' # Status-LED led_onboard = machine.Pin('LED', machine.Pin.OUT, value=0) # WLAN-Verbindung herstellen wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): print('WLAN-Verbindung herstellen:', wlanSSID) wlan.active(True) wlan.connect(wlanSSID, wlanPW) for i in range(10): if wlan.status() < 0 or wlan.status() >= 3: break led_onboard.toggle() print('.') time.sleep(1) # WLAN-Verbindung prüfen if wlan.isconnected(): print('WLAN-Verbindung hergestellt / WLAN-Status:', wlan.status()) led_onboard.on() ipconfig = wlan.ifconfig() print('IPv4-Adresse:', ipconfig[0]) else: led_onboard.off() print('WLAN-Status:', wlan.status()) raise RuntimeError('Keine WLAN-Verbindung') # Endlosschleife: Prompts absetzen while True: print() prompt = input('Prompt : ') if prompt != '': # HTTP-Header und Body für OpenAI header = { 'Authorization': 'Bearer ' + OPENAI_API_KEY, 'Content-Type' : 'application/json' } messages = { 'role': 'user', 'content': prompt } data = { 'model': 'gpt-3.5-turbo', 'temperature': 0.5, 'max_tokens': 150, 'messages': [ messages ] } # Anfrage an OpenAI response = requests.post(OPENAI_API_URL, headers=header, json=data) # Antwort auswerten if response.status_code == 200: json_data = response.json() output = json_data['choices'][0]['message']['content'] print() print('ChatGPT:', output) else: print() print('Fehler :', response.status_code) print('JSON :', response.json()) response.close()