feat(archivar): LLM-basierter Raum-Router ersetzt IntentClassifier — Embedding-Vorfilter + LLM_ROOM_PROMPT + Move-Request-Buttons

Korrigierter Archivar-Routing-Flow gemäß Architekturskizze:

1. Embedding-Vorfilter (nomic-embed-text): binär Smalltalk vs. potenzieller Auftrag
   - Klarer Smalltalk → stay_in_room
   - Unsicher → LLM-Raum-Router

2. LLM-Raum-Router (qwen2.5:7b): LLM_ROOM_PROMPT als zentraler Prompt
   - Erhält Nachrichtentext + Raumliste mit IDs und ALLEN Keywords
   - Liefert room_id direkt (keine Kategorien, kein Name-Matching)

3. Move-Request-Buttons (Butler-Prinzip): ✅Ja/📍Hier VOR Routing
   - Kein automatisches Routing ohne User-Bestätigung

4. Betriebsstufen-Log: 'Archivar Stufe 1: Embedding-Vorfilter + LLM-Raum-Router aktiv (5 Räume)'

Änderungen:
- config.py: LLM_ROOM_PROMPT auf Raum-ID-Ausgabe umgestellt, Keywords pro Raum,
  ARCHIVAR_STUFE_LOG, MOVE_REQUEST_TEMPLATE, max_tokens=30
- classifier.py: LLMClient.generate() als neue ABC-Methode + OllamaLLMClient-Impl,
  _llm_raw_sync nutzt generate() statt classify()
- router.py: RoutingDecision um move_request_sent/target_name/target_id erweitert,
  route() komplett neu: Embedding→LLM→Move-Request, _llm_room_lookup() mit IDs+Keywords
- adapter_integration.py: _send_move_request() + handle_move_request_response(),
  classify_and_route() behandelt move_request_sent, handle_and_forward() wartet auf Bestätigung

