Metadata-Version: 2.4
Name: intent-classify
Version: 0.2.0
Summary: Conversation-aware intent classification, guardrails and query planning for LLM assistants. Intents in YAML, evals built in.
Author: Shubhankar Saket
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/Shubhankar-saket/Intent-classifier-sdk
Project-URL: Repository, https://github.com/Shubhankar-saket/Intent-classifier-sdk
Project-URL: Issues, https://github.com/Shubhankar-saket/Intent-classifier-sdk/issues
Project-URL: Changelog, https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/CHANGELOG.md
Keywords: intent-classification,guardrails,prompt-injection,llm,chatbot,query-planning,slot-filling,evaluation,anthropic,openai
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: pydantic>=2.6
Requires-Dist: pyyaml>=6
Requires-Dist: numpy>=1.26
Provides-Extra: anthropic
Requires-Dist: anthropic<2,>=1; extra == "anthropic"
Provides-Extra: openai
Requires-Dist: openai>=1.40; extra == "openai"
Provides-Extra: local-embeddings
Requires-Dist: sentence-transformers>=3; extra == "local-embeddings"
Provides-Extra: all
Requires-Dist: anthropic<2,>=1; extra == "all"
Requires-Dist: openai>=1.40; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: anthropic<2,>=1; extra == "dev"
Requires-Dist: openai>=1.40; extra == "dev"
Requires-Dist: build>=1; extra == "dev"
Requires-Dist: twine>=5; extra == "dev"
Dynamic: license-file

# intent-classify

