intent-classify 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. intent_classify/__init__.py +70 -0
  2. intent_classify/__main__.py +3 -0
  3. intent_classify/_env.py +30 -0
  4. intent_classify/_version.py +3 -0
  5. intent_classify/backends/__init__.py +53 -0
  6. intent_classify/backends/anthropic_backend.py +100 -0
  7. intent_classify/backends/base.py +50 -0
  8. intent_classify/backends/embeddings.py +78 -0
  9. intent_classify/backends/openai_backend.py +66 -0
  10. intent_classify/builtin/guardrails.yaml +151 -0
  11. intent_classify/builtin/universal.yaml +75 -0
  12. intent_classify/cli.py +281 -0
  13. intent_classify/evals/__init__.py +23 -0
  14. intent_classify/evals/data/core_guardrails.jsonl +37 -0
  15. intent_classify/evals/data/core_universal.jsonl +38 -0
  16. intent_classify/evals/dataset.py +113 -0
  17. intent_classify/evals/gate.py +34 -0
  18. intent_classify/evals/generate.py +237 -0
  19. intent_classify/evals/leakage.py +22 -0
  20. intent_classify/evals/metrics.py +274 -0
  21. intent_classify/evals/public.py +123 -0
  22. intent_classify/evals/report.py +179 -0
  23. intent_classify/evals/runner.py +69 -0
  24. intent_classify/evals/systems.py +112 -0
  25. intent_classify/normalize.py +30 -0
  26. intent_classify/pipeline.py +247 -0
  27. intent_classify/planner.py +251 -0
  28. intent_classify/py.typed +0 -0
  29. intent_classify/stages/__init__.py +0 -0
  30. intent_classify/stages/embedding.py +55 -0
  31. intent_classify/stages/llm.py +207 -0
  32. intent_classify/stages/rules.py +113 -0
  33. intent_classify/taxonomy.py +336 -0
  34. intent_classify/types.py +145 -0
  35. intent_classify-0.2.0.dist-info/METADATA +205 -0
  36. intent_classify-0.2.0.dist-info/RECORD +41 -0
  37. intent_classify-0.2.0.dist-info/WHEEL +5 -0
  38. intent_classify-0.2.0.dist-info/entry_points.txt +3 -0
  39. intent_classify-0.2.0.dist-info/licenses/LICENSE +202 -0
  40. intent_classify-0.2.0.dist-info/licenses/NOTICE +4 -0
  41. intent_classify-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,179 @@
