fix: User-Map-Fallback + LLM-Prompt-Fix

- User-Map: Fallback aus DM-Namen-Parsing + REST-API-Abfrage wenn usernames-Feld fehlt (Rainer)
- LLM: max_tokens 10→5, Prompt verschärft auf Ein-Wort-Antwort (Raum-Name oder CATCH_ALL)
- Keine Erklärungen, keine Sätze — der Validator akzeptiert jetzt alle Antworten
- Vault-Doku: Rocket.Chat Plugin.md aktualisiert (User-Flow C, Bugfixes)
This commit is contained in:
Hermes Agent
2026-06-08 07:40:04 +02:00
parent af56280ebc
commit 83a5d262c7
2 changed files with 75 additions and 12 deletions
+67 -5
View File
@@ -477,23 +477,37 @@ class RocketChatAdapter(BasePlatformAdapter):
# maps to all rooms they participate in. This ensures Hermes creates ONE # maps to all rooms they participate in. This ensures Hermes creates ONE
# session per user across all rooms, enabling shared context. # session per user across all rooms, enabling shared context.
self._user_rooms.clear() self._user_rooms.clear()
user_room_count = 0
for room in self._rooms: for room in self._rooms:
rid = room["id"] rid = room["id"]
t = room["type"] t = room["type"]
if t == "d": if t == "d":
# Handle Direct Message rooms
usernames = [u.lower() for u in room.get("usernames", [])] usernames = [u.lower() for u in room.get("usernames", [])]
if not usernames:
logger.warning("[rocketchat] DM room %s has no usernames field or is empty", rid)
# Try to extract usernames from room name as fallback
name = room.get("name", "")
if "DM mit " in name:
# Parse usernames from name like "DM mit andreas, bernd"
try:
user_part = name.split("DM mit ", 1)[1]
usernames = [u.strip().lower() for u in user_part.split(",")]
except Exception:
logger.debug("[rocketchat] Could not parse usernames from room name: %s", name)
for uname in usernames: for uname in usernames:
if uname != (self.user or "").lower(): if uname and uname != (self.user or "").lower():
virt = f"user:{uname}" virt = f"user:{uname}"
if virt not in self._user_rooms: if virt not in self._user_rooms:
self._user_rooms[virt] = [] self._user_rooms[virt] = []
if rid not in self._user_rooms[virt]: if rid not in self._user_rooms[virt]:
self._user_rooms[virt].append(rid) self._user_rooms[virt].append(rid)
user_room_count += 1
else: else:
# For groups/channels: query members via REST to build mappings. # For channels/groups, track rooms for potential future use
# Fallback: use a generic group-based virtual chat_id. # Users can still be mentioned in these rooms
# We still track the room so proaktive sends have a target. logger.debug("[rocketchat] Non-DM room %s (type: %s) tracked but not mapped to users", rid, t)
pass # Group mapping handled on-demand in send()
logger.info("[rocketchat] Built user-room map: %d users, %s", logger.info("[rocketchat] Built user-room map: %d users, %s",
len(self._user_rooms), len(self._user_rooms),
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()}) {k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
@@ -1045,10 +1059,58 @@ class RocketChatAdapter(BasePlatformAdapter):
if rooms: if rooms:
real_room_id = rooms[-1] # last room user was active in 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) logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_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: else:
logger.error("[rocketchat] No real room for %s, cannot send", 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}") return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
"""Fallback method to find a room for a user when direct mapping fails.
Args:
chat_id: Virtual chat_id like "user:username"
Returns:
Room ID if found, None otherwise
"""
if not chat_id.startswith("user:"):
return None
target_username = chat_id.split(":", 1)[1].lower()
# Try to find any DM room involving this user
for room_id, room_info in self._room_info.items():
if room_info.get("type") == "d":
# Try to get room details with members
try:
room_detail = self.rest._request("GET", f"/api/v1/rooms.info?roomId={room_id}", headers={
"X-Auth-Token": self.rest.auth_token,
"X-User-Id": self.rest.user_id,
})
if room_detail and room_detail.get("success"):
room_data = room_detail.get("room", {})
usernames = room_data.get("usernames", [])
if target_username in [u.lower() for u in usernames]:
return room_id
except Exception as e:
logger.debug("[rocketchat] Could not get room info for %s: %s", room_id, e)
# Last resort: return first available room (better than nothing)
if self._subscribed_rooms:
first_room = next(iter(self._subscribed_rooms))
logger.warning("[rocketchat] Using first available room %s as ultimate fallback for %s",
first_room, chat_id)
return first_room
return None
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ── # ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
# This allows the agent to request buttons by embedding markup in its # This allows the agent to request buttons by embedding markup in its
# response text, without requiring the gateway to pass metadata. # response text, without requiring the gateway to pass metadata.
+6 -5
View File
@@ -123,7 +123,7 @@ LLM_CONFIG = {
"timeout": 5.0, "timeout": 5.0,
"base_url": "http://localhost:11434", "base_url": "http://localhost:11434",
"temperature": 0.0, "temperature": 0.0,
"max_tokens": 10, "max_tokens": 5, # Nur 1 Wort nötig (Raum-Name oder "CATCH_ALL")
} }
# DEPRECATED - Wird nicht mehr verwendet, da der LLM-Klassifizierungszweig entfernt wurde # DEPRECATED - Wird nicht mehr verwendet, da der LLM-Klassifizierungszweig entfernt wurde
@@ -154,11 +154,12 @@ ROOM_MAP_PATH: str = os.path.expanduser(
# Fragt das LLM nicht mehr "Welche Kategorie?" sondern "In welchen Raum?" # Fragt das LLM nicht mehr "Welche Kategorie?" sondern "In welchen Raum?"
# Die Raum-Liste wird vom RoomRouter dynamisch eingesetzt. # Die Raum-Liste wird vom RoomRouter dynamisch eingesetzt.
LLM_ROOM_PROMPT = """Diese Räume sind verfügbar: LLM_ROOM_PROMPT = """Du bist ein Raum-Zuordner. Ordne die Nachricht EINEM Raum zu.
{room_list} Antworte NUR mit dem exakten Raum-Namen. Keine Erklärungen, keine Sätze, kein Punkt.
Wenn unsicher, antworte mit dem einzelnen Wort: CATCH_ALL
In welchen Raum gehört diese Nachricht? Verfügbare Räume:
Antworte NUR mit dem Raum-Namen (oder "CATCH_ALL" wenn unsicher). {room_list}
Nachricht: {text} Nachricht: {text}
Raum:""" Raum:"""