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)
This commit is contained in:
+44
-32
@@ -9,7 +9,6 @@ Zero external dependencies — stdlib only.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import contextvars
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
@@ -37,18 +36,13 @@ if not logger.handlers:
|
|||||||
logger.propagate = False # Don't double-log to root
|
logger.propagate = False # Don't double-log to root
|
||||||
|
|
||||||
# ── Virtual Room Translation ──────────────────────────────────────────
|
# ── Virtual Room Translation ──────────────────────────────────────────
|
||||||
# ContextVar tracks the real Rocket.Chat room_id that triggered the current
|
# Global dict keyed by virtual chat_id (e.g. "user:alice") that tracks
|
||||||
# agent turn, so send() can route the response back to the correct room even
|
# the real Rocket.Chat room_id for the current agent turn.
|
||||||
# though the Hermes session uses a synthetic user-based chat_id.
|
# ContextVars were asyncio-task-local and invisible to the agent task,
|
||||||
# This is the mechanism that makes "one agent for all rooms" work
|
# causing send() to fall back to the home channel → error-not-allowed.
|
||||||
# without touching Hermes Core.
|
# This dict is shared across all asyncio tasks in the same process.
|
||||||
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {origin_room, thematic_target}
|
||||||
"_rocketchat_origin_room", default=""
|
_room_context_lock = threading.Lock()
|
||||||
)
|
|
||||||
|
|
||||||
_THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
|
||||||
"_rocketchat_thematic_target_room", default=""
|
|
||||||
)
|
|
||||||
|
|
||||||
# Globaler Monoton-Zähler für Archivar-Fragen
|
# Globaler Monoton-Zähler für Archivar-Fragen
|
||||||
import threading
|
import threading
|
||||||
@@ -652,7 +646,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
|
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
|
||||||
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
|
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
|
||||||
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
|
# 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 ───────────────────────────────────
|
# ── CLARIFY Response Handling ───────────────────────────────────
|
||||||
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
# 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']}"
|
target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}"
|
||||||
if move_req.get("username"):
|
if move_req.get("username"):
|
||||||
self.rest.post_message(move_req["target_room"], target_txt)
|
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
|
forwarded = True
|
||||||
feedback_type = "confirm"
|
feedback_type = "confirm"
|
||||||
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
|
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
|
||||||
@@ -787,7 +787,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
await self.archivar.handle_feedback_response(
|
await self.archivar.handle_feedback_response(
|
||||||
message_id=move_req["message_id"],
|
message_id=move_req["message_id"],
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
feedback_type=feedback_type
|
feedback_type=feedback_type,
|
||||||
|
username=username
|
||||||
)
|
)
|
||||||
return # Move-Request verarbeitet — keine weitere Verarbeitung
|
return # Move-Request verarbeitet — keine weitere Verarbeitung
|
||||||
|
|
||||||
@@ -842,7 +843,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
category = decision.category
|
category = decision.category
|
||||||
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
||||||
if hasattr(decision, 'target_room') and decision.target_room:
|
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
|
global _question_counter
|
||||||
with _question_counter_lock:
|
with _question_counter_lock:
|
||||||
_question_counter += 1
|
_question_counter += 1
|
||||||
@@ -957,14 +961,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
|
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
|
||||||
self.rest.post_message(room_id, note)
|
self.rest.post_message(room_id, note)
|
||||||
# Agent soll im Zielraum antworten, nicht im Ursprungsraum
|
# 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
|
forwarded = True
|
||||||
|
|
||||||
# Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy
|
# Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy
|
||||||
|
|
||||||
# ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
|
# ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
|
||||||
if not forwarded:
|
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 ─────────────────────────────────
|
# ── Virtual Room Translation ─────────────────────────────────
|
||||||
# Replace room-based chat_id with user-based virtual chat_id.
|
# 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
|
message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT
|
||||||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
# ── 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:
|
if target_room_id:
|
||||||
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
||||||
with _question_counter_lock:
|
with _question_counter_lock:
|
||||||
@@ -1647,14 +1659,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
|
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
|
||||||
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
|
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
|
||||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
with _room_context_lock:
|
||||||
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
|
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
|
real_room_id = thematic_target
|
||||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||||
else:
|
elif origin:
|
||||||
# Priority 1: ContextVar from the message that triggered this turn
|
|
||||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
|
||||||
if origin:
|
|
||||||
real_room_id = origin
|
real_room_id = origin
|
||||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||||
else:
|
else:
|
||||||
@@ -1854,14 +1866,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
|
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
|
||||||
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
|
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
|
||||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
with _room_context_lock:
|
||||||
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
|
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
|
real_room_id = thematic_target
|
||||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||||
else:
|
elif origin:
|
||||||
# Priority 1: ContextVar from the message that triggered this turn
|
|
||||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
|
||||||
if origin:
|
|
||||||
real_room_id = origin
|
real_room_id = origin
|
||||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -93,6 +93,13 @@ except ImportError:
|
|||||||
from .seed_data import SEED_DATA
|
from .seed_data import SEED_DATA
|
||||||
from .feedback_detector import RoutingWiderspruchDetector, ContradictionResult
|
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 = logging.getLogger(__name__)
|
||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
# Ensure adapter_integration logs are visible by adding a stderr handler
|
# Ensure adapter_integration logs are visible by adding a stderr handler
|
||||||
@@ -863,7 +870,8 @@ class ArchivarMessageHandler:
|
|||||||
self,
|
self,
|
||||||
message_id: str,
|
message_id: str,
|
||||||
user_id: str,
|
user_id: str,
|
||||||
feedback_type: str
|
feedback_type: str,
|
||||||
|
username: str = "",
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
Behandle eine Benutzerantwort auf eine Routing-Entscheidung.
|
Behandle eine Benutzerantwort auf eine Routing-Entscheidung.
|
||||||
@@ -872,14 +880,34 @@ class ArchivarMessageHandler:
|
|||||||
message_id: ID der gerouteten Nachricht
|
message_id: ID der gerouteten Nachricht
|
||||||
user_id: ID des Benutzers, der das Feedback gegeben hat
|
user_id: ID des Benutzers, der das Feedback gegeben hat
|
||||||
feedback_type: Art des Feedbacks ("confirm", "stay", "never")
|
feedback_type: Art des Feedbacks ("confirm", "stay", "never")
|
||||||
|
username: Rocket.Chat username (für _room_context-Update bei "stay")
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True wenn das Feedback erfolgreich verarbeitet wurde, False bei Fehler
|
True wenn das Feedback erfolgreich verarbeitet wurde, False bei Fehler
|
||||||
"""
|
"""
|
||||||
try:
|
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
|
# Prüfe ob die Nachricht existiert
|
||||||
if message_id not in self._routed_messages:
|
if message_id not in self._routed_messages:
|
||||||
logger.warning("Feedback for unknown message ID: %s", message_id)
|
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
|
return False
|
||||||
|
|
||||||
# Hole die geroutete Nachricht
|
# Hole die geroutete Nachricht
|
||||||
|
|||||||
@@ -488,7 +488,8 @@ class IntentClassifier:
|
|||||||
Intent-Kategorien. Uses ``LLMClient.generate()`` for free-form
|
Intent-Kategorien. Uses ``LLMClient.generate()`` for free-form
|
||||||
output. Used by the router for LLM_ROOM_PROMPT.
|
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:
|
Args:
|
||||||
prompt: The complete prompt to send.
|
prompt: The complete prompt to send.
|
||||||
@@ -499,7 +500,8 @@ class IntentClassifier:
|
|||||||
try:
|
try:
|
||||||
if not self._llm_client or not self._llm_enabled:
|
if not self._llm_client or not self._llm_enabled:
|
||||||
return None
|
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:
|
except Exception as e:
|
||||||
logger.warning("LLM raw call failed: %s", e)
|
logger.warning("LLM raw call failed: %s", e)
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ from typing import Dict
|
|||||||
# ── Ollama-Konfiguration ────────────────────────────────────────────────────
|
# ── Ollama-Konfiguration ────────────────────────────────────────────────────
|
||||||
|
|
||||||
OLLAMA_CONFIG: dict = {
|
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",
|
"model": "nomic-embed-text",
|
||||||
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s
|
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s
|
||||||
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
"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 mittlerem Score greift der Keyword-Booster zur Konfliktlösung.
|
||||||
# Bei niedrigem Score fällt der Flow an den Embedding-Vorfilter + LLM durch.
|
# Bei niedrigem Score fällt der Flow an den Embedding-Vorfilter + LLM durch.
|
||||||
|
|
||||||
FAISS_AUTO_ROUTE: float = 0.70
|
FAISS_AUTO_ROUTE: float = 0.55
|
||||||
"""FAISS-Score-Schwelle für automatisches Routing ohne LLM.
|
"""FAISS-Score-Schwelle für automatisches Routing ohne LLM.
|
||||||
Nachrichten mit FAISS-Score >= 0.70 (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."""
|
geroutet — kein LLM-Aufruf nötig. Spart ~2.4s Latenz pro Nachricht."""
|
||||||
|
|
||||||
FAISS_MIN_SCORE: float = 0.50
|
FAISS_MIN_SCORE: float = 0.50
|
||||||
|
|||||||
Reference in New Issue
Block a user