Преглед на файлове

Plugins: NLP-Classifier, Pizza-Order, Audio-Ducking + Fixes

Neue Plugins:
- nlp_classifier: 3-stufige Intent-Pipeline (Keyword → ONNX → LLM-Fallback)
  EventPriority.HIGHEST, cancelt Event bei ausreichender Confidence
- pizza_order: Beispiel fuer Follow-Up Dialoge mit Multi-Slot-Extraktion
  Individuelle Belaege, Groessen, mehrere Pizzen pro Bestellung
- audio_ducking: Musik leiser bei Sprachinteraktion (Server-seitig)

Plugin-Fixes:
- fritzbox: satellites.items() → satellites.get_connected()
- music: YouTube Music Suche (search_mode: music/music_fallback/youtube)
- nlp_llm: context_window 8192, Prompt-Trimming bei Token-Overflow
- timer: stop_timer Pattern erfordert jetzt "timer" im Satz

Installer:
- plugins.json: nlp_classifier als empfohlenes Plugin

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
patrick преди 7 месеца
родител
ревизия
bf8bcd185e

+ 7 - 1
make_installer/installer/plugins.json

@@ -44,9 +44,15 @@
     {
       "name": "KI",
       "plugins": [
+        {
+          "name": "nlp_classifier",
+          "description": "Intent-Erkennung via trainiertem ONNX-Modell (schnell, <100ms)",
+          "recommended": true,
+          "checked": true
+        },
         {
           "name": "nlp_llm",
-          "description": "Intent-Erkennung via lokalem LLM (Qwen 2.5)",
+          "description": "LLM-Fallback fuer komplexe Anfragen (Qwen 2.5 / Ollama)",
           "recommended": true,
           "checked": true
         }

+ 6 - 0
plugins/audio_ducking/config.json

@@ -0,0 +1,6 @@
+{
+    "enabled": true,
+    "duck_volume_percent": 10,
+    "fade_duration_ms": 300,
+    "restore_delay_ms": 500
+}

+ 124 - 0
plugins/audio_ducking/main.py

@@ -0,0 +1,124 @@
+# -*- coding: utf-8 -*-
+"""
+Audio-Ducking Plugin.
+
+Reduziert die Musik-Lautstaerke wenn das Wakeword erkannt wird
+und stellt sie nach der Conversation wieder her.
+
+Flow:
+  Wakeword erkannt → Musik auf 20% (duck)
+  Conversation laeuft → Musik bleibt leise
+  Conversation beendet → Musik zurueck auf Original (restore)
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from trixy_core.events.decorators import TrixyEvent
+from trixy_core.events.enums import EventPriority
+from trixy_core.plugins.trixy_plugin import TrixyPlugin
+from trixy_core.utils.debug import pdebug, pinfo
+
+
+class AudioDuckingPlugin(TrixyPlugin):
+    """Reduziert Musik-Lautstaerke bei Wakeword/Conversation."""
+
+    NAME = "audio_ducking"
+    VERSION = "1.0.0"
+    DESCRIPTION = "Musik leiser bei Sprachinteraktion"
+    AUTHOR = "Trixy"
+
+    def __init__(self, application, plugin_path, config=None) -> None:
+        super().__init__(application, plugin_path, config)
+        self._original_volume: float | None = None
+        self._ducked = False
+
+    async def on_load(self) -> None:
+        pinfo(f"AudioDucking: Lade v{self.VERSION}")
+
+    async def on_unload(self) -> None:
+        if self._ducked:
+            await self._restore_volume()
+
+    def _get_player(self):
+        """Gibt den MusicPlayer zurueck (mehrere Wege probieren)."""
+        # Weg 1: Ueber ServiceContainer
+        try:
+            for name, service in self.application.services.services.items():
+                if "music" in name.lower() or "Music" in type(service).__name__:
+                    player = getattr(service, "_player", None)
+                    if player:
+                        return player
+        except Exception:
+            pass
+
+        # Weg 2: Direkt am Application-Objekt
+        try:
+            svc = getattr(self.application, "_music_player_service", None)
+            if svc:
+                return getattr(svc, "_player", None)
+        except Exception:
+            pass
+
+        return None
+
+    async def _duck_volume(self) -> None:
+        """Reduziert die Musik-Lautstaerke."""
+        player = self._get_player()
+        if not player:
+            pdebug("AudioDucking: Kein MusicPlayer gefunden")
+            return
+
+        if not player.is_playing:
+            pdebug("AudioDucking: Keine Musik aktiv")
+            return
+
+        if self._ducked:
+            return
+
+        duck_pct = self.get_config_value("duck_volume_percent", 20)
+        self._original_volume = player.volume
+        duck_vol = duck_pct / 100.0
+
+        await player.set_volume(duck_vol)
+        self._ducked = True
+        pinfo(f"AudioDucking: {self._original_volume:.0%} → {duck_vol:.0%}")
+
+    async def _restore_volume(self) -> None:
+        """Stellt die urspruengliche Lautstaerke wieder her."""
+        if not self._ducked or self._original_volume is None:
+            return
+
+        player = self._get_player()
+        if player:
+            await player.set_volume(self._original_volume)
+            pinfo(f"AudioDucking: Wiederhergestellt auf {self._original_volume:.0%}")
+
+        self._original_volume = None
+        self._ducked = False
+
+    # === Events ===
+
+    @TrixyEvent(["wakeword_detected"], priority=EventPriority.HIGHEST)
+    async def on_wakeword(self, event_name: str, event_data) -> None:
+        """Wakeword erkannt → Musik leiser."""
+        pinfo("AudioDucking: Wakeword erkannt")
+        await self._duck_volume()
+
+    @TrixyEvent(["wakeword_manual_trigger"], priority=EventPriority.HIGHEST)
+    async def on_manual_trigger(self, event_name: str, event_data) -> None:
+        """Manueller Trigger → Musik leiser."""
+        pinfo("AudioDucking: Manueller Trigger")
+        await self._duck_volume()
+
+    @TrixyEvent(["recording_complete"])
+    async def on_recording_complete(self, event_name: str, event_data) -> None:
+        """Aufnahme beendet → Musik zurueck auf normal."""
+        pinfo("AudioDucking: Recording complete")
+        await self._restore_volume()
+
+    @TrixyEvent(["conversation_started"])
+    async def on_conversation_started(self, event_name: str, event_data) -> None:
+        """Conversation gestartet → sicherstellen dass Musik leise."""
+        await self._duck_volume()

+ 1 - 1
plugins/fritzbox/main.py

@@ -233,7 +233,7 @@ class FritzboxPlugin(TrixyPlugin):
         target_aliases = [a.lower() for a in notify_cfg.get("aliases", [])]
         target_rooms = [r.lower() for r in notify_cfg.get("rooms", [])]
 
-        for sat_id, sat in satellites.items():
+        for sat in satellites.get_connected():
             if not sat.is_connected:
                 continue
 

+ 2 - 1
plugins/music/config.json

@@ -5,7 +5,8 @@
         "max_results": 5,
         "cache_dir": "cache/youtube",
         "max_cache_size_mb": 500,
-        "preferred_format": "bestaudio[ext=m4a]/bestaudio/best"
+        "preferred_format": "bestaudio[ext=m4a]/bestaudio/best",
+        "search_mode": "music_fallback"
     },
     "local": {
         "enabled": true,

+ 1 - 0
plugins/music/main.py

@@ -65,6 +65,7 @@ class MusicPlugin(TrixyPlugin):
                     "preferred_format", "bestaudio[ext=m4a]/bestaudio/best"
                 ),
                 max_results=yt_config.get("max_results", 5),
+                search_mode=yt_config.get("search_mode", "music_fallback"),
             )
             yt_available = await self._youtube.connect()
             if not yt_available:

+ 19 - 2
plugins/music/sources/youtube.py

@@ -36,6 +36,7 @@ class YouTubeSource(MusicSource):
         max_cache_size_mb: int = 500,
         preferred_format: str = "bestaudio[ext=m4a]/bestaudio/best",
         max_results: int = 5,
+        search_mode: str = "music",
     ) -> None:
         """
         Initialisiert die YouTube-Quelle.
@@ -46,12 +47,14 @@ class YouTubeSource(MusicSource):
             max_cache_size_mb: Maximale Cache-Groesse in MB
             preferred_format: yt-dlp Format-String
             max_results: Maximale Suchergebnisse
+            search_mode: Suchmodus — "music" (YouTube Music) oder "youtube" (allgemein)
         """
         super().__init__(name=name, source_type=SourceType.YOUTUBE)
         self._cache_dir = Path(cache_dir)
         self._max_cache_size_mb = max_cache_size_mb
         self._preferred_format = preferred_format
         self._max_results = max_results
+        self._search_mode = search_mode
 
     @property
     def is_yt_dlp_available(self) -> bool:
@@ -130,11 +133,25 @@ class YouTubeSource(MusicSource):
             "no_warnings": True,
             "extract_flat": False,
             "skip_download": True,
-            "default_search": f"ytsearch{effective_limit}",
         }
 
         try:
-            results = await asyncio.to_thread(self._search_sync, query, ydl_opts)
+            results = []
+
+            # YouTube Music: URL-basierte Suche (ytmsearch funktioniert nicht als Prefix)
+            if self._search_mode in ("music", "music_fallback"):
+                music_query = f"https://music.youtube.com/search?q={query}"
+                results = await asyncio.to_thread(
+                    self._search_sync, music_query, {**ydl_opts, "playlistend": effective_limit},
+                )
+
+            # Allgemeine YouTube-Suche (oder Fallback)
+            if not results:
+                if self._search_mode == "music_fallback":
+                    pdebug(f"YouTubeSource: Kein Ergebnis auf YouTube Music, suche allgemein...")
+                ydl_opts["default_search"] = f"ytsearch{effective_limit}"
+                results = await asyncio.to_thread(self._search_sync, query, ydl_opts)
+
             return results
         except Exception as e:
             perror(f"YouTubeSource: Suchfehler: {e}")

+ 8 - 0
plugins/nlp_classifier/config.json

@@ -0,0 +1,8 @@
+{
+    "enabled": true,
+    "model_dir": "models/intent",
+    "min_confidence": 0.6,
+    "fallback_to_llm": true,
+    "log_predictions": true,
+    "tone_keywords_file": "config/tone_keywords.json"
+}

+ 281 - 0
plugins/nlp_classifier/main.py

@@ -0,0 +1,281 @@
+# -*- coding: utf-8 -*-
+"""
+NLP Classifier Plugin — Intent-Erkennung via trainiertem ONNX-Modell.
+
+3-stufige Pipeline:
+  1. KeywordMatcher (< 5ms) — Pattern-basiert, hoechste Praezision
+  2. ONNX-Classifier (< 100ms) — Trainiertes Sentence-Embedding-Modell
+  3. LLM-Fallback — Nur wenn nlp_llm Plugin aktiv und Confidence zu niedrig
+
+Hoert auf speech_recognized mit HIGHEST Prioritaet.
+Bei ausreichender Confidence wird das Event gecancelt,
+damit das nlp_llm Plugin nicht zusaetzlich aufgerufen wird.
+
+Event-Flow:
+  speech_recognized (HIGHEST Prioritaet)
+       ↓
+  [Classifier Plugin] KeywordMatcher → ONNX → Fallback
+       ↓
+  intent_received (mit confidence, slots, tones)
+       ↓
+  [Intent-Handler Plugin] verarbeitet Intent
+"""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+from typing import Any
+
+from trixy_core.events.decorators import TrixyEvent
+from trixy_core.events.enums import EventPriority
+from trixy_core.events.event_data.basic import IntentReceived, SpeechRecognized
+from trixy_core.nlp.intent_classifier import IntentClassifier
+from trixy_core.nlp.tone import get_analyzer, analyze_tone, emit_tone_events
+from trixy_core.plugins.trixy_plugin import TrixyPlugin
+from trixy_core.utils.debug import pdebug, perror, pinfo, pwarn
+
+
+class NLPClassifierPlugin(TrixyPlugin):
+    """
+    NLP-Backend via trainiertem Intent-Classifier.
+
+    Nutzt ein ONNX-Modell fuer schnelle Intent-Erkennung (<100ms auf Pi).
+    Faellt auf das LLM-Plugin zurueck wenn Confidence zu niedrig.
+    """
+
+    NAME = "nlp_classifier"
+    VERSION = "1.0.0"
+    DESCRIPTION = "Intent-Erkennung via trainiertem ONNX-Classifier"
+    AUTHOR = "Trixy"
+
+    def __init__(self, application, plugin_path, config=None) -> None:
+        super().__init__(application, plugin_path, config)
+        self._classifier: IntentClassifier | None = None
+        self._keyword_matcher = None
+        self._entity_registry = None
+
+    async def on_load(self) -> None:
+        """Plugin laden: Classifier, KeywordMatcher, ToneAnalyzer initialisieren."""
+        pinfo(f"[Classifier] Lade Plugin v{self.VERSION}...")
+
+        # 1. Intent-Classifier laden
+        model_dir = self.get_config_value("model_dir", "models/intent")
+        self._classifier = IntentClassifier()
+        ok = await self._classifier.load(model_dir)
+
+        if ok:
+            pinfo(f"[Classifier] ONNX-Modell geladen: {self._classifier.intent_count} Intents")
+        else:
+            pwarn("[Classifier] ONNX-Modell nicht verfuegbar — nur KeywordMatcher aktiv")
+
+        # 2. KeywordMatcher initialisieren (Pattern-basiert, schnellster Pfad)
+        try:
+            from trixy_core.nlp.keyword_matcher import KeywordIntentMatcher
+            from trixy_core.nlp.entities import EntityRegistry
+            from trixy_core.nlp.intent_registry import IntentRegistry
+
+            matcher_config = {"enabled": True}
+            self._keyword_matcher = KeywordIntentMatcher(matcher_config)
+
+            # Entity-Registry laden
+            nlp_dir = Path(__file__).resolve().parent.parent.parent / "trixy_core" / "nlp"
+            self._entity_registry = EntityRegistry()
+            self._entity_registry.load(nlp_dir, "de")
+            self._keyword_matcher.set_entity_registry(self._entity_registry)
+
+            # Intents aus der Registry laden und kompilieren
+            registry = IntentRegistry.get_instance()
+            all_intents = registry.get_all_as_dict()
+
+            # System-Intents hinzufuegen
+            try:
+                from trixy_core.nlp.system_intents import get_system_intents_for_context
+                system_intents = get_system_intents_for_context()
+                all_intents = system_intents + all_intents
+            except ImportError:
+                pass
+
+            self._keyword_matcher.compile_intents(all_intents)
+            pinfo(f"[Classifier] KeywordMatcher: {len(all_intents)} Intents kompiliert")
+        except Exception as e:
+            pwarn(f"[Classifier] KeywordMatcher nicht verfuegbar: {e}")
+
+        # 3. ToneAnalyzer laden
+        tone_file = self.get_config_value("tone_keywords_file", "config/tone_keywords.json")
+        if Path(tone_file).is_file():
+            get_analyzer().load_keywords(tone_file)
+            pdebug(f"[Classifier] ToneAnalyzer geladen")
+
+        pinfo(f"[Classifier] Plugin geladen — Pipeline: KeywordMatcher → ONNX → LLM-Fallback")
+
+    async def on_unload(self) -> None:
+        """Plugin entladen."""
+        self._classifier = None
+        self._keyword_matcher = None
+        self._entity_registry = None
+        pdebug("[Classifier] Plugin entladen")
+
+    # === KeywordMatcher aktualisieren bei Plugin-Aenderungen ===
+
+    @TrixyEvent(["plugin_loaded", "plugin_unloaded"])
+    async def on_plugin_change(self, event_name: str, event_data) -> None:
+        """Aktualisiert den KeywordMatcher wenn Plugins sich aendern."""
+        plugin_name = getattr(event_data, "plugin_name", "")
+        if plugin_name == self.NAME:
+            return
+
+        if self._keyword_matcher:
+            try:
+                from trixy_core.nlp.intent_registry import IntentRegistry
+                registry = IntentRegistry.get_instance()
+                all_intents = registry.get_all_as_dict()
+                self._keyword_matcher.compile_intents(all_intents)
+                pdebug(f"[Classifier] KeywordMatcher aktualisiert: {len(all_intents)} Intents")
+            except Exception:
+                pass
+
+    # === Intent-Erkennung ===
+
+    @TrixyEvent(["speech_recognized"], priority=EventPriority.HIGHEST)
+    async def on_speech_recognized(self, event_name: str, event_data: SpeechRecognized) -> None:
+        """
+        Erkennt Intent aus Spracheingabe.
+
+        Prioritaet HIGHEST — laeuft VOR dem nlp_llm Plugin.
+        Bei ausreichender Confidence wird das Event gecancelt.
+        """
+        text = getattr(event_data, "text", "")
+        if not text or not text.strip():
+            return
+
+        satellite_id = getattr(event_data, "satellite_id", "")
+        min_confidence = self.get_config_value("min_confidence", 0.7)
+        log_predictions = self.get_config_value("log_predictions", True)
+
+        t_start = time.monotonic()
+
+        # --- Stufe 1: KeywordMatcher (< 5ms) ---
+        intent = ""
+        confidence = 0.0
+        slots: dict[str, Any] = {}
+        matched_by = ""
+
+        if self._keyword_matcher:
+            kw_match = self._keyword_matcher.match(text)
+            if kw_match and kw_match.confidence >= min_confidence:
+                intent = kw_match.intent
+                confidence = kw_match.confidence
+                slots = kw_match.slots
+                matched_by = "keyword"
+
+                if log_predictions:
+                    t_kw = (time.monotonic() - t_start) * 1000
+                    pinfo(
+                        f"[Classifier] KeywordMatch: '{intent}' "
+                        f"(conf={confidence:.2f}, {t_kw:.1f}ms)"
+                    )
+
+        # --- Stufe 2: ONNX-Classifier (< 100ms) ---
+        if not intent and self._classifier and self._classifier.is_loaded:
+            prediction = await self._classifier.classify(text, min_confidence=min_confidence)
+
+            if prediction.confidence >= min_confidence:
+                intent = prediction.intent
+                confidence = prediction.confidence
+                slots = prediction.slots
+                matched_by = "classifier"
+
+                if log_predictions:
+                    pinfo(
+                        f"[Classifier] ONNX: '{intent}' "
+                        f"(conf={confidence:.2f}, {prediction.inference_ms:.1f}ms)"
+                    )
+
+        # --- Stufe 3: LLM-Fallback ---
+        if not intent:
+            fallback = self.get_config_value("fallback_to_llm", True)
+            if fallback:
+                t_elapsed = (time.monotonic() - t_start) * 1000
+                if log_predictions:
+                    pdebug(
+                        f"[Classifier] Keine Erkennung ({t_elapsed:.1f}ms) "
+                        f"— Fallback an LLM"
+                    )
+                # Event NICHT canceln → nlp_llm Plugin uebernimmt
+                return
+
+            # Kein Fallback — unknown emittieren
+            intent = "unknown"
+            confidence = 0.0
+            matched_by = "none"
+
+        # --- Tone-Analyse ---
+        tone_results = analyze_tone(text)
+        tones = [r.tag for r in tone_results]
+
+        # Tone-Events emittieren
+        events = getattr(self._application, "events", None)
+        if events and tone_results:
+            await emit_tone_events(tone_results, text, events)
+
+        # --- intent_received emittieren ---
+        t_total = (time.monotonic() - t_start) * 1000
+
+        # Session-Info sammeln
+        session_info = self._get_session_info(satellite_id)
+
+        intent_event = IntentReceived(
+            satellite_id=satellite_id,
+            intent=intent,
+            confidence=confidence,
+            slots=slots,
+            original_text=text,
+            session_id=session_info.get("session_id", ""),
+            room_id=session_info.get("room_id", ""),
+            wakeword_type=session_info.get("wakeword_type", "custom"),
+            is_authenticated=self._is_authenticated(satellite_id),
+            language=getattr(event_data, "language", "de") or "de",
+            metadata={
+                "matched_by": matched_by,
+                "tones": [{"tag": r.tag, "category": r.category} for r in tone_results],
+                "inference_ms": t_total,
+            },
+        )
+
+        pinfo(
+            f"[Classifier] Intent: '{intent}' (conf={confidence:.2f}, "
+            f"by={matched_by}, {t_total:.1f}ms, "
+            f"tones={tones[:3]})"
+        )
+
+        await self._application.events.trigger("intent_received", intent_event)
+
+        # Event canceln — verhindert dass nlp_llm nochmal laeuft
+        if hasattr(event_data, "cancel"):
+            event_data.cancel()
+
+    # === Hilfsmethoden ===
+
+    def _get_session_info(self, satellite_id: str) -> dict[str, Any]:
+        """Holt Session-Info fuer den Satellite."""
+        try:
+            if hasattr(self._application, "satellites"):
+                satellite = self._application.satellites.get(satellite_id)
+                if satellite:
+                    conv = getattr(satellite, "conversation", None)
+                    if conv:
+                        return {
+                            "session_id": getattr(conv, "session_id", ""),
+                            "room_id": getattr(satellite, "room", ""),
+                            "wakeword_type": getattr(conv, "wakeword_type", "custom"),
+                        }
+                    return {"room_id": getattr(satellite, "room", "")}
+        except Exception:
+            pass
+        return {}
+
+    def _is_authenticated(self, satellite_id: str) -> bool:
+        """Prueft ob der Satellite authentifiziert ist (Admin-Befehle)."""
+        # TODO: Admin-Session-Verwaltung (wie in nlp_llm)
+        return False

+ 1 - 1
plugins/nlp_llm/config.json

@@ -7,7 +7,7 @@
     "num_threads": 4,
     "temperature": 0.1,
     "max_tokens": 256,
-    "context_window": 4096,
+    "context_window": 8192,
     "ollama_host": "http://localhost:11434",
     "response_language": "de",
     "fallback_intent": "unknown",

+ 53 - 1
plugins/nlp_llm/prompts/system.py

@@ -13,6 +13,7 @@ def build_intent_recognition_prompt(
     available_intents: list[dict[str, Any]],
     room_id: str = "",
     language: str = "de",
+    max_tokens: int = 3000,
 ) -> str:
     """
     Erstellt den System-Prompt für Intent-Erkennung.
@@ -24,12 +25,14 @@ def build_intent_recognition_prompt(
         available_intents: Liste verfügbarer Intents mit Metadaten
         room_id: Aktuelle Raum-ID für Kontext
         language: Sprache für Slot-Extraktion
+        max_tokens: Maximale Token-Anzahl fuer den Intent-Katalog
 
     Returns:
         System-Prompt als String
     """
-    # Intents kompakt formatieren (nur fuer LLM relevante Felder)
+    # Intents kompakt formatieren und auf Token-Budget trimmen
     compact_intents = _compact_intents_for_llm(available_intents)
+    compact_intents = _trim_intents_to_budget(compact_intents, max_tokens)
     intents_json = json.dumps(compact_intents, ensure_ascii=False)
 
     prompt = f"""Du bist ein Intent-Erkennungssystem für einen Sprachassistenten.
@@ -233,6 +236,55 @@ Antworte NUR mit dem Antworttext:"""
     return prompt
 
 
+def _trim_intents_to_budget(
+    intents: list[dict[str, Any]], max_tokens: int = 3000,
+) -> list[dict[str, Any]]:
+    """
+    Kuerzt den Intent-Katalog auf ein Token-Budget.
+
+    Strategie (in dieser Reihenfolge):
+    1. Beispiele entfernen (spart am meisten)
+    2. Beschreibungen entfernen
+    3. Intents weglassen (letzte Option)
+
+    Grobe Token-Schaetzung: 1 Token ≈ 4 Zeichen
+    """
+    def estimate_tokens(data: list) -> int:
+        return len(json.dumps(data, ensure_ascii=False)) // 4
+
+    # Bereits klein genug?
+    if estimate_tokens(intents) <= max_tokens:
+        return intents
+
+    # Stufe 1: Beispiele auf 1 reduzieren
+    for intent in intents:
+        if "examples" in intent:
+            intent["examples"] = intent["examples"][:1]
+
+    if estimate_tokens(intents) <= max_tokens:
+        return intents
+
+    # Stufe 2: Alle Beispiele entfernen
+    for intent in intents:
+        intent.pop("examples", None)
+
+    if estimate_tokens(intents) <= max_tokens:
+        return intents
+
+    # Stufe 3: Beschreibungen entfernen
+    for intent in intents:
+        intent.pop("description", None)
+
+    if estimate_tokens(intents) <= max_tokens:
+        return intents
+
+    # Stufe 4: Intents kuerzen (die letzten weglassen)
+    while estimate_tokens(intents) > max_tokens and len(intents) > 10:
+        intents.pop()
+
+    return intents
+
+
 def _compact_intents_for_llm(intents: list[dict[str, Any]]) -> list[dict[str, Any]]:
     """
     Reduziert Intent-Daten auf das fuer das LLM Relevante.

+ 4 - 0
plugins/nlp_llm/provider.py

@@ -103,10 +103,14 @@ class LLMNLPProvider(NLPProvider):
 
         try:
             # Intent-Erkennungs-Prompt erstellen
+            # Token-Budget: Context-Window minus Platz fuer User-Text und Antwort
+            max_intent_tokens = max(1000, (self._config.context_window - 1500) if self._config else 2500)
+
             system_prompt = build_intent_recognition_prompt(
                 available_intents=context.available_intents,
                 room_id=context.room_id,
                 language=self._response_language,
+                max_tokens=max_intent_tokens,
             )
 
             # Nachrichtenliste erstellen

+ 26 - 0
plugins/pizza_order/config.json

@@ -0,0 +1,26 @@
+{
+    "enabled": true,
+
+    "sizes": ["klein", "mittel", "gross", "familien"],
+    "default_size": "mittel",
+
+    "pizza_types": {
+        "Margherita": ["Tomatensosse", "Mozzarella", "Basilikum"],
+        "Salami": ["Tomatensosse", "Mozzarella", "Salami"],
+        "Hawaii": ["Tomatensosse", "Mozzarella", "Schinken", "Ananas"],
+        "Tonno": ["Tomatensosse", "Mozzarella", "Thunfisch", "Zwiebeln"],
+        "Quattro Formaggi": ["Tomatensosse", "Mozzarella", "Gorgonzola", "Parmesan", "Ricotta"],
+        "Diavola": ["Tomatensosse", "Mozzarella", "Scharfe Salami", "Peperoni"],
+        "Capricciosa": ["Tomatensosse", "Mozzarella", "Schinken", "Pilze", "Artischocken"],
+        "Vegetariana": ["Tomatensosse", "Mozzarella", "Paprika", "Pilze", "Zwiebeln", "Oliven"]
+    },
+
+    "available_toppings": [
+        "Salami", "Schinken", "Pepperoni", "Thunfisch",
+        "Pilze", "Champions", "Zwiebeln", "Paprika", "Oliven",
+        "Ananas", "Mais", "Spinat", "Artischocken", "Rucola",
+        "Tomaten", "Jalapenos", "Peperoni",
+        "Mozzarella", "Gorgonzola", "Parmesan", "Feta",
+        "Extra Kaese", "Doppelt Kaese"
+    ]
+}

+ 70 - 0
plugins/pizza_order/intents_de.yml

@@ -0,0 +1,70 @@
+intents:
+  pizza_order:
+    description: "Pizza bestellen"
+    patterns:
+      - "(bestell|bestelle) [mir] [eine] [pizza]"
+      - "(bestell|bestelle) [mir] [eine] {size} [pizza]"
+      - "(bestell|bestelle) [mir] [eine] {size} {pizza_type} [pizza]"
+      - "(bestell|bestelle) [mir] [eine] {pizza_type} [pizza]"
+      - "(bestell|bestelle) [mir] [eine] {size} pizza mit {topping}"
+      - "(bestell|bestelle) [mir] [eine] pizza mit {topping}"
+      - "ich (moechte|haette|will) [gerne] [eine] pizza [bestellen]"
+      - "ich (moechte|haette|will) [gerne] [eine] {size} pizza"
+      - "ich (moechte|haette|will) [gerne] [eine] {pizza_type} [pizza]"
+      - "ich (moechte|haette|will) [gerne] [eine] {size} {pizza_type}"
+      - "ich (moechte|haette|will) [gerne] [eine] pizza mit {topping}"
+      - "pizza [bestellen]"
+      - "[eine] {pizza_type} [pizza] [bitte]"
+      - "[eine] {size} {pizza_type} [bitte]"
+    examples:
+      - "Bestell mir eine Pizza"
+      - "Bestelle eine grosse Salami Pizza"
+      - "Ich moechte eine Pizza Hawaii"
+      - "Bestell mir eine kleine Margherita"
+      - "Eine grosse Pizza mit Salami, Pepperoni und extra Kaese"
+      - "Ich haette gerne eine Pizza mit Pilzen und Schinken"
+      - "Pizza bestellen"
+      - "Bestelle eine familien Pizza Diavola"
+      - "Eine Margherita bitte"
+      - "Ich will eine mittelgrosse Pizza mit Thunfisch und Zwiebeln"
+
+  pizza_add_more:
+    description: "Weitere Pizza zur Bestellung hinzufuegen"
+    patterns:
+      - "[und] noch [eine] [pizza]"
+      - "[und] [dazu] [noch] [eine] {size} {pizza_type}"
+      - "[und] [dazu] [noch] [eine] {pizza_type}"
+      - "[und] [dazu] [noch] [eine] pizza mit {topping}"
+      - "eine weitere [pizza]"
+      - "noch eine [pizza] [dazu]"
+    examples:
+      - "Und noch eine Salami dazu"
+      - "Noch eine kleine Margherita"
+      - "Und dazu noch eine grosse Pizza mit Pilzen"
+      - "Eine weitere Hawaii"
+
+  pizza_confirm:
+    description: "Bestellung bestaetigen"
+    patterns:
+      - "(ja|genau|richtig|stimmt|passt|korrekt)"
+      - "das (stimmt|passt) [so]"
+      - "bestell [das] [bitte]"
+      - "[ja] (bestellen|abschicken|fertig)"
+    examples:
+      - "Ja genau"
+      - "Passt so"
+      - "Bestellen bitte"
+      - "Ja das stimmt"
+
+  pizza_cancel:
+    description: "Bestellung abbrechen"
+    patterns:
+      - "(nein|abbrechen|stopp|vergiss)"
+      - "bestellung (abbrechen|stornieren)"
+      - "doch nicht"
+      - "egal [vergiss es]"
+    examples:
+      - "Nein abbrechen"
+      - "Bestellung stornieren"
+      - "Vergiss es"
+      - "Doch nicht"

+ 399 - 0
plugins/pizza_order/main.py

@@ -0,0 +1,399 @@
+# -*- coding: utf-8 -*-
+"""
+Pizza-Bestell Plugin (Beispiel fuer Follow-Up Dialoge).
+
+Demonstriert:
+- Multi-Slot-Extraktion (Groesse, Typ, individuelle Belaege)
+- Follow-Up Rueckfragen mit Validierung
+- Mehrstufige Dialoge (Groesse → Belag → Bestaetigung)
+- Mehrere Pizzen in einer Bestellung
+- Teilweise Angaben ("grosse Pizza" → nur Belag fehlt)
+- Vollstaendige Angaben ("grosse Salami Pizza" → direkt Zusammenfassung)
+
+Beispiel-Dialoge:
+  User: "Bestell mir eine Pizza"
+  Trixy: "Welche Groesse? Klein, mittel, gross oder familien?"
+  User: "Gross"
+  Trixy: "Welchen Belag? Salami, Hawaii, Margherita, ... oder individuelle Belaege?"
+  User: "Salami, Pepperoni und extra Kaese"
+  Trixy: "Eine grosse Pizza mit Salami, Pepperoni und extra Kaese. Noch eine Pizza oder bestellen?"
+  User: "Noch eine kleine Margherita"
+  Trixy: "Eine grosse Pizza mit Salami, Pepperoni, extra Kaese und eine kleine Margherita. Bestellen?"
+  User: "Ja"
+  Trixy: "Bestellung aufgegeben: 2 Pizzen. Guten Appetit!"
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from trixy_core.nlp.handler import IntentReceivedData, IntentResult
+from trixy_core.nlp.decorators import intent, pattern, example
+from trixy_core.nlp.intent_registry import IntentRegistry
+from trixy_core.plugins.trixy_plugin import TrixyPlugin
+from trixy_core.utils.debug import pdebug, pinfo
+
+
+class PizzaOrderPlugin(TrixyPlugin):
+    """Pizza-Bestell Plugin mit Follow-Up Dialogen."""
+
+    NAME = "pizza_order"
+    VERSION = "1.0.0"
+    DESCRIPTION = "Pizza bestellen mit Rueckfragen (Beispiel-Plugin)"
+    AUTHOR = "Trixy"
+
+    def __init__(self, application, plugin_path, config=None) -> None:
+        super().__init__(application, plugin_path, config)
+        self._registry = IntentRegistry.get_instance()
+        # Aktive Bestellungen pro Satellite
+        self._orders: dict[str, list[dict]] = {}  # satellite_id → [pizza, pizza, ...]
+        self._current_pizza: dict[str, dict] = {}  # satellite_id → aktuelle Pizza
+
+    async def on_load(self) -> None:
+        pinfo(f"PizzaOrderPlugin: Lade v{self.VERSION}")
+
+    async def on_unload(self) -> None:
+        self._registry.unregister_plugin(self.NAME)
+        self._orders.clear()
+        self._current_pizza.clear()
+
+    # === Hilfsmethoden ===
+
+    def _get_sizes(self) -> list[str]:
+        return self.get_config_value("sizes", ["klein", "mittel", "gross", "familien"])
+
+    def _get_pizza_types(self) -> dict[str, list[str]]:
+        return self.get_config_value("pizza_types", {})
+
+    def _get_toppings(self) -> list[str]:
+        return self.get_config_value("available_toppings", [])
+
+    def _extract_size(self, text: str) -> str | None:
+        """Extrahiert Groesse aus dem Text."""
+        text_lower = text.lower()
+        for size in self._get_sizes():
+            if size in text_lower:
+                return size
+        # Synonyme
+        if "mittelgross" in text_lower or "normal" in text_lower:
+            return "mittel"
+        if "riesig" in text_lower or "xxl" in text_lower:
+            return "familien"
+        return None
+
+    def _extract_pizza_type(self, text: str) -> str | None:
+        """Extrahiert Pizza-Typ aus dem Text."""
+        text_lower = text.lower()
+        for name in self._get_pizza_types():
+            if name.lower() in text_lower:
+                return name
+        return None
+
+    def _extract_toppings(self, text: str) -> list[str]:
+        """Extrahiert individuelle Belaege aus dem Text."""
+        text_lower = text.lower()
+        found = []
+        for topping in self._get_toppings():
+            if topping.lower() in text_lower:
+                found.append(topping)
+        return found
+
+    def _format_pizza(self, pizza: dict) -> str:
+        """Formatiert eine Pizza als lesbaren Text."""
+        size = pizza.get("size", "mittel")
+        parts = [f"eine {size}"]
+
+        pizza_type = pizza.get("type")
+        toppings = pizza.get("toppings", [])
+
+        if pizza_type:
+            parts.append(f"Pizza {pizza_type}")
+        elif toppings:
+            parts.append(f"Pizza mit {self._join_list(toppings)}")
+        else:
+            parts.append("Pizza")
+
+        return " ".join(parts)
+
+    def _format_order(self, satellite_id: str) -> str:
+        """Formatiert die gesamte Bestellung."""
+        orders = self._orders.get(satellite_id, [])
+        if not orders:
+            return "Keine Bestellung"
+
+        parts = [self._format_pizza(p) for p in orders]
+        return self._join_list(parts)
+
+    @staticmethod
+    def _join_list(items: list[str]) -> str:
+        """Verbindet Liste mit Komma und 'und'."""
+        if not items:
+            return ""
+        if len(items) == 1:
+            return items[0]
+        return ", ".join(items[:-1]) + " und " + items[-1]
+
+    def _add_pizza_to_order(self, satellite_id: str, pizza: dict) -> None:
+        """Fuegt eine Pizza zur Bestellung hinzu."""
+        if satellite_id not in self._orders:
+            self._orders[satellite_id] = []
+        self._orders[satellite_id].append(pizza)
+
+    # === Intent-Handler ===
+
+    @intent("pizza_order", description="Pizza bestellen")
+    @example("Bestell mir eine Pizza", "Bestelle eine grosse Salami")
+    @example("Eine Pizza mit Salami und Pilzen bitte")
+    async def handle_pizza_order(self, data: IntentReceivedData) -> IntentResult:
+        """Startet eine Pizza-Bestellung."""
+        text = data.original_text
+        sat_id = data.satellite_id
+
+        # Vorherige Bestellung zuruecksetzen
+        self._orders[sat_id] = []
+        self._current_pizza[sat_id] = {}
+
+        # Versuche so viel wie moeglich direkt zu extrahieren
+        size = self._extract_size(text)
+        pizza_type = self._extract_pizza_type(text)
+        toppings = self._extract_toppings(text)
+
+        pizza: dict[str, Any] = {}
+        if size:
+            pizza["size"] = size
+        if pizza_type:
+            pizza["type"] = pizza_type
+            pizza["toppings"] = self._get_pizza_types()[pizza_type]
+        elif toppings:
+            pizza["toppings"] = toppings
+
+        self._current_pizza[sat_id] = pizza
+
+        # Was fehlt noch?
+        if not pizza.get("size"):
+            sizes = self._join_list(self._get_sizes())
+            return IntentResult.follow_up(
+                f"Welche Groesse? {sizes}?",
+                follow_up_intent="pizza_select_size",
+                valid_responses=self._get_sizes() + ["normal", "mittelgross", "xxl", "riesig"],
+                retry_text=f"Bitte waehle eine Groesse: {sizes}.",
+                order=pizza,
+            )
+
+        if not pizza.get("type") and not pizza.get("toppings"):
+            types = self._join_list(list(self._get_pizza_types().keys()))
+            return IntentResult.follow_up(
+                f"Welchen Belag? {types}, oder nenne individuelle Belaege.",
+                follow_up_intent="pizza_select_topping",
+                # Kein valid_responses — akzeptiert alles (individuelle Belaege)
+                order=pizza,
+            )
+
+        # Alles vorhanden — zusammenfassen
+        if not pizza.get("size"):
+            pizza["size"] = self.get_config_value("default_size", "mittel")
+
+        self._add_pizza_to_order(sat_id, pizza)
+        self._current_pizza[sat_id] = {}
+
+        summary = self._format_order(sat_id)
+        return IntentResult.follow_up(
+            f"{summary}. Noch eine Pizza dazu, oder bestellen?",
+            follow_up_intent="pizza_more_or_confirm",
+        )
+
+    @intent("pizza_select_size", description="Groesse waehlen (Follow-Up)")
+    async def handle_select_size(self, data: IntentReceivedData) -> IntentResult:
+        """Follow-Up: Groesse wurde gewaehlt."""
+        sat_id = data.satellite_id
+        text = data.original_text
+        pizza = self._current_pizza.get(sat_id, {})
+
+        size = self._extract_size(text)
+        if not size:
+            # Matched value aus Follow-Up Validierung
+            matched = data.slots.get("matched_value", "")
+            size = matched if matched else self.get_config_value("default_size", "mittel")
+
+        pizza["size"] = size
+        self._current_pizza[sat_id] = pizza
+
+        # Belag schon vorhanden?
+        if pizza.get("type") or pizza.get("toppings"):
+            self._add_pizza_to_order(sat_id, pizza)
+            self._current_pizza[sat_id] = {}
+            summary = self._format_order(sat_id)
+            return IntentResult.follow_up(
+                f"{summary}. Noch eine Pizza, oder bestellen?",
+                follow_up_intent="pizza_more_or_confirm",
+            )
+
+        # Belag fehlt noch
+        types = self._join_list(list(self._get_pizza_types().keys()))
+        return IntentResult.follow_up(
+            f"Welchen Belag? {types}, oder nenne individuelle Belaege.",
+            follow_up_intent="pizza_select_topping",
+        )
+
+    @intent("pizza_select_topping", description="Belag waehlen (Follow-Up)")
+    async def handle_select_topping(self, data: IntentReceivedData) -> IntentResult:
+        """Follow-Up: Belag wurde gewaehlt."""
+        sat_id = data.satellite_id
+        text = data.original_text
+        pizza = self._current_pizza.get(sat_id, {})
+
+        # Pizza-Typ oder individuelle Belaege?
+        pizza_type = self._extract_pizza_type(text)
+        toppings = self._extract_toppings(text)
+
+        if pizza_type:
+            pizza["type"] = pizza_type
+            pizza["toppings"] = self._get_pizza_types()[pizza_type]
+        elif toppings:
+            pizza["toppings"] = toppings
+        else:
+            # Text direkt als Belag nehmen
+            pizza["toppings"] = [text.strip()]
+
+        if not pizza.get("size"):
+            pizza["size"] = self.get_config_value("default_size", "mittel")
+
+        self._add_pizza_to_order(sat_id, pizza)
+        self._current_pizza[sat_id] = {}
+
+        summary = self._format_order(sat_id)
+        return IntentResult.follow_up(
+            f"{summary}. Noch eine Pizza dazu, oder bestellen?",
+            follow_up_intent="pizza_more_or_confirm",
+        )
+
+    @intent("pizza_more_or_confirm", description="Weitere Pizza oder bestellen (Follow-Up)")
+    async def handle_more_or_confirm(self, data: IntentReceivedData) -> IntentResult:
+        """Follow-Up: Noch eine Pizza oder bestellen?"""
+        text = data.original_text.lower()
+
+        # Abbruch?
+        cancel_words = ["nein", "abbrechen", "stopp", "vergiss", "doch nicht", "stornieren"]
+        if any(w in text for w in cancel_words):
+            return self._cancel_order(data.satellite_id)
+
+        # Bestaetigen?
+        confirm_words = ["ja", "bestell", "genau", "passt", "richtig", "fertig", "abschicken"]
+        if any(w in text for w in confirm_words):
+            return self._confirm_order(data.satellite_id)
+
+        # Noch eine Pizza?
+        # Versuche eine neue Pizza aus dem Text zu extrahieren
+        size = self._extract_size(text)
+        pizza_type = self._extract_pizza_type(text)
+        toppings = self._extract_toppings(text)
+
+        if pizza_type or toppings or size:
+            pizza: dict[str, Any] = {}
+            if size:
+                pizza["size"] = size
+            if pizza_type:
+                pizza["type"] = pizza_type
+                pizza["toppings"] = self._get_pizza_types()[pizza_type]
+            elif toppings:
+                pizza["toppings"] = toppings
+
+            if not pizza.get("size"):
+                pizza["size"] = self.get_config_value("default_size", "mittel")
+
+            self._add_pizza_to_order(data.satellite_id, pizza)
+
+            summary = self._format_order(data.satellite_id)
+            return IntentResult.follow_up(
+                f"{summary}. Noch eine Pizza, oder bestellen?",
+                follow_up_intent="pizza_more_or_confirm",
+            )
+
+        # Unverstaendlich
+        return IntentResult.follow_up(
+            "Moechtest du noch eine Pizza dazu, oder soll ich bestellen?",
+            follow_up_intent="pizza_more_or_confirm",
+        )
+
+    @intent("pizza_add_more", description="Weitere Pizza hinzufuegen")
+    @example("Und noch eine Salami dazu")
+    async def handle_add_more(self, data: IntentReceivedData) -> IntentResult:
+        """Fuegt eine weitere Pizza zur Bestellung hinzu."""
+        text = data.original_text
+        sat_id = data.satellite_id
+
+        if sat_id not in self._orders:
+            self._orders[sat_id] = []
+
+        size = self._extract_size(text)
+        pizza_type = self._extract_pizza_type(text)
+        toppings = self._extract_toppings(text)
+
+        pizza: dict[str, Any] = {"size": size or self.get_config_value("default_size", "mittel")}
+
+        if pizza_type:
+            pizza["type"] = pizza_type
+            pizza["toppings"] = self._get_pizza_types()[pizza_type]
+        elif toppings:
+            pizza["toppings"] = toppings
+        else:
+            # Belag fehlt
+            self._current_pizza[sat_id] = pizza
+            types = self._join_list(list(self._get_pizza_types().keys()))
+            return IntentResult.follow_up(
+                f"Welchen Belag fuer die naechste Pizza? {types}?",
+                follow_up_intent="pizza_select_topping",
+            )
+
+        self._add_pizza_to_order(sat_id, pizza)
+        summary = self._format_order(sat_id)
+        return IntentResult.follow_up(
+            f"{summary}. Noch eine Pizza, oder bestellen?",
+            follow_up_intent="pizza_more_or_confirm",
+        )
+
+    @intent("pizza_confirm", description="Bestellung bestaetigen")
+    @example("Ja bestellen", "Passt so")
+    async def handle_confirm(self, data: IntentReceivedData) -> IntentResult:
+        """Bestaetigt die Bestellung."""
+        return self._confirm_order(data.satellite_id)
+
+    @intent("pizza_cancel", description="Bestellung abbrechen")
+    @example("Abbrechen", "Vergiss es")
+    async def handle_cancel(self, data: IntentReceivedData) -> IntentResult:
+        """Bricht die Bestellung ab."""
+        return self._cancel_order(data.satellite_id)
+
+    # === Bestell-Logik ===
+
+    def _confirm_order(self, satellite_id: str) -> IntentResult:
+        """Gibt die Bestell-Zusammenfassung."""
+        orders = self._orders.get(satellite_id, [])
+
+        if not orders:
+            return IntentResult.success_with_response(
+                "Es gibt keine offene Bestellung."
+            )
+
+        count = len(orders)
+        summary = self._format_order(satellite_id)
+
+        # Bestellung "abschicken" (in diesem Beispiel nur Zusammenfassung)
+        pinfo(f"PizzaOrder: Bestellung bestaetigt — {count} Pizza(s) fuer {satellite_id}")
+
+        # Aufraeumen
+        self._orders.pop(satellite_id, None)
+        self._current_pizza.pop(satellite_id, None)
+
+        return IntentResult.success_with_response(
+            f"Bestellung aufgegeben: {summary}. "
+            f"Das {'ist' if count == 1 else 'sind'} {count} "
+            f"{'Pizza' if count == 1 else 'Pizzen'}. Guten Appetit!"
+        )
+
+    def _cancel_order(self, satellite_id: str) -> IntentResult:
+        """Bricht die Bestellung ab."""
+        self._orders.pop(satellite_id, None)
+        self._current_pizza.pop(satellite_id, None)
+        return IntentResult.success_with_response("Bestellung abgebrochen.")

+ 4 - 2
plugins/timer/intents_de.yml

@@ -14,13 +14,15 @@ set_timer:
 
 stop_timer:
   patterns:
-    - "(stoppe|stopp) [den] [timer] {name}"
-    - "timer [aus|abbrechen]"
+    - "(stoppe|stopp) [den] timer [{name}]"
+    - "timer (stoppen|stopp|aus|abbrechen)"
+    - "(stoppe|stopp) [den] {name} timer"
   examples:
     - "Stoppe den Timer"
     - "Timer aus"
     - "Stoppe den Pizza Timer"
     - "Timer abbrechen"
+    - "Timer stoppen"
 
 remove_timer:
   patterns: