Skip to main content

intent-classify

CI

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

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

Quick start

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.

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). 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. 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. Changes are listed in CHANGELOG.md.

License

Apache-2.0

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.

Metadata

Release files for intent-classify 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for intent-classify 0.2.0
File Size Uploaded Provenance Actions
intent_classify-0.2.0.tar.gz 114.1 kB Without provenance Details for intent_classify-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for intent-classify 0.2.0
File Interpreter ABI Platform Actions
intent_classify-0.2.0-py3-none-any.whl Python 3 none any Details for intent_classify-0.2.0-py3-none-any.whl

Total release size: 188.5 kB

Release files / intent_classify-0.2.0.tar.gz

Download URL intent_classify-0.2.0.tar.gz
Size 114.1 kB
Tags Source
SHA-256 checksum
How to use checksums
b8568abf47789035432f23f3a945bf0dd90c00b17c939cc0417f1abf4f648788
BLAKE2b-256 checksum
How to use checksums
b1e1330420fb8e17ec1ed597416e474da801a01c1af0fa72855bc420d301c625
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / intent_classify-0.2.0-py3-none-any.whl

Download URL intent_classify-0.2.0-py3-none-any.whl
Size 74.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7b96445588974720e8176006c4c1a6d379df9d85eab675a70c68f8409f0d1fbb
BLAKE2b-256 checksum
How to use checksums
4ecd7acb6ff733464ff85491a26cf525df09f8a85b59af48a56611752171da4f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for intent-classify 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page