bb8623aed5
- adapter.py: recopied from production (write_file corrupted the em-dash on line 8) - All archivar/*.py: from archivar.X → from .X for plugin-context compatibility
336 lines
12 KiB
Python
336 lines
12 KiB
Python
"""
|
||
Routing-Logik für klassifizierte Nachrichten.
|
||
|
||
Ermittelt den Zielraum basierend auf Klassifikationsergebnis, Konfidenzschwelle
|
||
und Fallback-Strategie. Unterstützt projektspezifisches Routing für FRAGE-Kategorie
|
||
und Meta-Fragen-Erkennung.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import re
|
||
from dataclasses import dataclass, field
|
||
from typing import Dict, List, Optional, Tuple
|
||
|
||
from .classifier import ClassificationResult, MessageClassifier
|
||
from .config import (
|
||
ROOM_MAPPING,
|
||
CATCH_ALL_ROOM,
|
||
CONFIDENCE_THRESHOLD,
|
||
FALLBACK_KEYWORDS,
|
||
OLLAMA_CONFIG,
|
||
)
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
# ── Meta-Fragen-Erkennung ───────────────────────────────────────────────────
|
||
# Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als
|
||
# FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind.
|
||
# Solche Nachrichten werden erkannt, aus dem Originalraum gelöscht und mit einem
|
||
# Hinweis in der Kopie versehen.
|
||
|
||
_META_PATTERNS: List[re.Pattern] = [
|
||
re.compile(r"(?:wohin|an wen|welcher raum|welchem raum|welchen raum|in welch)\s+(?:wurde|geht|ging|landet)",
|
||
re.IGNORECASE),
|
||
re.compile(r"warum\s+(?:wurde|ist)\s+(?:meine\s+)?(?:nachricht|frage)",
|
||
re.IGNORECASE),
|
||
re.compile(r"(?:archivar|klassifi(?:zier|kation)|routing|weiterleitung)",
|
||
re.IGNORECASE),
|
||
re.compile(r"(?:was|wie)\s+(?:macht|arbeitet|funktioniert)\s+(?:der\s+)?archivar",
|
||
re.IGNORECASE),
|
||
re.compile(r"(?:klasse|kategorie)\s+(?:meiner\s+)?(?:nachricht|würde|wurde)",
|
||
re.IGNORECASE),
|
||
re.compile(r"(?:in welch(?:er|em|en|e)?)\s+(?:kategorie|klasse|raum)",
|
||
re.IGNORECASE),
|
||
re.compile(r"(?:who|which room|where).*(?:message|routed|sent)",
|
||
re.IGNORECASE),
|
||
]
|
||
|
||
# ── Projekt-Keywords für FRAGE-Routing ──────────────────────────────────────
|
||
|
||
_PROJECT_KEYWORDS: Dict[str, List[str]] = {
|
||
"plugin": [
|
||
"plugin", "adapter", "rocketchat", "gateway", "webhook",
|
||
"archivar", "module", "schnittstelle",
|
||
],
|
||
"lan": [
|
||
"lan", "netzwerk", "router", "switch", "vlan", "dns",
|
||
"dhcp", "ip-adresse", "subnetz", "firewall", "wlan",
|
||
"ethernet", "kabel", "patchpanel", "zugangspunkt",
|
||
],
|
||
}
|
||
|
||
|
||
@dataclass
|
||
class RoutingDecision:
|
||
"""Entscheidung, wohin eine Nachricht weitergeleitet wird."""
|
||
|
||
category: str
|
||
"""Klassifikations-Kategorie: 'FAKT', 'FRAGE', 'ALARM'."""
|
||
|
||
target_room: str
|
||
"""Rocket.Chat Raum-ID des Zielraums."""
|
||
|
||
confidence: float
|
||
"""Konfidenz der Klassifikation (0.0–1.0)."""
|
||
|
||
is_catch_all: bool = False
|
||
"""True, wenn die Nachricht wegen zu niedriger Konfidenz an Catch-All ging."""
|
||
|
||
is_fallback: bool = False
|
||
"""True, wenn das Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||
|
||
is_meta: bool = False
|
||
"""True, wenn die Nachricht als Meta-Frage erkannt wurde."""
|
||
|
||
prefix: str = ""
|
||
"""Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK])."""
|
||
|
||
delete_original: bool = False
|
||
"""True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll."""
|
||
|
||
project: Optional[str] = None
|
||
"""Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None."""
|
||
|
||
all_scores: Dict[str, float] = field(default_factory=dict)
|
||
"""Alle Kategorie-Scores für Debugging/Logging."""
|
||
|
||
|
||
class MessageRouter:
|
||
"""Nachrichten-Router: Klassifikation → Raum-Ermittlung → RoutingDecision.
|
||
|
||
Usage::
|
||
|
||
router = MessageRouter(classifier)
|
||
decision = await router.route("Wie konfiguriere ich das Plugin?")
|
||
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin)
|
||
# decision.category → "FRAGE"
|
||
# decision.project → "plugin"
|
||
"""
|
||
|
||
def __init__(self, classifier: MessageClassifier) -> None:
|
||
"""
|
||
Args:
|
||
classifier: Ein (initialisierter) MessageClassifier.
|
||
"""
|
||
self._classifier = classifier
|
||
self._confidence_threshold = CONFIDENCE_THRESHOLD
|
||
|
||
# ── Public API ──────────────────────────────────────────────────────
|
||
|
||
async def route(self, text: str) -> RoutingDecision:
|
||
"""Klassifiziere und route eine Nachricht.
|
||
|
||
Der vollständige Routing-Flow:
|
||
1. Meta-Fragen-Check (vor Embedding, da billig)
|
||
2. Embedding-basierte Klassifikation via Classifier
|
||
3. Bei Classifier-Fehler → Fallback-Keyword-Heuristik
|
||
4. Konfidenz-Prüfung → Catch-All bei < threshold
|
||
5. Raum-Ermittlung (projektspezifisch für FRAGE)
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
|
||
Returns:
|
||
RoutingDecision mit Zielraum, Kategorie und Metadaten.
|
||
"""
|
||
if not text or not text.strip():
|
||
return RoutingDecision(
|
||
category="FAKT",
|
||
target_room=CATCH_ALL_ROOM,
|
||
confidence=0.0,
|
||
is_catch_all=True,
|
||
)
|
||
|
||
text = text.strip()
|
||
|
||
# ── Schritt 1: Meta-Fragen-Erkennung ──────────────────────────
|
||
if self._is_meta_question(text):
|
||
logger.info("Meta-question detected: %.80s...", text)
|
||
return RoutingDecision(
|
||
category="FRAGE",
|
||
target_room=CATCH_ALL_ROOM,
|
||
confidence=1.0,
|
||
is_meta=True,
|
||
delete_original=True,
|
||
prefix="[META-FRAGE] ",
|
||
)
|
||
|
||
# ── Schritt 2: Embedding-basierte Klassifikation ───────────────
|
||
result: Optional[ClassificationResult] = None
|
||
|
||
if self._classifier.is_initialized:
|
||
result = await self._classifier.classify(text)
|
||
|
||
# ── Schritt 3: Fallback bei Classifier-Versagen ────────────────
|
||
if result is None:
|
||
logger.info(
|
||
"Classifier unavailable — using keyword fallback for: %.80s...",
|
||
text,
|
||
)
|
||
category, is_fallback = self._keyword_classify(text)
|
||
return RoutingDecision(
|
||
category=category,
|
||
target_room=self._resolve_room(category, text),
|
||
confidence=0.0,
|
||
is_fallback=is_fallback,
|
||
prefix="[FALLBACK] " if is_fallback else "",
|
||
)
|
||
|
||
# ── Schritt 4: Konfidenz-Prüfung ───────────────────────────────
|
||
if not result.is_confident(self._confidence_threshold):
|
||
logger.debug(
|
||
"Low confidence (%.3f < %.1f) for category '%s' — routing to catch-all",
|
||
result.confidence, self._confidence_threshold, result.category,
|
||
)
|
||
return RoutingDecision(
|
||
category=result.category,
|
||
target_room=CATCH_ALL_ROOM,
|
||
confidence=result.confidence,
|
||
is_catch_all=True,
|
||
all_scores=result.all_scores,
|
||
)
|
||
|
||
# ── Schritt 5: Raum-Ermittlung ─────────────────────────────────
|
||
target_room, project = self._resolve_room_with_project(
|
||
result.category, text
|
||
)
|
||
|
||
return RoutingDecision(
|
||
category=result.category,
|
||
target_room=target_room,
|
||
confidence=result.confidence,
|
||
all_scores=result.all_scores,
|
||
project=project,
|
||
)
|
||
|
||
# ── Room Resolution ────────────────────────────────────────────────
|
||
|
||
def _resolve_room(self, category: str, text: str = "") -> str:
|
||
"""Resolve the target room ID for a category.
|
||
|
||
For FRAGE: checks project-specific keywords and falls back to default.
|
||
"""
|
||
room, _ = self._resolve_room_with_project(category, text)
|
||
return room
|
||
|
||
def _resolve_room_with_project(
|
||
self, category: str, text: str
|
||
) -> Tuple[str, Optional[str]]:
|
||
"""Resolve room and detect project for FRAGE routing.
|
||
|
||
Returns:
|
||
(room_id, project_name_or_None)
|
||
"""
|
||
mapping = ROOM_MAPPING.get(category)
|
||
|
||
if mapping is None:
|
||
logger.warning(
|
||
"Unknown category '%s' — falling back to CATCH_ALL_ROOM", category
|
||
)
|
||
return CATCH_ALL_ROOM, None
|
||
|
||
# Simple string mapping (FAKT, ALARM)
|
||
if isinstance(mapping, str):
|
||
return mapping, None
|
||
|
||
# Nested mapping (FRAGE)
|
||
if isinstance(mapping, dict):
|
||
default_room = mapping.get("default", CATCH_ALL_ROOM)
|
||
|
||
# Check project-specific keywords
|
||
project_specific = mapping.get("project_specific", {})
|
||
if isinstance(project_specific, dict) and project_specific:
|
||
detected_project = self._detect_project(text, project_specific)
|
||
if detected_project:
|
||
project_room = project_specific[detected_project]
|
||
logger.debug(
|
||
"FRAGE → project '%s' → room %s", detected_project, project_room
|
||
)
|
||
return project_room, detected_project
|
||
|
||
return default_room, None
|
||
|
||
return CATCH_ALL_ROOM, None
|
||
|
||
@staticmethod
|
||
def _detect_project(
|
||
text: str, project_specific: Dict[str, str]
|
||
) -> Optional[str]:
|
||
"""Detect which project a FRAGE targets based on keywords.
|
||
|
||
Args:
|
||
text: The message text (lowercased for matching).
|
||
project_specific: Mapping of project_key → room_id.
|
||
|
||
Returns:
|
||
The project key, or None if no project keywords match.
|
||
"""
|
||
text_lower = text.lower()
|
||
|
||
for project_key in project_specific:
|
||
keywords = _PROJECT_KEYWORDS.get(project_key, [project_key])
|
||
for kw in keywords:
|
||
if kw in text_lower:
|
||
return project_key
|
||
|
||
return None
|
||
|
||
# ── Meta-Question Detection ────────────────────────────────────────
|
||
|
||
@staticmethod
|
||
def _is_meta_question(text: str) -> bool:
|
||
"""Check if a message is a meta-question about the Archivar system.
|
||
|
||
Meta-questions ask about the classification/routing system itself.
|
||
They should NOT be forwarded as regular questions.
|
||
"""
|
||
for pattern in _META_PATTERNS:
|
||
if pattern.search(text):
|
||
return True
|
||
return False
|
||
|
||
# ── Fallback: Keyword-Heuristik ────────────────────────────────────
|
||
|
||
@staticmethod
|
||
def _keyword_classify(text: str) -> Tuple[str, bool]:
|
||
"""Classify using keyword heuristics when Ollama is unavailable.
|
||
|
||
Returns:
|
||
(category, is_fallback) — is_fallback is always True here.
|
||
"""
|
||
text_lower = text.lower()
|
||
|
||
# Check ALARM keywords first (highest priority)
|
||
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
||
if kw in text_lower:
|
||
return "ALARM", True
|
||
|
||
# Check FRAGE keywords
|
||
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
||
if kw in text_lower:
|
||
return "FRAGE", True
|
||
|
||
# Default: FAKT
|
||
return "FAKT", True
|
||
|
||
# ── Configuration ──────────────────────────────────────────────────
|
||
|
||
@property
|
||
def confidence_threshold(self) -> float:
|
||
"""Current confidence threshold."""
|
||
return self._confidence_threshold
|
||
|
||
def set_confidence_threshold(self, value: float) -> None:
|
||
"""Override the confidence threshold at runtime.
|
||
|
||
Args:
|
||
value: New threshold (0.0–1.0).
|
||
"""
|
||
if not 0.0 <= value <= 1.0:
|
||
raise ValueError(f"Confidence threshold must be in [0.0, 1.0], got {value}")
|
||
self._confidence_threshold = value
|
||
logger.info("Confidence threshold set to %.2f", value)
|