2 Commits

Author SHA1 Message Date
Bernd (Hermes) 0e13e4b30d fix(archivar): ContextVar→global dict, asyncio.to_thread, EMBEDDING_BASE_URL, FAISS_AUTO_ROUTE=0.55
- adapter.py: ContextVars durch globales _room_context dict + threading.Lock ersetzt
  (Agent-Task sieht jetzt Archivar-Zielraum — kein error-not-allowed mehr)
- adapter_integration.py: Stay-Feedback-Handler leert thematic_target
  (verhindert dass nächster Send auf alten Archivar-Vorschlag fällt)
- classifier.py: _llm_raw() nutzt asyncio.to_thread() statt direktem await
  (LLMClient.generate() ist synchron — vorher TypeError)
- config.py: ARCHIVAR_EMBEDDING_BASE_URL trennt Embeddings von Chat-URL
  (OLLAMA_BASE_URL-Kollision behoben). FAISS_AUTO_ROUTE 0.70→0.55
  (mehr Nachrichten durch Booster statt direktem FAISS-Routing)
2026-06-19 09:09:17 +02:00
Bernd (Hermes) d005eb769d feat(archivar): Booster-Gewichtung verstärkt — FAISS + Keywords
Booster-Strategie: IMMER aktiv (nicht nur bei Konflikten)
- router.py: Konfliktbedingung entfernt, Booster auf alle FAISS-Treffer
- booster.py: Boost +0.05→+0.10, zusätzlich +0.05 pro weiterem unique Keyword
- config.py: FAISS_AUTO_ROUTE 0.85→0.70

