Chapter 5 of 32 · ~20 min read & lab+75 XP
Chapter 5 · Agentic AI

Agentic Intent Routing: Fast Rule, Embedding & LLM Triage Routers

How a lightweight Intent Router cuts agent latency and API bills by 70%+: 3-tier Cascaded Routing (Regex → Semantic Embeddings → Small LLM), confidence thresholds τ, and safe ambiguity fallbacks.

What Is It?

Intent Routing classifies incoming user requests via fast keyword rules, embedding similarity, or a tiny triage LLM to dispatch each query to the cheapest specialized handler.

Why Is It Required?

Sending simple FAQ or billing queries to a heavy reasoning model with 40 tools wastes 90% of your latency and cost.

Everyday Analogy: A hospital reception desk sending a sprained ankle straight to urgent care instead of booking an operating room.
Why ML Engineers & Data Scientists Actually Need This

Sending 'What are your business hours?' to a 400B autonomous reasoning agent is burning money — an Intent Router handles 70%+ of traffic in <50 ms at 1/50th the cost!

ML / AI Engineer

Cascaded Routing (Rules → Embeddings → Small LLM with Strict JSON Enum) is one of the highest-ROI production patterns in all of Agentic AI.

Data Scientist

Knowing how to set asymmetric confidence thresholds (τ = 0.90 for destructive/billing actions vs. τ = 0.70 for benign FAQ lookup) prevents costly mis-routes.

Interview & Debug Edge

Common Agentic AI coding & architecture prompt: 'Build an Intent Router with keyword/semantic scoring, confidence thresholding, and a safe default fallback route!'

Step 0 · Test Your Gut Before Any Math!

In a 3-tier Cascaded Intent Router, which tier should run FIRST to minimize both latency and cost?

What You Will Master in This Chapter
  • Design a front-door Intent Router that dispatches queries to the cheapest, fastest qualified handler (FAQ, Workflow, or Full Agent)
  • Implement a 3-tier Cascaded Router: Deterministic Rules (0.1 ms, $0) → Semantic Embedding Similarity (5 ms) → Small Structured LLM (80 ms)
  • Tune routing confidence threshold τ to send ambiguous queries to a safe Fallback / Clarification route instead of mis-routing
  • Evaluate router quality using a per-route Confusion Matrix and Mis-Route Cost weighting
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Cascade: R1→R2→R3\text{Cascade: } R_1 \to R_2 \to R_3Say aloud:“tiered routing cascade”
Plain-English Meaning
Short-circuiting router escalating from Rules → Embeddings → Small LLM only when confidence < τ
Everyday Example
Cuts p50 routing latency to <10 ms!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of a hospital ER triage nurse (Intent Router): a patient with a scraped finger doesn't get wheeled straight into open-heart surgery (a 15-step frontier agent!). The triage nurse checks obvious signs in 1 second (Rules), matches known symptom clusters in 5 seconds (Semantic Embeddings), and only calls a senior specialist (LLM / Agent) for genuinely complex cases!

1. Front-Door Triage: Right-Sizing Compute per Query

Everyday Story First (Zero Math Yet!)

Routing decouples understanding what the user wants from executing the work — keeping each specialist prompt small, focused, and easy to evaluate!

Intent Router: Dispatching Every Query to the Right-Sized HandlerIncoming QueryIntent Routerclass + confidenceFAQ → Fast RAG (~200 ms, $0.0002)Billing → Deterministic API WorkflowComplex Debug → Full ReAct Agent
An Intent Router sits at the front door, dispatching simple FAQs to a fast cheap path, structured requests to deterministic workflows, and hard open-ended tasks to a full Agent!

Why Specialist Routes Beat One Giant 'Do-Everything' Prompt

Stuffing 40 tools and 10 pages of instructions into a single agent degrades tool-selection accuracy and explodes input token costs. Routing first lets each downstream specialist hold just 3–5 sharp tools!

2. The 3-Tier Cascaded Router (Rules → Embeddings → Small LLM)

Everyday Story First (Zero Math Yet!)

Short-circuiting across 3 tiers gives you sub-10 ms p50 latency without sacrificing accuracy on subtle phrasing.

3-Tier Cascaded Router: Fast & Cheap First, LLM Last!Tier 1: Rules / Regex0.1 ms · $0 · Exact commandsTier 2: Semantic Embed5 ms · Cosine to route centroidsTier 3: Small LLM80 ms · Structured enum output
Cascaded Routing checks regex/rules (0.1 ms, $0) → Embedding cosine match (5 ms) → small LLM classifier (80 ms) before ever invoking a frontier reasoning model!