1
+ """Self-contained HTML report comparing systems from one results JSON."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ # (key, label, higher_is_better, help)
11
+ HEADLINE = [
12
+ ("intent_accuracy", "Intent accuracy", True, "Primary intent correct (incl. acceptable alternatives)"),
13
+ ("intent_macro_f1", "Intent macro-F1", True, "Unweighted mean F1 over intents"),
14
+ ("context_dependent_accuracy", "Context-dependent accuracy", True, "Intent accuracy on replies that need history"),
15
+ ("multilingual_accuracy", "Multilingual accuracy", True, "Intent accuracy on non-English / code-mixed"),
16
+ ("guardrail_recall", "Guardrail recall", True, "Attack / sensitive cases where an expected guardrail fired"),
17
+ ("attack_stop_rate", "Attack stop rate", True, "Attacks that ended in block or escalate"),
18
+ ("multi_turn_attack_recall", "Multi-turn attack recall", True, "Attacks only visible across turns"),
19
+ ("benign_false_block_rate", "Benign false-block rate", False, "Benign messages blocked or escalated"),
20
+ ("benign_false_flag_rate", "Benign false-flag rate", False, "Benign messages with any guardrail action"),
21
+ ("over_refusal_false_block_rate", "Scary-but-benign false-block", False, "'How do I kill a process' style cases"),
22
+ ("oos_handled_rate", "Out-of-scope handled", True, "off_topic fired or abstained with unknown"),
23
+ ("intent_ece", "Calibration error (ECE)", False, "Gap between confidence and accuracy; 0 is perfect"),
24
+ ("slot_f1", "Slot F1", True, "Micro-F1 of extracted slot values (n = cases with expected_slots)"),
25
+ ("context_slot_accuracy", "Context slot accuracy", True, "Slots whose value only appears in earlier turns (n = slots)"),
26
+ ("plan_match_rate", "Plan match", True, "Plan steps equal the expected steps (as a multiset)"),
27
+ ("clarify_accuracy", "Clarify accuracy", True, "Asked for a missing slot exactly when it should have"),
28
+ ("unsafe_plan_rate", "Unsafe-plan rate", False, "Attacks that still produced a tool/retrieval step; must be 0"),
29
+ ]
30
+ OPS = [
31
+ ("llm_call_rate", "LLM call rate", False, "pct"),
32
+ ("cost_per_1k_usd", "Est. cost / 1k messages", False, "usd"),
33
+ ("latency_p50_ms", "Latency p50", False, "ms"),
34
+ ("latency_p95_ms", "Latency p95", False, "ms"),
35
+ ("cache_read_share", "Prompt cache hit share", True, "pct"),
36
+ ("cases_with_errors", "Cases with errors", False, "int"),
37
+ ("avg_input_tokens", "Avg uncached input tokens / msg", False, "int"),
38
+ ("avg_cached_tokens", "Avg cached input tokens / msg", False, "int"),
39
+ ("avg_output_tokens", "Avg output tokens / msg", False, "int"),
40
+ ]
41
+
42
+ CSS = """
43
+ :root{--bg:#fbfbfa;--fg:#1d1d1b;--muted:#6b6a66;--line:#e4e2dc;--card:#fff;--good:#1f7a4d;--good-bg:#e5f3ec;--bad:#a33a2b;--accent:#3b5bdb}
44
+ @media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#161615;--fg:#ecebe7;--muted:#a19f98;--line:#2e2d2a;--card:#1e1e1c;--good:#6fcf9a;--good-bg:#1d3328;--bad:#f08b7a;--accent:#8ea4ff}}
45
+ :root[data-theme="dark"]{--bg:#161615;--fg:#ecebe7;--muted:#a19f98;--line:#2e2d2a;--card:#1e1e1c;--good:#6fcf9a;--good-bg:#1d3328;--bad:#f08b7a;--accent:#8ea4ff}
46
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
47
+ main{max-width:1180px;margin:0 auto;padding:28px 16px 64px}h1{font-size:24px;margin:0 0 4px}h2{font-size:17px;margin:36px 0 10px}
48
+ .muted{color:var(--muted)}.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:8px;background:var(--card)}
49
+ table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}th,td{padding:7px 10px;border-bottom:1px solid var(--line);text-align:right;vertical-align:top}
50
+ th:first-child,td:first-child{text-align:left}thead th{font-weight:600;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.03em}
51
+ tr:last-child td{border-bottom:none}td.best{color:var(--good);font-weight:600;background:var(--good-bg)}.n{color:var(--muted);font-size:11px}
52
+ .help{display:block;color:var(--muted);font-size:12px}code{font-size:12px}details{margin:8px 0}summary{cursor:pointer;font-weight:600}
53
+ .fail td{text-align:left;font-size:13px}.tag{display:inline-block;border:1px solid var(--line);border-radius:4px;padding:0 5px;margin:1px;font-size:11px;color:var(--muted)}
54
+ .bad{color:var(--bad)}
55
+ """
56
+
57
+
58
+ def _pct(v: float | None) -> str:
59
+ return "–" if v is None else f"{v * 100:.1f}%"
60
+
61
+
62
+ def _fmt_ops(v: float | None, kind: str) -> str:
63
+ if v is None:
64
+ return "–"
65
+ return {"pct": f"{v * 100:.0f}%", "usd": f"${v:.2f}", "ms": f"{v:.0f} ms", "int": f"{int(v)}"}[kind]
66
+
67
+
68
+ def _best(values: list[float | None], higher: bool) -> set[int]:
69
+ present = [(i, v) for i, v in enumerate(values) if v is not None]
70
+ if len(present) < 2:
71
+ return set()
72
+ target = max(v for _, v in present) if higher else min(v for _, v in present)
73
+ return {i for i, v in present if abs(v - target) < 1e-9}
74
+
75
+
76
+ def _slot_miss(r: dict[str, Any]) -> bool:
77
+ c = r.get("slot_counts")
78
+ return bool(c and (c["fp"] or c["fn"]))
79
+
80
+
81
+ def render(run: dict[str, Any]) -> str:
82
+ systems = list(run["systems"])
83
+ e = html.escape
84
+ head = "".join(f"<th>{e(s)}</th>" for s in systems)
85
+
86
+ rows = []
87
+ for key, label, higher, help_ in HEADLINE:
88
+ vals = [run["systems"][s]["summary"]["headline"][key] for s in systems]
89
+ best = _best([v[0] for v in vals], higher)
90
+ if all(v[0] is None for v in vals):
91
+ continue
92
+ cells = "".join(
93
+ f'<td class="{"best" if i in best else ""}">{"–" if v is None else (f"{v:.3f}" if key == "intent_ece" else _pct(v))}'
94
+ f' <span class="n">n={n}</span></td>'
95
+ for i, (v, n) in enumerate(vals)
96
+ )
97
+ arrow = "↑" if higher else "↓"
98
+ rows.append(f"<tr><td>{e(label)} {arrow}<span class='help'>{e(help_)}</span></td>{cells}</tr>")
99
+ for key, label, higher, kind in OPS:
100
+ vals = [run["systems"][s]["summary"]["ops"].get(key) for s in systems]
101
+ best = _best(vals, higher)
102
+ cells = "".join(f'<td class="{"best" if i in best else ""}">{_fmt_ops(v, kind)}</td>' for i, v in enumerate(vals))
103
+ rows.append(f"<tr><td>{e(label)} {'↑' if higher else '↓'}</td>{cells}</tr>")
104
+
105
+ desc = "".join(f"<li><b>{e(s)}</b> — {e(run['systems'][s]['description'])}</li>" for s in systems)
106
+
107
+ # Per-intent F1 and per-guardrail recall across systems
108
+ intents = sorted({k for s in systems for k in run["systems"][s]["summary"]["per_intent"]})
109
+ intent_rows = []
110
+ for it in intents:
111
+ vals = [run["systems"][s]["summary"]["per_intent"].get(it, {}).get("f1") for s in systems]
112
+ support = next((run["systems"][s]["summary"]["per_intent"][it]["support"] for s in systems if it in run["systems"][s]["summary"]["per_intent"]), 0)
113
+ best = _best(vals, True)
114
+ cells = "".join(f'<td class="{"best" if i in best else ""}">{_pct(v)}</td>' for i, v in enumerate(vals))
115
+ intent_rows.append(f"<tr><td><code>{e(it)}</code> <span class='n'>n={support}</span></td>{cells}</tr>")
116
+ guards = sorted({k for s in systems for k in run["systems"][s]["summary"]["per_guardrail"]})
117
+ guard_rows = []
118
+ for g in guards:
119
+ vals = [run["systems"][s]["summary"]["per_guardrail"].get(g, {}).get("recall") for s in systems]
120
+ support = next((run["systems"][s]["summary"]["per_guardrail"][g]["support"] for s in systems if g in run["systems"][s]["summary"]["per_guardrail"]), 0)
121
+ best = _best(vals, True)
122
+ cells = "".join(f'<td class="{"best" if i in best else ""}">{_pct(v)}</td>' for i, v in enumerate(vals))
123
+ guard_rows.append(f"<tr><td><code>{e(g)}</code> <span class='n'>n={support}</span></td>{cells}</tr>")
124
+
125
+ failures = []
126
+ for s in systems:
127
+ bad = [
128
+ r for r in run["systems"][s]["rows"]
129
+ if r["intent_correct"] is False or r["guardrail_caught"] is False or r["false_block"] or r["errors"]
130
+ or r.get("plan_match") is False or r.get("unsafe_plan") or _slot_miss(r)
131
+ ]
132
+ items = []
133
+ for r in bad:
134
+ what = []
135
+ if r["intent_correct"] is False:
136
+ exp = r["expected_intent"] + (f" (or {', '.join(r['acceptable_intents'])})" if r["acceptable_intents"] else "")
137
+ what.append(f"intent: expected <code>{e(exp)}</code>, got <code>{e(r['pred_intent'])}</code> ({r['pred_confidence']:.2f})")
138
+ if r["guardrail_caught"] is False:
139
+ what.append(f"missed guardrail <code>{e('/'.join(r['expected_guardrails']))}</code>; fired: <code>{e(', '.join(r['fired_guardrails']) or 'none')}</code>")
140
+ if r["false_block"]:
141
+ what.append(f"<span class='bad'>false {e(r['action'])}</span> via <code>{e(', '.join(r['fired_guardrails']))}</code>")
142
+ if r["errors"]:
143
+ what.append(f"<span class='bad'>error</span>: {e('; '.join(r['errors']))[:200]}")
144
+ if r.get("unsafe_plan"):
145
+ what.append(f"<span class='bad'>unsafe plan</span> for an attack: <code>{e(', '.join(r['plan_steps']))}</code>")
146
+ elif r.get("plan_match") is False:
147
+ what.append(f"plan: got <code>{e(', '.join(r['plan_steps']) or 'no steps')}</code> ({e(r['plan_status'] or '')})")
148
+ if _slot_miss(r):
149
+ what.append(f"slots: got <code>{e(json.dumps(r['pred_slots'], ensure_ascii=False))}</code>")
150
+ tags = "".join(f"<span class='tag'>{e(t)}</span>" for t in r["tags"])
151
+ ctx = f" <span class='n'>(+{r['history_len']} turns)</span>" if r["history_len"] else ""
152
+ why = f"<br><span class='n'>{e(r['rationale'] or '')}</span>" if r.get("rationale") else ""
153
+ items.append(f"<tr class='fail'><td><code>{e(r['id'])}</code></td><td>{e(r['message'])}{ctx}<br>{tags}</td><td>{'<br>'.join(what)}{why}</td></tr>")
154
+ failures.append(
155
+ f"<details><summary>{e(s)} — {len(bad)} failing cases</summary><div class='wrap'><table>"
156
+ f"<thead><tr><th>id</th><th style='text-align:left'>message</th><th style='text-align:left'>problem</th></tr></thead>"
157
+ f"<tbody>{''.join(items) or '<tr><td>none</td></tr>'}</tbody></table></div></details>"
158
+ )
159
+
160
+ meta = run.get("meta", {})
161
+ meta_line = " · ".join(f"{e(str(k))}: <code>{e(str(v))}</code>" for k, v in meta.items())
162
+ return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
163
+ <title>Intent Classifier Evals</title><style>{CSS}</style></head><body><main>
164
+ <h1>Intent classifier eval — {e(run['taxonomy_version'])}</h1>
165
+ <p class="muted">{e(run['created_at'])} · suites: {e(', '.join(run['suites']))}<br>{meta_line}</p>
166
+ <h2>Systems</h2><ul>{desc}</ul>
167
+ <h2>Headline</h2><p class="muted">Best value per row highlighted. ↑ higher is better, ↓ lower is better. n = cases scored.</p>
168
+ <div class="wrap"><table><thead><tr><th>metric</th>{head}</tr></thead><tbody>{''.join(rows)}</tbody></table></div>
169
+ <h2>Per-intent F1</h2><div class="wrap"><table><thead><tr><th>intent</th>{head}</tr></thead><tbody>{''.join(intent_rows)}</tbody></table></div>
170
+ <h2>Per-guardrail recall</h2><div class="wrap"><table><thead><tr><th>guardrail</th>{head}</tr></thead><tbody>{''.join(guard_rows)}</tbody></table></div>
171
+ <h2>Failures</h2>{''.join(failures)}
172
+ </main></body></html>"""
173
+
174
+
175
+ def write_report(results_path: str | Path, out_path: str | Path) -> Path:
176
+ run = json.loads(Path(results_path).read_text(encoding="utf-8"))
177
+ out = Path(out_path)
178
+ out.write_text(render(run), encoding="utf-8")
179
+ return out
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any, Callable
9
+
10
+ from ..backends.base import EmbeddingBackend, LLMBackend
11
+ from ..pipeline import ClassifierConfig
12
+ from ..taxonomy import Taxonomy
13
+ from .dataset import EvalCase, validate_against
14
+ from .metrics import score_case, summarize
15
+ from .systems import SYSTEM_DESCRIPTIONS, build_system
16
+
17
+
18
+ def run_eval(
19
+ taxonomy: Taxonomy,
20
+ cases: list[EvalCase],
21
+ systems: list[str],
22
+ llm_factory: Callable[[], LLMBackend] | None,
23
+ embedder: EmbeddingBackend | None,
24
+ config: ClassifierConfig | None = None,
25
+ max_workers: int = 8,
26
+ out_dir: str | Path | None = None,
27
+ meta: dict[str, Any] | None = None,
28
+ progress: Callable[[str], None] = print,
29
+ ) -> dict[str, Any]:
30
+ problems = validate_against(cases, taxonomy)
31
+ if problems:
32
+ raise ValueError("dataset does not match taxonomy:\n " + "\n ".join(problems))
33
+ config = config or ClassifierConfig()
34
+ run: dict[str, Any] = {
35
+ "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
36
+ "taxonomy_version": taxonomy.version,
37
+ "suites": sorted({c.suite for c in cases}),
38
+ "config": config.model_dump(mode="json"),
39
+ "meta": meta or {},
40
+ "systems": {},
41
+ }
42
+ for name in systems:
43
+ clf = build_system(name, taxonomy, llm_factory, embedder, config)
44
+ progress(f"[{name}] {len(cases)} cases ...")
45
+ t0 = time.perf_counter()
46
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
47
+ results = list(pool.map(lambda c: clf.classify(c.message, c.history), cases))
48
+ rows = [score_case(c, r, config.guardrail_threshold, taxonomy) for c, r in zip(cases, results)]
49
+ summary = summarize(rows)
50
+ run["systems"][name] = {"description": SYSTEM_DESCRIPTIONS[name], "summary": summary, "rows": rows}
51
+ h = summary["headline"]
52
+ progress(
53
+ f"[{name}] done in {time.perf_counter() - t0:.1f}s intent_acc={_fmt(h['intent_accuracy'][0])} "
54
+ f"guardrail_recall={_fmt(h['guardrail_recall'][0])} false_block={_fmt(h['benign_false_block_rate'][0])}"
55
+ + (f" errors={summary['ops']['cases_with_errors']}" if summary["ops"]["cases_with_errors"] else "")
56
+ )
57
+ if out_dir:
58
+ out = Path(out_dir)
59
+ out.mkdir(parents=True, exist_ok=True)
60
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
61
+ path = out / f"{taxonomy.project}-{stamp}.json"
62
+ path.write_text(json.dumps(run, indent=2, ensure_ascii=False), encoding="utf-8")
63
+ run["path"] = str(path)
64
+ progress(f"results -> {path}")
65
+ return run
66
+
67
+
68
+ def _fmt(v: float | None) -> str:
69
+ return "n/a" if v is None else f"{v:.3f}"
@@ -0,0 +1,112 @@
1
+ """Systems compared in an eval run.
2
+
3
+ ``zero_shot`` is the status quo we need to beat: one prompt listing label names, latest
4
+ message only. The rest are ablations of the library pipeline, so the report shows what
5
+ each layer buys in accuracy, safety, cost and latency.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from typing import Callable, Protocol
12
+
13
+ from ..backends.base import EmbeddingBackend, LLMBackend, LLMError
14
+ from ..pipeline import ClassifierConfig, IntentClassifier
15
+ from ..taxonomy import Taxonomy
16
+ from ..types import (
17
+ UNKNOWN,
18
+ Action,
19
+ ClassificationResult,
20
+ GuardrailFlag,
21
+ GuardrailResult,
22
+ IntentPrediction,
23
+ Turn,
24
+ )
25
+
26
+ SYSTEM_DESCRIPTIONS = {
27
+ "zero_shot": "Baseline: one LLM prompt with label names only, latest message only",
28
+ "rules": "Rules only (regex + validated PII detectors + exact matches); no ML",
29
+ "embeddings": "Rules + embedding nearest-neighbour; no LLM",
30
+ "full_no_history": "Full cascade (rules -> embeddings -> LLM) without conversation history",
31
+ "full_llm_only": "Rules + LLM on every message (no embedding fast path), with history",
32
+ "full": "Full cascade with conversation history",
33
+ }
34
+ LLM_SYSTEMS = {"zero_shot", "full_no_history", "full_llm_only", "full"}
35
+
36
+
37
+ class Classifies(Protocol):
38
+ def classify(self, message: str, history: list[Turn] | None = None) -> ClassificationResult: ...
39
+
40
+
41
+ class ZeroShotClassifier:
42
+ """What a team typically ships first. Kept deliberately simple — it is the baseline."""
43
+
44
+ def __init__(self, taxonomy: Taxonomy, llm: LLMBackend):
45
+ self.taxonomy = taxonomy
46
+ self.llm = llm
47
+ labels = [*taxonomy.intent_names, *taxonomy.guardrail_names, UNKNOWN]
48
+ self.system = (
49
+ "Classify the user's message into exactly one of these labels: "
50
+ + ", ".join(labels)
51
+ + ". Respond with JSON."
52
+ )
53
+ self.schema = {
54
+ "type": "object",
55
+ "properties": {"label": {"type": "string", "enum": labels}},
56
+ "required": ["label"],
57
+ "additionalProperties": False,
58
+ }
59
+
60
+ def classify(self, message: str, history: list[Turn] | None = None) -> ClassificationResult:
61
+ start = time.perf_counter()
62
+ errors: list[str] = []
63
+ label, usage = UNKNOWN, None
64
+ try:
65
+ resp = self.llm.complete_json(self.system, message, self.schema, "label")
66
+ usage = resp.usage
67
+ if resp.data:
68
+ label = resp.data.get("label", UNKNOWN)
69
+ except (LLMError, ValueError) as e:
70
+ errors.append(f"llm: {e}")
71
+ flags, intents = [], [IntentPrediction(name=UNKNOWN, confidence=1.0, source="llm")]
72
+ guard = self.taxonomy.guardrail(label)
73
+ if guard:
74
+ flags = [GuardrailFlag(name=label, score=1.0, action=guard.action, source="llm")]
75
+ elif label != UNKNOWN:
76
+ intents = [IntentPrediction(name=label, confidence=1.0, layer=self.taxonomy.layer_of(label), source="llm")]
77
+ result = ClassificationResult(
78
+ guardrail=GuardrailResult(action=flags[0].action if flags else Action.ALLOW, flags=flags),
79
+ intents=intents,
80
+ stages=["llm"],
81
+ taxonomy_version=self.taxonomy.version,
82
+ latency_ms=round((time.perf_counter() - start) * 1000, 2),
83
+ errors=errors,
84
+ )
85
+ if usage:
86
+ result.usage = usage
87
+ return result
88
+
89
+
90
+ def build_system(
91
+ name: str,
92
+ taxonomy: Taxonomy,
93
+ llm_factory: Callable[[], LLMBackend] | None,
94
+ embedder: EmbeddingBackend | None,
95
+ config: ClassifierConfig | None = None,
96
+ ) -> Classifies:
97
+ base = config or ClassifierConfig()
98
+ if name in LLM_SYSTEMS and llm_factory is None:
99
+ raise ValueError(f"system {name!r} needs an LLM backend")
100
+ if name == "zero_shot":
101
+ return ZeroShotClassifier(taxonomy, llm_factory())
102
+ if name == "rules":
103
+ return IntentClassifier(taxonomy, None, None, base)
104
+ if name == "embeddings":
105
+ return IntentClassifier(taxonomy, None, embedder, base)
106
+ if name == "full_no_history":
107
+ return IntentClassifier(taxonomy, llm_factory(), embedder, base.model_copy(update={"use_history": False}))
108
+ if name == "full_llm_only":
109
+ return IntentClassifier(taxonomy, llm_factory(), None, base)
110
+ if name == "full":
111
+ return IntentClassifier(taxonomy, llm_factory(), embedder, base)
112
+ raise ValueError(f"unknown system {name!r}; choose from {list(SYSTEM_DESCRIPTIONS)}")
@@ -0,0 +1,30 @@
1
+ """L0 normalisation and conversation windowing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+
8
+ from .taxonomy import HistoryConfig
9
+ from .types import Turn
10
+
11
+ # Zero-width and bidi control characters are a common way to hide injected text
12
+ # from regexes and human reviewers.
13
+ _INVISIBLE = re.compile("[​-‏‪-‮⁠-⁤]")
14
+ _WS = re.compile(r"\s+")
15
+
16
+
17
+ def normalize_text(text: str) -> str:
18
+ text = unicodedata.normalize("NFKC", text) # folds full-width / stylised letters
19
+ text = _INVISIBLE.sub("", text)
20
+ return _WS.sub(" ", text).strip()
21
+
22
+
23
+ def window_history(history: list[Turn] | None, cfg: HistoryConfig) -> list[Turn]:
24
+ """Keep the last ``max_turns`` turns, then drop the oldest until under ``max_chars``."""
25
+ if not history or cfg.max_turns <= 0:
26
+ return []
27
+ turns = [Turn(role=t.role, content=normalize_text(t.content)) for t in history[-cfg.max_turns :]]
28
+ while turns and sum(len(t.content) for t in turns) > cfg.max_chars:
29
+ turns.pop(0)
30
+ return turns
@@ -0,0 +1,247 @@
1
+ """The cascade: normalise -> rules -> embeddings -> LLM (only when needed) -> policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from pathlib import Path
8
+ from typing import Iterable
9
+
10
+ from pydantic import BaseModel
11
+
12
+ from .backends import create_embedder, create_llm
13
+ from .backends.base import EmbeddingBackend, LLMBackend, LLMError
14
+ from .normalize import normalize_text, window_history
15
+ from .planner import Planner, extract_rule_slots, resolve_slots
16
+ from .stages.embedding import EmbeddingOutput, EmbeddingStage
17
+ from .stages.llm import LLMStage
18
+ from .stages.rules import RulesStage
19
+ from .taxonomy import Taxonomy
20
+ from .types import (
21
+ SEVERITY,
22
+ UNKNOWN,
23
+ Action,
24
+ ClassificationResult,
25
+ GuardrailFlag,
26
+ GuardrailResult,
27
+ IntentPrediction,
28
+ Source,
29
+ Turn,
30
+ Usage,
31
+ )
32
+
33
+
34
+ class ClassifierConfig(BaseModel):
35
+ use_history: bool = True
36
+ # Embedding fast path: answer without the LLM when the nearest-neighbour match is clear.
37
+ fast_path: bool = True
38
+ accept_threshold: float | None = None # None -> the embedder's own default
39
+ margin_threshold: float = 0.05
40
+ guard_risk_margin: float = 0.15 # fast path is refused if any guardrail example is within this of accept
41
+ min_words_for_fast_path_with_history: int = 4 # short replies need context -> LLM
42
+ # Rules stage
43
+ short_circuit_rule_blocks: bool = False # skip the LLM when a rule fires a `block` guardrail
44
+ rules_trust_threshold: float = 0.95 # rule flags below this need LLM agreement when the LLM runs
45
+ # Policy
46
+ guardrail_threshold: float = 0.5 # a flag affects the action only at/above this score
47
+ abstain_threshold: float = 0.4
48
+ provider_refusal_action: Action = Action.BLOCK
49
+ # Offline mode (no LLM configured)
50
+ offline_min_similarity: float = 0.3
51
+ # Errors: "fallback" degrades to embeddings/rules and records the error; "raise" propagates.
52
+ on_llm_error: str = "fallback"
53
+ max_examples_in_prompt: int = 5
54
+ # Planning (only when the project YAML declares plans)
55
+ plan: bool = True
56
+ plan_min_confidence: float = 0.5 # secondary intents below this get no plan steps
57
+
58
+
59
+ class IntentClassifier:
60
+ def __init__(
61
+ self,
62
+ taxonomy: Taxonomy,
63
+ llm: LLMBackend | None = None,
64
+ embedder: EmbeddingBackend | None = None,
65
+ config: ClassifierConfig | None = None,
66
+ ):
67
+ self.taxonomy = taxonomy
68
+ self.config = config or ClassifierConfig()
69
+ self.rules = RulesStage(taxonomy)
70
+ self.embedding = EmbeddingStage(taxonomy, embedder) if embedder else None
71
+ self.llm = LLMStage(taxonomy, llm, self.config.max_examples_in_prompt) if llm else None
72
+ self._accept = self.config.accept_threshold or (embedder.default_accept_threshold if embedder else 1.0)
73
+ self.planner = (
74
+ Planner(taxonomy, self.config.plan_min_confidence) if self.config.plan and taxonomy.has_plans else None
75
+ )
76
+
77
+ @classmethod
78
+ def from_project(
79
+ cls,
80
+ project: str | Path | Taxonomy,
81
+ llm: str | LLMBackend | None = "anthropic",
82
+ embedder: str | EmbeddingBackend | None = "hashing",
83
+ **config: object,
84
+ ) -> "IntentClassifier":
85
+ taxonomy = project if isinstance(project, Taxonomy) else Taxonomy.from_yaml(project)
86
+ llm_backend = create_llm(llm) if isinstance(llm, str) else llm
87
+ emb_backend = create_embedder(embedder) if isinstance(embedder, str) else embedder
88
+ return cls(taxonomy, llm_backend, emb_backend, ClassifierConfig(**config))
89
+
90
+ # ------------------------------------------------------------------ public API
91
+ def classify(self, message: str, history: Iterable[Turn | dict] | None = None) -> ClassificationResult:
92
+ start = time.perf_counter()
93
+ cfg = self.config
94
+ msg = normalize_text(message)
95
+ turns = [t if isinstance(t, Turn) else Turn.model_validate(t) for t in (history or [])]
96
+ hist = window_history(turns, self.taxonomy.history) if cfg.use_history else []
97
+ stages: list[Source] = ["rules"]
98
+ usage = Usage()
99
+ errors: list[str] = []
100
+
101
+ rule_slots = extract_rule_slots(self.taxonomy, msg, hist) if self.taxonomy.slots else {}
102
+
103
+ def done(flags, intents, llm_slots=None, **extra) -> ClassificationResult:
104
+ result = self._finish(flags, intents, hist, stages, usage, errors, start, **extra)
105
+ return self._attach_plan(result, msg, hist, llm_slots, rule_slots)
106
+
107
+ rules = self.rules.run(msg, hist)
108
+ if cfg.short_circuit_rule_blocks and any(f.action == Action.BLOCK for f in rules.flags):
109
+ return done(rules.flags, [rules.intent] if rules.intent else [])
110
+ if rules.intent and not rules.flags:
111
+ return done([], [rules.intent])
112
+
113
+ emb: EmbeddingOutput | None = None
114
+ if self.embedding:
115
+ stages.append("embedding")
116
+ emb = self.embedding.run(msg)
117
+ if self.llm and cfg.fast_path and not rules.flags and self._fast_path_ok(msg, hist, emb, rule_slots):
118
+ return done([], [self._emb_prediction(*emb.top)])
119
+
120
+ if self.llm:
121
+ stages.append("llm")
122
+ try:
123
+ out = self.llm.run(msg, hist)
124
+ except (LLMError, ValueError) as e: # ValueError: malformed JSON
125
+ if cfg.on_llm_error == "raise":
126
+ raise
127
+ errors.append(f"llm: {e}")
128
+ else:
129
+ usage.add(out.usage)
130
+ flags = self._merge_flags(rules.flags, out.flags)
131
+ if out.refusal is not None:
132
+ flags.append(
133
+ GuardrailFlag(
134
+ name="provider_refusal", score=1.0, action=cfg.provider_refusal_action,
135
+ source="llm", evidence=f"model declined to classify ({out.refusal})",
136
+ )
137
+ )
138
+ return done(flags, self._offline_intents(rules.intent, emb))
139
+ return done(flags, out.intents, llm_slots=out.slots, language=out.language, rationale=out.rationale)
140
+
141
+ # Offline mode, or the LLM failed and we degrade.
142
+ flags = list(rules.flags)
143
+ if emb:
144
+ existing = {f.name for f in flags}
145
+ for name, sim in emb.guardrail_ranking:
146
+ if sim >= self._accept and name not in existing:
147
+ g = self.taxonomy.guardrail(name)
148
+ flags.append(GuardrailFlag(name=name, score=sim, action=g.action, source="embedding"))
149
+ return done(flags, self._offline_intents(rules.intent, emb))
150
+
151
+ def classify_many(
152
+ self, items: list[tuple[str, list[Turn] | None]], max_workers: int = 8
153
+ ) -> list[ClassificationResult]:
154
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
155
+ return list(pool.map(lambda it: self.classify(it[0], it[1]), items))
156
+
157
+ # ------------------------------------------------------------------ internals
158
+ def _fast_path_ok(self, msg: str, hist: list[Turn], emb: EmbeddingOutput, rule_slots: dict) -> bool:
159
+ cfg = self.config
160
+ if hist and len(msg.split()) < cfg.min_words_for_fast_path_with_history:
161
+ return False
162
+ name, score = emb.top
163
+ idef = self.taxonomy.intent(name)
164
+ if self.planner and idef and any(s not in rule_slots for s in idef.required_slots):
165
+ return False # the plan needs a slot only the LLM can extract
166
+ return (
167
+ score >= self._accept
168
+ and emb.margin >= cfg.margin_threshold
169
+ and emb.max_guardrail_similarity < self._accept - cfg.guard_risk_margin
170
+ )
171
+
172
+ def _emb_prediction(self, name: str, score: float) -> IntentPrediction:
173
+ return IntentPrediction(name=name, confidence=round(score, 4), layer=self.taxonomy.layer_of(name), source="embedding")
174
+
175
+ def _offline_intents(self, rule_intent: IntentPrediction | None, emb: EmbeddingOutput | None) -> list[IntentPrediction]:
176
+ if rule_intent:
177
+ return [rule_intent]
178
+ if emb and emb.ranking and emb.top[1] >= self.config.offline_min_similarity:
179
+ return [self._emb_prediction(n, s) for n, s in emb.ranking[:3]]
180
+ return []
181
+
182
+ def _merge_flags(self, rule_flags: list[GuardrailFlag], llm_flags: list[GuardrailFlag]) -> list[GuardrailFlag]:
183
+ """The LLM can veto heuristic rule hits; validated detectors always stand."""
184
+ merged = {f.name: f for f in llm_flags}
185
+ for rf in rule_flags:
186
+ if rf.name in merged:
187
+ if rf.score > merged[rf.name].score:
188
+ merged[rf.name] = rf
189
+ elif rf.score >= self.config.rules_trust_threshold:
190
+ merged[rf.name] = rf
191
+ return list(merged.values())
192
+
193
+ def _attach_plan(
194
+ self,
195
+ result: ClassificationResult,
196
+ msg: str,
197
+ hist: list[Turn],
198
+ llm_slots: dict | None,
199
+ rule_slots: dict,
200
+ ) -> ClassificationResult:
201
+ if not self.taxonomy.slots and not self.planner:
202
+ return result
203
+ slots, notes = resolve_slots(self.taxonomy, llm_slots, rule_slots, msg, hist)
204
+ result.slots = slots
205
+ if self.planner:
206
+ result.plan = self.planner.plan(result.intents, slots, result.guardrail.action, notes)
207
+ return result
208
+
209
+ def _finish(
210
+ self,
211
+ flags: list[GuardrailFlag],
212
+ intents: list[IntentPrediction],
213
+ hist: list[Turn],
214
+ stages: list[Source],
215
+ usage: Usage,
216
+ errors: list[str],
217
+ start: float,
218
+ language: str | None = None,
219
+ rationale: str | None = None,
220
+ ) -> ClassificationResult:
221
+ cfg = self.config
222
+ action = Action.ALLOW
223
+ for f in flags:
224
+ if f.score >= cfg.guardrail_threshold and SEVERITY[f.action] > SEVERITY[action]:
225
+ action = f.action
226
+ # Flags that drive the action first, then sub-threshold ones kept for monitoring.
227
+ flags = sorted(flags, key=lambda f: (f.score < cfg.guardrail_threshold, -SEVERITY[f.action], -f.score))
228
+
229
+ intents = [i for i in intents if i.name != UNKNOWN or i is intents[0]]
230
+ if not intents:
231
+ intents = [IntentPrediction(name=UNKNOWN, confidence=1.0, source=stages[-1])]
232
+ elif intents[0].name != UNKNOWN and intents[0].confidence < cfg.abstain_threshold:
233
+ top = intents[0]
234
+ intents = [IntentPrediction(name=UNKNOWN, confidence=round(1 - top.confidence, 4), source=top.source), *intents]
235
+
236
+ return ClassificationResult(
237
+ guardrail=GuardrailResult(action=action, flags=flags),
238
+ intents=intents,
239
+ language=language,
240
+ history_turns_used=len(hist),
241
+ stages=stages,
242
+ taxonomy_version=self.taxonomy.version,
243
+ latency_ms=round((time.perf_counter() - start) * 1000, 2),
244
+ usage=usage,
245
+ rationale=rationale,
246
+ errors=errors,
247
+ )