Repository navigation
Expand file tree
/
Copy pathdetector.py
More file actions
89 lines (69 loc) · 2.09 KB
/
Copy pathdetector.py
File metadata and controls
89 lines (69 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
detector.py
LLM-based risk classifier.
"""
import json
from dataclasses import dataclass
from logger import logger
from llm_client import call_llm
from prompts import build_detector_messages
VALID_CATEGORIES = {
"SAFE",
"LOW_RISK",
"MEDIUM_RISK",
"HIGH_RISK"
}
@dataclass
class DetectionResult:
category: str
confidence: float
details: str
def _strip_markdown(text: str) -> str:
"""
Remove markdown code fences if the model wrapped JSON in them.
"""
text = text.strip()
if not text.startswith("```"):
return text
lines = text.splitlines()
# Drop opening fence (may be ``` or ```json)
if lines[0].strip().startswith("```"):
lines = lines[1:]
# Drop closing fence
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
return "\n".join(lines).strip()
def detect(message: str) -> DetectionResult:
"""
Classify a user message for risk level using the LLM.
Falls back to SAFE on any error.
"""
messages = build_detector_messages(message)
raw_response = call_llm(messages)
try:
clean_text = _strip_markdown(raw_response)
data = json.loads(clean_text)
category = data.get("category", "SAFE")
if category not in VALID_CATEGORIES:
category = "SAFE"
confidence = float(data.get("confidence", 0.0))
confidence = max(0.0, min(1.0, confidence))
details = data.get("reason", "No explanation provided.")
result = DetectionResult(
category=category,
confidence=confidence,
details=details
)
logger.info(
"Detector | category=%s confidence=%.2f",
result.category,
result.confidence
)
return result
except (json.JSONDecodeError, ValueError, TypeError, KeyError) as error:
logger.exception("Detector parse failed for message: %s", message)
return DetectionResult(
category="SAFE",
confidence=0.0,
details=f"Detection failed — defaulted to SAFE. ({error})"
)