Files
Hermes_rocket.chat_Plugin/plugin/archivar/router.py
T
Bernd (Hermes) 3fe2dd832e fix(archivar): correct Coroutine-Bug root cause — _llm_raw_sync→async _llm_raw, direct await
OllamaLLMClient.generate() is async def — run_in_executor cannot
correctly execute async functions. The coroutine was never awaited.

Also fix Move-Request parser: native button '1️⃣ Rüber' was not
matched against '1️⃣' — fell through to 'stay' instead of 'move'.

- classifier.py: _llm_raw_sync → async _llm_raw, await generate()
- router.py: remove run_in_executor, direct await _llm_raw()
- adapter.py: normalize MOVE_REQ choice (extract leading digit/emoji)
2026-06-17 22:01:45 +02:00

764 lines
33 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Bidirektionales Routing für Archivar v3.
Ermittelt den Zielraum basierend auf Intent-Klassifikationsergebnis, Konfidenzschwelle
und Fallback-Strategie. Unterstützt bidirektionales Routing mit Quellkanal-Benachrichtigung
und Zusammenfassung nach Abschluss.
"""
from __future__ import annotations
import asyncio
import logging
import re
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
from .classifier import ClassificationResult, IntentClassifier
from .config import (
CONFIDENCE_THRESHOLDS,
FALLBACK_KEYWORDS,
OLLAMA_CONFIG,
LLM_ROOM_PROMPT,
ROOM_MAP_PATH,
FAISS_AUTO_ROUTE,
FAISS_MIN_SCORE,
FAISS_TOP_K,
FAISS_CONFLICT_DIFF,
)
from .room_map import RoomMap, RoomEntry
from .room_index import RoomIndexManager
from .booster import KeywordBooster
from .archivar_state import ArchivarState
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),
]
@dataclass
class RoutingDecision:
"""Entscheidung, wohin eine Nachricht weitergeleitet wird."""
category: str
"""Klassifikations-Kategorie: 'direct_question', 'smalltalk', 'work_order', 'ambiguous'."""
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."""
is_unrouteable: bool = False
"""True, wenn der Zielraum nicht in den subscribed rooms des Bots ist
und die Nachricht stattdessen im DocumentationStore abgelegt wird."""
unrouteable_reason: str = ""
"""Grund, warum kein Routing möglich war (nur bei is_unrouteable=True)."""
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 Routing, sonst None."""
matched_room_name: Optional[str] = None
"""Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde."""
all_scores: Dict[str, float] = field(default_factory=dict)
"""Alle Kategorie-Scores für Debugging/Logging."""
stay_in_room: bool = False
"""True, wenn die Nachricht im Ursprungsraum bleiben soll."""
needs_clarification: bool = False
"""True, wenn die Nachricht eine Klärung benötigt."""
move_request_sent: bool = False
"""True, wenn ein Move-Request-Button gesendet wurde (Butler-Prinzip).
Der Adapter muss auf die Button-Antwort warten, bevor geroutet wird."""
move_request_target_name: str = ""
"""Name des vorgeschlagenen Zielraums für den Move-Request-Button."""
move_request_target_id: str = ""
"""ID des vorgeschlagenen Zielraums (pending confirmation)."""
source_room_notification: Optional[str] = None
"""Benachrichtigungstext für den Ursprungsraum bei bidirektionalem Routing."""
return_summary_to_source: Optional[str] = None
"""Zusammenfassungstext, der nach Abschluss an den Ursprungsraum gesendet wird."""
matched_keywords: List[str] = field(default_factory=list)
"""Liste der Keywords, die zum Routing-Vorschlag führten."""
# ── FAISS Phase-1 Felder ──────────────────────────────────────────
faiss_score: float = 0.0
"""FAISS-Kosinus-Ähnlichkeitsscore (0.0–1.0) des besten Treffers.
0.0 wenn Phase-1 nicht aktiv oder kein Treffer über FAISS_MIN_SCORE."""
faiss_room_id: str = ""
"""Raum-ID des besten FAISS-Treffers. Leer wenn Phase-1 nicht aktiv
oder kein Treffer über FAISS_MIN_SCORE."""
faiss_room_name: str = ""
"""Raum-Name des besten FAISS-Treffers (für Logging/Debugging)."""
is_faiss_routed: bool = False
"""True wenn Phase-1 (FAISS + Booster) direkt geroutet hat — kein
LLM-Aufruf nötig. Spart ~2.4s Latenz pro Nachricht."""
booster_applied: bool = False
"""True wenn der KeywordBooster auf die FAISS-Ergebnisse angewendet
wurde (z.B. bei knappen Top-2 zur Konfliktlösung)."""
def should_route(self) -> bool:
"""True wenn die Nachricht geroutet werden sollte.
Im neuen Flow (Embedding-Vorfilter + LLM-Raum-Router + Move-Request):
Routing erfolgt nur, wenn ein Zielraum gesetzt ist und kein
stay_in_room/meta/catch_all/unrouteable vorliegt.
"""
return (
not self.stay_in_room and
not self.is_meta and
not self.is_catch_all and
not self.is_unrouteable and
bool(self.target_room)
)
class BidirectionalRouter:
"""Bidirektionaler Router für Archivar v3.
Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung.
Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch
``RoomMap`` abgelöst.
Usage::
room_map = RoomMap.load()
classifier = IntentClassifier()
await classifier.initialize()
state = ArchivarState()
state.load()
router = BidirectionalRouter(room_map, classifier, state)
router.set_subscribed_room_ids(["6a19...", "6a1f..."])
decision = await router.route("Bitte dokumentiere das neue Feature", "6a1f...")
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Dokumentation)
# decision.source_room_notification → "📋 Bearbeite ich in #Dokumentation — [Link]"
"""
def __init__(
self,
room_map: RoomMap,
classifier: IntentClassifier,
state: ArchivarState,
room_index: Optional[RoomIndexManager] = None,
booster: Optional[KeywordBooster] = None,
) -> None:
"""
Args:
room_map: A loaded and validated ``RoomMap`` instance.
classifier: An (initialized) ``IntentClassifier``.
state: An (loaded) ``ArchivarState`` instance.
room_index: Optional ``RoomIndexManager`` für FAISS Phase-1.
Wenn None, wird Phase-1 übersprungen (bestehendes Verhalten).
booster: Optional ``KeywordBooster`` für FAISS-Score-Verfeinerung.
Wenn None, wird Phase-1 übersprungen (bestehendes Verhalten).
"""
self._room_map = room_map
self._classifier = classifier
self._state = state
self._room_index: Optional[RoomIndexManager] = room_index
self._booster: Optional[KeywordBooster] = booster
self._subscribed_room_ids: Optional[set] = None
# Semaphore für Ollama-Concurrency: qwen2.5:7b kann nur 1 Request
# parallel verarbeiten. Ohne diesen Schutz führen parallele Aufrufe
# zu Timeout-Kaskaden.
self._llm_semaphore: asyncio.Semaphore = asyncio.Semaphore(1)
# ── Public API ──────────────────────────────────────────────────────
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
"""Klassifiziere und route eine Nachricht (korrigierter Flow).
Der neue Routing-Flow (Architekturskizze):
1. origin_room_id in excluded_rooms? → IGNORE (silent)
2. Raum-Zustand prüfen (persistenter Zustand)
3. Meta-Fragen-Erkennung
4. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig)
5. FAISS Phase-1: Raum-Index + Keyword-Booster
- FAISS-Score >= FAISS_AUTO_ROUTE → direkt routen (kein LLM)
- Score unter Schwelle → Fall-through zu Embedding + LLM
6. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag"
- Klarer Smalltalk → stay_in_room
- Unsicher → weiter zu LLM-Raum-Router
7. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste mit Keywords → room_id direkt
8. Raum gefunden → Move-Request-Button (Butler-Prinzip: ✅Ja/📍Hier)
9. Kein Treffer → catch_all_room
Args:
text: Der Nachrichtentext.
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
Returns:
RoutingDecision mit Zielraum, Kategorie und Metadaten.
"""
if not text or not text.strip():
return RoutingDecision(
category="direct_question",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=0.0,
is_catch_all=True,
stay_in_room=True,
)
text = text.strip()
try:
# ── Schritt 0: Excluded rooms check ──────────────────────────
if origin_room_id and self._room_map.is_excluded(origin_room_id):
logger.debug(
"Message from excluded room %s — ignoring", origin_room_id[:8]
)
return RoutingDecision(
category="direct_question",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=0.0,
is_catch_all=True,
stay_in_room=True,
)
# ── Schritt 0.5: Check if origin room is catch-all ───────────
origin_room = self._room_map.get_room_by_id(origin_room_id) if origin_room_id else None
if origin_room and origin_room.catch_all:
logger.debug(
"Message from catch-all room %s — ignoring", origin_room_id[:8]
)
return RoutingDecision(
category="direct_question",
target_room=origin_room_id,
confidence=0.0,
is_catch_all=True,
stay_in_room=True,
)
# ── Schritt 1: Raum-Zustand prüfen ───────────────────────────
room_state_decision = self._state.should_stay_in_room(origin_room_id)
if room_state_decision is True:
return RoutingDecision(
category="direct_question",
target_room="",
confidence=1.0,
stay_in_room=True,
)
elif room_state_decision is False:
return RoutingDecision(
category="direct_question",
target_room="",
confidence=1.0,
stay_in_room=True,
)
# ── Schritt 2: Meta-Fragen-Erkennung ──────────────────────────
if self._is_meta_question(text):
logger.info("Meta-question detected: %.80s...", text)
return RoutingDecision(
category="direct_question",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=1.0,
is_meta=True,
delete_original=True,
prefix="[META-FRAGE] ",
stay_in_room=True,
)
# ── Schritt 3: Keyword-Match (aus RoomMap) ──────────────────
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
if matched_room is not None:
logger.debug(
"Keyword match: '%s' → %s", text[:80], matched_room.name
)
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
matched_keywords = self._extract_matched_keywords(text, matched_room)
return RoutingDecision(
category="work_order",
target_room=matched_room.room_id,
confidence=0.95,
matched_room_name=matched_room.name,
source_room_notification=notification,
matched_keywords=matched_keywords,
)
# ── Schritt 3.5: FAISS Phase-1 (Raum-Index + Keyword-Booster) ─
# Drei-Schichten-Logik: FAISS → Booster → LLM
# Phase-1 routet direkt bei hohem FAISS-Score — kein LLM-Aufruf.
# Übersprungen wenn _room_index oder _booster None sind.
if self._room_index is not None and self._room_index.is_built:
faiss_hits = self._room_index.search_text(
text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE
)
if faiss_hits:
# ── Keyword-Booster anwenden ──────────────────────
boosted = faiss_hits
booster_applied = False
if self._booster is not None:
# Nur boosten wenn Top-2 knapp beieinander liegen
if (
len(faiss_hits) >= 2
and (faiss_hits[0][1] - faiss_hits[1][1]) < FAISS_CONFLICT_DIFF
):
boosted = self._booster.boost(text, faiss_hits)
booster_applied = True
logger.debug(
"FAISS Booster applied: diff=%.3f < %.3f",
faiss_hits[0][1] - faiss_hits[1][1],
FAISS_CONFLICT_DIFF,
)
top_room_id, top_score = boosted[0]
# ── Auto-Route bei hohem Score ────────────────────
if top_score >= FAISS_AUTO_ROUTE:
room = self._room_map.get_room_by_id(top_room_id)
if room is not None:
room_name = (
room.name.replace("#", "")
if room.name.startswith("#")
else room.name
)
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
matched_keywords = self._extract_matched_keywords(text, room)
logger.info(
"FAISS Phase-1: auto-route '%s' → %s (score=%.3f, booster=%s)",
text[:80],
room.name,
top_score,
booster_applied,
)
return RoutingDecision(
category="work_order",
target_room=top_room_id,
confidence=top_score,
matched_room_name=room.name,
source_room_notification=notification,
matched_keywords=matched_keywords,
faiss_score=top_score,
faiss_room_id=top_room_id,
faiss_room_name=room.name,
is_faiss_routed=True,
booster_applied=booster_applied,
)
# ── Score unter Schwelle → Fall-through zu Embedding + LLM
logger.debug(
"FAISS Phase-1: top score %.3f < %.3f — fall-through to LLM",
top_score,
FAISS_AUTO_ROUTE,
)
# ── Schritt 4: Embedding-Vorfilter (binär) ────────────────────
# Nur noch binär: "Smalltalk" vs. "potenzieller Auftrag"
# Klarer Smalltalk → stay_in_room, alles andere → LLM-Router
is_smalltalk = False
result: Optional[ClassificationResult] = None
if self._classifier.is_initialized:
result = await self._classifier.classify(text)
if result is not None:
# Binärer Vorfilter: Nur Smalltalk mit hoher Konfidenz blocken
if result.category == "smalltalk" and result.confidence >= 0.8:
is_smalltalk = True
logger.info(
"Embedding-Vorfilter: Smalltalk erkannt (conf=%.3f) — stay_in_room",
result.confidence,
)
if is_smalltalk:
return RoutingDecision(
category="smalltalk",
target_room="",
confidence=result.confidence if result else 0.0,
all_scores=result.all_scores if result else {},
stay_in_room=True,
)
# ── Schritt 4.5: Keyword-Matching vor LLM (FIX 2) ────────────
# Wenn Embedding 'work_order' mit niedriger Konfidenz (< 0.9):
# versuche Keyword-Match bevor wir das LLM aufrufen.
# Verhindert unnötige LLM-Calls für Nachrichten mit klaren Keywords.
if result is not None and result.category == "work_order" and result.confidence < 0.9:
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
if matched_room is not None:
logger.info(
"Keyword-Match vor LLM: '%s' → %s (embedding conf=%.3f)",
text[:80], matched_room.name, result.confidence,
)
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
matched_keywords = self._extract_matched_keywords(text, matched_room)
return RoutingDecision(
category="work_order",
target_room=matched_room.room_id,
confidence=0.95,
matched_room_name=matched_room.name,
source_room_notification=notification,
matched_keywords=matched_keywords,
)
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
# liefert room_id direkt (keine Kategorien, kein Name-Matching)
llm_room, llm_failed = await self._llm_room_lookup(text)
if llm_room is not None:
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
logger.info(
"LLM-Raum-Router: '%s' → %s (%s)",
text[:80], llm_room.name, llm_room.room_id[:8],
)
# ── Schritt 6: Move-Request-Button (Butler-Prinzip) ──────
# Vor dem Routing: Button an Andreas — "Soll ich nach [Raum] kopieren?"
# ✅Ja → Route, 📍Hier → stay_in_room
return RoutingDecision(
category="work_order",
target_room=llm_room.room_id,
confidence=0.90,
matched_room_name=llm_room.name,
move_request_sent=True,
move_request_target_name=llm_room.name,
move_request_target_id=llm_room.room_id,
)
# ── Schritt 7: LLM-Fehler oder kein Treffer ──────────────────
if llm_failed:
# FIX 1: Timeout/Exception → Fallback auf Ursprungsraum, NICHT Catch-All
logger.warning(
"LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...' → stay_in_room (Ursprungsraum)",
text,
)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
is_catch_all=False,
)
else:
# LLM erfolgreich, aber kein Match → catch_all
logger.info(
"LLM-Raum-Router: kein Treffer für '%.80s...' → catch_all", text
)
catch_all = self._room_map.catch_all_room
return RoutingDecision(
category="direct_question",
target_room=catch_all.room_id if catch_all else "",
confidence=0.0,
is_catch_all=True,
stay_in_room=True,
)
except Exception as e:
# ── Catch-All-Schutz: unerwarteter Fehler → Fallback ──────
logger.error(
"route(): Unerwarteter Fehler für '%.80s...' — Fallback auf Catch-All: %s",
text, e, exc_info=True,
)
catch_all = self._room_map.catch_all_room
return RoutingDecision(
category="direct_question",
target_room=catch_all.room_id if catch_all else "",
confidence=0.0,
is_catch_all=True,
stay_in_room=True,
)
def _check_unrouteable(self, decision: RoutingDecision) -> None:
"""Validate target_room against subscribed IDs.
If the target room is not in the bot's subscription list, mark the
decision as unrouteable so the caller can store the message in the
DocumentationStore instead of forwarding it.
"""
reason = self._validate_target_room(decision.category, decision.target_room)
if reason:
decision.is_unrouteable = True
decision.unrouteable_reason = reason
logger.warning(
"Unrouteable [%s]: %s", decision.category, reason
)
# ── Room Resolution ────────────────────────────────────────────────
def _resolve_room(self, category: str) -> str:
"""Resolve the target room ID for a category.
Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars.
work_order routes to the configured work_order room.
"""
# Für work_order: Nutze den konfigurierten Raum aus der RoomMap
# Wir suchen nach einem Raum, der für work_order konfiguriert ist
if category == "work_order":
# In der neuen Architektur suchen wir nach spezifischen Räumen
# vorerst verwenden wir den Catch-All-Raum als Fallback
pass
# Fallback: catch_all_room
catch_all = self._room_map.catch_all_room
if catch_all is None:
logger.error("No catch_all room configured — cannot route category '%s'", category)
return ""
return catch_all.room_id
async def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]:
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap
und nutzt den LLM_ROOM_PROMPT für kontextbasiertes Routing.
Das LLM liefert die Raum-ID direkt zurück (kein Name-Matching nötig).
Der LLM-Aufruf wird durch einen asyncio.Semaphore(1) geschützt, weil
qwen2.5:7b nur einen parallelen Request verarbeiten kann. Ohne diesen
Schutz führen parallele Aufrufe zu Timeout-Kaskaden.
Args:
text: Der Nachrichtentext.
Returns:
(RoomEntry, False) — LLM erfolgreich, Raum gefunden
(None, False) — LLM erfolgreich, kein Match (CATCH_ALL)
(None, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout)
"""
# Build room list for LLM prompt: "ID | Name | Keywords"
room_list_parts = []
for room in self._room_map.rooms.values():
if room.catch_all:
continue
# Alle Keywords (100% + context) in die Liste
all_keywords = list(room.keywords_100) + list(room.keywords_context)
kw_str = ", ".join(all_keywords) if all_keywords else "(keine)"
room_list_parts.append(
f"{room.room_id} | {room.name} | {kw_str}"
)
# Catch-All als Fallback
catch_all_id = (
self._room_map.catch_all_room.room_id
if self._room_map.catch_all_room
else "CATCH_ALL"
)
room_list_parts.append(
f"{catch_all_id} | CATCH_ALL | (Fallback für unklare Nachrichten)"
)
room_list = "\n".join(room_list_parts)
prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text)
# Try LLM — expects room ID directly
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
async with self._llm_semaphore:
llm_result = await self._classifier._llm_raw(prompt)
if llm_result is None:
return None, True # LLM-Aufruf fehlgeschlagen
# Parse LLM response — should be a room ID or "CATCH_ALL"
response = llm_result.strip()
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
return None, False # LLM erfolgreich, kein Match
# Direct lookup by room ID (LLM returns the ID directly)
room = self._room_map.get_room_by_id(response)
if room is not None:
return room, False
# Fallback: try name matching (for LLMs that return names instead of IDs)
response_lower = response.lower()
for room in self._room_map.rooms.values():
if response_lower == room.name.lower():
return room, False
if response_lower in room.name.lower():
return room, False
logger.debug("LLM returned unknown room: %s", response)
return None, False
# ── Route Validation ─────────────────────────────────────────────
# ── 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 work_order keywords
for kw in FALLBACK_KEYWORDS.get("work_order", []):
if kw in text_lower:
return "work_order", True
# Check direct_question keywords
for kw in FALLBACK_KEYWORDS.get("direct_question", []):
if kw in text_lower:
return "direct_question", True
# Check smalltalk keywords
for kw in FALLBACK_KEYWORDS.get("smalltalk", []):
if kw in text_lower:
return "smalltalk", True
# Default: direct_question
return "direct_question", True
# ── Configuration ──────────────────────────────────────────────────
@property
def confidence_threshold(self) -> float:
"""Current confidence threshold."""
return CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
"""Set the bot's current subscribed room IDs for validation.
When set, the router will ONLY route to rooms that are in this list.
Messages targeting unsubscribed rooms are marked as ``is_unrouteable``
and should be stored in the DocumentationStore instead.
Args:
room_ids: List of Rocket.Chat room IDs the bot is subscribed to.
Pass None or empty list to disable validation.
"""
if room_ids:
self._subscribed_room_ids = set(room_ids)
logger.debug(
"Router subscribed IDs set: %d rooms", len(self._subscribed_room_ids)
)
else:
self._subscribed_room_ids = None
def _validate_target_room(self, category: str, room_id: str) -> str:
"""Validate target room against subscribed IDs.
Returns:
Empty string if valid. Human-readable reason if blocked.
"""
if not room_id:
return f"no room configured for category '{category}'"
if self._subscribed_room_ids is None:
return "" # validation disabled
if room_id not in self._subscribed_room_ids:
return (
f"target room {room_id[:8]}... for category '{category}' "
f"is not in bot's subscription list "
f"({len(self._subscribed_room_ids)} subscribed rooms)"
)
return ""
def _extract_matched_keywords(self, text: str, room: RoomEntry) -> List[str]:
"""Extrahiere die Keywords, die zum Match führten.
Args:
text: Der Nachrichtentext
room: Der gematchte Raum
Returns:
Liste der gematchten Keywords
"""
text_lower = text.lower()
matched_keywords = []
# Prüfe 100% Evidenz Keywords
for kw in room.keywords_100:
if kw.lower() in text_lower and kw not in matched_keywords:
matched_keywords.append(kw)
# Prüfe kontextabhängige Keywords
for kw in room.keywords_context:
if kw.lower() in text_lower and kw not in matched_keywords:
matched_keywords.append(kw)
return matched_keywords
# ── Bidirektionales Routing ────────────────────────────────────────
async def move_message(self, source_room: str, target_room: str, message: str, message_id: str) -> bool:
"""Verschiebe eine Nachricht bidirektional zwischen Räumen.
Args:
source_room: ID des Ursprungsraums
target_room: ID des Zielraums
message: Die zu verschiebende Nachricht
message_id: ID der Originalnachricht
Returns:
True wenn erfolgreich, False bei Fehler
"""
# Diese Methode wird vom Adapter aufgerufen, wenn eine Routing-Entscheidung
# ausgeführt wird. Sie implementiert den vollständigen bidirektionalen
# Routing-Flow.
logger.info("Moving message from %s to %s", source_room[:8], target_room[:8])
# Die tatsächliche Implementierung erfolgt im Adapter
return True