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:
Hermes Agent
2026-06-04 21:49:17 +02:00
parent 4b2e933529
commit e5a32abf5c
3 changed files with 236 additions and 6 deletions
+188 -1
View File
@@ -19,7 +19,7 @@ import urllib.request
from dataclasses import dataclass, field
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__)
@@ -152,6 +152,104 @@ class OllamaEmbeddingClient(EmbeddingClient):
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:
"""Embedding-basierter Nachrichten-Klassifizierer.
@@ -173,6 +271,7 @@ class MessageClassifier:
model: Optional[str] = None,
timeout: Optional[float] = None,
embedding_client: Optional[EmbeddingClient] = None,
llm_client: Optional[LLMClient] = None,
) -> None:
"""
Args:
@@ -188,6 +287,10 @@ class MessageClassifier:
Backends). Wenn ``None``, wird ein
``OllamaEmbeddingClient`` mit *base_url*, *model*
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:
self._embedding_client: EmbeddingClient = embedding_client
@@ -203,6 +306,20 @@ class MessageClassifier:
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
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)
self._category_vectors: Dict[str, List[float]] = {}
self._initialized: bool = False
@@ -212,6 +329,37 @@ class MessageClassifier:
self._message_cache: Dict[str, List[float]] = {}
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 ──────────────────────────────────────────────────────
async def initialize(self) -> bool:
@@ -286,7 +434,22 @@ class MessageClassifier:
text = text.strip()
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)
if vector is None:
logger.debug("Failed to embed message: %.60s...", text)
@@ -309,6 +472,30 @@ class MessageClassifier:
if best_score < 0:
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(
category=best_category,
confidence=best_score,