feat(archivar): Implement Intent-Erkenner und Confidence-Framework für Archivar v3
This commit is contained in:
+127
-52
@@ -1,10 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
Embedding-basierte Klassifikation via nomic-embed-text (Ollama, localhost:11434).
|
Embedding-basierte Intent-Klassifikation für Archivar v3.
|
||||||
|
|
||||||
Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab
|
Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab
|
||||||
berechneten Kategorie-Vektoren (FAKT, FRAGE, ALARM) via Kosinus-Ähnlichkeit.
|
berechneten Kategorie-Vektoren (direct_question, smalltalk, work_order, ambiguous)
|
||||||
Bei Ollama-Fehlern oder Timeout wird None als ClassificationResult
|
via Kosinus-Ähnlichkeit. Bei Ollama-Fehlern oder Timeout wird None als
|
||||||
zurückgegeben — der Router übernimmt dann den Fallback.
|
ClassificationResult zurückgegeben — der Router übernimmt dann den Fallback.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -17,19 +17,27 @@ import time
|
|||||||
import urllib.error
|
import urllib.error
|
||||||
import urllib.request
|
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, Tuple
|
||||||
|
|
||||||
from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD, LLM_CONFIG, LLM_CLASSIFY_PROMPT, LLM_CONFIDENCE_THRESHOLD
|
from .config import (
|
||||||
|
OLLAMA_CONFIG,
|
||||||
|
CATEGORY_TEXTS,
|
||||||
|
CONFIDENCE_THRESHOLDS,
|
||||||
|
LLM_CONFIG,
|
||||||
|
LLM_CLASSIFY_PROMPT,
|
||||||
|
LLM_CONFIDENCE_THRESHOLD,
|
||||||
|
FALLBACK_KEYWORDS
|
||||||
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ClassificationResult:
|
class ClassificationResult:
|
||||||
"""Ergebnis einer Embedding-basierten Klassifikation."""
|
"""Ergebnis einer Intent-Klassifikation."""
|
||||||
|
|
||||||
category: str
|
category: str
|
||||||
"""Kategorie-Label: 'FAKT', 'FRAGE', oder 'ALARM'."""
|
"""Kategorie-Label: 'direct_question', 'smalltalk', 'work_order', oder 'ambiguous'."""
|
||||||
|
|
||||||
confidence: float
|
confidence: float
|
||||||
"""Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor."""
|
"""Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor."""
|
||||||
@@ -43,10 +51,35 @@ class ClassificationResult:
|
|||||||
fallback: bool = False
|
fallback: bool = False
|
||||||
"""True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
"""True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||||||
|
|
||||||
def is_confident(self, threshold: float = CONFIDENCE_THRESHOLD) -> bool:
|
llm_verified: bool = False
|
||||||
"""True wenn die Konfidenz über dem Schwellenwert liegt."""
|
"""True, wenn das Ergebnis durch LLM-Verifikation bestätigt wurde."""
|
||||||
|
|
||||||
|
def is_confident(self, threshold: float = CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]) -> bool:
|
||||||
|
"""True wenn die Konfidenz über dem Schwellenwert für automatisches Routing liegt."""
|
||||||
return self.confidence >= threshold
|
return self.confidence >= threshold
|
||||||
|
|
||||||
|
def needs_clarification(self) -> bool:
|
||||||
|
"""True wenn die Konfidenz im Bereich 60-90% liegt und Klärung benötigt."""
|
||||||
|
return (
|
||||||
|
self.confidence >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||||
|
self.confidence < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def should_route(self) -> bool:
|
||||||
|
"""True wenn die Nachricht geroutet werden sollte.
|
||||||
|
|
||||||
|
- work_order mit >90% Konfidenz wird geroutet
|
||||||
|
- direct_question und smalltalk werden nie geroutet
|
||||||
|
- ambiguous benötigt Klärung
|
||||||
|
"""
|
||||||
|
if self.category in ("direct_question", "smalltalk"):
|
||||||
|
return False
|
||||||
|
if self.category == "work_order":
|
||||||
|
return self.confidence >= CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||||
|
if self.category == "ambiguous":
|
||||||
|
return False # Benötigt Klärung
|
||||||
|
return False
|
||||||
|
|
||||||
def is_fallback(self) -> bool:
|
def is_fallback(self) -> bool:
|
||||||
"""True wenn dieses Ergebnis aus der Keyword-Heuristik stammt."""
|
"""True wenn dieses Ergebnis aus der Keyword-Heuristik stammt."""
|
||||||
return self.fallback
|
return self.fallback
|
||||||
@@ -59,10 +92,10 @@ class EmbeddingClient(abc.ABC):
|
|||||||
"""Interface for embedding providers. Injectable for testability.
|
"""Interface for embedding providers. Injectable for testability.
|
||||||
|
|
||||||
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||||
single ``get_embedding()`` method so that ``MessageClassifier`` can
|
single ``get_embedding()`` method so that ``IntentClassifier`` can
|
||||||
work with real Ollama, mocks, or alternative backends without change.
|
work with real Ollama, mocks, or alternative backends without change.
|
||||||
|
|
||||||
Implementations must be thread-safe since ``MessageClassifier`` calls
|
Implementations must be thread-safe since ``IntentClassifier`` calls
|
||||||
``get_embedding()`` synchronously inside ``asyncio.to_thread``.
|
``get_embedding()`` synchronously inside ``asyncio.to_thread``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -159,10 +192,10 @@ class LLMClient(abc.ABC):
|
|||||||
"""Interface for LLM providers. Injectable for testability.
|
"""Interface for LLM providers. Injectable for testability.
|
||||||
|
|
||||||
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||||
single ``classify()`` method so that ``MessageClassifier`` can
|
single ``classify()`` method so that ``IntentClassifier`` can
|
||||||
work with real Ollama, mocks, or alternative backends without change.
|
work with real Ollama, mocks, or alternative backends without change.
|
||||||
|
|
||||||
Implementations must be thread-safe since ``MessageClassifier`` calls
|
Implementations must be thread-safe since ``IntentClassifier`` calls
|
||||||
``classify()`` synchronously inside ``asyncio.to_thread``.
|
``classify()`` synchronously inside ``asyncio.to_thread``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -171,6 +204,11 @@ class LLMClient(abc.ABC):
|
|||||||
"""Klassifiziere Text. Gibt Kategorie-String oder None zurück."""
|
"""Klassifiziere Text. Gibt Kategorie-String oder None zurück."""
|
||||||
...
|
...
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||||
|
"""Verifiziere die Konfidenz mit dem LLM und gib (Kategorie, Konfidenz) zurück."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
class OllamaLLMClient(LLMClient):
|
class OllamaLLMClient(LLMClient):
|
||||||
"""LLM client backed by Ollama's `/api/generate` endpoint.
|
"""LLM client backed by Ollama's `/api/generate` endpoint.
|
||||||
@@ -183,7 +221,7 @@ class OllamaLLMClient(LLMClient):
|
|||||||
|
|
||||||
client = OllamaLLMClient()
|
client = OllamaLLMClient()
|
||||||
category = client.classify("Wie funktioniert das Plugin?")
|
category = client.classify("Wie funktioniert das Plugin?")
|
||||||
# → "FRAGE"
|
# → "direct_question"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -230,8 +268,8 @@ class OllamaLLMClient(LLMClient):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
# Trim whitespace and normalize category
|
# Trim whitespace and normalize category
|
||||||
category = response_text.strip().upper()
|
category = response_text.strip().lower()
|
||||||
if category in ("FAKT", "FRAGE", "ALARM"):
|
if category in ("direct_question", "smalltalk", "work_order", "ambiguous"):
|
||||||
return category
|
return category
|
||||||
else:
|
else:
|
||||||
logger.warning("LLM returned invalid category: %s", category)
|
logger.warning("LLM returned invalid category: %s", category)
|
||||||
@@ -249,9 +287,30 @@ class OllamaLLMClient(LLMClient):
|
|||||||
logger.error("Unexpected error in classify: %s", e)
|
logger.error("Unexpected error in classify: %s", e)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||||
|
"""Verifiziere die Konfidenz mit dem LLM."""
|
||||||
|
try:
|
||||||
|
# Erstelle einen Prompt mit den Scores für die LLM-Verifikation
|
||||||
|
scores_text = "\n".join([f"- {cat}: {score:.2f}" for cat, score in scores.items()])
|
||||||
|
prompt = f"""Nachricht: {text}
|
||||||
|
|
||||||
class MessageClassifier:
|
Embedding-basierte Scores:
|
||||||
"""Embedding-basierter Nachrichten-Klassifizierer.
|
{scores_text}
|
||||||
|
|
||||||
|
Welche Kategorie ist am wahrscheinlichsten? Antworte nur mit dem Kategorienamen:
|
||||||
|
direct_question, smalltalk, work_order, oder ambiguous"""
|
||||||
|
|
||||||
|
category = self.classify(prompt)
|
||||||
|
if category:
|
||||||
|
# Setze eine hohe Konfidenz für LLM-verifizierte Ergebnisse
|
||||||
|
return (category, 0.95)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("LLM confidence verification failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class IntentClassifier:
|
||||||
|
"""Embedding-basierter Intent-Klassifizierer für Archivar v3.
|
||||||
|
|
||||||
Verwendet nomic-embed-text via Ollama-API auf localhost:11434.
|
Verwendet nomic-embed-text via Ollama-API auf localhost:11434.
|
||||||
Kategorie-Vektoren werden einmalig beim Start berechnet und im Speicher
|
Kategorie-Vektoren werden einmalig beim Start berechnet und im Speicher
|
||||||
@@ -259,10 +318,10 @@ class MessageClassifier:
|
|||||||
|
|
||||||
Usage::
|
Usage::
|
||||||
|
|
||||||
classifier = MessageClassifier()
|
classifier = IntentClassifier()
|
||||||
await classifier.initialize() # pre-compute category vectors
|
await classifier.initialize() # pre-compute category vectors
|
||||||
result = await classifier.classify("Wie funktioniert das Plugin?")
|
result = await classifier.classify("Wie funktioniert das Plugin?")
|
||||||
print(result.category) # → "FRAGE"
|
print(result.category) # → "direct_question"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -330,32 +389,28 @@ class MessageClassifier:
|
|||||||
self._cache_max_size: int = 100
|
self._cache_max_size: int = 100
|
||||||
|
|
||||||
def _keyword_prefilter(self, text: str) -> Optional[str]:
|
def _keyword_prefilter(self, text: str) -> Optional[str]:
|
||||||
"""Stufe 0: Keyword-Vorfilter. Liefert 'ALARM', 'FRAGE' oder None."""
|
"""Stufe 0: Keyword-Vorfilter. Liefert Intent-Kategorie oder None."""
|
||||||
from .config import FALLBACK_KEYWORDS
|
|
||||||
|
|
||||||
t = text.lower()
|
t = text.lower()
|
||||||
# ALARM ZUERST — höchste Priorität
|
|
||||||
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
# Prüfe zuerst auf direkte Matches
|
||||||
if kw in t:
|
for category, keywords in FALLBACK_KEYWORDS.items():
|
||||||
return "ALARM"
|
if category == "ambiguous":
|
||||||
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
continue # Ambiguous wird nicht über Keywords erkannt
|
||||||
if kw in t:
|
for kw in keywords:
|
||||||
return "FRAGE"
|
if kw in t:
|
||||||
|
return category
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def _llm_classify(self, text: str) -> Optional[str]:
|
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||||
import asyncio
|
import asyncio
|
||||||
return await asyncio.to_thread(self._llm_classify_sync, text)
|
return await asyncio.to_thread(self._llm_classify_sync, text, scores)
|
||||||
|
|
||||||
def _llm_classify_sync(self, text: str) -> Optional[str]:
|
def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||||
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
|
||||||
|
|
||||||
prompt = LLM_CLASSIFY_PROMPT.format(text=text)
|
return self._llm_client.verify_confidence(text, scores)
|
||||||
result = self._llm_client.classify(prompt)
|
|
||||||
if result in ("FAKT", "FRAGE", "ALARM"):
|
|
||||||
return result
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("LLM classification failed: %s", e)
|
logger.warning("LLM classification failed: %s", e)
|
||||||
return None
|
return None
|
||||||
@@ -364,8 +419,7 @@ class MessageClassifier:
|
|||||||
"""Send a raw prompt to the LLM and return its response.
|
"""Send a raw prompt to the LLM and return its response.
|
||||||
|
|
||||||
Unlike ``_llm_classify_sync``, this does NOT validate against
|
Unlike ``_llm_classify_sync``, this does NOT validate against
|
||||||
FAKT/FRAGE/ALARM categories. Used by the RoomRouter for the
|
Intent-Kategorien. Used by den Router.
|
||||||
``LLM_ROOM_PROMPT`` where the expected answer is a room name.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
prompt: The complete prompt to send.
|
prompt: The complete prompt to send.
|
||||||
@@ -404,7 +458,7 @@ class MessageClassifier:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"Initializing classifier: model=%s, base_url=%s, timeout=%.1fs",
|
"Initializing intent classifier: model=%s, base_url=%s, timeout=%.1fs",
|
||||||
self._model, self._base_url, self._timeout,
|
self._model, self._base_url, self._timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -426,7 +480,7 @@ class MessageClassifier:
|
|||||||
if success:
|
if success:
|
||||||
self._initialized = True
|
self._initialized = True
|
||||||
logger.info(
|
logger.info(
|
||||||
"Classifier initialized successfully (%d categories)",
|
"Intent classifier initialized successfully (%d categories)",
|
||||||
len(self._category_vectors),
|
len(self._category_vectors),
|
||||||
)
|
)
|
||||||
return success
|
return success
|
||||||
@@ -461,17 +515,22 @@ class MessageClassifier:
|
|||||||
|
|
||||||
# Stufe 0: Keyword-Vorfilter
|
# Stufe 0: Keyword-Vorfilter
|
||||||
keyword_result = self._keyword_prefilter(text)
|
keyword_result = self._keyword_prefilter(text)
|
||||||
if keyword_result == "ALARM":
|
if keyword_result:
|
||||||
# ALARM hat höchste Priorität - sofortige Rückgabe
|
# Keyword-Treffer haben hohe Priorität
|
||||||
latency_ms = (time.monotonic() - t0) * 1000.0
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
confidence = 0.85 # Hohe Konfidenz für Keyword-Treffer
|
||||||
|
|
||||||
|
# Für ambiguous Ergebnisse setzen wir eine niedrigere Konfidenz
|
||||||
|
if keyword_result == "ambiguous":
|
||||||
|
confidence = 0.75
|
||||||
|
|
||||||
return ClassificationResult(
|
return ClassificationResult(
|
||||||
category="ALARM",
|
category=keyword_result,
|
||||||
confidence=0.95, # Hohe Konfidenz für Keyword-Treffer
|
confidence=confidence,
|
||||||
all_scores={"ALARM": 0.95, "FRAGE": 0.0, "FAKT": 0.0},
|
all_scores={keyword_result: confidence},
|
||||||
latency_ms=latency_ms,
|
latency_ms=latency_ms,
|
||||||
fallback=False,
|
fallback=True,
|
||||||
)
|
)
|
||||||
# Für FRAGE geht es weiter zur Embedding-Klassifikation (mit niedrigerem Schwellwert)
|
|
||||||
|
|
||||||
# Stufe 1: Embedding-Klassifikation
|
# Stufe 1: Embedding-Klassifikation
|
||||||
vector = self._get_cached_or_compute(text)
|
vector = self._get_cached_or_compute(text)
|
||||||
@@ -496,13 +555,29 @@ class MessageClassifier:
|
|||||||
if best_score < 0:
|
if best_score < 0:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Direktes Return des Embedding-Ergebnisses
|
# Stufe 2: LLM-Verifikation bei ambiguous Ergebnissen
|
||||||
|
llm_verified = False
|
||||||
|
final_category = best_category
|
||||||
|
final_score = best_score
|
||||||
|
|
||||||
|
# Wenn der Score im Klärungsbereich liegt, führe LLM-Verifikation durch
|
||||||
|
if (
|
||||||
|
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||||
|
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||||
|
):
|
||||||
|
llm_result = self._llm_classify_sync(text, scores)
|
||||||
|
if llm_result:
|
||||||
|
final_category, final_score = llm_result
|
||||||
|
llm_verified = True
|
||||||
|
|
||||||
|
# Direktes Return des Ergebnisses
|
||||||
return ClassificationResult(
|
return ClassificationResult(
|
||||||
category=best_category,
|
category=final_category,
|
||||||
confidence=best_score,
|
confidence=final_score,
|
||||||
all_scores=scores,
|
all_scores=scores,
|
||||||
latency_ms=latency_ms,
|
latency_ms=latency_ms,
|
||||||
fallback=False,
|
fallback=False,
|
||||||
|
llm_verified=llm_verified,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ── Embedding-API ───────────────────────────────────────────────────
|
# ── Embedding-API ───────────────────────────────────────────────────
|
||||||
|
|||||||
Reference in New Issue
Block a user