main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. # -*- coding: utf-8 -*-
  2. """
  3. LLM-basiertes NLP Plugin für Trixy.
  4. Verantwortlich für:
  5. 1. Intent-Erkennung: speech_recognized → intent_received
  6. 2. Antwort-Generierung: create_output_text → output_text_created
  7. Event-Flow:
  8. speech_recognized
  9. ↓
  10. [NLP Plugin] Intent-Erkennung
  11. ↓
  12. intent_received
  13. ↓
  14. [Intent Dispatcher] Handler aufrufen
  15. ↓
  16. intent_handled
  17. ↓
  18. [NLP Plugin] Antwort generieren (falls nötig)
  19. ↓
  20. output_text_created
  21. ↓
  22. [TTS Plugin] Sprachausgabe
  23. """
  24. import asyncio
  25. import json
  26. import time
  27. import uuid
  28. from typing import Any
  29. from trixy_core.plugins.trixy_plugin import TrixyPlugin
  30. from trixy_core.plugins.extensions.points.conversation import NLPExtension
  31. from trixy_core.events.decorators import TrixyEvent
  32. from trixy_core.events.event_data.basic import (
  33. SpeechRecognized,
  34. IntentReceived,
  35. IntentHandled,
  36. CreateOutputText,
  37. OutputTextCreated,
  38. PluginLoaded,
  39. PluginUnloaded,
  40. )
  41. from trixy_core.nlp import (
  42. NLPConfig,
  43. NLPContext,
  44. IntentRegistry,
  45. get_system_intents_for_context,
  46. is_admin_intent,
  47. )
  48. from trixy_core.utils.debug import pinfo, pdebug, perror, pwarn
  49. # Cache-Refresh-Intervall in Sekunden
  50. INTENT_CACHE_REFRESH_INTERVAL = 600 # 10 Minuten
  51. class LLMNLPExtension(NLPExtension):
  52. """NLP Extension für LLM-basierte Verarbeitung."""
  53. def __init__(self, plugin: "LLMNLPPlugin") -> None:
  54. super().__init__(
  55. extension_id="nlp_llm",
  56. name="LLM NLP",
  57. plugin_name=plugin.name,
  58. engine="llm",
  59. capabilities=["intent", "response", "entity"],
  60. offline=True,
  61. description="Lokales LLM für Intent-Erkennung und Antwortgenerierung",
  62. )
  63. self._plugin = plugin
  64. async def create_instance(self, config: dict[str, Any]):
  65. return self._plugin.provider
  66. class IntentCache:
  67. """Cache für verfügbare Intents."""
  68. def __init__(self) -> None:
  69. self._plugin_intents: list[dict[str, Any]] = []
  70. self._last_refresh: float = 0
  71. self._cached_prompt_intents: dict[str, str] = {}
  72. def refresh_plugin_intents(self) -> None:
  73. """Lädt Plugin-Intents aus der Registry neu."""
  74. registry = IntentRegistry.get_instance()
  75. self._plugin_intents = registry.get_all_as_dict()
  76. self._cached_prompt_intents.clear()
  77. self._last_refresh = time.time()
  78. pdebug(f"Intent-Cache aktualisiert: {len(self._plugin_intents)} Plugin-Intents")
  79. def needs_refresh(self) -> bool:
  80. return (time.time() - self._last_refresh) > INTENT_CACHE_REFRESH_INTERVAL
  81. def get_intents_for_context(
  82. self,
  83. wakeword_type: str = "custom",
  84. is_authenticated: bool = False,
  85. ) -> list[dict[str, Any]]:
  86. """Gibt alle verfügbaren Intents für den Kontext zurück."""
  87. system_intents = get_system_intents_for_context(
  88. wakeword_type=wakeword_type,
  89. is_authenticated=is_authenticated,
  90. )
  91. return system_intents + self._plugin_intents
  92. @property
  93. def plugin_intent_count(self) -> int:
  94. return len(self._plugin_intents)
  95. class LLMNLPPlugin(TrixyPlugin):
  96. """
  97. LLM-basiertes NLP Plugin.
  98. Aufgaben:
  99. 1. Intent-Erkennung aus speech_recognized
  100. 2. Antwort-Generierung für create_output_text
  101. """
  102. NAME = "nlp_llm"
  103. VERSION = "2.0.0"
  104. DESCRIPTION = "LLM-basierte NLP (Event-Driven)"
  105. AUTHOR = "Trixy"
  106. def __init__(self, application, plugin_path, config) -> None:
  107. super().__init__(application, plugin_path, config)
  108. self._provider = None
  109. self._extension = None
  110. self._intent_cache = IntentCache()
  111. self._refresh_task: asyncio.Task | None = None
  112. self._admin_sessions: dict[str, dict[str, Any]] = {}
  113. @property
  114. def provider(self):
  115. return self._provider
  116. async def on_load(self) -> None:
  117. """Initialisiert das Plugin."""
  118. pinfo(f"Lade {self.NAME} Plugin...")
  119. backend = self.get_config_value("backend", "llama_cpp")
  120. if backend == "ollama":
  121. from plugins.nlp_llm.backends.ollama import OllamaNLPBackend
  122. self._provider = OllamaNLPBackend()
  123. else:
  124. from plugins.nlp_llm.backends.llama_cpp import LlamaCppNLPBackend
  125. self._provider = LlamaCppNLPBackend()
  126. nlp_config = NLPConfig(
  127. backend=backend,
  128. model_name=self.get_config_value("model_name", "qwen2.5-1.5b-instruct"),
  129. model_path=self.get_config_value("model_path"),
  130. use_gpu=self.get_config_value("use_gpu", False),
  131. num_threads=self.get_config_value("num_threads", 4),
  132. temperature=self.get_config_value("temperature", 0.1),
  133. max_tokens=self.get_config_value("max_tokens", 256),
  134. context_window=self.get_config_value("context_window", 2048),
  135. extra={
  136. "ollama_host": self.get_config_value("ollama_host", "http://localhost:11434"),
  137. "response_language": self.get_config_value("response_language", "de"),
  138. }
  139. )
  140. success = await self._provider.initialize(nlp_config)
  141. if success:
  142. pinfo(f"[NLP] Provider initialisiert: {backend}, model={nlp_config.model_name}, ready={self._provider.is_ready}")
  143. else:
  144. perror(f"[NLP] Provider-Initialisierung fehlgeschlagen: {backend}")
  145. self._intent_cache.refresh_plugin_intents()
  146. self._refresh_task = asyncio.create_task(self._periodic_cache_refresh())
  147. self._extension = LLMNLPExtension(self)
  148. # Extension nicht registrieren - das Plugin arbeitet direkt event-driven
  149. pinfo(f"{self.NAME} Plugin geladen (Event-Driven Mode)")
  150. async def on_unload(self) -> None:
  151. """Fährt das Plugin herunter."""
  152. if self._refresh_task:
  153. self._refresh_task.cancel()
  154. try:
  155. await self._refresh_task
  156. except asyncio.CancelledError:
  157. pass
  158. if self._provider:
  159. await self._provider.shutdown()
  160. self._provider = None
  161. self._extension = None
  162. async def _periodic_cache_refresh(self) -> None:
  163. """Periodischer Cache-Refresh."""
  164. while True:
  165. await asyncio.sleep(INTENT_CACHE_REFRESH_INTERVAL)
  166. self._intent_cache.refresh_plugin_intents()
  167. # =========================================================================
  168. # Event Handler: Plugin Changes
  169. # =========================================================================
  170. @TrixyEvent(["plugin_loaded", "plugin_unloaded"])
  171. async def on_plugin_change(self, event_name: str, event_data) -> None:
  172. """Aktualisiert Cache bei Plugin-Änderungen."""
  173. plugin_name = getattr(event_data, "plugin_name", "")
  174. if plugin_name != self.NAME:
  175. self._intent_cache.refresh_plugin_intents()
  176. # =========================================================================
  177. # Event Handler: Intent-Erkennung (speech_recognized → intent_received)
  178. # =========================================================================
  179. @TrixyEvent(["speech_recognized"])
  180. async def on_speech_recognized(self, event_name: str, event_data: SpeechRecognized) -> None:
  181. """
  182. Erkennt Intent aus Spracheingabe.
  183. Emittiert: intent_received
  184. """
  185. pinfo(f"[NLP] speech_recognized empfangen: '{getattr(event_data, 'text', '?')}'")
  186. if not self._provider:
  187. pwarn("[NLP] Kein Provider konfiguriert")
  188. return
  189. if not self._provider.is_ready:
  190. pwarn(f"[NLP] Provider nicht bereit (state={getattr(self._provider, '_state', '?')})")
  191. return
  192. text = event_data.text
  193. if not text or not text.strip():
  194. pdebug("[NLP] Leerer Text, überspringe")
  195. return
  196. # STT-Korrektur: Häufige Fehlerkennungen korrigieren
  197. text = self._correct_stt_text(text)
  198. pinfo(f"[NLP] Starte Intent-Erkennung für: '{text}'")
  199. # Session-Info holen
  200. session_info = self._get_session_info(event_data.satellite_id)
  201. wakeword_type = session_info.get("wakeword_type", "custom")
  202. is_authenticated = self._is_authenticated(event_data.satellite_id)
  203. # Cache aktualisieren falls nötig
  204. if self._intent_cache.needs_refresh():
  205. self._intent_cache.refresh_plugin_intents()
  206. available_intents = self._intent_cache.get_intents_for_context(
  207. wakeword_type=wakeword_type,
  208. is_authenticated=is_authenticated,
  209. )
  210. pinfo(f"[NLP] {len(available_intents)} Intents verfügbar, sende an LLM...")
  211. # Intent erkennen
  212. import time as _time
  213. t_start = _time.monotonic()
  214. result = await self._recognize_intent(
  215. text=text,
  216. satellite_id=event_data.satellite_id,
  217. session_info=session_info,
  218. wakeword_type=wakeword_type,
  219. is_authenticated=is_authenticated,
  220. language=event_data.language or "de",
  221. )
  222. t_elapsed = _time.monotonic() - t_start
  223. if not result.success:
  224. perror(f"[NLP] Intent-Erkennung fehlgeschlagen nach {t_elapsed:.1f}s: {result.error}")
  225. return
  226. pinfo(f"[NLP] Intent erkannt in {t_elapsed:.1f}s: intent='{result.intent}', confidence={result.confidence:.2f}, slots={result.slots}")
  227. # Sicherheitsprüfung
  228. if not self._check_authorization(result.intent, wakeword_type, is_authenticated):
  229. pwarn(f"[NLP] Autorisierung verweigert für Intent: {result.intent}")
  230. await self._emit_authorization_error(event_data.satellite_id, session_info)
  231. return
  232. # Konfidenz prüfen
  233. min_confidence = self.get_config_value("min_confidence", 0.3)
  234. intent = result.intent if result.confidence >= min_confidence else "unknown"
  235. if intent == "unknown" and result.intent != "unknown":
  236. pdebug(f"[NLP] Konfidenz zu niedrig ({result.confidence:.2f} < {min_confidence}), Intent -> 'unknown'")
  237. # intent_received emittieren
  238. intent_event = IntentReceived(
  239. satellite_id=event_data.satellite_id,
  240. intent=intent,
  241. confidence=result.confidence,
  242. slots=result.slots,
  243. original_text=text,
  244. session_id=session_info.get("session_id", ""),
  245. room_id=session_info.get("room_id", ""),
  246. wakeword_type=wakeword_type,
  247. is_authenticated=is_authenticated,
  248. language=event_data.language or "de",
  249. )
  250. pinfo(f"[NLP] Emittiere intent_received: '{intent}' (confidence={result.confidence:.2f})")
  251. await self._application.events.trigger("intent_received", intent_event)
  252. async def _recognize_intent(
  253. self,
  254. text: str,
  255. satellite_id: str,
  256. session_info: dict[str, Any],
  257. wakeword_type: str,
  258. is_authenticated: bool,
  259. language: str,
  260. ):
  261. """Führt Intent-Erkennung durch."""
  262. available_intents = self._intent_cache.get_intents_for_context(
  263. wakeword_type=wakeword_type,
  264. is_authenticated=is_authenticated,
  265. )
  266. context = NLPContext(
  267. text=text,
  268. satellite_id=satellite_id,
  269. room_id=session_info.get("room_id", ""),
  270. session_id=session_info.get("session_id", ""),
  271. available_intents=available_intents,
  272. language=language,
  273. )
  274. return await self._provider.process(context)
  275. # =========================================================================
  276. # Event Handler: Antwort-Generierung (create_output_text → output_text_created)
  277. # =========================================================================
  278. @TrixyEvent(["create_output_text"])
  279. async def on_create_output_text(self, event_name: str, event_data: CreateOutputText) -> None:
  280. """
  281. Generiert Antworttext aus Handler-Ergebnis.
  282. Emittiert: output_text_created
  283. """
  284. pinfo(f"[NLP] create_output_text empfangen: intent='{event_data.intent}', text='{event_data.original_text[:50]}'")
  285. if not self._provider or not self._provider.is_ready:
  286. pwarn("[NLP] Provider nicht bereit für Antwort-Generierung")
  287. return
  288. pinfo(f"[NLP] Generiere Antwort für Intent: '{event_data.intent}'...")
  289. # Antwort generieren
  290. response_text = await self._provider.generate_response(
  291. intent=event_data.intent,
  292. slots=event_data.slots,
  293. handler_result=event_data.handler_data,
  294. original_text=event_data.original_text,
  295. room_id=event_data.room_id,
  296. )
  297. if not response_text:
  298. # Fallback für unbekannte Intents
  299. response_text = await self._provider.generate_fallback_response(
  300. event_data.original_text
  301. )
  302. # output_text_created emittieren
  303. output_event = OutputTextCreated(
  304. satellite_id=event_data.satellite_id,
  305. session_id=event_data.session_id,
  306. room_id=event_data.room_id,
  307. text=response_text,
  308. intent=event_data.intent,
  309. is_followup=False,
  310. expects_response=False,
  311. )
  312. pdebug(f"Emittiere output_text_created: {response_text[:50]}...")
  313. await self._application.events.trigger("output_text_created", output_event)
  314. # =========================================================================
  315. # Hilfsmethoden
  316. # =========================================================================
  317. # STT-Korrekturen: Wort-Aliase für häufige Fehlerkennungen.
  318. # Nur angewendet wenn das Wort alleine steht (gesamter Text).
  319. _STT_WORD_ALIASES: dict[str, str] = {
  320. "shop": "stopp",
  321. "schop": "stopp",
  322. }
  323. def _correct_stt_text(self, text: str) -> str:
  324. """Korrigiert häufige STT-Fehlerkennungen."""
  325. stripped = text.strip().lower()
  326. # Einzelwort-Aliase (nur wenn das Wort alleine steht)
  327. if stripped in self._STT_WORD_ALIASES:
  328. corrected = self._STT_WORD_ALIASES[stripped]
  329. pdebug(f"[NLP] STT-Korrektur: '{text}' → '{corrected}'")
  330. return corrected
  331. return text
  332. def _get_session_info(self, satellite_id: str) -> dict[str, Any]:
  333. """Holt Session-Info."""
  334. info = {"session_id": "", "room_id": "", "wakeword_type": "custom"}
  335. if hasattr(self._application, "services"):
  336. try:
  337. conv_service = self._application.services.get_service("ConversationService")
  338. if conv_service:
  339. session = conv_service.get_active_session(satellite_id)
  340. if session:
  341. info["session_id"] = session.session_id
  342. info["room_id"] = getattr(session, "room_id", "")
  343. info["wakeword_type"] = getattr(session, "wakeword_type", "custom")
  344. except Exception:
  345. pass
  346. return info
  347. def _is_authenticated(self, satellite_id: str) -> bool:
  348. """Prüft Admin-Authentifizierung."""
  349. session = self._admin_sessions.get(satellite_id)
  350. if not session:
  351. return False
  352. if time.time() > session.get("expires", 0):
  353. del self._admin_sessions[satellite_id]
  354. return False
  355. return session.get("authenticated", False)
  356. def _check_authorization(
  357. self, intent: str, wakeword_type: str, is_authenticated: bool
  358. ) -> bool:
  359. """Prüft Intent-Autorisierung."""
  360. if not is_admin_intent(intent):
  361. return True
  362. if wakeword_type != "system_command":
  363. return False
  364. if intent == "system_login":
  365. return True
  366. return is_authenticated
  367. async def _emit_authorization_error(
  368. self, satellite_id: str, session_info: dict[str, Any]
  369. ) -> None:
  370. """Emittiert Autorisierungs-Fehler."""
  371. error_event = OutputTextCreated(
  372. satellite_id=satellite_id,
  373. session_id=session_info.get("session_id", ""),
  374. room_id=session_info.get("room_id", ""),
  375. text="Dieser Befehl erfordert Administrator-Rechte. "
  376. "Bitte verwende das System-Wakeword und melde dich an.",
  377. intent="authorization_error",
  378. )
  379. await self._application.events.trigger("output_text_created", error_event)