[![CI](https://github.com/Shubhankar-saket/Intent-classifier-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/Shubhankar-saket/Intent-classifier-sdk/actions/workflows/ci.yml)

Intent classification, guardrails and query planning for LLM assistants and chatbots.

- **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.
- **Conversation-aware.** "yes", "the second one" and "cancel it" are resolved from the last N turns, and so are attacks spread across several turns.
- **Plans, not just labels (optional).** Validated slots plus ordered tool-call and retrieval steps for your executor.
- **Evals are built in.** One command compares the cascade against a zero-shot baseline on accuracy, safety, cost and latency.
- **Works with any provider.** Anthropic, OpenAI and anything OpenAI-compatible (Azure, vLLM, Ollama).

```bash
pip install "intent-classify[anthropic]"     # or [openai], or [all]
```

```
user message + last N turns
   │
   ├─ L0  normalise          unicode folding, invisible-char stripping, history window
   ├─ L1  guardrails (shared) injection · jailbreak · prompt extraction · harmful · exfiltration
   │                          self-harm · toxicity · PII · off-topic       → allow/flag/escalate/block
   ├─ L2  universal (shared)  greeting · goodbye · thanks · small talk · human handoff · complaint
   │                          feedback · affirm · deny · capabilities · clarification · gibberish
   ├─ L3  project intents     from projects/<name>.yaml
   └─ L4  slots + plan        (optional) validated slots -> tool / retrieval / ask_user steps
   ▼
ClassificationResult { guardrail.action, flags[], intents[] (primary first), slots, plan, language, usage, ... }
```

## How a message is classified (cheapest first)

1. **Rules.** Free and deterministic:
   - Strict regexes catch obvious injection or jailbreak attempts. These are *heuristic*: the LLM can veto them.
   - Validated detectors catch PII, e.g. Luhn-checked card numbers, SSN, PAN, and disclosed passwords or OTPs. These are *deterministic* and always kept.
   - Exact matches handle one-liners like "hi" or "thanks".
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.
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.
4. **Policy.** The guardrail action is the most severe flag at or above the threshold. Below `abstain_threshold`, the primary intent becomes `unknown`.

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).

## Slots and planning (classifier + query planner)

Optional, per project. When the YAML declares `slots`, `tools`, `retrievers` and per-intent
`plan` templates, every result also carries validated `slots` and a `plan`: an ordered list of
tool calls, retrieval queries, canned replies or clarifying questions. **The library plans; your
executor runs the steps.**

```yaml
slots:
  order_id: {type: string, pattern: "[0-9]{4,6}", ask: "Which order is this about?"}
  products: {type: list, description: Product names or models mentioned}
tools:
  orders.get:    {required_args: [order_id]}
  orders.cancel: {required_args: [order_id], side_effect: true}   # -> requires_confirmation
retrievers:
  catalog: {description: Product catalogue}
intents:
  - name: order.cancel
    slots: {order_id: required, items: optional}
    plan:
      - {id: lookup, tool: orders.get, args: {order_id: $order_id}}
      - {id: cancel, tool: orders.cancel, args: {order_id: $order_id, items: $items}, depends_on: [lookup]}
  - name: product.info
    slots: {products: required, aspect: optional}
    plan:
      - {retrieve: catalog, for_each: products, query: "{item} {aspect}"}   # one sub-query per product
```

```python
r = clf.classify("yes", history=[...cancel order 5512... Shall I cancel it?])
r.slots["order_id"]   # SlotValue(value="5512", source="history", extractor="llm")
r.plan.status         # "ready"   (or "needs_input" | "blocked" | "no_plan")
[s.signature for s in r.plan.steps]   # ["tool:orders.get", "tool:orders.cancel"]
```

How it works:
- **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.
- **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`.
- **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.
- **Missing required slot:** the plan contains a single `ask_user` step with the slot's question, instead of guessing.
- **Guardrails come first.** A `block` or `escalate` result gets `status: blocked` and no steps. An abstained (`unknown`) intent gets `no_plan`.
- **Every reference is checked when the YAML loads:** tools, retrievers, slots, `depends_on`, and the tools' required args.

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)).

## Quick start

```python
import intent_classify as ic

clf = ic.IntentClassifier.from_project("projects/shopease.yaml", llm="anthropic", embedder="hashing")
r = clf.classify("yes", history=[
    {"role": "user", "content": "I'd like to cancel order 5512"},
    {"role": "assistant", "content": "It hasn't shipped yet. Shall I cancel it?"},
])
r.guardrail.action      # Action.ALLOW
r.top_intent.name       # "order.cancel"   (secondary: "affirm")
```

Credentials: `ANTHROPIC_API_KEY` (or an `ant auth login` profile) / `OPENAI_API_KEY`. The CLI
(`intent-classify`, or the short alias `ic`) also reads them from a local `.env`.

```bash
ic classify "where is order 55120?" --project projects/shopease.yaml --llm none   # offline: rules + embeddings
```

`projects/shopease.yaml` is a complete example project (a synthetic e-commerce support bot). Copy it to start your own.

## Your own project

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.
2. Optionally use `core:` to switch off universal intents you don't want, or change a guardrail's action (e.g. `toxicity: block`).
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
   **off-topic** and **scary-but-benign** cases from your own domain, since only you know what those are. The core
   guardrail and universal suites ship with the package and run automatically, adapted to your taxonomy.
4. Run `ic eval --project projects/<project>.yaml --datasets "evals/datasets/*.jsonl"` and commit gate thresholds.

## Evals

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.

## Layout

```
src/intent_classify/
  types.py            stable result contract
  taxonomy.py         YAML loading + merging of shared and project layers, versioning
  builtin/            shared guardrails.yaml + universal.yaml
  normalize.py        L0 + history window
  stages/             rules · embedding · llm (prompt + schema)
  pipeline.py         cascade + policy (IntentClassifier, ClassifierConfig)
  planner.py          slot extraction/validation + deterministic plan templates
  backends/           anthropic · openai · embeddings · registry
  evals/              dataset · systems · metrics · runner · report · gate · leakage
  evals/data/         core eval suites shipped with the package
  cli.py              intent-classify / ic: classify | eval | report | gate | check-leakage | generate ...
projects/shopease.yaml   example project (synthetic e-commerce support)
evals/datasets/          example project's eval suites
scripts/release_check.py pre-release check (tests, build, clean-venv smoke test, gate)
```

## Contributing

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).

## License

[Apache-2.0](https://github.com/Shubhankar-saket/Intent-classifier-sdk/blob/main/LICENSE)

## Design decisions worth knowing

- **Primary intent = the task, resolved with context.** Dialogue acts like affirm, deny or complaint come second when a task is present.
- **Conversation content is data, not instructions.** It's escaped and wrapped in tags. An injected instruction becomes evidence for a guardrail, never a command.
- **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.
- **LLM errors degrade instead of crash** (`on_llm_error="fallback"`). The result records `errors`, so callers can choose to fail closed.
- **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.
