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.
- intent_classify/__init__.py +70 -0
- intent_classify/__main__.py +3 -0
- intent_classify/_env.py +30 -0
- intent_classify/_version.py +3 -0
- intent_classify/backends/__init__.py +53 -0
- intent_classify/backends/anthropic_backend.py +100 -0
- intent_classify/backends/base.py +50 -0
- intent_classify/backends/embeddings.py +78 -0
- intent_classify/backends/openai_backend.py +66 -0
- intent_classify/builtin/guardrails.yaml +151 -0
- intent_classify/builtin/universal.yaml +75 -0
- intent_classify/cli.py +281 -0
- intent_classify/evals/__init__.py +23 -0
- intent_classify/evals/data/core_guardrails.jsonl +37 -0
- intent_classify/evals/data/core_universal.jsonl +38 -0
- intent_classify/evals/dataset.py +113 -0
- intent_classify/evals/gate.py +34 -0
- intent_classify/evals/generate.py +237 -0
- intent_classify/evals/leakage.py +22 -0
- intent_classify/evals/metrics.py +274 -0
- intent_classify/evals/public.py +123 -0
- intent_classify/evals/report.py +179 -0
- intent_classify/evals/runner.py +69 -0
- intent_classify/evals/systems.py +112 -0
- intent_classify/normalize.py +30 -0
- intent_classify/pipeline.py +247 -0
- intent_classify/planner.py +251 -0
- intent_classify/py.typed +0 -0
- intent_classify/stages/__init__.py +0 -0
- intent_classify/stages/embedding.py +55 -0
- intent_classify/stages/llm.py +207 -0
- intent_classify/stages/rules.py +113 -0
- intent_classify/taxonomy.py +336 -0
- intent_classify/types.py +145 -0
- intent_classify-0.2.0.dist-info/METADATA +205 -0
- intent_classify-0.2.0.dist-info/RECORD +41 -0
- intent_classify-0.2.0.dist-info/WHEEL +5 -0
- intent_classify-0.2.0.dist-info/entry_points.txt +3 -0
- intent_classify-0.2.0.dist-info/licenses/LICENSE +202 -0
- intent_classify-0.2.0.dist-info/licenses/NOTICE +4 -0
- intent_classify-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""Taxonomy = built-in guardrails + built-in universal intents + one project's intents.
|
|
2
|
+
|
|
3
|
+
Projects only write their own YAML; the shared layers are loaded from ``builtin/``
|
|
4
|
+
and can be selectively disabled or have their guardrail actions overridden.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from importlib import resources
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
import yaml
|
|
17
|
+
from pydantic import BaseModel, Field, field_validator, model_validator
|
|
18
|
+
|
|
19
|
+
from .types import UNKNOWN, Action, Layer
|
|
20
|
+
|
|
21
|
+
CORE_VERSION = "0.1.0"
|
|
22
|
+
_NAME_RE = re.compile(r"^[a-z][a-z0-9_]*(\.[a-z0-9_]+)*$")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class LabelDef(BaseModel):
|
|
26
|
+
name: str
|
|
27
|
+
description: str
|
|
28
|
+
examples: list[str] = Field(default_factory=list)
|
|
29
|
+
negative_examples: list[str] = Field(default_factory=list)
|
|
30
|
+
layer: Layer = "project"
|
|
31
|
+
|
|
32
|
+
@field_validator("name")
|
|
33
|
+
@classmethod
|
|
34
|
+
def _valid_name(cls, v: str) -> str:
|
|
35
|
+
if not _NAME_RE.match(v) or v == UNKNOWN:
|
|
36
|
+
raise ValueError(f"invalid label name {v!r}: use lowercase snake_case, dots for hierarchy")
|
|
37
|
+
return v
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def category(self) -> str:
|
|
41
|
+
return self.name.split(".", 1)[0]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
SlotType = Literal["string", "integer", "number", "boolean", "list", "enum"]
|
|
45
|
+
_REF_RE = re.compile(r"\{(\w+)\}")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SlotDef(BaseModel):
|
|
49
|
+
"""A value the planner needs, declared once per project and shared by intents."""
|
|
50
|
+
|
|
51
|
+
type: SlotType = "string"
|
|
52
|
+
description: str = ""
|
|
53
|
+
# Validates the value (full match; each item for lists). With a pattern the slot is an
|
|
54
|
+
# identifier: it must appear verbatim in the conversation, and the rules stage can
|
|
55
|
+
# extract it without an LLM.
|
|
56
|
+
pattern: str | None = None
|
|
57
|
+
values: list[str] = Field(default_factory=list) # for type: enum
|
|
58
|
+
from_history: bool = True # may be resolved from earlier turns ("cancel it")
|
|
59
|
+
grounded: bool | None = None # must appear in the conversation; default: True when pattern is set
|
|
60
|
+
max_length: int = 200
|
|
61
|
+
ask: str | None = None # clarifying question when the slot is missing
|
|
62
|
+
|
|
63
|
+
@model_validator(mode="after")
|
|
64
|
+
def _check(self) -> "SlotDef":
|
|
65
|
+
if self.type == "enum" and not self.values:
|
|
66
|
+
raise ValueError("enum slots need `values`")
|
|
67
|
+
if self.pattern:
|
|
68
|
+
re.compile(self.pattern)
|
|
69
|
+
if self.grounded is None:
|
|
70
|
+
self.grounded = bool(self.pattern)
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ToolDef(BaseModel):
|
|
75
|
+
description: str = ""
|
|
76
|
+
required_args: list[str] = Field(default_factory=list)
|
|
77
|
+
side_effect: bool = False # changes state (cancel, refund...) -> steps need confirmation by default
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class RetrieverDef(BaseModel):
|
|
81
|
+
description: str = ""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class PlanStepDef(BaseModel):
|
|
85
|
+
"""Template step. Exactly one of ``tool`` / ``retrieve`` / ``reply``.
|
|
86
|
+
|
|
87
|
+
``args`` values: ``"$slot"`` -> the slot's value (omitted when unset), ``"{slot} text"`` ->
|
|
88
|
+
interpolated string, anything else -> literal. ``$item`` / ``{item}`` refer to the current
|
|
89
|
+
element when ``for_each`` fans the step out over a list slot.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
id: str | None = None
|
|
93
|
+
tool: str | None = None
|
|
94
|
+
retrieve: str | None = None
|
|
95
|
+
reply: str | None = None
|
|
96
|
+
args: dict[str, Any] = Field(default_factory=dict)
|
|
97
|
+
query: str | None = None # shorthand for args.query on retrieve steps
|
|
98
|
+
for_each: str | None = None
|
|
99
|
+
when: str | None = None # include only if this slot is set
|
|
100
|
+
unless: str | None = None # include only if this slot is NOT set
|
|
101
|
+
depends_on: list[str] = Field(default_factory=list)
|
|
102
|
+
confirm: bool | None = None # default: the tool's side_effect
|
|
103
|
+
|
|
104
|
+
@model_validator(mode="after")
|
|
105
|
+
def _one_kind(self) -> "PlanStepDef":
|
|
106
|
+
kinds = [k for k in ("tool", "retrieve", "reply") if getattr(self, k)]
|
|
107
|
+
if len(kinds) != 1:
|
|
108
|
+
raise ValueError(f"a plan step needs exactly one of tool/retrieve/reply, got {kinds or 'none'}")
|
|
109
|
+
if self.query is not None:
|
|
110
|
+
if not self.retrieve:
|
|
111
|
+
raise ValueError("`query` is only valid on retrieve steps")
|
|
112
|
+
self.args = {"query": self.query, **self.args}
|
|
113
|
+
if self.id is None:
|
|
114
|
+
self.id = (self.tool or self.retrieve or self.reply or "").replace(".", "_")
|
|
115
|
+
return self
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def kind(self) -> Literal["tool", "retrieve", "reply"]:
|
|
119
|
+
if self.tool:
|
|
120
|
+
return "tool"
|
|
121
|
+
return "retrieve" if self.retrieve else "reply"
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def target(self) -> str:
|
|
125
|
+
return self.tool or self.retrieve or self.reply or ""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class IntentDef(LabelDef):
|
|
129
|
+
slots: dict[str, Literal["required", "optional"]] = Field(default_factory=dict)
|
|
130
|
+
plan: list[PlanStepDef] = Field(default_factory=list)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def required_slots(self) -> list[str]:
|
|
134
|
+
return [s for s, r in self.slots.items() if r == "required"]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _arg_refs(value: Any) -> set[str]:
|
|
138
|
+
"""Slot names referenced by a template arg value."""
|
|
139
|
+
if isinstance(value, str):
|
|
140
|
+
if value.startswith("$"):
|
|
141
|
+
return {value[1:]}
|
|
142
|
+
return set(_REF_RE.findall(value))
|
|
143
|
+
if isinstance(value, dict):
|
|
144
|
+
return set().union(*(_arg_refs(v) for v in value.values())) if value else set()
|
|
145
|
+
if isinstance(value, list):
|
|
146
|
+
return set().union(*(_arg_refs(v) for v in value)) if value else set()
|
|
147
|
+
return set()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _check_plans(
|
|
151
|
+
intents: list[IntentDef], slots: dict[str, SlotDef], tools: dict[str, ToolDef], retrievers: dict[str, RetrieverDef]
|
|
152
|
+
) -> None:
|
|
153
|
+
"""Fail at load time, not at runtime, on any dangling reference in a plan."""
|
|
154
|
+
for intent in intents:
|
|
155
|
+
for s in intent.slots:
|
|
156
|
+
if s not in slots:
|
|
157
|
+
raise ValueError(f"intent {intent.name!r}: unknown slot {s!r} (declare it under top-level `slots:`)")
|
|
158
|
+
seen: set[str] = set()
|
|
159
|
+
for step in intent.plan:
|
|
160
|
+
where = f"intent {intent.name!r}, step {step.id!r}"
|
|
161
|
+
if step.id in seen:
|
|
162
|
+
raise ValueError(f"{where}: duplicate step id")
|
|
163
|
+
bad_deps = [d for d in step.depends_on if d not in seen]
|
|
164
|
+
if bad_deps:
|
|
165
|
+
raise ValueError(f"{where}: depends_on {bad_deps} must name earlier steps")
|
|
166
|
+
seen.add(step.id)
|
|
167
|
+
_check_step(where, step, intent, slots, tools, retrievers)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _check_step(
|
|
171
|
+
where: str,
|
|
172
|
+
step: PlanStepDef,
|
|
173
|
+
intent: IntentDef,
|
|
174
|
+
slots: dict[str, SlotDef],
|
|
175
|
+
tools: dict[str, ToolDef],
|
|
176
|
+
retrievers: dict[str, RetrieverDef],
|
|
177
|
+
) -> None:
|
|
178
|
+
if step.tool and step.tool not in tools:
|
|
179
|
+
raise ValueError(f"{where}: unknown tool {step.tool!r} (declare it under `tools:`)")
|
|
180
|
+
if step.retrieve and step.retrieve not in retrievers:
|
|
181
|
+
raise ValueError(f"{where}: unknown retriever {step.retrieve!r} (declare it under `retrievers:`)")
|
|
182
|
+
missing = set(tools[step.tool].required_args) - set(step.args) if step.tool else set()
|
|
183
|
+
if missing:
|
|
184
|
+
raise ValueError(f"{where}: tool {step.tool!r} requires args {sorted(missing)}")
|
|
185
|
+
if step.for_each and (step.for_each not in intent.slots or slots[step.for_each].type != "list"):
|
|
186
|
+
raise ValueError(f"{where}: for_each must name a list slot of this intent")
|
|
187
|
+
allowed = set(intent.slots) | ({"item"} if step.for_each else set())
|
|
188
|
+
bad_refs = sorted((_arg_refs(step.args) | {r for r in (step.when, step.unless) if r}) - allowed)
|
|
189
|
+
if bad_refs:
|
|
190
|
+
raise ValueError(f"{where}: references {bad_refs}, which are not slots of this intent")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class GuardrailDef(LabelDef):
|
|
194
|
+
layer: Layer = "guardrail"
|
|
195
|
+
action: Action = Action.BLOCK
|
|
196
|
+
# High-precision regexes for the rules stage. Keep them strict: a match can
|
|
197
|
+
# short-circuit the pipeline without an LLM call.
|
|
198
|
+
patterns: list[str] = Field(default_factory=list)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class HistoryConfig(BaseModel):
|
|
202
|
+
max_turns: int = 6
|
|
203
|
+
max_chars: int = 4000
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class CoreOverrides(BaseModel):
|
|
207
|
+
disable_intents: list[str] = Field(default_factory=list)
|
|
208
|
+
disable_guardrails: list[str] = Field(default_factory=list)
|
|
209
|
+
guardrail_actions: dict[str, Action] = Field(default_factory=dict)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class ProjectSpec(BaseModel):
|
|
213
|
+
"""Schema of a project YAML file."""
|
|
214
|
+
|
|
215
|
+
project: str
|
|
216
|
+
version: str = "0.1.0"
|
|
217
|
+
domain: str = Field(description="One or two sentences on what the assistant is for; drives off-topic detection.")
|
|
218
|
+
languages: list[str] = Field(default_factory=lambda: ["en"])
|
|
219
|
+
history: HistoryConfig = Field(default_factory=HistoryConfig)
|
|
220
|
+
core: CoreOverrides = Field(default_factory=CoreOverrides)
|
|
221
|
+
# Planning (optional): slots are shared by intents; tools and retrievers are what plan
|
|
222
|
+
# steps may call. The library only plans — the caller's executor runs the steps.
|
|
223
|
+
slots: dict[str, SlotDef] = Field(default_factory=dict)
|
|
224
|
+
tools: dict[str, ToolDef] = Field(default_factory=dict)
|
|
225
|
+
retrievers: dict[str, RetrieverDef] = Field(default_factory=dict)
|
|
226
|
+
intents: list[IntentDef]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class Taxonomy(BaseModel):
|
|
230
|
+
project: str
|
|
231
|
+
project_version: str
|
|
232
|
+
domain: str
|
|
233
|
+
languages: list[str]
|
|
234
|
+
history: HistoryConfig
|
|
235
|
+
guardrails: list[GuardrailDef]
|
|
236
|
+
intents: list[IntentDef] # universal + project
|
|
237
|
+
slots: dict[str, SlotDef] = Field(default_factory=dict)
|
|
238
|
+
tools: dict[str, ToolDef] = Field(default_factory=dict)
|
|
239
|
+
retrievers: dict[str, RetrieverDef] = Field(default_factory=dict)
|
|
240
|
+
|
|
241
|
+
@model_validator(mode="after")
|
|
242
|
+
def _unique_names(self) -> "Taxonomy":
|
|
243
|
+
seen: set[str] = set()
|
|
244
|
+
for label in [*self.guardrails, *self.intents]:
|
|
245
|
+
if label.name in seen:
|
|
246
|
+
raise ValueError(f"duplicate label {label.name!r} (project intents may not reuse built-in names)")
|
|
247
|
+
seen.add(label.name)
|
|
248
|
+
_check_plans(self.intents, self.slots, self.tools, self.retrievers)
|
|
249
|
+
return self
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def has_plans(self) -> bool:
|
|
253
|
+
return any(i.plan for i in self.intents)
|
|
254
|
+
|
|
255
|
+
# -- lookup -----------------------------------------------------------------
|
|
256
|
+
@property
|
|
257
|
+
def intent_names(self) -> list[str]:
|
|
258
|
+
return [i.name for i in self.intents]
|
|
259
|
+
|
|
260
|
+
@property
|
|
261
|
+
def guardrail_names(self) -> list[str]:
|
|
262
|
+
return [g.name for g in self.guardrails]
|
|
263
|
+
|
|
264
|
+
def intent(self, name: str) -> IntentDef | None:
|
|
265
|
+
return next((i for i in self.intents if i.name == name), None)
|
|
266
|
+
|
|
267
|
+
def guardrail(self, name: str) -> GuardrailDef | None:
|
|
268
|
+
return next((g for g in self.guardrails if g.name == name), None)
|
|
269
|
+
|
|
270
|
+
def layer_of(self, name: str) -> Layer | None:
|
|
271
|
+
label = self.intent(name) or self.guardrail(name)
|
|
272
|
+
return label.layer if label else None
|
|
273
|
+
|
|
274
|
+
@property
|
|
275
|
+
def fingerprint(self) -> str:
|
|
276
|
+
payload = json.dumps(self.model_dump(mode="json"), sort_keys=True).encode()
|
|
277
|
+
return hashlib.sha256(payload).hexdigest()[:10]
|
|
278
|
+
|
|
279
|
+
@property
|
|
280
|
+
def version(self) -> str:
|
|
281
|
+
"""e.g. ``shopease@0.1.0+core0.1.0#a1b2c3d4e5`` — the hash catches unversioned edits."""
|
|
282
|
+
return f"{self.project}@{self.project_version}+core{CORE_VERSION}#{self.fingerprint}"
|
|
283
|
+
|
|
284
|
+
# -- loading ----------------------------------------------------------------
|
|
285
|
+
@classmethod
|
|
286
|
+
def from_spec(cls, spec: ProjectSpec) -> "Taxonomy":
|
|
287
|
+
guardrails = [
|
|
288
|
+
g.model_copy(update={"action": spec.core.guardrail_actions.get(g.name, g.action)})
|
|
289
|
+
for g in load_builtin_guardrails()
|
|
290
|
+
if g.name not in spec.core.disable_guardrails
|
|
291
|
+
]
|
|
292
|
+
universal = [i for i in load_builtin_universal() if i.name not in spec.core.disable_intents]
|
|
293
|
+
_check_known(spec.core.disable_guardrails, [g.name for g in load_builtin_guardrails()], "guardrail")
|
|
294
|
+
_check_known(list(spec.core.guardrail_actions), [g.name for g in load_builtin_guardrails()], "guardrail")
|
|
295
|
+
_check_known(spec.core.disable_intents, [i.name for i in load_builtin_universal()], "universal intent")
|
|
296
|
+
project_intents = [i.model_copy(update={"layer": "project"}) for i in spec.intents]
|
|
297
|
+
return cls(
|
|
298
|
+
project=spec.project,
|
|
299
|
+
project_version=spec.version,
|
|
300
|
+
domain=spec.domain,
|
|
301
|
+
languages=spec.languages,
|
|
302
|
+
history=spec.history,
|
|
303
|
+
guardrails=guardrails,
|
|
304
|
+
intents=[*universal, *project_intents],
|
|
305
|
+
slots=spec.slots,
|
|
306
|
+
tools=spec.tools,
|
|
307
|
+
retrievers=spec.retrievers,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
@classmethod
|
|
311
|
+
def from_dict(cls, data: dict[str, Any]) -> "Taxonomy":
|
|
312
|
+
return cls.from_spec(ProjectSpec.model_validate(data))
|
|
313
|
+
|
|
314
|
+
@classmethod
|
|
315
|
+
def from_yaml(cls, path: str | Path) -> "Taxonomy":
|
|
316
|
+
with open(path, encoding="utf-8") as f:
|
|
317
|
+
return cls.from_dict(yaml.safe_load(f))
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _check_known(names: list[str], known: list[str], kind: str) -> None:
|
|
321
|
+
unknown = sorted(set(names) - set(known))
|
|
322
|
+
if unknown:
|
|
323
|
+
raise ValueError(f"unknown built-in {kind}(s) in core overrides: {unknown}")
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _load_builtin(filename: str) -> list[dict[str, Any]]:
|
|
327
|
+
text = resources.files("intent_classify.builtin").joinpath(filename).read_text(encoding="utf-8")
|
|
328
|
+
return yaml.safe_load(text)["labels"]
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def load_builtin_guardrails() -> list[GuardrailDef]:
|
|
332
|
+
return [GuardrailDef.model_validate({**d, "layer": "guardrail"}) for d in _load_builtin("guardrails.yaml")]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def load_builtin_universal() -> list[IntentDef]:
|
|
336
|
+
return [IntentDef.model_validate({**d, "layer": "universal"}) for d in _load_builtin("universal.yaml")]
|
intent_classify/types.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Public data types: conversation input and the stable classification result contract."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
Role = Literal["user", "assistant"]
|
|
11
|
+
Layer = Literal["guardrail", "universal", "project"]
|
|
12
|
+
Source = Literal["rules", "embedding", "llm"]
|
|
13
|
+
|
|
14
|
+
UNKNOWN = "unknown"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Turn(BaseModel):
|
|
18
|
+
role: Role
|
|
19
|
+
content: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Action(str, Enum):
|
|
23
|
+
"""What the caller should do. Ordered by severity (see ``SEVERITY``)."""
|
|
24
|
+
|
|
25
|
+
ALLOW = "allow"
|
|
26
|
+
FLAG = "flag" # proceed, but log / mask / monitor
|
|
27
|
+
ESCALATE = "escalate" # route to a human or a safe flow (e.g. self-harm)
|
|
28
|
+
BLOCK = "block" # refuse to process
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
SEVERITY = {Action.ALLOW: 0, Action.FLAG: 1, Action.ESCALATE: 2, Action.BLOCK: 3}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class GuardrailFlag(BaseModel):
|
|
35
|
+
name: str
|
|
36
|
+
score: float
|
|
37
|
+
action: Action
|
|
38
|
+
source: Source
|
|
39
|
+
evidence: str | None = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class GuardrailResult(BaseModel):
|
|
43
|
+
action: Action = Action.ALLOW
|
|
44
|
+
flags: list[GuardrailFlag] = Field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def triggered(self) -> bool:
|
|
48
|
+
return self.action != Action.ALLOW
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class IntentPrediction(BaseModel):
|
|
52
|
+
name: str
|
|
53
|
+
confidence: float
|
|
54
|
+
layer: Layer | None = None # None for the synthetic "unknown" label
|
|
55
|
+
source: Source
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Usage(BaseModel):
|
|
59
|
+
input_tokens: int = 0
|
|
60
|
+
output_tokens: int = 0
|
|
61
|
+
cache_read_tokens: int = 0
|
|
62
|
+
cache_write_tokens: int = 0
|
|
63
|
+
llm_calls: int = 0
|
|
64
|
+
estimated_cost_usd: float | None = None
|
|
65
|
+
|
|
66
|
+
def add(self, other: "Usage") -> None:
|
|
67
|
+
self.input_tokens += other.input_tokens
|
|
68
|
+
self.output_tokens += other.output_tokens
|
|
69
|
+
self.cache_read_tokens += other.cache_read_tokens
|
|
70
|
+
self.cache_write_tokens += other.cache_write_tokens
|
|
71
|
+
self.llm_calls += other.llm_calls
|
|
72
|
+
if other.estimated_cost_usd is not None:
|
|
73
|
+
self.estimated_cost_usd = (self.estimated_cost_usd or 0.0) + other.estimated_cost_usd
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
SlotSource = Literal["message", "history", "inferred"]
|
|
77
|
+
StepType = Literal["tool", "retrieve", "reply", "ask_user"]
|
|
78
|
+
PlanStatus = Literal["ready", "needs_input", "blocked", "no_plan"]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class SlotValue(BaseModel):
|
|
82
|
+
value: str | int | float | bool | list[str]
|
|
83
|
+
# Where the value was found: the latest message, an earlier turn, or neither (the LLM
|
|
84
|
+
# normalised it, e.g. "iphone15" -> "iPhone 15"). Identifier slots are never "inferred".
|
|
85
|
+
source: SlotSource
|
|
86
|
+
extractor: Literal["llm", "rules"]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class PlanStep(BaseModel):
|
|
90
|
+
"""One step for the caller's executor. The library plans; it never executes."""
|
|
91
|
+
|
|
92
|
+
id: str # "<intent>:<step id>", with "#<n>" appended for for_each fan-out
|
|
93
|
+
type: StepType
|
|
94
|
+
name: str # tool name | retriever name | reply key | "clarify"
|
|
95
|
+
args: dict[str, object] = Field(default_factory=dict)
|
|
96
|
+
depends_on: list[str] = Field(default_factory=list)
|
|
97
|
+
requires_confirmation: bool = False # side-effecting tools: confirm with the user first
|
|
98
|
+
intent: str
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def signature(self) -> str:
|
|
102
|
+
return self.type if self.type == "ask_user" else f"{self.type}:{self.name}"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Plan(BaseModel):
|
|
106
|
+
status: PlanStatus
|
|
107
|
+
steps: list[PlanStep] = Field(default_factory=list)
|
|
108
|
+
missing_slots: dict[str, list[str]] = Field(default_factory=dict) # intent -> required slots not found
|
|
109
|
+
notes: list[str] = Field(default_factory=list) # e.g. slot values dropped by validation
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ClassificationResult(BaseModel):
|
|
113
|
+
"""Stable output contract. Add fields; never rename or remove them."""
|
|
114
|
+
|
|
115
|
+
guardrail: GuardrailResult
|
|
116
|
+
# intents[0] is the primary, task-level intent of the latest user message, resolved
|
|
117
|
+
# with conversation context ("yes" -> the thing being confirmed). Dialogue acts such
|
|
118
|
+
# as `affirm` follow as secondary intents. Below the abstain threshold intents[0] is
|
|
119
|
+
# `unknown` and the low-confidence candidates follow it.
|
|
120
|
+
intents: list[IntentPrediction]
|
|
121
|
+
language: str | None = None
|
|
122
|
+
history_turns_used: int = 0
|
|
123
|
+
stages: list[Source] = Field(default_factory=list)
|
|
124
|
+
taxonomy_version: str
|
|
125
|
+
latency_ms: float
|
|
126
|
+
usage: Usage = Field(default_factory=Usage)
|
|
127
|
+
rationale: str | None = None
|
|
128
|
+
# Non-empty when a stage failed and the result came from a cheaper fallback stage.
|
|
129
|
+
errors: list[str] = Field(default_factory=list)
|
|
130
|
+
# Validated slot values (flat, project-level namespace) and the plan built from them.
|
|
131
|
+
# ``plan`` is None when the project declares no plans or the system doesn't plan.
|
|
132
|
+
slots: dict[str, SlotValue] = Field(default_factory=dict)
|
|
133
|
+
plan: Plan | None = None
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def top_intent(self) -> IntentPrediction:
|
|
137
|
+
return self.intents[0]
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def is_unknown(self) -> bool:
|
|
141
|
+
return self.top_intent.name == UNKNOWN
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def multi_intent(self) -> bool:
|
|
145
|
+
return sum(1 for i in self.intents if i.name != UNKNOWN and i.confidence >= 0.5) > 1
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: intent-classify
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Conversation-aware intent classification, guardrails and query planning for LLM assistants. Intents in YAML, evals built in.
|
|
5
|
+
Author: Shubhankar Saket
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Shubhankar-saket/Intent-classifier-sdk
|
|
8
|
+
Project-URL: Repository, https://github.com/Shubhankar-saket/Intent-classifier-sdk
|
|
9
|
+
Project-URL: Issues, https://github.com/Shubhankar-saket/Intent-classifier-sdk/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: intent-classification,guardrails,prompt-injection,llm,chatbot,query-planning,slot-filling,evaluation,anthropic,openai
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
License-File: NOTICE
|
|
28
|
+
Requires-Dist: pydantic>=2.6
|
|
29
|
+
Requires-Dist: pyyaml>=6
|
|
30
|
+
Requires-Dist: numpy>=1.26
|
|
31
|
+
Provides-Extra: anthropic
|
|
32
|
+
Requires-Dist: anthropic<2,>=1; extra == "anthropic"
|
|
33
|
+
Provides-Extra: openai
|
|
34
|
+
Requires-Dist: openai>=1.40; extra == "openai"
|
|
35
|
+
Provides-Extra: local-embeddings
|
|
36
|
+
Requires-Dist: sentence-transformers>=3; extra == "local-embeddings"
|
|
37
|
+
Provides-Extra: all
|
|
38
|
+
Requires-Dist: anthropic<2,>=1; extra == "all"
|
|
39
|
+
Requires-Dist: openai>=1.40; extra == "all"
|
|
40
|
+
Provides-Extra: dev
|
|
41
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
42
|
+
Requires-Dist: anthropic<2,>=1; extra == "dev"
|
|
43
|
+
Requires-Dist: openai>=1.40; extra == "dev"
|
|
44
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
45
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
46
|
+
Dynamic: license-file
|
|
47
|
+
|
|
48
|
+
# intent-classify
|
|
49
|
+
|
|
50
|
+
[](https://github.com/Shubhankar-saket/Intent-classifier-sdk/actions/workflows/ci.yml)
|
|
51
|
+
|
|
52
|
+
Intent classification, guardrails and query planning for LLM assistants and chatbots.
|
|
53
|
+
|
|
54
|
+
- **Guardrails and common conversational intents are built in**: prompt injection, jailbreaks, PII, off-topic, greetings, human handoff and more. You add only your own intents, in a YAML file.
|
|
55
|
+
- **Conversation-aware.** "yes", "the second one" and "cancel it" are resolved from the last N turns, and so are attacks spread across several turns.
|
|
56
|
+
- **Plans, not just labels (optional).** Validated slots plus ordered tool-call and retrieval steps for your executor.
|
|
57
|
+
- **Evals are built in.** One command compares the cascade against a zero-shot baseline on accuracy, safety, cost and latency.
|
|
58
|
+
- **Works with any provider.** Anthropic, OpenAI and anything OpenAI-compatible (Azure, vLLM, Ollama).
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install "intent-classify[anthropic]" # or [openai], or [all]
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
user message + last N turns
|
|
66
|
+
│
|
|
67
|
+
├─ L0 normalise unicode folding, invisible-char stripping, history window
|
|
68
|
+
├─ L1 guardrails (shared) injection · jailbreak · prompt extraction · harmful · exfiltration
|
|
69
|
+
│ self-harm · toxicity · PII · off-topic → allow/flag/escalate/block
|
|
70
|
+
├─ L2 universal (shared) greeting · goodbye · thanks · small talk · human handoff · complaint
|
|
71
|
+
│ feedback · affirm · deny · capabilities · clarification · gibberish
|
|
72
|
+
├─ L3 project intents from projects/<name>.yaml
|
|
73
|
+
└─ L4 slots + plan (optional) validated slots -> tool / retrieval / ask_user steps
|
|
74
|
+
▼
|
|
75
|
+
ClassificationResult { guardrail.action, flags[], intents[] (primary first), slots, plan, language, usage, ... }
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## How a message is classified (cheapest first)
|
|
79
|
+
|
|
80
|
+
1. **Rules.** Free and deterministic:
|
|
81
|
+
- Strict regexes catch obvious injection or jailbreak attempts. These are *heuristic*: the LLM can veto them.
|
|
82
|
+
- Validated detectors catch PII, e.g. Luhn-checked card numbers, SSN, PAN, and disclosed passwords or OTPs. These are *deterministic* and always kept.
|
|
83
|
+
- Exact matches handle one-liners like "hi" or "thanks".
|
|
84
|
+
2. **Embeddings.** Nearest neighbour against the intent examples. If the match is clear, nothing looks risky, and the message doesn't depend on context, we answer without an LLM.
|
|
85
|
+
3. **LLM.** Gets a structured-output prompt generated from the taxonomy (cached per project) plus the last N turns. It resolves context ("yes" → `order.cancel`) and catches multi-turn attacks.
|
|
86
|
+
4. **Policy.** The guardrail action is the most severe flag at or above the threshold. Below `abstain_threshold`, the primary intent becomes `unknown`.
|
|
87
|
+
|
|
88
|
+
Providers are swappable: `anthropic[:model]`, `openai:<model>` (which also covers Azure, vLLM and Ollama via `base_url`), and embedders `hashing` (offline), `openai`, or `st` (local multilingual sentence-transformers).
|
|
89
|
+
|
|
90
|
+
## Slots and planning (classifier + query planner)
|
|
91
|
+
|
|
92
|
+
Optional, per project. When the YAML declares `slots`, `tools`, `retrievers` and per-intent
|
|
93
|
+
`plan` templates, every result also carries validated `slots` and a `plan`: an ordered list of
|
|
94
|
+
tool calls, retrieval queries, canned replies or clarifying questions. **The library plans; your
|
|
95
|
+
executor runs the steps.**
|
|
96
|
+
|
|
97
|
+
```yaml
|
|
98
|
+
slots:
|
|
99
|
+
order_id: {type: string, pattern: "[0-9]{4,6}", ask: "Which order is this about?"}
|
|
100
|
+
products: {type: list, description: Product names or models mentioned}
|
|
101
|
+
tools:
|
|
102
|
+
orders.get: {required_args: [order_id]}
|
|
103
|
+
orders.cancel: {required_args: [order_id], side_effect: true} # -> requires_confirmation
|
|
104
|
+
retrievers:
|
|
105
|
+
catalog: {description: Product catalogue}
|
|
106
|
+
intents:
|
|
107
|
+
- name: order.cancel
|
|
108
|
+
slots: {order_id: required, items: optional}
|
|
109
|
+
plan:
|
|
110
|
+
- {id: lookup, tool: orders.get, args: {order_id: $order_id}}
|
|
111
|
+
- {id: cancel, tool: orders.cancel, args: {order_id: $order_id, items: $items}, depends_on: [lookup]}
|
|
112
|
+
- name: product.info
|
|
113
|
+
slots: {products: required, aspect: optional}
|
|
114
|
+
plan:
|
|
115
|
+
- {retrieve: catalog, for_each: products, query: "{item} {aspect}"} # one sub-query per product
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
r = clf.classify("yes", history=[...cancel order 5512... Shall I cancel it?])
|
|
120
|
+
r.slots["order_id"] # SlotValue(value="5512", source="history", extractor="llm")
|
|
121
|
+
r.plan.status # "ready" (or "needs_input" | "blocked" | "no_plan")
|
|
122
|
+
[s.signature for s in r.plan.steps] # ["tool:orders.get", "tool:orders.cancel"]
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
How it works:
|
|
126
|
+
- **Slots come from the same LLM call** as the intents. The schema and prompt only grow when a project declares slots. Identifier slots (those with a `pattern`) are also pulled out by regex, so the fast path and offline mode still get them. A plan that needs a slot only the LLM can extract skips the fast path.
|
|
127
|
+
- **Values are validated, never trusted.** Each value is checked for type, pattern, enum and length. Identifier slots must also appear verbatim in the conversation, so an order number the LLM invents is dropped. Dropped values are listed in `plan.notes`.
|
|
128
|
+
- **Planning is deterministic.** Templates are filled from slots. `$slot` gives the raw value, `"{slot} text"` interpolates it, `for_each` fans one step out into parallel sub-queries, and `when`/`unless` pick steps based on which slots are present. Every confident intent gets planned, so a multi-intent message yields one combined plan.
|
|
129
|
+
- **Missing required slot:** the plan contains a single `ask_user` step with the slot's question, instead of guessing.
|
|
130
|
+
- **Guardrails come first.** A `block` or `escalate` result gets `status: blocked` and no steps. An abstained (`unknown`) intent gets `no_plan`.
|
|
131
|
+
- **Every reference is checked when the YAML loads:** tools, retrievers, slots, `depends_on`, and the tools' required args.
|
|
132
|
+
|
|
133
|
+
Not yet built: an LLM planner for open-ended requests that no template covers (step 3 in [docs/PLAN.md](https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/docs/PLAN.md)).
|
|
134
|
+
|
|
135
|
+
## Quick start
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
import intent_classify as ic
|
|
139
|
+
|
|
140
|
+
clf = ic.IntentClassifier.from_project("projects/shopease.yaml", llm="anthropic", embedder="hashing")
|
|
141
|
+
r = clf.classify("yes", history=[
|
|
142
|
+
{"role": "user", "content": "I'd like to cancel order 5512"},
|
|
143
|
+
{"role": "assistant", "content": "It hasn't shipped yet. Shall I cancel it?"},
|
|
144
|
+
])
|
|
145
|
+
r.guardrail.action # Action.ALLOW
|
|
146
|
+
r.top_intent.name # "order.cancel" (secondary: "affirm")
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Credentials: `ANTHROPIC_API_KEY` (or an `ant auth login` profile) / `OPENAI_API_KEY`. The CLI
|
|
150
|
+
(`intent-classify`, or the short alias `ic`) also reads them from a local `.env`.
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
ic classify "where is order 55120?" --project projects/shopease.yaml --llm none # offline: rules + embeddings
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`projects/shopease.yaml` is a complete example project (a synthetic e-commerce support bot). Copy it to start your own.
|
|
157
|
+
|
|
158
|
+
## Your own project
|
|
159
|
+
|
|
160
|
+
1. Copy `projects/shopease.yaml`. Write a one-paragraph `domain` (this drives off-topic detection) and your intents. For each intent, give a precise description, 5–8 examples, and **negative examples** for the intents it's most often confused with.
|
|
161
|
+
2. Optionally use `core:` to switch off universal intents you don't want, or change a guardrail's action (e.g. `toxicity: block`).
|
|
162
|
+
3. Write `evals/datasets/<project>_*.jsonl` (format in [evals/datasets/README.md](https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/evals/datasets/README.md)). Include
|
|
163
|
+
**off-topic** and **scary-but-benign** cases from your own domain, since only you know what those are. The core
|
|
164
|
+
guardrail and universal suites ship with the package and run automatically, adapted to your taxonomy.
|
|
165
|
+
4. Run `ic eval --project projects/<project>.yaml --datasets "evals/datasets/*.jsonl"` and commit gate thresholds.
|
|
166
|
+
|
|
167
|
+
## Evals
|
|
168
|
+
|
|
169
|
+
See **[docs/EVALS.md](https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/docs/EVALS.md)**. One command compares six systems: the zero-shot baseline vs. each layer of the cascade. It reports accuracy, guardrail recall *with* false-block rate, context and multilingual slices, calibration, latency and cost, plus a failure browser.
|
|
170
|
+
|
|
171
|
+
## Layout
|
|
172
|
+
|
|
173
|
+
```
|
|
174
|
+
src/intent_classify/
|
|
175
|
+
types.py stable result contract
|
|
176
|
+
taxonomy.py YAML loading + merging of shared and project layers, versioning
|
|
177
|
+
builtin/ shared guardrails.yaml + universal.yaml
|
|
178
|
+
normalize.py L0 + history window
|
|
179
|
+
stages/ rules · embedding · llm (prompt + schema)
|
|
180
|
+
pipeline.py cascade + policy (IntentClassifier, ClassifierConfig)
|
|
181
|
+
planner.py slot extraction/validation + deterministic plan templates
|
|
182
|
+
backends/ anthropic · openai · embeddings · registry
|
|
183
|
+
evals/ dataset · systems · metrics · runner · report · gate · leakage
|
|
184
|
+
evals/data/ core eval suites shipped with the package
|
|
185
|
+
cli.py intent-classify / ic: classify | eval | report | gate | check-leakage | generate ...
|
|
186
|
+
projects/shopease.yaml example project (synthetic e-commerce support)
|
|
187
|
+
evals/datasets/ example project's eval suites
|
|
188
|
+
scripts/release_check.py pre-release check (tests, build, clean-venv smoke test, gate)
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Contributing
|
|
192
|
+
|
|
193
|
+
Contributions are welcome. See [CONTRIBUTING.md](https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/CONTRIBUTING.md). Changes are listed in [CHANGELOG.md](https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/CHANGELOG.md).
|
|
194
|
+
|
|
195
|
+
## License
|
|
196
|
+
|
|
197
|
+
[Apache-2.0](https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/LICENSE)
|
|
198
|
+
|
|
199
|
+
## Design decisions worth knowing
|
|
200
|
+
|
|
201
|
+
- **Primary intent = the task, resolved with context.** Dialogue acts like affirm, deny or complaint come second when a task is present.
|
|
202
|
+
- **Conversation content is data, not instructions.** It's escaped and wrapped in tags. An injected instruction becomes evidence for a guardrail, never a command.
|
|
203
|
+
- **Provider refusals become a `provider_refusal` flag** (default `block`). When the model's own safety layer declines to even classify a message, that is itself a strong signal. On Claude Opus 5.5 / Sonnet 5.5 the adapter enables server-side refusal fallbacks first.
|
|
204
|
+
- **LLM errors degrade instead of crash** (`on_llm_error="fallback"`). The result records `errors`, so callers can choose to fail closed.
|
|
205
|
+
- **Default model is `claude-opus-5-5` at `low` effort.** Cheaper options are one flag away (`--llm anthropic:claude-haiku-4-5`). Compare them in the eval report before choosing; don't guess.
|