Skip to content

About

JEV intent classification using Python

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

Intent Routing with TypeSafe's JEV Model

AI-powered intent classification for customer support conversations. It identifies the customer's primary intent from a free-text message, returning a structured result with confidence scores and probability distributions so downstream systems can route the conversation appropriately.

Routing decisions remain configurable; the tool provides probabilistic intent detection, not hardcoded rules.

Run locally

uv run python main.py

What the code does

The code orchestrates a single-step intent classification using TypeSafe's JEV (Judgmental Evaluation of Values) model through the typesafe-sdk. Given a customer message, it returns a structured intent classification composed of:

  • intent — The identified intent label from a predefined set (e.g., order_status, delivery_tracking, payment_refund).
  • confidence — A probability score (0.0–1.0) indicating the model's certainty in the classification.
  • requires_clarification — A boolean flag set to true when confidence is below 0.8, signaling the need for follow-up questions.
  • probabilities — A dictionary mapping each possible intent to its probability score, enabling downstream fallback logic.
  • source — Which classifier produced the result: jev or openai_fallback.

Supported Intents

Intent Description
order_status The customer wants to know the status of an order.
order_cancel The customer wants to cancel an order.
delivery_tracking The customer wants to track a delivery or discover where the order is.
delivery_delayed The customer says the delivery is delayed.
delivery_address_change The customer wants to change the delivery address.
payment_failed The payment failed or was declined.
payment_refund The customer wants a refund.
product_information The customer wants information about a product.
product_availability The customer wants to know whether a product is available.
return_request The customer wants to return a product.
return_status The customer wants to know the status of a return.
unknown The message does not clearly match any other intent.

Example

Input message: "I want to know where is my order"

Output:

IntentResult(
    intent='delivery_tracking',
    confidence=0.92,
    requires_clarification=False,
    probabilities={
        'delivery_tracking': 0.92,
        'order_status': 0.05,
        'delivery_delayed': 0.02,
        'order_cancel': 0.01,
        ...
    }
)

Multi-turn context

Pass prior turns via history to disambiguate short or ambiguous follow-ups. Only the latest message is classified; history is used as context.

history = [
    Turn(role="user", content="My package was supposed to arrive yesterday."),
    Turn(role="assistant", content="Sorry about that! How can I help?"),
]
classifier.classify("I just want my money back", history=history)

Architecture

main.py
  -> IntentClassifier.classify(message, history)
     -> TypeSafeClient.system_one()
        -> JEV Model (OpenRouter API)
     -> on error: OpenAIFallbackClassifier.classify()  (if configured)
        -> OpenAI chat completions (structured output)
     <- IntentResult

Components

  1. domain.py — Pydantic models defining the intent schema and descriptions.

    • Turn: A prior conversation turn (user or assistant) used as context.
    • IntentResult: Structured output with intent, confidence, and probabilities.
    • INTENTS: Mapping of intent labels to human-readable descriptions.
  2. classifier.py — The IntentClassifier class wrapping the TypeSafe SDK.

    • Uses Choice questions with criteria to constrain the model output.
    • Applies a confidence threshold (0.8) to flag messages needing clarification.
    • If the JEV call raises and a fallback is configured, delegates to it.
  3. classifier_fallback.py — OpenAIFallbackClassifier, an LLM fallback using the OpenAI SDK.

    • Uses structured output constrained to the same intent labels.
    • Confidence is self-reported by the model (less calibrated than JEV); probabilities only contains the chosen intent.
  4. main.py — Entry point demonstrating usage.

    • Loads API credentials from environment variables.
    • Classifies a sample message and prints the result.

Configuration

Create a .env file (see .env.example):

OPENROUTER_API_KEY=sk-or-v1-...
OPENAI_API_KEY=sk-...          # optional: enables the LLM fallback
OPENAI_MODEL=gpt-4.1-mini      # optional: fallback model

Dependencies

  • python-dotenv — Environment variable management.
  • typesafe-sdk — TypeSafe SDK for structured LLM interactions.
  • openai — OpenAI SDK used by the LLM fallback.
  • deepeval, pytest (dev) — Evaluation framework and test runner.

Evaluations