Kombiniert semantische Breite (FAISS) mit präziser Keyword-Diskriminierung.
Ziel: granulare Raum-Entscheidungen bei überlappenden Themen.
2026-06-18 07:55:14 +02:00
6 changed files with 135 additions and 76 deletions
+59 -47
View File
@@ -9,7 +9,6 @@ Zero external dependencies — stdlib only.
"""
import asyncio
import contextvars
import json
import logging
import os
@@ -37,18 +36,13 @@ if not logger.handlers:
logger.propagate = False # Don't double-log to root
# ── Virtual Room Translation ──────────────────────────────────────────
# ContextVar tracks the real Rocket.Chat room_id that triggered the current
# agent turn, so send() can route the response back to the correct room even
# though the Hermes session uses a synthetic user-based chat_id.
# This is the mechanism that makes "one agent for all rooms" work
# without touching Hermes Core.
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
"_rocketchat_origin_room", default=""
)
_THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
"_rocketchat_thematic_target_room", default=""
)
# Global dict keyed by virtual chat_id (e.g. "user:alice") that tracks
# the real Rocket.Chat room_id for the current agent turn.
# ContextVars were asyncio-task-local and invisible to the agent task,
# causing send() to fall back to the home channel → error-not-allowed.
# This dict is shared across all asyncio tasks in the same process.
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {origin_room, thematic_target}
_room_context_lock = threading.Lock()
# Globaler Monoton-Zähler für Archivar-Fragen
import threading
@@ -652,7 +646,10 @@ class RocketChatAdapter(BasePlatformAdapter):
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
_THEMATIC_TARGET_ROOM.set("")
virtual_chat_id = f"user:{username}"
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["thematic_target"] = ""
# ── CLARIFY Response Handling ───────────────────────────────────
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
@@ -768,7 +765,10 @@ class RocketChatAdapter(BasePlatformAdapter):
target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}"
if move_req.get("username"):
self.rest.post_message(move_req["target_room"], target_txt)
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
virtual_chat_id = f"user:{move_req['username']}"
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["origin_room"] = move_req["target_room"]
forwarded = True
feedback_type = "confirm"
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
@@ -787,7 +787,8 @@ class RocketChatAdapter(BasePlatformAdapter):
await self.archivar.handle_feedback_response(
message_id=move_req["message_id"],
user_id=user_id,
feedback_type=feedback_type
feedback_type=feedback_type,
username=username
)
return # Move-Request verarbeitet — keine weitere Verarbeitung
@@ -842,7 +843,10 @@ class RocketChatAdapter(BasePlatformAdapter):
category = decision.category
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
if hasattr(decision, 'target_room') and decision.target_room:
_THEMATIC_TARGET_ROOM.set(decision.target_room)
virtual_chat_id = f"user:{username}"
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["thematic_target"] = decision.target_room
global _question_counter
with _question_counter_lock:
_question_counter += 1
@@ -957,14 +961,20 @@ class RocketChatAdapter(BasePlatformAdapter):
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
self.rest.post_message(room_id, note)
# Agent soll im Zielraum antworten, nicht im Ursprungsraum
_CURRENT_ORIGIN_ROOM.set(decision.target_room)
virtual_chat_id = f"user:{username}"
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["origin_room"] = decision.target_room
forwarded = True
# Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy
# ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
if not forwarded:
_CURRENT_ORIGIN_ROOM.set(room_id)
virtual_chat_id = f"user:{username}"
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["origin_room"] = room_id
# ── Virtual Room Translation ─────────────────────────────────
# Replace room-based chat_id with user-based virtual chat_id.
@@ -987,7 +997,9 @@ class RocketChatAdapter(BasePlatformAdapter):
message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
target_room_id = _THEMATIC_TARGET_ROOM.get()
with _room_context_lock:
ctx = _room_context.get(virtual_chat_id, {})
target_room_id = ctx.get("thematic_target", "")
if target_room_id:
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
with _question_counter_lock:
@@ -1647,32 +1659,32 @@ class RocketChatAdapter(BasePlatformAdapter):
if chat_id.startswith("user:"):
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
thematic_target = _THEMATIC_TARGET_ROOM.get()
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
with _room_context_lock:
ctx = _room_context.get(chat_id, {})
thematic_target = ctx.get("thematic_target", "")
origin = ctx.get("origin_room", "")
if thematic_target and thematic_target != origin:
real_room_id = thematic_target
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
elif origin:
real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
else:
# Priority 1: ContextVar from the message that triggered this turn
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
# Priority 2: proaktive Nachricht — use most recent room for this user
rooms = self._user_rooms.get(chat_id, [])
if rooms:
real_room_id = rooms[-1] # last room user was active in
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
else:
# Priority 2: proaktive Nachricht — use most recent room for this user
rooms = self._user_rooms.get(chat_id, [])
if rooms:
real_room_id = rooms[-1] # last room user was active in
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
# Fallback: try to find any room with recent activity involving this user
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
fallback_room = self._find_fallback_room_for_user(chat_id)
if fallback_room:
real_room_id = fallback_room
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
else:
# Fallback: try to find any room with recent activity involving this user
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
fallback_room = self._find_fallback_room_for_user(chat_id)
if fallback_room:
real_room_id = fallback_room
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
else:
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
# This allows the agent to request buttons by embedding markup in its
@@ -1854,14 +1866,14 @@ class RocketChatAdapter(BasePlatformAdapter):
if chat_id.startswith("user:"):
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
thematic_target = _THEMATIC_TARGET_ROOM.get()
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
with _room_context_lock:
ctx = _room_context.get(chat_id, {})
thematic_target = ctx.get("thematic_target", "")
origin = ctx.get("origin_room", "")
if thematic_target and thematic_target != origin:
real_room_id = thematic_target
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
else:
# Priority 1: ContextVar from the message that triggered this turn
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
elif origin:
real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
else:
+29 -1
View File
@@ -93,6 +93,13 @@ except ImportError:
from .seed_data import SEED_DATA
from .feedback_detector import RoutingWiderspruchDetector, ContradictionResult
# ── _room_context import from adapter.py ─────────────────────────────
# Needed by handle_feedback_response to clear thematic_target on 'stay'.
try:
from adapter import _room_context, _room_context_lock
except ImportError:
from ..adapter import _room_context, _room_context_lock
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Ensure adapter_integration logs are visible by adding a stderr handler
@@ -863,7 +870,8 @@ class ArchivarMessageHandler:
self,
message_id: str,
user_id: str,
feedback_type: str
feedback_type: str,
username: str = "",
) -> bool:
"""
Behandle eine Benutzerantwort auf eine Routing-Entscheidung.
@@ -872,14 +880,34 @@ class ArchivarMessageHandler:
message_id: ID der gerouteten Nachricht
user_id: ID des Benutzers, der das Feedback gegeben hat
feedback_type: Art des Feedbacks ("confirm", "stay", "never")
username: Rocket.Chat username (für _room_context-Update bei "stay")
Returns:
True wenn das Feedback erfolgreich verarbeitet wurde, False bei Fehler
"""
try:
# ── 'stay': _room_context zurücksetzen ─────────────────────
# Wenn der User "Hier bleiben" klickt, muss der thematic_target
# geleert werden, damit der nächste Send nicht auf den falschen
# (Archivar-vorgeschlagenen) Zielraum fällt.
if feedback_type == "stay" and username:
virtual_chat_id = f"user:{username}"
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["thematic_target"] = ""
# origin_room bleibt unverändert
logger.info(
"Stay-Feedback: _room_context[%s].thematic_target geleert",
virtual_chat_id,
)
# Prüfe ob die Nachricht existiert
if message_id not in self._routed_messages:
logger.warning("Feedback for unknown message ID: %s", message_id)
# 'stay' ohne _routed_messages-Eintrag ist trotzdem gültig —
# _room_context wurde oben bereits bereinigt.
if feedback_type == "stay":
return True
return False
# Hole die geroutete Nachricht
+34 -11
View File
@@ -2,9 +2,10 @@
Keyword-Booster für Archivar v5.
Verfeinert FAISS-Suchergebnisse durch Keyword-Analyse:
- Eindeutige Keywords (nur in einem Raum) geben +0.05 Boost
- Eindeutige Keywords (nur in einem Raum) geben +0.10 Boost
- Mehrere eindeutige Keywords geben zusätzlichen Boost (+0.05 pro weiterem Keyword)
- Mehrdeutige Keywords sind neutral
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords (+0.05 Boost)
Usage::
@@ -17,7 +18,7 @@ Usage::
scores = [("room_a", 0.87), ("room_b", 0.85), ("room_c", 0.62)]
text = "Das Plugin hat einen Bug im Router"
boosted = booster.boost(text, scores)
# → [("room_a", 0.92), ("room_b", 0.85), ("room_c", 0.62)]
# → [("room_a", 0.97), ("room_b", 0.85), ("room_c", 0.62)]
"""
from __future__ import annotations
@@ -107,19 +108,41 @@ class KeywordBooster:
# Keine Keywords → Scores unverändert zurück
return sorted(scores, key=lambda x: x[1], reverse=True)
# ── Boost-Phase: +0.05 für eindeutige Keywords ────────────
# ── Boost-Phase: +0.10 für eindeutige Keywords ────────────
for kw in matched_keywords:
rooms = self._keyword_to_rooms[kw]
if len(rooms) == 1:
unique_room = next(iter(rooms))
if unique_room in score_dict:
score_dict[unique_room] += 0.05
score_dict[unique_room] += 0.10
logger.debug(
"Boost +0.05: keyword='%s' → room='%s' (unique)",
"Boost +0.10: keyword='%s' → room='%s' (unique)",
kw,
unique_room[:8],
)
# ── Zusätzlicher Boost für mehrere eindeutige Keywords ────
# Zähle eindeutige Keywords pro Raum und gib Bonus für hohe Anzahl
unique_counts_per_room: Dict[str, int] = {}
for kw in matched_keywords:
rooms = self._keyword_to_rooms[kw]
if len(rooms) == 1:
unique_room = next(iter(rooms))
if unique_room in score_dict:
unique_counts_per_room[unique_room] = unique_counts_per_room.get(unique_room, 0) + 1
# Bonus: +0.05 für jeden weiteren unique Match über dem ersten
for room_id, count in unique_counts_per_room.items():
if count > 1:
additional_boost = (count - 1) * 0.05
score_dict[room_id] += additional_boost
logger.debug(
"Additional boost +%s: room='%s' has %d unique keywords",
additional_boost,
room_id[:8],
count,
)
# ── Nach Boost sortieren ──────────────────────────────────
boosted = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
@@ -129,23 +152,23 @@ class KeywordBooster:
top2_room, top2_score = boosted[1]
diff = top1_score - top2_score
if diff < 0.03:
if diff < 0.05:
# Zähle eindeutige Keyword-Treffer für beide Räume
unique_count_1 = self._count_unique_matches(text_lower, top1_room)
unique_count_2 = self._count_unique_matches(text_lower, top2_room)
if unique_count_1 > unique_count_2:
score_dict[top1_room] += 0.02
score_dict[top1_room] += 0.05
logger.debug(
"Conflict resolution: +0.02 for '%s' (%d unique vs %d)",
"Conflict resolution: +0.05 for '%s' (%d unique vs %d)",
top1_room[:8],
unique_count_1,
unique_count_2,
)
elif unique_count_2 > unique_count_1:
score_dict[top2_room] += 0.02
score_dict[top2_room] += 0.05
logger.debug(
"Conflict resolution: +0.02 for '%s' (%d unique vs %d)",
"Conflict resolution: +0.05 for '%s' (%d unique vs %d)",
top2_room[:8],
unique_count_2,
unique_count_1,
+4 -2
View File
@@ -488,7 +488,8 @@ class IntentClassifier:
Intent-Kategorien. Uses ``LLMClient.generate()`` for free-form
output. Used by the router for LLM_ROOM_PROMPT.
Async because OllamaLLMClient.generate() is async.
Uses ``asyncio.to_thread()`` because ``LLMClient.generate()`` is
synchronous.
Args:
prompt: The complete prompt to send.
@@ -499,7 +500,8 @@ class IntentClassifier:
try:
if not self._llm_client or not self._llm_enabled:
return None
return await self._llm_client.generate(prompt)
import asyncio
return await asyncio.to_thread(self._llm_client.generate, prompt)
except Exception as e:
logger.warning("LLM raw call failed: %s", e)
return None
+3 -3
View File
@@ -14,7 +14,7 @@ from typing import Dict
# ── Ollama-Konfiguration ────────────────────────────────────────────────────
OLLAMA_CONFIG: dict = {
"base_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"),
"base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")),
"model": "nomic-embed-text",
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
@@ -228,9 +228,9 @@ Enthält Entscheidungen wie "immer im Raum bleiben" oder "nie routen".
# Bei mittlerem Score greift der Keyword-Booster zur Konfliktlösung.
# Bei niedrigem Score fällt der Flow an den Embedding-Vorfilter + LLM durch.
FAISS_AUTO_ROUTE: float = 0.85
FAISS_AUTO_ROUTE: float = 0.55
"""FAISS-Score-Schwelle für automatisches Routing ohne LLM.
Nachrichten mit FAISS-Score >= 0.85 (nach Keyword-Boost) werden direkt
Nachrichten mit FAISS-Score >= 0.55 (nach Keyword-Boost) werden direkt
geroutet — kein LLM-Aufruf nötig. Spart ~2.4s Latenz pro Nachricht."""
FAISS_MIN_SCORE: float = 0.50
+6 -12
View File
@@ -343,18 +343,12 @@ class BidirectionalRouter:
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,
)
# 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]