1|""" 2|Routing-Logik für klassifizierte Nachrichten. 3| 4|Ermittelt den Zielraum basierend auf Klassifikationsergebnis, Konfidenzschwelle 5|und Fallback-Strategie. Unterstützt projektspezifisches Routing für FRAGE-Kategorie 6|und Meta-Fragen-Erkennung. 7|""" 8| 9|from __future__ import annotations 10| 11|import logging 12|import re 13|from dataclasses import dataclass, field 14|from typing import Dict, List, Optional, Tuple 15| 16|from .classifier import ClassificationResult, MessageClassifier 17|from .config import ( 18| ROOM_MAPPING, 19| CATCH_ALL_ROOM, 20| CONFIDENCE_THRESHOLD, 21| FALLBACK_KEYWORDS, 22| OLLAMA_CONFIG, 23|) 24| 25|logger = logging.getLogger(__name__) 26| 27| 28|# ── Meta-Fragen-Erkennung ─────────────────────────────────────────────────── 29|# Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als 30|# FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind. 31|# Solche Nachrichten werden erkannt, aus dem Originalraum gelöscht und mit einem 32|# Hinweis in der Kopie versehen. 33| 34|_META_PATTERNS: List[re.Pattern] = [ 35| re.compile(r"(?:wohin|an wen|welcher raum|welchem raum|welchen raum|in welch)\s+(?:wurde|geht|ging|landet)", 36| re.IGNORECASE), 37| re.compile(r"warum\s+(?:wurde|ist)\s+(?:meine\s+)?(?:nachricht|frage)", 38| re.IGNORECASE), 39| re.compile(r"(?:archivar|klassifi(?:zier|kation)|routing|weiterleitung)", 40| re.IGNORECASE), 41| re.compile(r"(?:was|wie)\s+(?:macht|arbeitet|funktioniert)\s+(?:der\s+)?archivar", 42| re.IGNORECASE), 43| re.compile(r"(?:klasse|kategorie)\s+(?:meiner\s+)?(?:nachricht|würde|wurde)", 44| re.IGNORECASE), 45| re.compile(r"(?:in welch(?:er|em|en|e)?)\s+(?:kategorie|klasse|raum)", 46| re.IGNORECASE), 47| re.compile(r"(?:who|which room|where).*(?:message|routed|sent)", 48| re.IGNORECASE), 49|] 50| 51|# ── Projekt-Keywords für FRAGE-Routing ────────────────────────────────────── 52| 53|_PROJECT_KEYWORDS: Dict[str, List[str]] = { 54| "plugin": [ 55| "plugin", "adapter", "rocketchat", "gateway", "webhook", 56| "archivar", "module", "schnittstelle", 57| ], 58| "lan": [ 59| "lan", "netzwerk", "router", "switch", "vlan", "dns", 60| "dhcp", "ip-adresse", "subnetz", "firewall", "wlan", 61| "ethernet", "kabel", "patchpanel", "zugangspunkt", 62| ], 63|} 64| 65| 66|@dataclass 67|class RoutingDecision: 68| """Entscheidung, wohin eine Nachricht weitergeleitet wird.""" 69| 70| category: str 71| """Klassifikations-Kategorie: 'FAKT', 'FRAGE', 'ALARM'.""" 72| 73| target_room: str 74| """Rocket.Chat Raum-ID des Zielraums.""" 75| 76| confidence: float 77| """Konfidenz der Klassifikation (0.0–1.0).""" 78| 79| is_catch_all: bool = False 80| """True, wenn die Nachricht wegen zu niedriger Konfidenz an Catch-All ging.""" 81| 82| is_fallback: bool = False 83| """True, wenn das Ergebnis aus der Keyword-Heuristik stammt (Ollama down).""" 84| 85| is_meta: bool = False 86| """True, wenn die Nachricht als Meta-Frage erkannt wurde.""" 87| 88| prefix: str = "" 89| """Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK]).""" 90| 91| delete_original: bool = False 92| """True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll.""" 93| 94| project: Optional[str] = None 95| """Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None.""" 96| 97| all_scores: Dict[str, float] = field(default_factory=dict) 98| """Alle Kategorie-Scores für Debugging/Logging.""" 99| 100| 101|class MessageRouter: 102| """Nachrichten-Router: Klassifikation → Raum-Ermittlung → RoutingDecision. 103| 104| Usage:: 105| 106| router = MessageRouter(classifier) 107| decision = await router.route("Wie konfiguriere ich das Plugin?") 108| # decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin) 109| # decision.category → "FRAGE" 110| # decision.project → "plugin" 111| """ 112| 113| def __init__(self, classifier: MessageClassifier) -> None: 114| """ 115| Args: 116| classifier: Ein (initialisierter) MessageClassifier. 117| """ 118| self._classifier = classifier 119| self._confidence_threshold = CONFIDENCE_THRESHOLD 120| 121| # ── Public API ────────────────────────────────────────────────────── 122| 123| async def route(self, text: str) -> RoutingDecision: 124| """Klassifiziere und route eine Nachricht. 125| 126| Der vollständige Routing-Flow: 127| 1. Meta-Fragen-Check (vor Embedding, da billig) 128| 2. Embedding-basierte Klassifikation via Classifier 129| 3. Bei Classifier-Fehler → Fallback-Keyword-Heuristik 130| 4. Konfidenz-Prüfung → Catch-All bei < threshold 131| 5. Raum-Ermittlung (projektspezifisch für FRAGE) 132| 133| Args: 134| text: Der Nachrichtentext. 135| 136| Returns: 137| RoutingDecision mit Zielraum, Kategorie und Metadaten. 138| """ 139| if not text or not text.strip(): 140| return RoutingDecision( 141| category="FAKT", 142| target_room=CATCH_ALL_ROOM, 143| confidence=0.0, 144| is_catch_all=True, 145| ) 146| 147| text = text.strip() 148| 149| # ── Schritt 1: Meta-Fragen-Erkennung ────────────────────────── 150| if self._is_meta_question(text): 151| logger.info("Meta-question detected: %.80s...", text) 152| return RoutingDecision( 153| category="FRAGE", 154| target_room=CATCH_ALL_ROOM, 155| confidence=1.0, 156| is_meta=True, 157| delete_original=True, 158| prefix="[META-FRAGE] ", 159| ) 160| 161| # ── Schritt 2: Embedding-basierte Klassifikation ─────────────── 162| result: Optional[ClassificationResult] = None 163| 164| if self._classifier.is_initialized: 165| result = await self._classifier.classify(text) 166| 167| # ── Schritt 3: Fallback bei Classifier-Versagen ──────────────── 168| if result is None: 169| logger.info( 170| "Classifier unavailable — using keyword fallback for: %.80s...", 171| text, 172| ) 173| category, is_fallback = self._keyword_classify(text) 174| return RoutingDecision( 175| category=category, 176| target_room=self._resolve_room(category, text), 177| confidence=0.0, 178| is_fallback=is_fallback, 179| prefix="[FALLBACK] " if is_fallback else "", 180| ) 181| 182| # ── Schritt 4: Konfidenz-Prüfung ─────────────────────────────── 183| if not result.is_confident(self._confidence_threshold): 184| logger.debug( 185| "Low confidence (%.3f < %.1f) for category '%s' — routing to catch-all", 186| result.confidence, self._confidence_threshold, result.category, 187| ) 188| return RoutingDecision( 189| category=result.category, 190| target_room=CATCH_ALL_ROOM, 191| confidence=result.confidence, 192| is_catch_all=True, 193| all_scores=result.all_scores, 194| ) 195| 196| # ── Schritt 5: Raum-Ermittlung ───────────────────────────────── 197| target_room, project = self._resolve_room_with_project( 198| result.category, text 199| ) 200| 201| return RoutingDecision( 202| category=result.category, 203| target_room=target_room, 204| confidence=result.confidence, 205| all_scores=result.all_scores, 206| project=project, 207| ) 208| 209| # ── Room Resolution ──────────────────────────────────────────────── 210| 211| def _resolve_room(self, category: str, text: str = "") -> str: 212| """Resolve the target room ID for a category. 213| 214| For FRAGE: checks project-specific keywords and falls back to default. 215| """ 216| room, _ = self._resolve_room_with_project(category, text) 217| return room 218| 219| def _resolve_room_with_project( 220| self, category: str, text: str 221| ) -> Tuple[str, Optional[str]]: 222| """Resolve room and detect project for FRAGE routing. 223| 224| Returns: 225| (room_id, project_name_or_None) 226| """ 227| mapping = ROOM_MAPPING.get(category) 228| 229| if mapping is None: 230| logger.warning( 231| "Unknown category '%s' — falling back to CATCH_ALL_ROOM", category 232| ) 233| return CATCH_ALL_ROOM, None 234| 235| # Simple string mapping (FAKT, ALARM) 236| if isinstance(mapping, str): 237| return mapping, None 238| 239| # Nested mapping (FRAGE) 240| if isinstance(mapping, dict): 241| default_room = mapping.get("default", CATCH_ALL_ROOM) 242| 243| # Check project-specific keywords 244| project_specific = mapping.get("project_specific", {}) 245| if isinstance(project_specific, dict) and project_specific: 246| detected_project = self._detect_project(text, project_specific) 247| if detected_project: 248| project_room = project_specific[detected_project] 249| logger.debug( 250| "FRAGE → project '%s' → room %s", detected_project, project_room 251| ) 252| return project_room, detected_project 253| 254| return default_room, None 255| 256| return CATCH_ALL_ROOM, None 257| 258| @staticmethod 259| def _detect_project( 260| text: str, project_specific: Dict[str, str] 261| ) -> Optional[str]: 262| """Detect which project a FRAGE targets based on keywords. 263| 264| Args: 265| text: The message text (lowercased for matching). 266| project_specific: Mapping of project_key → room_id. 267| 268| Returns: 269| The project key, or None if no project keywords match. 270| """ 271| text_lower = text.lower() 272| 273| for project_key in project_specific: 274| keywords = _PROJECT_KEYWORDS.get(project_key, [project_key]) 275| for kw in keywords: 276| if kw in text_lower: 277| return project_key 278| 279| return None 280| 281| # ── Meta-Question Detection ──────────────────────────────────────── 282| 283| @staticmethod 284| def _is_meta_question(text: str) -> bool: 285| """Check if a message is a meta-question about the Archivar system. 286| 287| Meta-questions ask about the classification/routing system itself. 288| They should NOT be forwarded as regular questions. 289| """ 290| for pattern in _META_PATTERNS: 291| if pattern.search(text): 292| return True 293| return False 294| 295| # ── Fallback: Keyword-Heuristik ──────────────────────────────────── 296| 297| @staticmethod 298| def _keyword_classify(text: str) -> Tuple[str, bool]: 299| """Classify using keyword heuristics when Ollama is unavailable. 300| 301| Returns: 302| (category, is_fallback) — is_fallback is always True here. 303| """ 304| text_lower = text.lower() 305| 306| # Check ALARM keywords first (highest priority) 307| for kw in FALLBACK_KEYWORDS.get("ALARM", []): 308| if kw in text_lower: 309| return "ALARM", True 310| 311| # Check FRAGE keywords 312| for kw in FALLBACK_KEYWORDS.get("FRAGE", []): 313| if kw in text_lower: 314| return "FRAGE", True 315| 316| # Default: FAKT 317| return "FAKT", True 318| 319| # ── Configuration ────────────────────────────────────────────────── 320| 321| @property 322| def confidence_threshold(self) -> float: 323| """Current confidence threshold.""" 324| return self._confidence_threshold 325| 326| def set_confidence_threshold(self, value: float) -> None: 327| """Override the confidence threshold at runtime. 328| 329| Args: 330| value: New threshold (0.0–1.0). 331| """ 332| if not 0.0 <= value <= 1.0: 333| raise ValueError(f"Confidence threshold must be in [0.0, 1.0], got {value}") 334| self._confidence_threshold = value 335| logger.info("Confidence threshold set to %.2f", value) 336|