feat(archivar): dreistufiger Klassifikator — Keyword + Embedding + LLM (qwen2.5:7b)
Phase 3 (Miguel): 236 Zeilen in config.py, classifier.py, adapter_integration.py. Phase 4 (Rainer): Quality Gate F1–F5 bestanden. - Stufe 0: Keyword-Vorfilter mit erweiterten ALARM/FRAGE-Listen - Stufe 1: Embedding (nomic-embed-text, Schwelle 0.70) - Stufe 2: LLM-Klassifikation (qwen2.5:7b) für Grenzfälle - Feature-Flag ARCHIVAR_ENABLE_LLM über Env-Variable - LLMClient-Interface für Testbarkeit - router.py unverändert (Blackbox-Integration)
This commit is contained in:
@@ -45,8 +45,10 @@ from .classifier import (
|
|||||||
ClassificationResult,
|
ClassificationResult,
|
||||||
EmbeddingClient,
|
EmbeddingClient,
|
||||||
MessageClassifier,
|
MessageClassifier,
|
||||||
|
LLMClient,
|
||||||
|
OllamaLLMClient,
|
||||||
)
|
)
|
||||||
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG
|
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG, LLM_CONFIG
|
||||||
from .doc_store import DocumentationStore
|
from .doc_store import DocumentationStore
|
||||||
from .router import MessageRouter, RoutingDecision
|
from .router import MessageRouter, RoutingDecision
|
||||||
|
|
||||||
@@ -78,6 +80,7 @@ class ArchivarMessageHandler:
|
|||||||
confidence_threshold: float = CONFIDENCE_THRESHOLD,
|
confidence_threshold: float = CONFIDENCE_THRESHOLD,
|
||||||
ollama_base_url: Optional[str] = None,
|
ollama_base_url: Optional[str] = None,
|
||||||
embedding_client: Optional[EmbeddingClient] = None,
|
embedding_client: Optional[EmbeddingClient] = None,
|
||||||
|
llm_client: Optional[LLMClient] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
@@ -90,10 +93,21 @@ class ArchivarMessageHandler:
|
|||||||
embedding_client: Optionales ``EmbeddingClient``-Interface.
|
embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||||||
Wird an den ``MessageClassifier`` durchgereicht.
|
Wird an den ``MessageClassifier`` durchgereicht.
|
||||||
Ermöglicht Mocking/alternative Embedding-Backends.
|
Ermöglicht Mocking/alternative Embedding-Backends.
|
||||||
|
llm_client: Optionales ``LLMClient``-Interface.
|
||||||
|
Wird an den ``MessageClassifier`` durchgereicht.
|
||||||
|
Ermöglicht Mocking/alternative LLM-Backends.
|
||||||
"""
|
"""
|
||||||
self._send_callback = send_callback
|
self._send_callback = send_callback
|
||||||
|
self._enable_llm = LLM_CONFIG["enabled"]
|
||||||
|
|
||||||
|
# Create LLM client if enabled and not provided
|
||||||
|
if self._enable_llm and llm_client is None:
|
||||||
|
llm_client = OllamaLLMClient() if LLM_CONFIG["enabled"] else None
|
||||||
|
|
||||||
self._classifier = MessageClassifier(
|
self._classifier = MessageClassifier(
|
||||||
base_url=ollama_base_url, embedding_client=embedding_client
|
base_url=ollama_base_url,
|
||||||
|
embedding_client=embedding_client,
|
||||||
|
llm_client=llm_client
|
||||||
)
|
)
|
||||||
self._router = MessageRouter(self._classifier)
|
self._router = MessageRouter(self._classifier)
|
||||||
self._router.set_confidence_threshold(confidence_threshold)
|
self._router.set_confidence_threshold(confidence_threshold)
|
||||||
@@ -108,6 +122,7 @@ class ArchivarMessageHandler:
|
|||||||
"fallback": 0,
|
"fallback": 0,
|
||||||
"meta": 0,
|
"meta": 0,
|
||||||
"errors": 0,
|
"errors": 0,
|
||||||
|
"llm_classified": 0, # Neue Statistik für LLM-Klassifikationen
|
||||||
"avg_latency_ms": 0.0, # float — gleitender Durchschnitt
|
"avg_latency_ms": 0.0, # float — gleitender Durchschnitt
|
||||||
"last_error": None, # str | None — letzter Fehler
|
"last_error": None, # str | None — letzter Fehler
|
||||||
"latencies": [], # list[float] — per-request ms
|
"latencies": [], # list[float] — per-request ms
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import urllib.request
|
|||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Dict, List, Optional
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD
|
from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD, LLM_CONFIG, LLM_CLASSIFY_PROMPT, LLM_CONFIDENCE_THRESHOLD
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -152,6 +152,104 @@ class OllamaEmbeddingClient(EmbeddingClient):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── LLM Client Interface (injectable) ───────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class LLMClient(abc.ABC):
|
||||||
|
"""Interface for LLM providers. Injectable for testability.
|
||||||
|
|
||||||
|
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||||
|
single ``classify()`` method so that ``MessageClassifier`` can
|
||||||
|
work with real Ollama, mocks, or alternative backends without change.
|
||||||
|
|
||||||
|
Implementations must be thread-safe since ``MessageClassifier`` calls
|
||||||
|
``classify()`` synchronously inside ``asyncio.to_thread``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Klassifiziere Text. Gibt Kategorie-String oder None zurück."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class OllamaLLMClient(LLMClient):
|
||||||
|
"""LLM client backed by Ollama's `/api/generate` endpoint.
|
||||||
|
|
||||||
|
Wraps ``urllib.request.urlopen`` so the transport is hidden behind
|
||||||
|
the ``LLMClient`` interface. Works with every Ollama model that
|
||||||
|
exposes the generate API (``qwen2.5:7b`` recommended).
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
client = OllamaLLMClient()
|
||||||
|
category = client.classify("Wie funktioniert das Plugin?")
|
||||||
|
# → "FRAGE"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: Optional[str] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
timeout: Optional[float] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
base_url: Ollama base URL (default from ``config.LLM_CONFIG``).
|
||||||
|
model: LLM model (default from ``config.LLM_CONFIG``).
|
||||||
|
timeout: Request timeout in seconds (default from ``config.LLM_CONFIG``).
|
||||||
|
"""
|
||||||
|
self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/")
|
||||||
|
self._model = model or LLM_CONFIG["model"]
|
||||||
|
self._timeout = timeout or LLM_CONFIG["timeout"]
|
||||||
|
|
||||||
|
def classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||||
|
url = f"{self._base_url}/api/generate"
|
||||||
|
payload = json.dumps(
|
||||||
|
{
|
||||||
|
"model": self._model,
|
||||||
|
"prompt": text,
|
||||||
|
"stream": False,
|
||||||
|
"options": {
|
||||||
|
"temperature": LLM_CONFIG["temperature"],
|
||||||
|
"num_predict": LLM_CONFIG["max_tokens"],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
).encode("utf-8")
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=payload, headers=headers, method="POST"
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
response_text = data.get("response", "")
|
||||||
|
if not response_text:
|
||||||
|
logger.error("Ollama returned empty response")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Trim whitespace and normalize category
|
||||||
|
category = response_text.strip().upper()
|
||||||
|
if category in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
return category
|
||||||
|
else:
|
||||||
|
logger.warning("LLM returned invalid category: %s", category)
|
||||||
|
return None
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.warning("Ollama HTTP %d: %s", e.code, e.reason)
|
||||||
|
return None
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
logger.warning("Ollama connection failed: %s", e)
|
||||||
|
return None
|
||||||
|
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||||
|
logger.error("Ollama response parse error: %s", e)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Unexpected error in classify: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
class MessageClassifier:
|
class MessageClassifier:
|
||||||
"""Embedding-basierter Nachrichten-Klassifizierer.
|
"""Embedding-basierter Nachrichten-Klassifizierer.
|
||||||
|
|
||||||
@@ -173,6 +271,7 @@ class MessageClassifier:
|
|||||||
model: Optional[str] = None,
|
model: Optional[str] = None,
|
||||||
timeout: Optional[float] = None,
|
timeout: Optional[float] = None,
|
||||||
embedding_client: Optional[EmbeddingClient] = None,
|
embedding_client: Optional[EmbeddingClient] = None,
|
||||||
|
llm_client: Optional[LLMClient] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
@@ -188,6 +287,10 @@ class MessageClassifier:
|
|||||||
Backends). Wenn ``None``, wird ein
|
Backends). Wenn ``None``, wird ein
|
||||||
``OllamaEmbeddingClient`` mit *base_url*, *model*
|
``OllamaEmbeddingClient`` mit *base_url*, *model*
|
||||||
und *timeout* erstellt.
|
und *timeout* erstellt.
|
||||||
|
llm_client: Optionales ``LLMClient``-Interface.
|
||||||
|
Wenn gesetzt, werden LLM-Calls an diesen Client
|
||||||
|
delegiert. Wenn ``None`` und LLM aktiviert ist,
|
||||||
|
wird ein ``OllamaLLMClient`` erstellt.
|
||||||
"""
|
"""
|
||||||
if embedding_client is not None:
|
if embedding_client is not None:
|
||||||
self._embedding_client: EmbeddingClient = embedding_client
|
self._embedding_client: EmbeddingClient = embedding_client
|
||||||
@@ -203,6 +306,20 @@ class MessageClassifier:
|
|||||||
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||||
self._embedding_dim = OLLAMA_CONFIG["embedding_dim"]
|
self._embedding_dim = OLLAMA_CONFIG["embedding_dim"]
|
||||||
|
|
||||||
|
# Handle LLM client
|
||||||
|
self._llm_enabled = LLM_CONFIG["enabled"]
|
||||||
|
if self._llm_enabled:
|
||||||
|
if llm_client is not None:
|
||||||
|
self._llm_client: Optional[LLMClient] = llm_client
|
||||||
|
else:
|
||||||
|
self._llm_client = OllamaLLMClient(
|
||||||
|
base_url=LLM_CONFIG["base_url"],
|
||||||
|
model=LLM_CONFIG["model"],
|
||||||
|
timeout=LLM_CONFIG["timeout"]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._llm_client = None
|
||||||
|
|
||||||
# Cache: category → embedding vector (768 floats)
|
# Cache: category → embedding vector (768 floats)
|
||||||
self._category_vectors: Dict[str, List[float]] = {}
|
self._category_vectors: Dict[str, List[float]] = {}
|
||||||
self._initialized: bool = False
|
self._initialized: bool = False
|
||||||
@@ -212,6 +329,37 @@ class MessageClassifier:
|
|||||||
self._message_cache: Dict[str, List[float]] = {}
|
self._message_cache: Dict[str, List[float]] = {}
|
||||||
self._cache_max_size: int = 100
|
self._cache_max_size: int = 100
|
||||||
|
|
||||||
|
def _keyword_prefilter(self, text: str) -> Optional[str]:
|
||||||
|
"""Stufe 0: Keyword-Vorfilter. Liefert 'ALARM', 'FRAGE' oder None."""
|
||||||
|
from .config import FALLBACK_KEYWORDS
|
||||||
|
|
||||||
|
t = text.lower()
|
||||||
|
# ALARM ZUERST — höchste Priorität
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
||||||
|
if kw in t:
|
||||||
|
return "ALARM"
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
||||||
|
if kw in t:
|
||||||
|
return "FRAGE"
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _llm_classify(self, text: str) -> Optional[str]:
|
||||||
|
import asyncio
|
||||||
|
return await asyncio.to_thread(self._llm_classify_sync, text)
|
||||||
|
|
||||||
|
def _llm_classify_sync(self, text: str) -> Optional[str]:
|
||||||
|
try:
|
||||||
|
if not self._llm_client or not self._llm_enabled:
|
||||||
|
return None
|
||||||
|
|
||||||
|
prompt = LLM_CLASSIFY_PROMPT.format(text=text)
|
||||||
|
result = self._llm_client.classify(prompt)
|
||||||
|
if result in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("LLM classification failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
# ── Public API ──────────────────────────────────────────────────────
|
# ── Public API ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
async def initialize(self) -> bool:
|
async def initialize(self) -> bool:
|
||||||
@@ -287,6 +435,21 @@ class MessageClassifier:
|
|||||||
|
|
||||||
t0 = time.monotonic()
|
t0 = time.monotonic()
|
||||||
|
|
||||||
|
# Stufe 0: Keyword-Vorfilter
|
||||||
|
keyword_result = self._keyword_prefilter(text)
|
||||||
|
if keyword_result == "ALARM":
|
||||||
|
# ALARM hat höchste Priorität - sofortige Rückgabe
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
return ClassificationResult(
|
||||||
|
category="ALARM",
|
||||||
|
confidence=0.95, # Hohe Konfidenz für Keyword-Treffer
|
||||||
|
all_scores={"ALARM": 0.95, "FRAGE": 0.0, "FAKT": 0.0},
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
# Für FRAGE geht es weiter zur Embedding-Klassifikation (mit niedrigerem Schwellwert)
|
||||||
|
|
||||||
|
# Stufe 1: Embedding-Klassifikation
|
||||||
vector = self._get_cached_or_compute(text)
|
vector = self._get_cached_or_compute(text)
|
||||||
if vector is None:
|
if vector is None:
|
||||||
logger.debug("Failed to embed message: %.60s...", text)
|
logger.debug("Failed to embed message: %.60s...", text)
|
||||||
@@ -309,6 +472,30 @@ class MessageClassifier:
|
|||||||
if best_score < 0:
|
if best_score < 0:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# Prüfe, ob die Embedding-Konfidenz ausreicht
|
||||||
|
if best_score >= LLM_CONFIDENCE_THRESHOLD:
|
||||||
|
return ClassificationResult(
|
||||||
|
category=best_category,
|
||||||
|
confidence=best_score,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Stufe 2: LLM-Klassifikation, wenn Konfidenz niedrig ist
|
||||||
|
if self._llm_enabled and best_score < LLM_CONFIDENCE_THRESHOLD and self._llm_client:
|
||||||
|
llm_category = self._llm_classify_sync(text)
|
||||||
|
if llm_category:
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
return ClassificationResult(
|
||||||
|
category=llm_category,
|
||||||
|
confidence=0.95, # Hohe Konfidenz für LLM-Klassifikation
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ansonsten: originales Embedding-Ergebnis zurückgeben (auch wenn unter Schwellwert)
|
||||||
return ClassificationResult(
|
return ClassificationResult(
|
||||||
category=best_category,
|
category=best_category,
|
||||||
confidence=best_score,
|
confidence=best_score,
|
||||||
|
|||||||
@@ -102,12 +102,40 @@ CATCH_ALL_ROOM: str = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip() or None
|
|||||||
FALLBACK_KEYWORDS: dict = {
|
FALLBACK_KEYWORDS: dict = {
|
||||||
"FRAGE": ["frage", "wie", "was ist", "warum", "wieso", "weshalb",
|
"FRAGE": ["frage", "wie", "was ist", "warum", "wieso", "weshalb",
|
||||||
"kannst du", "können sie", "help", "hilfe", "problem",
|
"kannst du", "können sie", "help", "hilfe", "problem",
|
||||||
"funktioniert nicht", "kaputt", "erklären", "erkläre"],
|
"funktioniert nicht", "kaputt", "erklären", "erkläre",
|
||||||
|
"was bedeutet", "zeig mir", "konflikt"],
|
||||||
"ALARM": ["alarm", "hilfe", "dringend", "sofort", "notfall",
|
"ALARM": ["alarm", "hilfe", "dringend", "sofort", "notfall",
|
||||||
"ausfall", "absturz", "kritisch", "emergency",
|
"ausfall", "absturz", "kritisch", "emergency",
|
||||||
"feuer", "panne", "sos", "sicherheitslücke"],
|
"feuer", "panne", "sos", "sicherheitslücke",
|
||||||
|
"stop", "red flag", "abort", "kompromittiert", "datenverlust",
|
||||||
|
"exploit", "gehackt", "ausgefallen", "produktivsystem"],
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
Bei Ollama-Down-Fallback: Enthält die Nachricht eines dieser Keywords,
|
Bei Ollama-Down-Fallback: Enthält die Nachricht eines dieser Keywords,
|
||||||
wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# ── LLM-Konfiguration ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
LLM_CONFIG = {
|
||||||
|
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
||||||
|
"model": "qwen2.5:7b",
|
||||||
|
"timeout": 5.0,
|
||||||
|
"base_url": "http://localhost:11434",
|
||||||
|
"temperature": 0.0,
|
||||||
|
"max_tokens": 10,
|
||||||
|
}
|
||||||
|
|
||||||
|
LLM_CLASSIFY_PROMPT = """Klassifiziere die folgende Nachricht in EINE Kategorie.
|
||||||
|
Antworte NUR mit einem Wort: FAKT, FRAGE oder ALARM.
|
||||||
|
|
||||||
|
Kategorien:
|
||||||
|
- FAKT: Information, Dokumentation, Status-Update ohne Handlungsbedarf
|
||||||
|
- FRAGE: Frage, Problembeschreibung, Bitte um Hilfe oder Erklärung
|
||||||
|
- ALARM: Dringend! Ausfall, Sicherheitsvorfall, Datenverlust, sofortiger Handlungsbedarf
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
|
||||||
|
Kategorie:"""
|
||||||
|
|
||||||
|
LLM_CONFIDENCE_THRESHOLD = 0.70
|
||||||
|
|||||||
Reference in New Issue
Block a user