e1d68ec00a
P-039 (Pulse-Intervall + Drift-Korrektur): - PULSE_INTERVAL_S: 3.0 -> 5.0 (429-Storms mit 2+ Agenten) - _drift_correction: nur delegate_subagent via pgrep resetten, chat_profile + background_term (Hook-gesetzt) bleiben unveraendert - _count_real_subagents -> _count_delegated_subagents umbenannt - Reconciliation-Schutz: skip wenn letzte Counter-Mutation < 5s her (_last_counter_change in __init__ + _apply_counter_delta + _on_reconcile) P-040 (Move-Request in DM ohne origin==target Check): - router.py DM-Branch: origin==target Check VOR is_100_percent_match - router.py: origin_room_id=None -> origin_room_id=origin_room_id (Origin-Priorisierung aktivieren) - adapter_integration.py _send_move_request: defensiver origin==target Check am Anfang, return False ohne Button Tests: 10/10 passed - test_p039_pulse_interval_5s.py (3 tests) - test_p039_drift_keeps_chat_profile.py (3 tests) - test_p040_dm_move_request_origin_target.py (2 tests) - test_p040_move_request_skips_self.py (2 tests) REVERSIBLE-VIA-GIT
2279 lines
105 KiB
Python
2279 lines
105 KiB
Python
"""
|
||
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 datetime import datetime
|
||
from typing import Any, 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,
|
||
ARCHIVAR_RED_FLAG,
|
||
RED_FLAG_PROMPT,
|
||
SENTENCE_MARKER_LLM_THRESHOLD,
|
||
)
|
||
from .room_map import RoomMap, RoomEntry
|
||
from .room_index import RoomIndexManager
|
||
from .booster import KeywordBooster
|
||
from .archivar_state import ArchivarState
|
||
from .routing_counter import routing_counter
|
||
from .routing_telemetry import routing_telemetry
|
||
|
||
from .keyword_matcher import match_keyword, match_keyword_exact, find_matching_keywords
|
||
from .sentence_markers import (
|
||
detect_sentence_marker,
|
||
SentenceMarkerResult,
|
||
MarkerClass,
|
||
)
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
# ── V7-4: Rekursive Einleitungen ────────────────────────────────────────────
|
||
# Ebene 1: Heuristische Marker-Erkennung (schnell, vor LLM).
|
||
# Wenn einer dieser Marker im Text gefunden wird, ist ein rekursiver Bezug
|
||
# WAHRSCHEINLICH → LLM-Check wird getriggert (Ebene 2).
|
||
|
||
RECURSIVE_MARKERS: list[str] = [
|
||
"nochmal",
|
||
"zurückkommen",
|
||
"zurück gehen",
|
||
"zurückgehen",
|
||
"eingefallen",
|
||
"wie wir",
|
||
"als du",
|
||
"davor",
|
||
"gerade",
|
||
"vorhin",
|
||
"nochmal auf",
|
||
"weitermachen",
|
||
"weitermachen wo",
|
||
"wo waren wir",
|
||
"weitermachen bei",
|
||
"zurück zu",
|
||
"zurück zum",
|
||
"anknüpfen",
|
||
"anknüpfen an",
|
||
"aufgreifen",
|
||
"wieder aufgreifen",
|
||
"fortsetzen",
|
||
"weitermachen mit",
|
||
"dranbleiben",
|
||
"dran bleiben",
|
||
"stehen geblieben",
|
||
"stehengeblieben",
|
||
"aufgehört",
|
||
"unterbrochen",
|
||
"pause vorbei",
|
||
"weitermachen können",
|
||
]
|
||
|
||
# ── V7-4: LLM-Prompt für rekursive Erkennung ────────────────────────────────
|
||
# Wird an qwen2.5:7b (lokal via Ollama) gesendet.
|
||
# Der Prompt unterscheidet zwischen rekursivem Bezug (REKURSIV) und
|
||
# neuer Frage (NEU). Kritisch: 'Lass uns nochmal auf X zurückkommen'
|
||
# ist REKURSIV, 'Ich habe eine neue Frage zu X' ist NEU.
|
||
|
||
_RECURSIVE_DETECTION_PROMPT: str = """\
|
||
Du bist ein Konversationsanalysator. Deine Aufgabe: Erkenne, ob eine Nachricht \
|
||
ein REKURSIVER BEZUG auf ein früheres Thema ist oder eine NEUE Frage.
|
||
|
||
KONVERSATIONSHISTORIE (letzte Nachrichten):
|
||
{history}
|
||
|
||
AKTUELLE NACHRICHT:
|
||
{current_message}
|
||
|
||
ALTES THEMA (topic_hint):
|
||
{old_topic}
|
||
|
||
UNTERSCHEIDUNG:
|
||
- REKURSIV: Der Nutzer will ein früheres Thema WIEDER AUFGREIFEN, \
|
||
weitermachen, zurückkommen. Signalwörter: 'nochmal', 'zurückkommen', \
|
||
'weitermachen', 'wo waren wir', 'davor', 'vorhin', 'anknüpfen', 'aufgreifen', \
|
||
'fortsetzen', 'stehen geblieben', 'unterbrochen', 'pause vorbei'.
|
||
- NEU: Der Nutzer stellt eine NEUE Frage, auch wenn sie das gleiche \
|
||
Thema betrifft. Signalwörter: 'neue Frage', 'anderes Thema', 'was anderes', \
|
||
'ich habe eine Frage', 'kannst du mir erklären'.
|
||
|
||
WICHTIG: 'Lass uns nochmal auf X zurückkommen' → REKURSIV. \
|
||
'Ich habe eine neue Frage zu X' → NEU.
|
||
|
||
ANTWORTE NUR mit EINEM der folgenden Formate:
|
||
- REKURSIV: <topic-slug> (z.B. 'REKURSIV: lan-dokumentation')
|
||
- NEU
|
||
|
||
Antwort:"""
|
||
|
||
# ── A1b: LLM-Validierung für Weich-Muster (Stufe 4/5) ────────────────────────
|
||
# Wird NUR bei Konfidenz < 0.8 aufgerufen (weiche Muster, indirekte Muster).
|
||
# Das LLM validiert die Satzeinleitungs-Klassifikation, trifft aber KEINE
|
||
# Routing-Entscheidung. Das Routing bleibt bei FAISS + Classifier.
|
||
# V7-4 ist ein Kontext-Signal, kein Routing-Signal.
|
||
|
||
_SENTENCE_MARKER_VALIDATION_PROMPT: str = """\
|
||
Du bist ein Konversationsanalysator. Deine Aufgabe: Validiere, ob eine \
|
||
Satzeinleitung einen echten THEMENWECHSEL, einen RÜCKBEZUG auf ein früheres \
|
||
Thema oder KEINE klare Einleitung darstellt.
|
||
|
||
KONVERSATIONSHISTORIE (letzte Nachrichten):
|
||
{history}
|
||
|
||
AKTUELLE NACHRICHT:
|
||
{current_message}
|
||
|
||
ERKANNTE SATZEINLEITUNG (Regex):
|
||
- Klasse: {marker_class}
|
||
- Konfidenz (Regex): {regex_confidence}
|
||
- Gematchter Text: {matched_text}
|
||
- Extrahiertes Referenz-Topic: {referenz_topic}
|
||
|
||
V7-3 STATE (jetzt-Topic-Fenster):
|
||
{v7_3_state}
|
||
|
||
UNTERSCHEIDUNG:
|
||
- THEMENWECHSEL: Der Nutzer beginnt ein NEUES Thema. Das alte 'jetzt'-Topic \
|
||
soll verblassen. Signalwörter: 'anderes Thema', 'kurze Frage zu etwas anderem', \
|
||
'wechsel zum Thema', 'komplett anderes Thema'.
|
||
- RUECKBEZUG: Der Nutzer will ein FRÜHERES Thema WIEDER AUFGREIFEN. Das alte \
|
||
'jetzt'-Topic soll wiederbelebt werden. Signalwörter: 'nochmal auf', \
|
||
'zurückkommen', 'zurück zu', 'bezüglich', 'wie wir vorhin über'.
|
||
- UNENTSCHIEDBAR: Die Einleitung ist zu vage oder mehrdeutig. Keine Aktion.
|
||
|
||
WICHTIG:
|
||
- 'Da fällt mir ein,' kann Themenwechsel ODER Rückbezug sein — prüfe den Kontext.
|
||
- 'In dem Zusammenhang —' ist meist ein Rückbezug, aber nicht immer.
|
||
- 'Übrigens,' ist meist ein Themenwechsel, aber nicht immer.
|
||
- Bei UNENTSCHIEDBAR: konservativ behandeln = keine 'jetzt'-Manipulation.
|
||
|
||
ANTWORTE NUR mit EINEM JSON-Objekt (kein Markdown, kein extra Text):
|
||
{{"action": "themenwechsel"|"rueckbezug"|"unentscheidbar", "confidence": 0.0-1.0, "referenz_topic": "topic-slug oder null"}}
|
||
|
||
Antwort:"""
|
||
|
||
# ── 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),
|
||
# P0-BUGFIX: Pattern 3 war zu aggressiv — matchte JEDES Vorkommen von
|
||
# 'archivar', auch in Sachfragen wie "Was hat der Archivar empfohlen?".
|
||
# Jetzt: 'archivar' nur in Kombination mit System-Operationsverben
|
||
# (klassifiziert, routet, leitet weiter, arbeitet, funktioniert, macht).
|
||
# Bidirektional: sowohl "Archivar klassifiziert" als auch
|
||
# "klassifiziert der Archivar".
|
||
# System-Begriffe ohne 'archivar' (klassifikation, routing, weiterleitung)
|
||
# sind weiterhin eigenständige Meta-Signale.
|
||
re.compile(r"archivar\s+(?:klassifiziert|routet|leitet\s+weiter|arbeitet|funktioniert|macht)",
|
||
re.IGNORECASE),
|
||
re.compile(r"(?:klassifiziert|routet|leitet\s+weiter|arbeitet|funktioniert|macht)\s+(?:der\s+)?archivar",
|
||
re.IGNORECASE),
|
||
re.compile(r"(?: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)."""
|
||
|
||
set_sticky: bool = False
|
||
"""V8.3.2 F1: True wenn diese Routing-Entscheidung einen Topic-Scoped
|
||
Sticky setzen soll. Nur 100%-Keyword-Match (Auto-Route) und expliziter
|
||
Wechsel setzen Sticky. FAISS, LLM, Kontext-Keywords → False."""
|
||
|
||
# ── V8.4: Red Flag Felder ──────────────────────────────────────────
|
||
|
||
is_red_flag: bool = False
|
||
"""True wenn Archivar unsicher ist (STAY bei >1 verfügbarem Raum)
|
||
und der Agent als 6. Entscheidungsträger entscheiden soll."""
|
||
|
||
red_flag_rooms: List[str] = field(default_factory=list)
|
||
"""Liste der verfügbaren Raum-Namen für den Red-Flag-Prompt.
|
||
Format: '#Raumname (Thema)'. Leer wenn kein Red Flag."""
|
||
|
||
red_flag_prompt: str = ""
|
||
"""Strukturierter Prompt für den Agenten: 'Router unsicher. Räume: ...'
|
||
Leer wenn kein Red Flag."""
|
||
|
||
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/move_request_sent vorliegt.
|
||
move_request_sent=True bedeutet: Butler-Prinzip aktiv — erst auf
|
||
Button-Antwort warten, nicht direkt routen.
|
||
"""
|
||
return (
|
||
not self.stay_in_room and
|
||
not self.is_meta and
|
||
not self.is_catch_all and
|
||
not self.is_unrouteable and
|
||
not self.move_request_sent 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,
|
||
conversation_history: Optional[Any] = 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).
|
||
conversation_history: Optional ``ConversationHistory`` (B5v6.5).
|
||
Für Konversationskontext bei Themenwechsel- und rekursiver Erkennung.
|
||
"""
|
||
self._room_map = room_map
|
||
self._classifier = classifier
|
||
self._state = state
|
||
self._room_index: Optional[RoomIndexManager] = room_index
|
||
self._booster: Optional[KeywordBooster] = booster
|
||
self._conversation_history = conversation_history
|
||
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 ──────────────────────────────────────────────────────
|
||
|
||
def _resolve_move_request(self, move_request_sent: bool) -> bool:
|
||
"""Fix C v7: Butler-Mode berücksichtigen.
|
||
|
||
Args:
|
||
move_request_sent: Der vom Router berechnete Wert.
|
||
|
||
Returns:
|
||
Effektiver move_request_sent-Wert nach Butler-Mode.
|
||
"""
|
||
mode = self._room_map.butler_mode
|
||
if mode == "off":
|
||
return False # Niemals Butler
|
||
# 'cognitive' und 'strict': aktuelles Verhalten beibehalten
|
||
return move_request_sent
|
||
|
||
async def route(self, text: str, origin_room_id: str = "", is_dm: bool = False) -> RoutingDecision:
|
||
"""Klassifiziere und route eine Nachricht (v6 Flow mit Origin-First Guard).
|
||
|
||
Der neue Routing-Flow (v6):
|
||
-0.5 ORIGIN-FIRST GUARD (VOR allen anderen Schritten):
|
||
1. is_dm=True (DM-Kontext) → DM-Routing (100%-Keywords → Butler, Rest → Catch-All)
|
||
2. origin_room ist Catch-All-Raum → stay_in_room
|
||
3. origin_room ist excluded → ignore
|
||
0. Excluded rooms check
|
||
1. Raum-Zustand prüfen (persistenter Zustand)
|
||
2. Meta-Fragen-Erkennung
|
||
3. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig)
|
||
3.5 FAISS Phase-1: Raum-Index + Keyword-Booster
|
||
4. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag"
|
||
5. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste → STAY oder room_id
|
||
6. ORIGIN-FIRST GUARD (nach LLM):
|
||
- LLM sagt STAY → stay_in_room
|
||
- LLM == origin_room → stay_in_room
|
||
- LLM == catch_all_room → stay_in_room (kein DM-Routing aus Projekträumen!)
|
||
- LLM == anderer Raum → Move-Request (Butler-Prinzip)
|
||
7. LLM-Fehler → stay_in_room
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||
is_dm: True wenn die Nachricht aus einem DM-Raum stammt.
|
||
Erfordert dass der Adapter bei DMs is_dm=True übergibt.
|
||
Bei is_dm=True: 100%-Keywords → Butler (Move-Request),
|
||
weiche Keywords / kein Match → Catch-All (stay_in_room).
|
||
|
||
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: DM-Guard (VOR allem anderen) ──────────────────
|
||
# V8.2 A4: DMs erlauben jetzt Butler-Routing.
|
||
# Der alte DM-Guard (stay_in_room für alle DMs) wird durch
|
||
# einen modifizierten Guard ersetzt, der LLM-basiertes Routing
|
||
# aus DMs erlaubt. Der Archivar schlägt Zielräume vor,
|
||
# der User bestätigt via Move-Request-Button.
|
||
# Strategie-Themen (absprache, planung, strategie, entscheidung)
|
||
# → Strategie-Modus, KEIN Lernen.
|
||
# P0-FIX: is_dm muss vom Adapter explizit gesetzt werden.
|
||
# Erfordert dass der Adapter bei DMs is_dm=True übergibt.
|
||
# Der alte Proxy 'if not origin_room_id' war falsch — der Adapter
|
||
# übergibt bei DMs die echte DM-Room-ID, nicht None/leer.
|
||
if is_dm:
|
||
# DM: Erlaube Routing, aber markiere als DM-Kontext
|
||
# V8.2.1 A4: Strategie-Themen im DM → stay_in_room (kein Routing, kein Lernen)
|
||
if self._is_strategie_topic(text):
|
||
logger.info(
|
||
"DM-Guard V8.2.1 A4: Strategie-Thema im DM erkannt → stay_in_room"
|
||
)
|
||
routing_counter.increment('dm_strategie_stay')
|
||
logger.info("ROUTING DECISION: reason=dm_strategie_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# ── V8.5: DM-Routing differenziert ──────────────────────
|
||
# Stufe 0 (100%-Keywords): IMMER ausführen, auch in DMs.
|
||
# 100%-Keyword-Treffer → Move-Request (Butler-Prinzip).
|
||
# Kein 100%-Treffer → Catch-All (LLM antwortet im DM).
|
||
# FAISS + weiche Keywords: in DMs NICHT ausführen.
|
||
routing_telemetry.start_timer()
|
||
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
||
if matched_room is not None:
|
||
# P-040: origin==target Check — wenn der gefundene Raum
|
||
# der eigene DM-Raum ist, KEIN Move-Request (Nachricht
|
||
# ist bereits im korrekten Raum).
|
||
if matched_room.room_id == origin_room_id:
|
||
logger.info(
|
||
"P-040: DM-Match ist origin_room %s — skip Move-Request",
|
||
origin_room_id[:8],
|
||
)
|
||
routing_counter.increment('dm_self_match_stay')
|
||
logger.info("ROUTING DECISION: reason=dm_self_match_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
is_catch_all=True,
|
||
stay_in_room=True,
|
||
)
|
||
is_100 = self._room_map.is_100_percent_match(text, matched_room)
|
||
if is_100:
|
||
# 100%-Keyword in DM → Butler (Move-Request vorschlagen)
|
||
logger.info(
|
||
"DM 100%% Keyword-Match: '%s' → %s — Butler (Move-Request)",
|
||
text[:80], matched_room.name,
|
||
)
|
||
routing_counter.increment('dm_100_keyword_butler')
|
||
routing_telemetry.record(
|
||
stage='dm_100_keyword', score=1.0, decision='butler',
|
||
target=matched_room.room_id, origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=dm_100_keyword_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, matched_room.room_id)
|
||
matched_keywords = self._extract_matched_keywords(text, matched_room)
|
||
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
|
||
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
|
||
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,
|
||
move_request_sent=True, # Butler-Prinzip: vorschlagen, nicht automatisch
|
||
move_request_target_name=matched_room.name,
|
||
move_request_target_id=matched_room.room_id,
|
||
)
|
||
else:
|
||
# Kontext-Keyword in DM → Catch-All (kein Routing)
|
||
logger.info(
|
||
"DM Kontext-Keyword-Match: '%s' → %s — Catch-All (kein Routing in DM)",
|
||
text[:80], matched_room.name,
|
||
)
|
||
routing_counter.increment('dm_context_catch_all')
|
||
logger.info("ROUTING DECISION: reason=dm_context_catch_all, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
is_catch_all=True,
|
||
stay_in_room=True,
|
||
)
|
||
else:
|
||
# Kein Keyword-Match in DM → Catch-All
|
||
logger.debug("DM: Kein Keyword-Match → Catch-All")
|
||
routing_counter.increment('dm_no_match_catch_all')
|
||
logger.info("ROUTING DECISION: reason=dm_no_match_catch_all, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
is_catch_all=True,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# ── 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]
|
||
)
|
||
routing_counter.increment('excluded_room_skip')
|
||
logger.info("ROUTING BYPASS: reason=excluded_room_skip, origin_room=%s", origin_room_id)
|
||
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]
|
||
)
|
||
routing_counter.increment('catch_all_origin_bypass')
|
||
logger.info("ROUTING BYPASS: reason=catch_all_origin_bypass, origin_room=%s", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room=origin_room_id,
|
||
confidence=0.0,
|
||
is_catch_all=True,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# ── Schritt 0.6: A1b Stufe 0 — Satzeinleitungs-Erkennung ──────
|
||
# Läuft VOR allen anderen Stufen (Regex, kein Embedding, kein LLM).
|
||
# Drei Erkennungs-Klassen:
|
||
# Hart-Themenwechsel → jetzt verblasst (immediate)
|
||
# Hart-Rückbezug → jetzt wiederbelebt (immediate)
|
||
# Weich → unsicher → normaler Flow (LLM-Validierung in Stufe 4/5)
|
||
sentence_marker = detect_sentence_marker(text)
|
||
if sentence_marker is not None:
|
||
routing_telemetry.start_timer()
|
||
logger.info(
|
||
"A1b Stufe 0: Satzeinleitung erkannt — class=%s, "
|
||
"confidence=%.2f, action=%s, topic=%s, pattern=%s",
|
||
sentence_marker.marker_class.value,
|
||
sentence_marker.confidence,
|
||
sentence_marker.action,
|
||
sentence_marker.referenz_topic or "N/A",
|
||
sentence_marker.matched_pattern,
|
||
)
|
||
routing_telemetry.record(
|
||
stage='stufe0',
|
||
score=sentence_marker.confidence,
|
||
decision=sentence_marker.action,
|
||
target=sentence_marker.referenz_topic or '',
|
||
origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
routing_counter.increment(
|
||
f'stufe0_{sentence_marker.marker_class.value}'
|
||
)
|
||
|
||
if sentence_marker.marker_class == MarkerClass.HART_THEMENWECHSEL:
|
||
# ── Hart-Themenwechsel: jetzt verblasst ──────────
|
||
# Alle AKTIVEN never_route-Einträge für diesen Raum
|
||
# auf VERBLASST setzen (Themenwechsel blendet 'jetzt' aus).
|
||
topics = self._state.get_never_route_topics(origin_room_id)
|
||
verblasst_count = 0
|
||
for topic, entry in topics.items():
|
||
if entry.get("state") == "AKTIV":
|
||
entry["state"] = "VERBLASST"
|
||
verblasst_count += 1
|
||
logger.info(
|
||
"A1b Stufe 0: Themenwechsel — '%s' AKTIV → VERBLASST",
|
||
topic,
|
||
)
|
||
if verblasst_count > 0:
|
||
self._state.save()
|
||
logger.info(
|
||
"A1b Stufe 0: %d never_route Einträge verblasst "
|
||
"(Themenwechsel)",
|
||
verblasst_count,
|
||
)
|
||
routing_counter.increment('stufe0_themenwechsel_stay')
|
||
logger.info(
|
||
"ROUTING DECISION: reason=stufe0_themenwechsel, "
|
||
"origin_room=%s, stay=True",
|
||
origin_room_id,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
elif sentence_marker.marker_class == MarkerClass.HART_RUECKBEZUG:
|
||
# ── Hart-Rückbezug: jetzt wiederbelebt ───────────
|
||
# Wenn referenz_topic extrahiert wurde und ein VERBLASSTER
|
||
# Eintrag existiert → wiederbeleben (VERBLASST → AKTIV).
|
||
if sentence_marker.referenz_topic is not None:
|
||
topic = sentence_marker.referenz_topic
|
||
entry = self._state.get_never_route_entry(
|
||
origin_room_id, topic
|
||
)
|
||
if entry is not None:
|
||
if entry.get("state") == "VERBLASST":
|
||
restored = self._state.topic_revive(
|
||
origin_room_id, topic
|
||
)
|
||
if restored:
|
||
logger.info(
|
||
"A1b Stufe 0: Rückbezug auf '%s' → "
|
||
"VERBLASST → AKTIV (wiederbelebt), "
|
||
"stay_in_room",
|
||
topic,
|
||
)
|
||
routing_counter.increment(
|
||
'stufe0_rueckbezug_restore'
|
||
)
|
||
logger.info(
|
||
"ROUTING DECISION: reason=stufe0_rueckbezug_restore, "
|
||
"origin_room=%s, stay=True",
|
||
origin_room_id,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
elif entry.get("state") == "AKTIV":
|
||
# Bereits AKTIV → verlängern
|
||
self._state.extend_never_route(
|
||
origin_room_id, topic
|
||
)
|
||
logger.info(
|
||
"A1b Stufe 0: Rückbezug auf '%s' → "
|
||
"never_route verlängert (bereits AKTIV), "
|
||
"stay_in_room",
|
||
topic,
|
||
)
|
||
routing_counter.increment(
|
||
'stufe0_rueckbezug_extend'
|
||
)
|
||
logger.info(
|
||
"ROUTING DECISION: reason=stufe0_rueckbezug_extend, "
|
||
"origin_room=%s, stay=True",
|
||
origin_room_id,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
else:
|
||
# Kein never_route Eintrag → normaler Flow
|
||
logger.debug(
|
||
"A1b Stufe 0: Rückbezug auf '%s' aber kein "
|
||
"never_route Eintrag → normaler Flow",
|
||
topic,
|
||
)
|
||
else:
|
||
# Kein Topic extrahierbar → normaler Flow
|
||
logger.debug(
|
||
"A1b Stufe 0: Rückbezug ohne Topic → normaler Flow"
|
||
)
|
||
|
||
elif sentence_marker.marker_class == MarkerClass.WEICH:
|
||
# ── Weich-Muster: LLM-Validierung (Stufe 4/5) ────
|
||
# Konfidenz < SENTENCE_MARKER_LLM_THRESHOLD → LLM
|
||
# validiert die Klassifikation und manipuliert
|
||
# V7-3-State entsprechend.
|
||
if sentence_marker.confidence < SENTENCE_MARKER_LLM_THRESHOLD:
|
||
logger.info(
|
||
"A1b Stufe 4/5: Weich-Muster (conf=%.2f < %.2f) → "
|
||
"LLM-Validierung gestartet",
|
||
sentence_marker.confidence,
|
||
SENTENCE_MARKER_LLM_THRESHOLD,
|
||
)
|
||
routing_telemetry.start_timer()
|
||
llm_result = await validate_sentence_marker(
|
||
marker_result=sentence_marker,
|
||
current_message=text,
|
||
room_id=origin_room_id,
|
||
conversation_history=self._conversation_history,
|
||
state=self._state,
|
||
classifier=self._classifier,
|
||
llm_semaphore=self._llm_semaphore,
|
||
)
|
||
if llm_result is not None:
|
||
llm_action = llm_result.get("action", "unentscheidbar")
|
||
llm_confidence = llm_result.get("confidence", 0.0)
|
||
llm_topic = llm_result.get("referenz_topic")
|
||
|
||
# ── R1: Telemetrie für LLM-Validierung ──
|
||
routing_telemetry.record(
|
||
stage='stufe0_llm',
|
||
score=llm_confidence,
|
||
decision=llm_action,
|
||
target=llm_topic or '',
|
||
origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
routing_counter.increment(
|
||
f'stufe0_llm_{llm_action}'
|
||
)
|
||
|
||
if llm_action == "themenwechsel":
|
||
# LLM bestätigt Themenwechsel → jetzt verblasst
|
||
topics = self._state.get_never_route_topics(
|
||
origin_room_id
|
||
)
|
||
verblasst_count = 0
|
||
for topic, entry in topics.items():
|
||
if entry.get("state") == "AKTIV":
|
||
entry["state"] = "VERBLASST"
|
||
verblasst_count += 1
|
||
logger.info(
|
||
"A1b Stufe 4/5: LLM-Themenwechsel — "
|
||
"'%s' AKTIV → VERBLASST",
|
||
topic,
|
||
)
|
||
if verblasst_count > 0:
|
||
self._state.save()
|
||
logger.info(
|
||
"A1b Stufe 4/5: %d never_route Einträge "
|
||
"verblasst (LLM-Themenwechsel)",
|
||
verblasst_count,
|
||
)
|
||
routing_counter.increment(
|
||
'stufe0_llm_themenwechsel_stay'
|
||
)
|
||
logger.info(
|
||
"ROUTING DECISION: "
|
||
"reason=stufe0_llm_themenwechsel, "
|
||
"origin_room=%s, stay=True",
|
||
origin_room_id,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
elif llm_action == "rueckbezug":
|
||
# LLM bestätigt Rückbezug → wiederbeleben
|
||
if llm_topic is not None:
|
||
entry = self._state.get_never_route_entry(
|
||
origin_room_id, llm_topic
|
||
)
|
||
if entry is not None:
|
||
if entry.get("state") == "VERBLASST":
|
||
restored = self._state.topic_revive(
|
||
origin_room_id, llm_topic
|
||
)
|
||
if restored:
|
||
logger.info(
|
||
"A1b Stufe 4/5: LLM-Rückbezug "
|
||
"auf '%s' → VERBLASST → AKTIV "
|
||
"(wiederbelebt), stay_in_room",
|
||
llm_topic,
|
||
)
|
||
routing_counter.increment(
|
||
'stufe0_llm_rueckbezug_restore'
|
||
)
|
||
logger.info(
|
||
"ROUTING DECISION: "
|
||
"reason=stufe0_llm_rueckbezug_restore, "
|
||
"origin_room=%s, stay=True",
|
||
origin_room_id,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
elif entry.get("state") == "AKTIV":
|
||
self._state.extend_never_route(
|
||
origin_room_id, llm_topic
|
||
)
|
||
logger.info(
|
||
"A1b Stufe 4/5: LLM-Rückbezug "
|
||
"auf '%s' → never_route verlängert "
|
||
"(bereits AKTIV), stay_in_room",
|
||
llm_topic,
|
||
)
|
||
routing_counter.increment(
|
||
'stufe0_llm_rueckbezug_extend'
|
||
)
|
||
logger.info(
|
||
"ROUTING DECISION: "
|
||
"reason=stufe0_llm_rueckbezug_extend, "
|
||
"origin_room=%s, stay=True",
|
||
origin_room_id,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
else:
|
||
logger.debug(
|
||
"A1b Stufe 4/5: LLM-Rückbezug auf "
|
||
"'%s' aber kein never_route Eintrag → "
|
||
"normaler Flow",
|
||
llm_topic,
|
||
)
|
||
else:
|
||
logger.debug(
|
||
"A1b Stufe 4/5: LLM-Rückbezug ohne "
|
||
"Topic → normaler Flow"
|
||
)
|
||
else:
|
||
# unentscheidbar → normaler Flow
|
||
logger.debug(
|
||
"A1b Stufe 4/5: LLM unentscheidbar → "
|
||
"normaler Flow"
|
||
)
|
||
else:
|
||
# LLM-Validierung fehlgeschlagen → normaler Flow
|
||
logger.debug(
|
||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen "
|
||
"→ normaler Flow"
|
||
)
|
||
else:
|
||
# Konfidenz >= Schwelle → kein LLM nötig
|
||
logger.debug(
|
||
"A1b Stufe 0: Weich-Muster aber conf=%.2f >= %.2f → "
|
||
"kein LLM, normaler Flow",
|
||
sentence_marker.confidence,
|
||
SENTENCE_MARKER_LLM_THRESHOLD,
|
||
)
|
||
|
||
# ── Schritt 1: Raum-Zustand prüfen ───────────────────────────
|
||
room_state_decision = self._state.should_stay_in_room(origin_room_id)
|
||
if room_state_decision == "always":
|
||
# Origin-First Guard: Stay, kein Move-Request nötig — same room
|
||
routing_counter.increment('never_route_stay')
|
||
logger.info("ROUTING DECISION: reason=never_route_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
# P0-B: "never_route" ist jetzt thematisch (v7) — nicht mehr
|
||
# auf Raum-Ebene prüfbar. Der Check erfolgt nach dem Match
|
||
# mit is_never_route(room_id, topic).
|
||
|
||
# ── V7-3: Verfall-Logik VOR never_route-Check ──────────────
|
||
# expire_stale_entries MUSS vor _check_never_route_topic laufen,
|
||
# damit VERBLASST-Einträge den Butler nicht mehr blocken.
|
||
expired = self._state.expire_stale_entries(
|
||
now=datetime.now(),
|
||
conversation_history=self._conversation_history,
|
||
)
|
||
if expired > 0:
|
||
logger.info(
|
||
"V7-3: %d never_route Einträge verfallen (AKTIV → VERBLASST)",
|
||
expired,
|
||
)
|
||
|
||
# ── V7-4: Rekursive Einleitungen erkennen + wiederherstellen ──
|
||
# Nach expire_stale_entries, VOR Meta-Fragen-Erkennung.
|
||
# Wenn rekursiver Bezug erkannt UND es gibt einen VERBLASSTEN
|
||
# Stick für ein Thema → topic_revive + stay_in_room.
|
||
# V7-5 W3: LLM-Bypass wenn keine never_route-Einträge für den
|
||
# Raum existieren (Performance — spart ~2.4s LLM-Latenz).
|
||
recursive_topic = None
|
||
if self._state.has_never_route_entries(origin_room_id):
|
||
recursive_topic = await self._detect_recursive_reference(
|
||
text, origin_room_id
|
||
)
|
||
else:
|
||
logger.debug(
|
||
"V7-5 W3: Keine never_route Einträge für Raum %s → "
|
||
"rekursive Erkennung übersprungen (Performance)",
|
||
origin_room_id[:8],
|
||
)
|
||
if recursive_topic is not None:
|
||
# Prüfe ob es einen VERBLASSTEN Eintrag für dieses Thema gibt
|
||
verblasst_entry = self._state.get_never_route_entry(
|
||
origin_room_id, recursive_topic
|
||
)
|
||
if verblasst_entry and verblasst_entry.get("state") == "VERBLASST":
|
||
# ── Wiederherstellung: VERBLASST → AKTIV ──────────
|
||
restored = self._state.topic_revive(
|
||
origin_room_id, recursive_topic
|
||
)
|
||
if restored:
|
||
logger.info(
|
||
"V7-4: Rekursiver Bezug auf '%s' → "
|
||
"never_route wiederhergestellt (VERBLASST → AKTIV), "
|
||
"stay_in_room",
|
||
recursive_topic,
|
||
)
|
||
# topic_hint in Konversationshistorie aktualisieren
|
||
if self._conversation_history is not None:
|
||
try:
|
||
self._conversation_history._topic_hints[
|
||
origin_room_id
|
||
] = recursive_topic
|
||
except Exception:
|
||
pass
|
||
# Butler NICHT auslösen — Thema ist wieder aktiv
|
||
routing_counter.increment('recursive_restore')
|
||
logger.info("ROUTING DECISION: reason=recursive_restore, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
elif verblasst_entry and verblasst_entry.get("state") == "AKTIV":
|
||
# Thema ist bereits AKTIV → verlängern + stay_in_room
|
||
self._state.extend_never_route(
|
||
origin_room_id, recursive_topic
|
||
)
|
||
# V7-5 W2: topic_hint auch im AKTIV-Pfad aktualisieren
|
||
if self._conversation_history is not None:
|
||
try:
|
||
self._conversation_history._topic_hints[
|
||
origin_room_id
|
||
] = recursive_topic
|
||
except Exception:
|
||
pass
|
||
logger.info(
|
||
"V7-4: Rekursiver Bezug auf '%s' → "
|
||
"never_route verlängert (bereits AKTIV), stay_in_room",
|
||
recursive_topic,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
else:
|
||
# Kein VERBLASST/AKTIV Eintrag → normaler Flow
|
||
logger.debug(
|
||
"V7-4: Rekursiver Bezug auf '%s' aber kein "
|
||
"never_route Eintrag → normaler Flow",
|
||
recursive_topic,
|
||
)
|
||
|
||
# ── Schritt 2: Meta-Fragen-Erkennung ──────────────────────────
|
||
if self._is_meta_question(text):
|
||
logger.info("Meta-question detected: %.80s...", text)
|
||
routing_counter.increment('meta_check_stay')
|
||
logger.info("ROUTING DECISION: reason=meta_check_stay, origin_room=%s, target_room=%s, stay=True, butler_mode=False", origin_room_id, origin_room_id)
|
||
# P0-BUGFIX: target_room=origin_room_id statt catch_all_id,
|
||
# damit _THEMATIC_TARGET_ROOM im Adapter den korrekten Raum
|
||
# bekommt und der Agent nicht denkt, er sei im DM.
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room=origin_room_id,
|
||
confidence=1.0,
|
||
is_meta=True,
|
||
delete_original=True,
|
||
prefix="[META-FRAGE] ",
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# ── Schritt 3: Keyword-Match (aus RoomMap) ──────────────────
|
||
routing_telemetry.start_timer()
|
||
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
||
if matched_room is not None:
|
||
# Self-Match-Schutz: Wenn Keyword-Match den Ursprungsraum
|
||
# selbst trifft (z.B. 'RC' matched #RC und User ist bereits
|
||
# in #RC), dann stay_in_room statt Routing.
|
||
if matched_room.room_id == origin_room_id:
|
||
logger.debug(
|
||
"Keyword self-match: '%s' matched origin room %s → stay_in_room",
|
||
text[:80], matched_room.name,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
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)
|
||
|
||
# ── P0-B: never_route topic check ──────────────────────
|
||
if self._check_never_route_topic(origin_room_id, matched_room):
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# ── FIX C: 100% Keywords → Auto-Route (kein Butler) ──────
|
||
# Andreas' Regel: Wenn Kategorie-1-Wörter (100% Keywords)
|
||
# gefunden werden, ist der Butler nicht notwendig.
|
||
# Kontext-Keywords (Kategorie 2) → Butler fragt (Lernmöglichkeit).
|
||
is_100 = self._room_map.is_100_percent_match(text, matched_room)
|
||
if is_100:
|
||
logger.info(
|
||
"100%% Keyword-Match: '%s' → %s — Auto-Route (kein Butler)",
|
||
text[:80], matched_room.name,
|
||
)
|
||
routing_counter.increment('keyword_100_auto_route')
|
||
routing_telemetry.record(
|
||
stage='keyword_100', score=1.0, decision='route',
|
||
target=matched_room.room_id, origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=keyword_100_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, matched_room.room_id)
|
||
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,
|
||
move_request_sent=False, # FIX C: 100% → kein Butler
|
||
move_request_target_name=matched_room.name,
|
||
move_request_target_id=matched_room.room_id,
|
||
set_sticky=True, # V8.3.2 F1: Nur 100%-Match setzt Sticky
|
||
)
|
||
else:
|
||
logger.info(
|
||
"Kontext-Keyword-Match: '%s' → %s — Butler fragt",
|
||
text[:80], matched_room.name,
|
||
)
|
||
routing_counter.increment('keyword_context_butler')
|
||
routing_telemetry.record(
|
||
stage='context_keyword', score=0.95, decision='butler',
|
||
target=matched_room.room_id, origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=keyword_context_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, matched_room.room_id)
|
||
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,
|
||
move_request_sent=self._resolve_move_request(True), # Fix C v7: Kontext → Butler
|
||
move_request_target_name=matched_room.name,
|
||
move_request_target_id=matched_room.room_id,
|
||
)
|
||
|
||
# ── 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:
|
||
routing_telemetry.start_timer()
|
||
faiss_hits = self._room_index.search_text(
|
||
text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE
|
||
)
|
||
if faiss_hits:
|
||
# ── V8.4.6: Ursprungsraum aus FAISS-Ergebnissen ausschließen ─
|
||
# FAISS findet oft den Ursprungsraum als ähnlichsten Raum
|
||
# (z.B. score=0.62, target=#RC-Plugin, origin=#RC-Plugin).
|
||
# Das ist sinnlos — Butler kann keinen Wechsel von
|
||
# #RC-Plugin → #RC-Plugin vorschlagen.
|
||
faiss_hits = [
|
||
(rid, score) for rid, score in faiss_hits
|
||
if rid != origin_room_id
|
||
]
|
||
if not faiss_hits:
|
||
# Alle FAISS-Treffer waren der Ursprungsraum → fall-through
|
||
logger.debug(
|
||
"FAISS Phase-1: all hits were origin room %s → fall-through to LLM",
|
||
origin_room_id[:8] if origin_room_id else "DM",
|
||
)
|
||
routing_counter.increment('faiss_origin_excluded')
|
||
else:
|
||
# ── Keyword-Booster anwenden ──────────────────────
|
||
boosted = faiss_hits
|
||
booster_applied = False
|
||
if self._booster is not None:
|
||
# Boosten immer anwenden, nicht nur bei Konflikten
|
||
boosted = self._booster.boost(text, faiss_hits)
|
||
booster_applied = True
|
||
logger.debug(
|
||
"FAISS Booster applied: always active",
|
||
)
|
||
|
||
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)
|
||
|
||
# ── P0-B: never_route topic check ──────────
|
||
if self._check_never_route_topic(origin_room_id, room):
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
logger.info(
|
||
"FAISS Phase-1: auto-route '%s' → %s (score=%.3f, booster=%s)",
|
||
text[:80],
|
||
room.name,
|
||
top_score,
|
||
booster_applied,
|
||
)
|
||
routing_counter.increment('faiss_auto_route')
|
||
routing_telemetry.record(
|
||
stage='faiss', score=top_score, decision='route',
|
||
target=top_room_id, origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=faiss_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, top_room_id)
|
||
|
||
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,
|
||
move_request_sent=False, # FIX D: FAISS-Auto-Route → kein Butler
|
||
move_request_target_name=room.name,
|
||
move_request_target_id=top_room_id,
|
||
)
|
||
|
||
# ── 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,
|
||
)
|
||
routing_counter.increment('faiss_butler')
|
||
routing_telemetry.record(
|
||
stage='faiss', score=top_score, decision='butler',
|
||
target=top_room_id, origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=faiss_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, top_room_id)
|
||
|
||
# ── 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:
|
||
# Self-Match-Schutz (auch in Schritt 4.5)
|
||
if matched_room.room_id == origin_room_id:
|
||
logger.debug(
|
||
"Keyword self-match (4.5): '%s' matched origin room %s → stay_in_room",
|
||
text[:80], matched_room.name,
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
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)
|
||
|
||
# ── P0-B: never_route topic check ──────────────────
|
||
if self._check_never_route_topic(origin_room_id, matched_room):
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# ── FIX C: 100% vs Kontext-Keywords unterscheiden ──
|
||
is_100 = self._room_map.is_100_percent_match(text, matched_room)
|
||
if is_100:
|
||
logger.info(
|
||
"100%% Keyword-Match (4.5): '%s' → %s — Auto-Route (kein Butler)",
|
||
text[:80], matched_room.name,
|
||
)
|
||
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,
|
||
move_request_sent=False, # FIX C: 100% → kein Butler
|
||
move_request_target_name=matched_room.name,
|
||
move_request_target_id=matched_room.room_id,
|
||
set_sticky=True, # V8.3.2 F1: Nur 100%-Match setzt Sticky
|
||
)
|
||
else:
|
||
logger.info(
|
||
"Kontext-Keyword-Match (4.5): '%s' → %s — Butler fragt",
|
||
text[:80], matched_room.name,
|
||
)
|
||
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,
|
||
move_request_sent=self._resolve_move_request(True), # Fix C v7: Kontext → Butler
|
||
move_request_target_name=matched_room.name,
|
||
move_request_target_id=matched_room.room_id,
|
||
)
|
||
|
||
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
|
||
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
|
||
# liefert STAY oder room_id direkt (keine Kategorien, kein Name-Matching)
|
||
routing_telemetry.start_timer()
|
||
llm_room, llm_stay, llm_failed = await self._llm_room_lookup(text, origin_room_id)
|
||
|
||
# ── Schritt 6: ORIGIN-FIRST GUARD (v6) ──────────────────────
|
||
# Paradigmenwechsel: Ursprungsraum entscheidet WOHIN die Antwort geht.
|
||
# Archivar schlägt nur VERLEGUNG vor (Move-Request).
|
||
if llm_failed:
|
||
# V8.4.4: LLM-Ausfall = UNCERTAIN = Red Flag bei >1 Raum
|
||
# Statt blind STAY: Prüfe ob >1 verfügbarer Raum existiert.
|
||
# Bei >1 Raum → Red Flag (Agent als 6. Entscheidungsträger).
|
||
# Bei 1 Raum → stay_in_room (kein Red Flag nötig).
|
||
logger.warning(
|
||
"LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...'",
|
||
text,
|
||
)
|
||
routing_counter.increment('llm_unavailable')
|
||
routing_telemetry.record(
|
||
stage='llm', score=0.0, decision='stay',
|
||
target='', origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
|
||
# ── V8.4.4: Red Flag bei >1 verfügbarem Raum ──────────
|
||
if ARCHIVAR_RED_FLAG:
|
||
available_rooms = self._get_red_flag_rooms(origin_room_id)
|
||
if len(available_rooms) > 1:
|
||
routing_counter.increment('red_flag_triggered')
|
||
logger.info(
|
||
"V8.4.4 Red Flag: LLM unavailable bei %d verfügbaren Räumen → "
|
||
"Agent als 6. Entscheidungsträger",
|
||
len(available_rooms),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=llm_unavailable_red_flag, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return self._build_red_flag_decision(
|
||
text, origin_room_id, available_rooms
|
||
)
|
||
|
||
# Nur 1 Raum oder Red Flag deaktiviert → stay_in_room
|
||
logger.info("ROUTING DECISION: reason=llm_unavailable_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
is_catch_all=False,
|
||
)
|
||
|
||
if llm_stay or llm_room is None:
|
||
# LLM sagt STAY oder unsicher → stay_in_room
|
||
logger.info(
|
||
"LLM-Raum-Router: STAY für '%.80s...' → stay_in_room", text[:80]
|
||
)
|
||
routing_counter.increment('llm_stay')
|
||
routing_telemetry.record(
|
||
stage='llm', score=0.0, decision='stay',
|
||
target='', origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=llm_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||
|
||
# ── V8.4: Red Flag — Agent als 6. Entscheidungsträger ──
|
||
# Wenn >1 verfügbarer Raum (nicht Catch-All, nicht Origin),
|
||
# schickt der Archivar einen strukturierten Prompt an den Agenten.
|
||
# Der Agent entscheidet VOR der Antwort: WO antworten.
|
||
if ARCHIVAR_RED_FLAG:
|
||
available_rooms = self._get_red_flag_rooms(origin_room_id)
|
||
if len(available_rooms) > 1:
|
||
routing_counter.increment('red_flag_triggered')
|
||
logger.info(
|
||
"V8.4 Red Flag: STAY bei %d verfügbaren Räumen → "
|
||
"Agent als 6. Entscheidungsträger",
|
||
len(available_rooms),
|
||
)
|
||
return self._build_red_flag_decision(
|
||
text, origin_room_id, available_rooms
|
||
)
|
||
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# LLM hat einen Raum vorgeschlagen — Origin-First Guard prüfen
|
||
catch_all = self._room_map.catch_all_room
|
||
catch_all_id = catch_all.room_id if catch_all else ""
|
||
|
||
# Guard 1: LLM == origin_room → stay_in_room
|
||
if origin_room_id and llm_room.room_id == origin_room_id:
|
||
logger.info(
|
||
"Origin-First Guard: LLM schlägt Ursprungsraum vor → stay_in_room"
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# Guard 2: LLM == catch_all_room → stay_in_room
|
||
# (Kein DM-Routing aus Projekträumen!)
|
||
if catch_all_id and llm_room.room_id == catch_all_id:
|
||
logger.info(
|
||
"Origin-First Guard: LLM schlägt Catch-All vor → stay_in_room"
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# Guard 2.5: LLM == excluded room → stay_in_room
|
||
# Verhindert, dass der LLM einen excluded room vorschlägt und
|
||
# ein Move-Request dorthin gesendet wird (Release-blockierend).
|
||
if self._room_map.is_excluded(llm_room.room_id):
|
||
logger.warning(
|
||
"Origin-First Guard: LLM schlug excluded room '%s' (%s) vor → stay_in_room",
|
||
llm_room.name, llm_room.room_id[:8],
|
||
)
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
# Guard 3: LLM == anderer Raum → Move-Request (Butler-Prinzip)
|
||
# ── P0-B: never_route topic check ──────────────────────────
|
||
if self._check_never_route_topic(origin_room_id, llm_room):
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=1.0,
|
||
stay_in_room=True,
|
||
)
|
||
|
||
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
|
||
logger.info(
|
||
"LLM-Raum-Router: '%s' → %s (%s) — Move-Request pending",
|
||
text[:80], llm_room.name, llm_room.room_id[:8],
|
||
)
|
||
routing_counter.increment('llm_route')
|
||
routing_telemetry.record(
|
||
stage='llm', score=0.90, decision='butler',
|
||
target=llm_room.room_id, origin=origin_room_id,
|
||
duration_ms=routing_telemetry.elapsed_ms(),
|
||
)
|
||
logger.info("ROUTING DECISION: reason=llm_route, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, llm_room.room_id)
|
||
|
||
return RoutingDecision(
|
||
category="work_order",
|
||
target_room=llm_room.room_id,
|
||
confidence=0.90,
|
||
matched_room_name=llm_room.name,
|
||
move_request_sent=self._resolve_move_request(True), # Fix C v7: LLM → Butler
|
||
move_request_target_name=llm_room.name,
|
||
move_request_target_id=llm_room.room_id,
|
||
)
|
||
|
||
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,
|
||
)
|
||
routing_telemetry.record(
|
||
stage='default', score=0.0, decision='stay',
|
||
target='', origin=origin_room_id,
|
||
duration_ms=0.0,
|
||
)
|
||
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, origin_room_id: str = "") -> Tuple[Optional[RoomEntry], bool, 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.
|
||
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums (für Kontext).
|
||
|
||
Returns:
|
||
(RoomEntry, False, False) — LLM erfolgreich, Raum gefunden (ROUTE)
|
||
(None, False, False) — LLM erfolgreich, STAY (kein Routing)
|
||
(None, False, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout)
|
||
"""
|
||
# Build room list for LLM prompt: "ID | Name | Keywords"
|
||
# Nur Nicht-Catch-All-Räume als Optionen (Catch-All ist nie ein Routing-Ziel)
|
||
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}"
|
||
)
|
||
|
||
if not room_list_parts:
|
||
# Keine Nicht-Catch-All-Räume → STAY
|
||
return None, False, False
|
||
|
||
room_list = "\n".join(room_list_parts)
|
||
|
||
# Ursprungsraum-Name für Kontext
|
||
origin_name = ""
|
||
if origin_room_id:
|
||
origin_room = self._room_map.get_room_by_id(origin_room_id)
|
||
if origin_room:
|
||
origin_name = origin_room.name
|
||
|
||
prompt = LLM_ROOM_PROMPT.format(
|
||
room_list=room_list,
|
||
text=text,
|
||
origin_room=origin_name or "unbekannt",
|
||
)
|
||
|
||
# Try LLM — expects room ID directly or "STAY"
|
||
# 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, False, True # LLM-Aufruf fehlgeschlagen
|
||
|
||
# Parse LLM response — should be a room ID or "STAY"
|
||
response = llm_result.strip()
|
||
|
||
# STAY = Nachricht bleibt im Ursprungsraum
|
||
if response.upper() == "STAY":
|
||
return None, False, False # LLM erfolgreich, STAY
|
||
|
||
# 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, 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, False
|
||
if response_lower in room.name.lower():
|
||
return room, False, False
|
||
|
||
logger.debug("LLM returned unknown room: %s", response)
|
||
return None, False, False # Unbekannte Antwort → STAY
|
||
|
||
# ── 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
|
||
|
||
# ── V8.2.1 A4: Strategie-Themen-Erkennung ──────────────────────────
|
||
|
||
@staticmethod
|
||
def _is_strategie_topic(text: str) -> bool:
|
||
"""Prüft ob der Text ein Strategie-Thema enthält.
|
||
|
||
Strategie-Themen: absprache, planung, strategie, entscheidung.
|
||
Bei diesen Themen → Strategie-Modus, KEIN Lernen, KEIN Routing.
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
|
||
Returns:
|
||
True wenn Strategie-Thema erkannt.
|
||
"""
|
||
strategie_keywords = {"absprache", "planung", "strategie", "entscheidung"}
|
||
text_lower = text.lower()
|
||
return any(kw in text_lower for kw in strategie_keywords)
|
||
|
||
# ── 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.
|
||
|
||
Uses morphological matching for 100%-keywords and exact matching
|
||
for context keywords.
|
||
|
||
Args:
|
||
text: Der Nachrichtentext
|
||
room: Der gematchte Raum
|
||
|
||
Returns:
|
||
Liste der gematchten Keywords
|
||
"""
|
||
matched_keywords = []
|
||
|
||
# Prüfe 100% Evidenz Keywords (morphologisches Matching)
|
||
for kw in room.keywords_100:
|
||
if match_keyword(kw, text) and kw not in matched_keywords:
|
||
matched_keywords.append(kw)
|
||
|
||
# Prüfe kontextabhängige Keywords (exaktes Matching)
|
||
for kw in room.keywords_context:
|
||
if match_keyword_exact(kw, text) and kw not in matched_keywords:
|
||
matched_keywords.append(kw)
|
||
|
||
return matched_keywords
|
||
|
||
@staticmethod
|
||
def _room_name_to_topic(room_name: str) -> str:
|
||
"""Konvertiert einen Raum-Namen in einen Topic-Slug.
|
||
|
||
'#LAN-Dokumentation' → 'lan-dokumentation'
|
||
'#DevOps' → 'devops'
|
||
|
||
Args:
|
||
room_name: Der Raum-Name (mit oder ohne #).
|
||
|
||
Returns:
|
||
Topic-Slug (lowercase, ohne #, Leerzeichen → Bindestrich).
|
||
"""
|
||
name = room_name.lstrip("#")
|
||
return name.lower().replace(" ", "-")
|
||
|
||
# ── V7-4: Rekursive Einleitungen ────────────────────────────────────
|
||
|
||
@staticmethod
|
||
def _has_recursive_marker(text: str) -> bool:
|
||
"""Ebene 1: Heuristische Marker-Erkennung (schnell, vor LLM).
|
||
|
||
Prüft ob der Text einen rekursiven Marker enthält.
|
||
Case-insensitive, Substring-Match.
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
|
||
Returns:
|
||
True wenn mindestens ein Marker gefunden wurde.
|
||
"""
|
||
text_lower = text.lower()
|
||
for marker in RECURSIVE_MARKERS:
|
||
if marker in text_lower:
|
||
return True
|
||
return False
|
||
|
||
async def _detect_recursive_reference(
|
||
self, text: str, room_id: str
|
||
) -> Optional[str]:
|
||
"""V7-4: Erkenne rekursive Bezüge (zweistufig: heuristisch + LLM).
|
||
|
||
Ebene 1: Keyword-Match auf RECURSIVE_MARKERS.
|
||
Ebene 2: Wenn Marker gefunden → LLM-Check mit Konversationshistorie.
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
room_id: Rocket.Chat Raum-ID.
|
||
|
||
Returns:
|
||
Das erkannte Thema (topic slug) wenn rekursiver Bezug erkannt,
|
||
None wenn kein rekursiver Bezug oder LLM sagt NEU.
|
||
"""
|
||
# ── Ebene 1: Heuristisch ──────────────────────────────────────
|
||
if not self._has_recursive_marker(text):
|
||
return None
|
||
|
||
logger.debug(
|
||
"V7-4: Rekursiver Marker in '%s' gefunden → LLM-Check",
|
||
text[:80],
|
||
)
|
||
|
||
# ── Ebene 2: LLM-Check ───────────────────────────────────────
|
||
# Hole Konversationshistorie für den Raum
|
||
history_context = ""
|
||
if self._conversation_history is not None:
|
||
try:
|
||
buf = self._conversation_history._buffers.get(room_id)
|
||
if buf:
|
||
# Letzte 5 Nachrichten als Kontext
|
||
recent = list(buf)[-5:]
|
||
history_lines = []
|
||
for entry in recent:
|
||
role = getattr(entry, "role", "user")
|
||
msg_text = getattr(entry, "text", "")
|
||
history_lines.append(f"[{role}] {msg_text}")
|
||
history_context = "\n".join(history_lines)
|
||
except Exception as e:
|
||
logger.debug("V7-4: Konnte Historie nicht laden: %s", e)
|
||
|
||
# Hole topic_hint (altes Thema)
|
||
old_topic = None
|
||
if self._conversation_history is not None:
|
||
try:
|
||
old_topic = self._conversation_history._topic_hints.get(room_id)
|
||
except Exception:
|
||
pass
|
||
|
||
# Baue LLM-Prompt
|
||
prompt = _RECURSIVE_DETECTION_PROMPT.format(
|
||
history=history_context or "(keine Historie)",
|
||
current_message=text,
|
||
old_topic=old_topic or "(kein altes Thema)",
|
||
)
|
||
|
||
# LLM-Aufruf mit 5s Timeout
|
||
try:
|
||
async with self._llm_semaphore:
|
||
llm_result = await asyncio.wait_for(
|
||
self._classifier._llm_raw(prompt),
|
||
timeout=5.0,
|
||
)
|
||
except asyncio.TimeoutError:
|
||
logger.warning("V7-4: LLM-Check Timeout (5s) → Fallback: NEU")
|
||
return None
|
||
except Exception as e:
|
||
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
|
||
return None
|
||
|
||
if llm_result is None:
|
||
logger.warning("V7-4: LLM-Check returned None → Fallback: NEU")
|
||
return None
|
||
|
||
# Parse LLM-Antwort: "REKURSIV: <topic>" oder "NEU"
|
||
response = llm_result.strip()
|
||
logger.debug("V7-4: LLM-Antwort: %s", response)
|
||
|
||
if response.upper().startswith("REKURSIV"):
|
||
# Extrahiere Topic aus "REKURSIV: lan-dokumentation"
|
||
parts = response.split(":", 1)
|
||
if len(parts) == 2:
|
||
topic = parts[1].strip().lower()
|
||
logger.info(
|
||
"V7-4: Rekursiver Bezug erkannt → Thema '%s'", topic,
|
||
)
|
||
return topic
|
||
# Fallback: REKURSIV ohne Topic → old_topic verwenden
|
||
if old_topic:
|
||
logger.info(
|
||
"V7-4: Rekursiver Bezug erkannt (ohne Topic) → old_topic '%s'",
|
||
old_topic,
|
||
)
|
||
return old_topic
|
||
logger.warning("V7-4: REKURSIV ohne Topic und kein old_topic")
|
||
return None
|
||
|
||
# NEU oder unbekannte Antwort
|
||
logger.debug("V7-4: Kein rekursiver Bezug (LLM sagt NEU)")
|
||
return None
|
||
|
||
def _check_never_route_topic(
|
||
self, origin_room_id: str, matched_room: RoomEntry
|
||
) -> bool:
|
||
"""Prüft ob das Thema des gematchten Raums in never_route ist.
|
||
|
||
V7-3: Führt auch Themenwechsel-Erkennung durch:
|
||
- Neues Thema ≠ altes Thema → altes never_route VERBLASST
|
||
- Neues Thema == altes Thema → never_route verlängern
|
||
- Aktualisiert topic_hint in conversation_history
|
||
|
||
Args:
|
||
origin_room_id: Der Ursprungsraum.
|
||
matched_room: Der gematchte Zielraum.
|
||
|
||
Returns:
|
||
True wenn das Thema in never_route ist (AKTIV) → stay_in_room.
|
||
"""
|
||
topic = self._room_name_to_topic(matched_room.name)
|
||
|
||
# ── V7-3: Themenwechsel-Erkennung ──────────────────────────
|
||
self._detect_topic_change(origin_room_id, topic)
|
||
|
||
if self._state.is_never_route(origin_room_id, topic):
|
||
logger.info(
|
||
"P0-B: never_route match — room %s, topic '%s' → stay_in_room",
|
||
origin_room_id[:8], topic,
|
||
)
|
||
return True
|
||
return False
|
||
|
||
def _detect_topic_change(self, room_id: str, new_topic: str) -> None:
|
||
"""V7-3: Erkenne Themenwechsel und aktualisiere never_route-Zustände.
|
||
|
||
- Holt altes Thema aus conversation_history
|
||
- Neues Thema ≠ altes Thema → altes never_route VERBLASST
|
||
- Neues Thema == altes Thema → never_route verlängern (extend)
|
||
- Aktualisiert topic_hint in conversation_history
|
||
|
||
Args:
|
||
room_id: Rocket.Chat Raum-ID.
|
||
new_topic: Das neue Thema (aus gematchtem Raum).
|
||
"""
|
||
if self._conversation_history is None:
|
||
return
|
||
|
||
try:
|
||
# Hole altes Thema (sync, da wir im async-Kontext sind,
|
||
# aber conversation_history._topic_hints ist ein dict)
|
||
old_topic = self._conversation_history._topic_hints.get(room_id)
|
||
except Exception:
|
||
old_topic = None
|
||
|
||
if old_topic is None:
|
||
# Kein altes Thema → nur topic_hint setzen
|
||
if self._conversation_history is not None:
|
||
try:
|
||
self._conversation_history._topic_hints[room_id] = new_topic
|
||
except Exception:
|
||
pass
|
||
return
|
||
|
||
if old_topic != new_topic:
|
||
# ── Themenwechsel: altes Thema → VERBLASST ──────────────
|
||
old_entry = self._state.get_never_route_entry(room_id, old_topic)
|
||
if old_entry and old_entry.get("state") == "AKTIV":
|
||
old_entry["state"] = "VERBLASST"
|
||
self._state.save()
|
||
logger.info(
|
||
"V7-3: Themenwechsel in %s — '%s' → '%s', "
|
||
"altes never_route '%s' AKTIV → VERBLASST",
|
||
room_id[:8], old_topic, new_topic, old_topic,
|
||
)
|
||
else:
|
||
# ── Gleiches Thema: never_route verlängern ──────────────
|
||
self._state.extend_never_route(room_id, new_topic)
|
||
|
||
# Aktualisiere topic_hint
|
||
if self._conversation_history is not None:
|
||
try:
|
||
self._conversation_history._topic_hints[room_id] = new_topic
|
||
except Exception:
|
||
pass
|
||
|
||
# ── 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
|
||
|
||
# ── V8.4: Red Flag — Agent als 6. Entscheidungsträger ──────────────
|
||
|
||
def _get_red_flag_rooms(self, origin_room_id: str) -> List[str]:
|
||
"""Ermittelt verfügbare Räume für den Red-Flag-Prompt.
|
||
|
||
Nur Nicht-Catch-All-Räume, die NICHT der Ursprungsraum sind.
|
||
Format: '#Raumname (Thema)'.
|
||
|
||
Args:
|
||
origin_room_id: Der Ursprungsraum (wird ausgeschlossen).
|
||
|
||
Returns:
|
||
Liste von Raum-Strings für den Prompt.
|
||
"""
|
||
rooms = []
|
||
for room in self._room_map.rooms.values():
|
||
if room.catch_all:
|
||
continue
|
||
if room.room_id == origin_room_id:
|
||
continue
|
||
theme = room.theme or ""
|
||
if theme:
|
||
rooms.append(f"#{room.name.lstrip('#')} ({theme})")
|
||
else:
|
||
rooms.append(f"#{room.name.lstrip('#')}")
|
||
return rooms
|
||
|
||
def _build_red_flag_decision(
|
||
self, text: str, origin_room_id: str, available_rooms: List[str]
|
||
) -> RoutingDecision:
|
||
"""Baut eine Red-Flag-RoutingDecision mit strukturiertem Prompt.
|
||
|
||
Args:
|
||
text: Der Nachrichtentext (für Kontext).
|
||
origin_room_id: Der Ursprungsraum.
|
||
available_rooms: Liste der verfügbaren Raum-Strings.
|
||
|
||
Returns:
|
||
RoutingDecision mit is_red_flag=True und red_flag_prompt.
|
||
"""
|
||
origin_name = ""
|
||
if origin_room_id:
|
||
origin_room = self._room_map.get_room_by_id(origin_room_id)
|
||
if origin_room:
|
||
origin_name = origin_room.name
|
||
|
||
room_list = "\n".join(f"- {r}" for r in available_rooms)
|
||
prompt = RED_FLAG_PROMPT.format(
|
||
room_list=room_list,
|
||
origin_room=origin_name or "unbekannt",
|
||
)
|
||
|
||
return RoutingDecision(
|
||
category="direct_question",
|
||
target_room="",
|
||
confidence=0.0,
|
||
stay_in_room=True,
|
||
is_red_flag=True,
|
||
red_flag_rooms=available_rooms,
|
||
red_flag_prompt=prompt,
|
||
)
|
||
|
||
|
||
# ── V8.4: Red-Flag-Response-Parsing (Modul-Level) ──────────────────────
|
||
|
||
|
||
def _parse_red_flag_response(response: str, room_map: RoomMap) -> Optional[str]:
|
||
"""Extrahiere ROOM: <raumname> aus der Agent-Antwort.
|
||
|
||
Sucht nach 'ROOM:' am Zeilenanfang (case-insensitive) und löst den
|
||
Raum-Namen gegen die RoomMap auf.
|
||
|
||
Args:
|
||
response: Die vollständige Agent-Antwort.
|
||
room_map: Die RoomMap zur Auflösung von Namen → IDs.
|
||
|
||
Returns:
|
||
room_id wenn gefunden und auflösbar, None sonst (→ STAY-Fallback).
|
||
"""
|
||
if not response or not response.strip():
|
||
return None
|
||
|
||
# Suche nach ROOM: am Anfang einer Zeile (case-insensitive)
|
||
import re
|
||
match = re.search(r'^ROOM:\s*(.+?)$', response, re.IGNORECASE | re.MULTILINE)
|
||
if not match:
|
||
return None
|
||
|
||
room_name = match.group(1).strip()
|
||
if not room_name:
|
||
return None
|
||
|
||
# Normalisiere: entferne führendes #, lowercase
|
||
normalized = room_name.lstrip("#").lower()
|
||
|
||
# Exakter Match gegen RoomMap
|
||
for room_id, entry in room_map.rooms.items():
|
||
entry_name = entry.name.lstrip("#").lower()
|
||
if entry_name == normalized:
|
||
return room_id
|
||
|
||
# Fallback: partial match (z.B. 'LAN-Doku' matcht '#LAN-Dokumentation')
|
||
for room_id, entry in room_map.rooms.items():
|
||
entry_name = entry.name.lstrip("#").lower()
|
||
if normalized in entry_name or entry_name in normalized:
|
||
return room_id
|
||
|
||
return None
|
||
|
||
|
||
def _strip_red_flag_prefix(response: str) -> str:
|
||
"""Entfernt die ROOM: Zeile aus der Agent-Antwort.
|
||
|
||
Args:
|
||
response: Die vollständige Agent-Antwort.
|
||
|
||
Returns:
|
||
Bereinigter Text ohne ROOM:-Zeile.
|
||
"""
|
||
if not response:
|
||
return response
|
||
|
||
import re
|
||
# Entferne ROOM: Zeile + folgende Leerzeilen
|
||
cleaned = re.sub(r'^ROOM:\s*.+?\n\s*\n?', '', response, flags=re.IGNORECASE | re.MULTILINE)
|
||
return cleaned.strip()
|
||
|
||
|
||
# ── A1b: LLM-Validierung für Weich-Muster (Stufe 4/5) ──────────────────────
|
||
|
||
|
||
async def validate_sentence_marker(
|
||
marker_result: SentenceMarkerResult,
|
||
current_message: str,
|
||
room_id: str,
|
||
conversation_history: Any,
|
||
state: ArchivarState,
|
||
classifier: Any,
|
||
llm_semaphore: asyncio.Semaphore,
|
||
) -> Optional[dict]:
|
||
"""Validiere eine Satzeinleitungs-Erkennung via LLM (Stufe 4/5).
|
||
|
||
Wird NUR bei Konfidenz < 0.8 aufgerufen (weiche Muster).
|
||
Das LLM validiert die Klassifikation, trifft aber KEINE Routing-Entscheidung.
|
||
|
||
Args:
|
||
marker_result: Das Ergebnis der Regex-Erkennung (Stufe 0).
|
||
current_message: Der aktuelle Nachrichtentext.
|
||
room_id: Rocket.Chat Raum-ID.
|
||
conversation_history: ConversationHistory-Instanz (für Kontext).
|
||
state: ArchivarState-Instanz (für V7-3-State).
|
||
classifier: IntentClassifier-Instanz (für _llm_raw).
|
||
llm_semaphore: asyncio.Semaphore für Ollama-Concurrency.
|
||
|
||
Returns:
|
||
Dict mit {action, confidence, referenz_topic} oder None bei Fehler.
|
||
"""
|
||
import json as _json
|
||
|
||
# ── Konversationshistorie (letzte 3-5 Nachrichten) ─────────────────
|
||
history_context = "(keine Historie)"
|
||
if conversation_history is not None:
|
||
try:
|
||
buf = conversation_history._buffers.get(room_id)
|
||
if buf:
|
||
recent = list(buf)[-5:]
|
||
history_lines = []
|
||
for entry in recent:
|
||
role = getattr(entry, "role", "user")
|
||
msg_text = getattr(entry, "text", "")
|
||
history_lines.append(f"[{role}] {msg_text}")
|
||
if history_lines:
|
||
history_context = "\n".join(history_lines)
|
||
except Exception:
|
||
pass
|
||
|
||
# ── V7-3 State ────────────────────────────────────────────────────
|
||
v7_3_state = "(keine never_route Einträge)"
|
||
try:
|
||
topics = state.get_never_route_topics(room_id)
|
||
if topics:
|
||
lines = []
|
||
for topic, entry in topics.items():
|
||
st = entry.get("state", "?")
|
||
lines.append(f" - {topic}: {st}")
|
||
v7_3_state = "\n".join(lines)
|
||
except Exception:
|
||
pass
|
||
|
||
# ── Prompt bauen ──────────────────────────────────────────────────
|
||
prompt = _SENTENCE_MARKER_VALIDATION_PROMPT.format(
|
||
history=history_context,
|
||
current_message=current_message,
|
||
marker_class=marker_result.marker_class.value,
|
||
regex_confidence=f"{marker_result.confidence:.2f}",
|
||
matched_text=marker_result.matched_text,
|
||
referenz_topic=marker_result.referenz_topic or "N/A",
|
||
v7_3_state=v7_3_state,
|
||
)
|
||
|
||
# ── LLM-Aufruf mit 5s Timeout ─────────────────────────────────────
|
||
try:
|
||
async with llm_semaphore:
|
||
llm_result = await asyncio.wait_for(
|
||
classifier._llm_raw(prompt),
|
||
timeout=5.0,
|
||
)
|
||
except asyncio.TimeoutError:
|
||
logger.warning(
|
||
"A1b Stufe 4/5: LLM-Validierung Timeout (5s) → Fallback: unentscheidbar"
|
||
)
|
||
return None
|
||
except Exception as e:
|
||
logger.warning(
|
||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
||
e,
|
||
)
|
||
return None
|
||
|
||
if llm_result is None:
|
||
logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar")
|
||
return None
|
||
|
||
# ── Parse JSON-Antwort ────────────────────────────────────────────
|
||
try:
|
||
response_text = llm_result.strip()
|
||
# Entferne mögliche Markdown-Code-Blöcke
|
||
if response_text.startswith("```"):
|
||
lines = response_text.split("\n")
|
||
response_text = "\n".join(lines[1:]) if len(lines) > 1 else response_text
|
||
if response_text.endswith("```"):
|
||
response_text = response_text[:-3]
|
||
result = _json.loads(response_text)
|
||
except (_json.JSONDecodeError, ValueError) as e:
|
||
logger.warning(
|
||
"A1b Stufe 4/5: JSON-Parse-Fehler: %s — raw: %.200s",
|
||
e, llm_result,
|
||
)
|
||
return None
|
||
|
||
# ── Validierung ───────────────────────────────────────────────────
|
||
action = result.get("action", "unentscheidbar")
|
||
if action not in ("themenwechsel", "rueckbezug", "unentscheidbar"):
|
||
logger.warning(
|
||
"A1b Stufe 4/5: Unbekannte action '%s' → unentscheidbar", action
|
||
)
|
||
action = "unentscheidbar"
|
||
|
||
confidence = float(result.get("confidence", 0.5))
|
||
confidence = max(0.0, min(1.0, confidence))
|
||
|
||
referenz_topic = result.get("referenz_topic")
|
||
if referenz_topic == "null" or referenz_topic == "None":
|
||
referenz_topic = None
|
||
|
||
logger.info(
|
||
"A1b Stufe 4/5: LLM-Validierung — action=%s, confidence=%.2f, topic=%s",
|
||
action, confidence, referenz_topic or "N/A",
|
||
)
|
||
|
||
return {
|
||
"action": action,
|
||
"confidence": confidence,
|
||
"referenz_topic": referenz_topic,
|
||
}
|
||
|
||
|
||
# ── Module-level alias für externe Nutzer (adapter.py) ──────────────
|
||
# Zentralisierte Topic-Extraktion: adapter.py importiert diese Funktion
|
||
# statt die Logik an mehreren Stellen zu duplizieren.
|
||
room_name_to_topic = BidirectionalRouter._room_name_to_topic |