Exact Tier Responsibilities

  • Tier 1 (Rules / Regex): Instant exact triggers (e.g., /reset, invoice #\d+, cancel subscription).
  • Tier 2 (Semantic Router): Compare query embedding against 10–20 example utterances per route (cosine similarity in <5 ms!).
  • Tier 3 (Small Fast LLM): Handles multi-intent or sarcastic queries using a Strict JSON Schema {"route": enum, "confidence": float}.

3. Confidence Thresholds & Safe Ambiguity Fallbacks

Everyday Story First (Zero Math Yet!)

Drag threshold τ in the mini-lab below to see how an ambiguous message ("It's broken and I'm mad") safely routes to FALLBACK / CLARIFY instead of triggering the wrong tool!

Confidence-Gated Routing: Never Dispatch Ambiguous Intents Blindly!Confidence ≥ τ (e.g. 0.80)Dispatch directly to specialist route ✓Confidence < τ (Ambiguous)Route to Safe Fallback / Ask Clarification!
When router confidence falls below threshold τ, never guess blindly — route to a safe Fallback (clarifying question or human escalation)!

Asymmetric Mis-Route Cost

Not all routing errors cost the same: mis-routing a BILLING_REFUND query to FAQ annoys a user, whereas mis-routing an ambiguous complaint to DELETE_ACCOUNT is catastrophic! Set higher τ\tau (and add HITL approval, Module 5.1) on high-impact routes!

Walk Through With Me · Interactive Worked Example

Worked Example: Scoring & Gating a Multi-Route Query

Routes: BILLING (score 0.58), TECH_SUPPORT (score 0.54), FAQ (score 0.30); threshold τ = 0.70.

11. Find top-scoring routeStep 1 / 2

BILLING wins with 0.58 — BUT 0.58 < 0.70 (and margin over #2 is only 0.04!).

Teacher's Note: Low top score OR tiny top-1 vs. top-2 margin = genuine ambiguity!
Animated Mini-Lab • 1.4

Confidence-Gated Intent Router (τ = 0.75)

"Reset my password"0.94 → AUTH_FLOW
"Upgrade to Pro plan"0.81 → BILLING_FLOW
"It's broken and I'm mad"0.58 → FALLBACK / CLARIFY
Pause & Check · Quick Intuition Pulse

In a Confidence-Gated Intent Router with τ = 0.75, what should happen when the highest-scoring route only achieves confidence 0.52?

Try It YourselfStandard

What happens if a user sends a compound query containing TWO intents at once ('Reset my password AND download my March invoice')?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Build a 200-query labeled golden set across all routes + out-of-scope queries and measure macro-F1, per-route Confusion Matrix, and Fallback rate — just like classic supervised classification!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Cascaded Intent Router resolve 3 queries across Tier 1 (Regex), Tier 2 (Embedding), and Tier 3 (Small LLM).
Interactive Animation • 1.4 Deep Lab

Cascaded Intent Router: Regex → Embedding → LLM Triage

Watch incoming queries get resolved at the fastest, cheapest tier possible before ever touching a heavy autonomous agent.

BILLING_API
Incoming User Query:
"Where is my invoice #402?"
Matched At
Tier 1: Regex Rule (0.1 ms)
Dispatched Route
BILLING_API ✓
0%
Query 1 / 3
Intuition Takeaway: A 3-tier Cascaded Intent Router (Rules → Semantic Embeddings → Small LLM) with a confidence threshold τ\tau and safe Fallback slashes latency and cost while keeping specialist agents focused.
Where This Powers Real ML, Deep Learning & Generative AI

Model Routing (Cheap vs. Frontier LLM)

Routes easy queries to fast 8B/Mini models and hard coding/math queries to frontier reasoning models — cutting API spend by 60%+!

Production NumPy & PyTorch Code Patterns
import math

# Fast Hybrid Intent Router: Rule Fast-Path -> Cosine Embedding Similarity -> Fallback
ROUTES = {
    "billing": [0.95, 0.10, 0.05],
    "code_help": [0.05, 0.95, 0.10],
    "general": [0.10, 0.15, 0.95],
}

def cosine(a: list[float], b: list[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    return dot / (na * nb + 1e-9)

def route_intent(query: str, query_vec: list[float], threshold: float = 0.75) -> str:
    if any(k in query.lower() for k in ("refund", "invoice", "charge")):
        return "billing (rule fast-path)"
    scores = {name: cosine(query_vec, vec) for name, vec in ROUTES.items()}
    best_route, best_score = max(scores.items(), key=lambda kv: kv[1])
    return best_route if best_score >= threshold else "llm_triage_fallback"

print(route_intent("Need a refund for invoice #12", [0.1, 0.2, 0.3]))
print(route_intent("Fix my PyTorch DataLoader", [0.08, 0.92, 0.12]))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting an explicit OUT_OF_SCOPE / FALLBACK class in your router enum.
Best Practice: Always include an explicit FALLBACK route so off-topic or ambiguous queries are never forced into a real tool!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1Why does routing queries to focused specialist agents (3–5 tools each) outperform giving one monolithic agent 40 tools?

Apply What You Learned — Solve Matching Coding Problems