diff --git a/plugin/adapter.py b/plugin/adapter.py index 33597a1..2a6e461 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -50,7 +50,9 @@ _THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar( ) # Globaler Monoton-Zähler für Archivar-Fragen +import threading _question_counter: int = 0 +_question_counter_lock: threading.Lock = threading.Lock() try: from gateway.platforms.base import ( @@ -810,7 +812,8 @@ class RocketChatAdapter(BasePlatformAdapter): if hasattr(decision, 'target_room') and decision.target_room: _THEMATIC_TARGET_ROOM.set(decision.target_room) global _question_counter - _question_counter += 1 + with _question_counter_lock: + _question_counter += 1 # ── Ende Kontext-Weitergabe ────────────────────────────── # Archivar v4 Move-Request: _pending_move_requests befüllen, damit # der Button-Response-Handler (lines 717-764) die Antwort korrekt @@ -836,7 +839,8 @@ class RocketChatAdapter(BasePlatformAdapter): } except asyncio.TimeoutError: logger.warning("[rocketchat] Archivar classify_and_route() timed out") - _question_counter += 1 + with _question_counter_lock: + _question_counter += 1 # _THEMATIC_TARGET_ROOM bleibt leer → Prompt sagt "Timeout" except Exception as e: logger.debug("[rocketchat] Archivar classification skipped: %s", e) @@ -954,13 +958,15 @@ class RocketChatAdapter(BasePlatformAdapter): target_room_id = _THEMATIC_TARGET_ROOM.get() if target_room_id: target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…") - archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]" + with _question_counter_lock: + archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]" else: # Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung room_names = [info.get("name", "?") for rid, info in self._room_info.items() if info.get("type") in ("c", "p") and rid != room_id] rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume" - archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]" + with _question_counter_lock: + archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]" # ── Ende Kontext-Weitergabe ────────────────────────────────────── source = SessionSource( platform=Platform("rocketchat"), diff --git a/plugin/archivar/router.py b/plugin/archivar/router.py index cae822b..eee2760 100644 --- a/plugin/archivar/router.py +++ b/plugin/archivar/router.py @@ -8,6 +8,7 @@ und Zusammenfassung nach Abschluss. from __future__ import annotations +import asyncio import logging import re from dataclasses import dataclass, field @@ -209,6 +210,10 @@ class BidirectionalRouter: self._room_index: Optional[RoomIndexManager] = room_index self._booster: Optional[KeywordBooster] = booster self._subscribed_room_ids: Optional[set] = None + # Semaphore für Ollama-Concurrency: qwen2.5:7b kann nur 1 Request + # parallel verarbeiten. Ohne diesen Schutz führen parallele Aufrufe + # zu Timeout-Kaskaden. + self._llm_semaphore: asyncio.Semaphore = asyncio.Semaphore(1) # ── Public API ────────────────────────────────────────────────────── @@ -248,176 +253,74 @@ class BidirectionalRouter: text = text.strip() - # ── Schritt 0: Excluded rooms check ────────────────────────── - if origin_room_id and self._room_map.is_excluded(origin_room_id): - logger.debug( - "Message from excluded room %s — ignoring", origin_room_id[:8] - ) - return RoutingDecision( - category="direct_question", - target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", - confidence=0.0, - is_catch_all=True, - stay_in_room=True, - ) - - # ── Schritt 1: Raum-Zustand prüfen ─────────────────────────── - room_state_decision = self._state.should_stay_in_room(origin_room_id) - if room_state_decision is True: - return RoutingDecision( - category="direct_question", - target_room="", - confidence=1.0, - stay_in_room=True, - ) - elif room_state_decision is False: - return RoutingDecision( - category="direct_question", - target_room="", - confidence=1.0, - stay_in_room=True, - ) - - # ── Schritt 2: Meta-Fragen-Erkennung ────────────────────────── - if self._is_meta_question(text): - logger.info("Meta-question detected: %.80s...", text) - return RoutingDecision( - category="direct_question", - target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", - confidence=1.0, - is_meta=True, - delete_original=True, - prefix="[META-FRAGE] ", - stay_in_room=True, - ) - - # ── Schritt 3: Keyword-Match (aus RoomMap) ────────────────── - matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id) - if matched_room is not None: - logger.debug( - "Keyword match: '%s' → %s", text[:80], matched_room.name - ) - room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name - notification = f"📋 Bearbeite ich in #{room_name} — [Link]" - matched_keywords = self._extract_matched_keywords(text, matched_room) - - return RoutingDecision( - category="work_order", - target_room=matched_room.room_id, - confidence=0.95, - matched_room_name=matched_room.name, - source_room_notification=notification, - matched_keywords=matched_keywords, - ) - - # ── Schritt 3.5: FAISS Phase-1 (Raum-Index + Keyword-Booster) ─ - # Drei-Schichten-Logik: FAISS → Booster → LLM - # Phase-1 routet direkt bei hohem FAISS-Score — kein LLM-Aufruf. - # Übersprungen wenn _room_index oder _booster None sind. - if self._room_index is not None and self._room_index.is_built: - faiss_hits = self._room_index.search_text( - text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE - ) - if faiss_hits: - # ── Keyword-Booster anwenden ────────────────────── - boosted = faiss_hits - booster_applied = False - if self._booster is not None: - # Nur boosten wenn Top-2 knapp beieinander liegen - if ( - len(faiss_hits) >= 2 - and (faiss_hits[0][1] - faiss_hits[1][1]) < FAISS_CONFLICT_DIFF - ): - boosted = self._booster.boost(text, faiss_hits) - booster_applied = True - logger.debug( - "FAISS Booster applied: diff=%.3f < %.3f", - faiss_hits[0][1] - faiss_hits[1][1], - FAISS_CONFLICT_DIFF, - ) - - top_room_id, top_score = boosted[0] - - # ── Auto-Route bei hohem Score ──────────────────── - if top_score >= FAISS_AUTO_ROUTE: - room = self._room_map.get_room_by_id(top_room_id) - if room is not None: - room_name = ( - room.name.replace("#", "") - if room.name.startswith("#") - else room.name - ) - notification = f"📋 Bearbeite ich in #{room_name} — [Link]" - matched_keywords = self._extract_matched_keywords(text, room) - - logger.info( - "FAISS Phase-1: auto-route '%s' → %s (score=%.3f, booster=%s)", - text[:80], - room.name, - top_score, - booster_applied, - ) - - return RoutingDecision( - category="work_order", - target_room=top_room_id, - confidence=top_score, - matched_room_name=room.name, - source_room_notification=notification, - matched_keywords=matched_keywords, - faiss_score=top_score, - faiss_room_id=top_room_id, - faiss_room_name=room.name, - is_faiss_routed=True, - booster_applied=booster_applied, - ) - - # ── Score unter Schwelle → Fall-through zu Embedding + LLM + try: + # ── Schritt 0: Excluded rooms check ────────────────────────── + if origin_room_id and self._room_map.is_excluded(origin_room_id): logger.debug( - "FAISS Phase-1: top score %.3f < %.3f — fall-through to LLM", - top_score, - FAISS_AUTO_ROUTE, + "Message from excluded room %s — ignoring", origin_room_id[:8] + ) + return RoutingDecision( + category="direct_question", + target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", + confidence=0.0, + is_catch_all=True, + stay_in_room=True, ) - # ── Schritt 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 0.5: Check if origin room is catch-all ─────────── + origin_room = self._room_map.get_room_by_id(origin_room_id) if origin_room_id else None + if origin_room and origin_room.catch_all: + logger.debug( + "Message from catch-all room %s — ignoring", origin_room_id[:8] + ) + return RoutingDecision( + category="direct_question", + target_room=origin_room_id, + confidence=0.0, + is_catch_all=True, + stay_in_room=True, + ) - 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 1: Raum-Zustand prüfen ─────────────────────────── + room_state_decision = self._state.should_stay_in_room(origin_room_id) + if room_state_decision is True: + return RoutingDecision( + category="direct_question", + target_room="", + confidence=1.0, + stay_in_room=True, + ) + elif room_state_decision is False: + return RoutingDecision( + category="direct_question", + target_room="", + confidence=1.0, + stay_in_room=True, + ) - # ── Schritt 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: + # ── Schritt 2: Meta-Fragen-Erkennung ────────────────────────── + if self._is_meta_question(text): + logger.info("Meta-question detected: %.80s...", text) + return RoutingDecision( + category="direct_question", + target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", + confidence=1.0, + is_meta=True, + delete_original=True, + prefix="[META-FRAGE] ", + stay_in_room=True, + ) + + # ── Schritt 3: Keyword-Match (aus RoomMap) ────────────────── matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id) if matched_room is not None: - logger.info( - "Keyword-Match vor LLM: '%s' → %s (embedding conf=%.3f)", - text[:80], matched_room.name, result.confidence, + logger.debug( + "Keyword match: '%s' → %s", text[:80], matched_room.name ) room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name notification = f"📋 Bearbeite ich in #{room_name} — [Link]" matched_keywords = self._extract_matched_keywords(text, matched_room) + return RoutingDecision( category="work_order", target_room=matched_room.room_id, @@ -427,48 +330,180 @@ class BidirectionalRouter: matched_keywords=matched_keywords, ) - # ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ──────────── - # LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords, - # liefert room_id direkt (keine Kategorien, kein Name-Matching) - llm_room, llm_failed = self._llm_room_lookup(text) - if llm_room is not None: - room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name - logger.info( - "LLM-Raum-Router: '%s' → %s (%s)", - text[:80], llm_room.name, llm_room.room_id[:8], - ) + # ── Schritt 3.5: FAISS Phase-1 (Raum-Index + Keyword-Booster) ─ + # Drei-Schichten-Logik: FAISS → Booster → LLM + # Phase-1 routet direkt bei hohem FAISS-Score — kein LLM-Aufruf. + # Übersprungen wenn _room_index oder _booster None sind. + if self._room_index is not None and self._room_index.is_built: + faiss_hits = self._room_index.search_text( + text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE + ) + if faiss_hits: + # ── Keyword-Booster anwenden ────────────────────── + boosted = faiss_hits + booster_applied = False + if self._booster is not None: + # Nur boosten wenn Top-2 knapp beieinander liegen + if ( + len(faiss_hits) >= 2 + and (faiss_hits[0][1] - faiss_hits[1][1]) < FAISS_CONFLICT_DIFF + ): + boosted = self._booster.boost(text, faiss_hits) + booster_applied = True + logger.debug( + "FAISS Booster applied: diff=%.3f < %.3f", + faiss_hits[0][1] - faiss_hits[1][1], + FAISS_CONFLICT_DIFF, + ) - # ── Schritt 6: Move-Request-Button (Butler-Prinzip) ────── - # Vor dem Routing: Button an Andreas — "Soll ich nach [Raum] kopieren?" - # ✅Ja → Route, 📍Hier → stay_in_room - return RoutingDecision( - category="work_order", - target_room=llm_room.room_id, - confidence=0.90, - matched_room_name=llm_room.name, - move_request_sent=True, - move_request_target_name=llm_room.name, - move_request_target_id=llm_room.room_id, - ) + top_room_id, top_score = boosted[0] - # ── Schritt 7: LLM-Fehler oder kein Treffer ────────────────── - if llm_failed: - # FIX 1: Timeout/Exception → Fallback auf Ursprungsraum, NICHT Catch-All - logger.warning( - "LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...' → stay_in_room (Ursprungsraum)", - text, - ) - return RoutingDecision( - category="direct_question", - target_room="", - confidence=0.0, - stay_in_room=True, - is_catch_all=False, - ) - else: - # LLM erfolgreich, aber kein Match → catch_all - logger.info( - "LLM-Raum-Router: kein Treffer für '%.80s...' → catch_all", text + # ── Auto-Route bei hohem Score ──────────────────── + if top_score >= FAISS_AUTO_ROUTE: + room = self._room_map.get_room_by_id(top_room_id) + if room is not None: + room_name = ( + room.name.replace("#", "") + if room.name.startswith("#") + else room.name + ) + notification = f"📋 Bearbeite ich in #{room_name} — [Link]" + matched_keywords = self._extract_matched_keywords(text, room) + + logger.info( + "FAISS Phase-1: auto-route '%s' → %s (score=%.3f, booster=%s)", + text[:80], + room.name, + top_score, + booster_applied, + ) + + return RoutingDecision( + category="work_order", + target_room=top_room_id, + confidence=top_score, + matched_room_name=room.name, + source_room_notification=notification, + matched_keywords=matched_keywords, + faiss_score=top_score, + faiss_room_id=top_room_id, + faiss_room_name=room.name, + is_faiss_routed=True, + booster_applied=booster_applied, + ) + + # ── Score unter Schwelle → Fall-through zu Embedding + LLM + logger.debug( + "FAISS Phase-1: top score %.3f < %.3f — fall-through to LLM", + top_score, + FAISS_AUTO_ROUTE, + ) + + # ── Schritt 4: Embedding-Vorfilter (binär) ──────────────────── + # Nur noch binär: "Smalltalk" vs. "potenzieller Auftrag" + # Klarer Smalltalk → stay_in_room, alles andere → LLM-Router + is_smalltalk = False + result: Optional[ClassificationResult] = None + if self._classifier.is_initialized: + result = await self._classifier.classify(text) + if result is not None: + # Binärer Vorfilter: Nur Smalltalk mit hoher Konfidenz blocken + if result.category == "smalltalk" and result.confidence >= 0.8: + is_smalltalk = True + logger.info( + "Embedding-Vorfilter: Smalltalk erkannt (conf=%.3f) — stay_in_room", + result.confidence, + ) + + if is_smalltalk: + return RoutingDecision( + category="smalltalk", + target_room="", + confidence=result.confidence if result else 0.0, + all_scores=result.all_scores if result else {}, + stay_in_room=True, + ) + + # ── Schritt 4.5: Keyword-Matching vor LLM (FIX 2) ──────────── + # Wenn Embedding 'work_order' mit niedriger Konfidenz (< 0.9): + # versuche Keyword-Match bevor wir das LLM aufrufen. + # Verhindert unnötige LLM-Calls für Nachrichten mit klaren Keywords. + if result is not None and result.category == "work_order" and result.confidence < 0.9: + matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id) + if matched_room is not None: + logger.info( + "Keyword-Match vor LLM: '%s' → %s (embedding conf=%.3f)", + text[:80], matched_room.name, result.confidence, + ) + room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name + notification = f"📋 Bearbeite ich in #{room_name} — [Link]" + matched_keywords = self._extract_matched_keywords(text, matched_room) + return RoutingDecision( + category="work_order", + target_room=matched_room.room_id, + confidence=0.95, + matched_room_name=matched_room.name, + source_room_notification=notification, + matched_keywords=matched_keywords, + ) + + # ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ──────────── + # LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords, + # liefert room_id direkt (keine Kategorien, kein Name-Matching) + llm_room, llm_failed = await self._llm_room_lookup(text) + if llm_room is not None: + room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name + logger.info( + "LLM-Raum-Router: '%s' → %s (%s)", + text[:80], llm_room.name, llm_room.room_id[:8], + ) + + # ── Schritt 6: Move-Request-Button (Butler-Prinzip) ────── + # Vor dem Routing: Button an Andreas — "Soll ich nach [Raum] kopieren?" + # ✅Ja → Route, 📍Hier → stay_in_room + return RoutingDecision( + category="work_order", + target_room=llm_room.room_id, + confidence=0.90, + matched_room_name=llm_room.name, + move_request_sent=True, + move_request_target_name=llm_room.name, + move_request_target_id=llm_room.room_id, + ) + + # ── Schritt 7: LLM-Fehler oder kein Treffer ────────────────── + if llm_failed: + # FIX 1: Timeout/Exception → Fallback auf Ursprungsraum, NICHT Catch-All + logger.warning( + "LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...' → stay_in_room (Ursprungsraum)", + text, + ) + return RoutingDecision( + category="direct_question", + target_room="", + confidence=0.0, + stay_in_room=True, + is_catch_all=False, + ) + else: + # LLM erfolgreich, aber kein Match → catch_all + logger.info( + "LLM-Raum-Router: kein Treffer für '%.80s...' → catch_all", text + ) + catch_all = self._room_map.catch_all_room + return RoutingDecision( + category="direct_question", + target_room=catch_all.room_id if catch_all else "", + confidence=0.0, + is_catch_all=True, + stay_in_room=True, + ) + + except Exception as e: + # ── Catch-All-Schutz: unerwarteter Fehler → Fallback ────── + logger.error( + "route(): Unerwarteter Fehler für '%.80s...' — Fallback auf Catch-All: %s", + text, e, exc_info=True, ) catch_all = self._room_map.catch_all_room return RoutingDecision( @@ -517,13 +552,17 @@ class BidirectionalRouter: return catch_all.room_id - def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]: + async def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]: """Fragt das LLM: „In welchen Raum gehört diese Nachricht?“ Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap und nutzt den LLM_ROOM_PROMPT für kontextbasiertes Routing. Das LLM liefert die Raum-ID direkt zurück (kein Name-Matching nötig). + Der LLM-Aufruf wird durch einen asyncio.Semaphore(1) geschützt, weil + qwen2.5:7b nur einen parallelen Request verarbeiten kann. Ohne diesen + Schutz führen parallele Aufrufe zu Timeout-Kaskaden. + Args: text: Der Nachrichtentext. @@ -557,7 +596,11 @@ class BidirectionalRouter: prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text) # Try LLM — expects room ID directly - llm_result = self._classifier._llm_raw_sync(prompt) + # Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request) + async with self._llm_semaphore: + llm_result = await asyncio.to_thread( + self._classifier._llm_raw_sync, prompt + ) if llm_result is None: return None, True # LLM-Aufruf fehlgeschlagen