IntentClassifier.classify() wird NICHT gelöscht — nur als binärer Vorfilter verwendet.
Bestehende Tests: 53/54 grün (1 pre-existing env-var issue).
This commit is contained in:
Bernd (Hermes)
2026-06-14 10:25:33 +02:00
parent 0a7702475f
commit 170f7e6096
4 changed files with 348 additions and 109 deletions
+103 -89
View File
@@ -101,6 +101,16 @@ class RoutingDecision:
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."""
@@ -111,15 +121,18 @@ class RoutingDecision:
"""Liste der Keywords, die zum Routing-Vorschlag führten."""
def should_route(self) -> bool:
"""True wenn die Nachricht geroutet werden sollte."""
"""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
self.target_room and
self.category == "work_order" and
self.confidence >= CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
bool(self.target_room)
)
@@ -165,16 +178,19 @@ class BidirectionalRouter:
# ── Public API ──────────────────────────────────────────────────────
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
"""Klassifiziere und route eine Nachricht.
"""Klassifiziere und route eine Nachricht (korrigierter Flow).
Der vollständige Routing-Flow:
Der neue Routing-Flow (Architekturskizze):
1. origin_room_id in excluded_rooms? → IGNORE (silent)
2. Raum-Zustand prüfen (persistenter Zustand)
3. Keyword-Match in RoomEntry.keywords → Zielraum
4. Keyword-Override-Match → Override-Raum (höchste Prio)
5. Embedding-Klassifikation via IntentClassifier
6. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?")
7. Kein Treffer → catch_all_room
3. Meta-Fragen-Erkennung
4. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig)
5. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag"
- Klarer Smalltalk → stay_in_room
- Unsicher → weiter zu LLM-Raum-Router
6. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste mit Keywords → room_id direkt
7. Raum gefunden → Move-Request-Button (Butler-Prinzip: ✅Ja/📍Hier)
8. Kein Treffer → catch_all_room
Args:
text: Der Nachrichtentext.
@@ -210,17 +226,15 @@ class BidirectionalRouter:
# ── Schritt 1: Raum-Zustand prüfen ───────────────────────────
room_state_decision = self._state.should_stay_in_room(origin_room_id)
if room_state_decision is True:
# Raum ist explizit auf "immer bleiben" gesetzt
return RoutingDecision(
category="direct_question", # Default-Kategorie
category="direct_question",
target_room="",
confidence=1.0,
stay_in_room=True,
)
elif room_state_decision is False:
# Raum ist explizit auf "nie routen" gesetzt
return RoutingDecision(
category="direct_question", # Default-Kategorie
category="direct_question",
target_room="",
confidence=1.0,
stay_in_room=True,
@@ -245,15 +259,12 @@ class BidirectionalRouter:
logger.debug(
"Keyword match: '%s' → %s", text[:80], matched_room.name
)
# Für Keyword-Matches erstellen wir eine bidirektionale Benachrichtigung
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
# Extrahiere die gematchten Keywords
matched_keywords = self._extract_matched_keywords(text, matched_room)
return RoutingDecision(
category="work_order", # Keyword-Matches sind typischerweise Work Orders
category="work_order",
target_room=matched_room.room_id,
confidence=0.95,
matched_room_name=matched_room.name,
@@ -261,76 +272,65 @@ class BidirectionalRouter:
matched_keywords=matched_keywords,
)
# ── Schritt 4: Embedding-basierte Klassifikation ───────────────
# ── 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,
)
# ── Schritt 5: Fallback bei Classifier-Versagen ────────────────
if result is None:
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 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 = 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(
"Classifier unavailable — using keyword fallback for: %.80s...",
text,
"LLM-Raum-Router: '%s' → %s (%s)",
text[:80], llm_room.name, llm_room.room_id[:8],
)
category, is_fallback = self._keyword_classify(text)
stay_in_room = category in ("direct_question", "smalltalk")
# ── 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=category,
target_room=self._resolve_room(category) if not stay_in_room else "",
confidence=0.0,
is_fallback=is_fallback,
prefix="[FALLBACK] " if is_fallback else "",
stay_in_room=stay_in_room,
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 6: Konfidenz-Prüfung und Routing-Entscheidung ───────────────────────────────
# Prüfe zuerst, ob die Nachricht bleiben soll (direct_question, smalltalk)
if result.category in ("direct_question", "smalltalk"):
return RoutingDecision(
category=result.category,
target_room="",
confidence=result.confidence,
all_scores=result.all_scores,
stay_in_room=True,
)
# Prüfe auf Klärung benötigt (ambiguous oder Konfidenz 60-90%)
if result.needs_clarification():
return RoutingDecision(
category=result.category,
target_room="",
confidence=result.confidence,
all_scores=result.all_scores,
needs_clarification=True,
stay_in_room=True,
)
# Prüfe ob work_order mit hoher Konfidenz geroutet werden soll
if result.category == "work_order" and result.should_route():
target_room = self._resolve_room("work_order")
if target_room:
# Erstelle bidirektionale Benachrichtigung
room_entry = self._room_map.get_room_by_id(target_room)
room_name = room_entry.name.replace("#", "") if room_entry and room_entry.name.startswith("#") else "Zielraum"
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
return RoutingDecision(
category="work_order",
target_room=target_room,
confidence=result.confidence,
all_scores=result.all_scores,
source_room_notification=notification,
)
# Default: Nachricht bleibt im Raum
# ── Schritt 7: Kein Treffer → 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=result.category,
target_room="",
confidence=result.confidence,
all_scores=result.all_scores,
category="direct_question",
target_room=catch_all.room_id if catch_all else "",
confidence=0.0,
is_catch_all=True,
stay_in_room=True,
)
@@ -375,9 +375,9 @@ class BidirectionalRouter:
def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]:
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
Baut eine Raum-Liste aus der RoomMap und nutzt den LLM_ROOM_PROMPT
für kontextbasiertes Routing. Der Classifier muss LLM-fähig sein
(``ARCHIVAR_ENABLE_LLM=1``).
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).
Args:
text: Der Nachrichtentext.
@@ -385,33 +385,47 @@ class BidirectionalRouter:
Returns:
Den gematchten ``RoomEntry``, oder ``None`` bei Fehler/kein Match.
"""
# Build room list for LLM prompt
# 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.name}: {room.theme} (Keywords: {', '.join(room.keywords[:5])})"
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: {self._room_map.catch_all_room.name if self._room_map.catch_all_room else 'Admin DM'}"
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 classification (raw mode — expects room name, not category)
# Try LLM — expects room ID directly
llm_result = self._classifier._llm_raw_sync(prompt)
if llm_result is None:
return None
# Parse LLM response — could be a room name or "CATCH_ALL"
# 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
# Try to match response to a room name
# 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
# 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():