Evals use deepeval and call the real models (OpenRouter for JEV, OpenAI for the fallback and the judge). Everything stays local: telemetry is off and nothing is uploaded to Confident AI.

uv sync --group dev

# Full run: both systems, all metrics, LLM judge, Markdown/JSON report in evals/results/<timestamp>/
uv run python -m evals.run_evals
uv run python -m evals.run_evals --systems jev --no-judge --limit 10   # quick smoke test

# Regression gate (for CI): per-case asserts plus dataset-level thresholds
uv run deepeval test run evals/test_intent_classifier.py
EVAL_SYSTEMS=jev uv run pytest evals -q

Systems under test

System What it is
jev IntentClassifier without a fallback, so JEV errors count as errors instead of being hidden by the fallback.
openai_fallback OpenAIFallbackClassifier called directly, as if JEV were down.

Golden datasets (evals/datasets/, synthetic)

  • single_turn.json (114 Goldens): 8 per intent (canonical phrasing, paraphrases, indirect phrasing, slang/typos, non-English text, confusable pairs), plus out-of-scope, off-topic, gibberish, prompt-injection, ambiguous and multi-intent messages.
  • multi_turn.json (18 ConversationalGoldens): pronoun references, ellipsis, answers to the assistant's clarifying questions, topic switches and corrections where the history must not override the latest message.

Each golden has the following labels in additional_metadata:

  • acceptable_intents: every label a human would accept. The first one is expected_output, the strict label.
  • should_clarify: whether a follow-up question is the right move. null means not labeled (multi-intent messages).
  • category, difficulty, and (multi-turn only) history_dependent.

Metrics

Per test case (deepeval metrics, see evals/metrics.py):

Metric Type Checks
Exact Match built-in, deterministic predicted label == strict label
Acceptable Intent custom BaseMetric predicted label ∈ acceptable_intents
Clarification Flag custom BaseMetric requires_clarification == should_clarify
Output Contract custom BaseMetric valid distribution, argmax == intent, confidence == P(intent), flag follows the 0.8 rule
Acceptable Probability Mass custom BaseMetric probability placed on acceptable labels (soft accuracy)
Contextual Acceptable Intent / Clarification Flag custom BaseConversationalMetric the same checks on multi-turn ConversationalTestCases
Routing Severity GEval (LLM judge, EVAL_JUDGE_MODEL, default gpt-6-luna) only for misroutes: whether the wrong label is a harmless near miss or a harmful misroute

Dataset level (evals/aggregate.py, computed outside deepeval because its scores are per test case):

  • Classification: strict and lenient accuracy, macro-F1, per-intent precision/recall/F1, confusion pairs, accuracy by category.
  • Calibration: ECE (10 bins, against lenient correctness), multiclass Brier score, reliability table.
  • Clarification threshold sweep: clarification precision/recall and auto-route coverage/accuracy at thresholds 0.5–0.95.
  • History ablation: multi-turn accuracy with vs. without history, to show whether context actually helps.
  • Latency: p50, p95 and max.

CI gates (evals/config.py → GATES)

  • Every easy golden must route correctly and return a valid result.
  • Lenient accuracy ≥ 90%.
  • Macro-F1 ≥ 0.85.
  • Lenient recall per intent ≥ 75%.
  • Clarification accuracy ≥ 75%.
  • Multi-turn lenient accuracy ≥ 85%.
  • Error rate ≤ 2%.
  • ECE ≤ 0.10 (JEV only, since the fallback's confidence is self-reported).

Extending the classifier

  1. Add new intents:

    • Update INTENTS dictionary in domain.py with the new label and description.
    • Update the intent Literal type in IntentResult to include the new label.
  2. Adjust confidence threshold:

    • Modify the requires_clarification logic in classifier.py (default: 0.8).
  3. Add metadata extraction:

    • Extend IntentResult with additional fields (e.g., order_id, product_name).
    • Add corresponding Choice or extraction questions to the system_one() call.

TODO List

  • Implement intent-specific entity extraction (order IDs, tracking numbers, etc.).
  • Support confidence calibration for production monitoring.

About

JEV intent classification using Python

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Contributors

Languages