Course
AI · Module 03: Structured Outputs & Reliable PipelinesTutorial 8 of 21
AI Course·~1.5 hrs

3.2 Classification, Entity Extraction & Model Routing Pipelines

Build the three highest-ROI enterprise AI pipelines in existence: high-precision multi-label classifiers, span-grounded entity extractors, and tiered Flash-to-Frontier model routers that slash bills by 80%.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Secret Truth: The Highest-ROI AI Systems Aren't Chatbots!

Chatbots get all the conference demos, yet inside Stripe, Uber, Shopify, and Linear, 80% of production LLM volume runs invisibly in background workers with zero chat UI! Those silent workhorses do three jobs at massive scale:

  1. Classification & Triage: Tagging tickets, moderating content, detecting user intent, routing alerts.
  2. Unstructured → Structured Extraction: Turning messy PDFs, invoices, call transcripts, and crash logs into clean relational rows in PostgreSQL.
  3. Tiered Model Routing (Cascades): Using a $0.15 / 1M Flash/Mini model to handle 85% of traffic in 220 ms, escalating only the tricky 15% to a $3.00+ / 1M Frontier / Reasoning model!

2. Engineering Bulletproof Classifiers (Beyond Toy Sentiment)

When a naive LLM classifier hits 88% accuracy on day one and stalls there, apply these four upgrades to push precision past 97%:

  1. Mutually Exclusive, Exhaustive Definitions + "OTHER": Never give overlapping enum labels like ["account", "login", "security"] for a password-reset ticket without crisp boundary rules! Define exact one-line inclusion/exclusion criteria per label, and always include "other" or "ambiguous".
  2. Multi-Label vs. Single-Label: Real customer messages contain two intents ("Cancel my Pro plan AND refund last Tuesday's charge"). If business workflows need both, use labels: list[CategoryEnum] instead of forcing a single label!
  3. Calibrated Confidence Gating: Combine logprobs (Lesson 1.3) or a rubric-based needs_human_review: bool flag so ambiguous edge cases route to a human queue instead of triggering wrong automation.
  4. Taxonomy Size Limit (<= 15–20 labels per call): Dumping 180 flat category names into one prompt tanks accuracy! Use 2-Stage Hierarchical Classification: Step 1 classifies into 6 top-level departments (BILLING), then Step 2 classifies only among the 8 BILLING sub-categories!

3. Span-Grounded Extraction (How to Catch Hallucinated Numbers)

Suppose you extract renewal_date and annual_contract_value from a 25-page vendor PDF. How do you prove in deterministic Python code that the LLM didn't misread or hallucinate a digit?

Require an exact_source_quote: str alongside every critical extracted value — and verify substring existence in Python!

PYTHON
class ContractClause(BaseModel):
    exact_source_quote: str  # Must appear verbatim in source document!
    auto_renews: bool
    notice_period_days: int | None

def verify_grounding(clause: ContractClause, raw_doc: str) -> bool:
    # Normalize whitespace so line-wraps in PDFs don't cause false negatives
    norm_quote = " ".join(clause.exact_source_quote.split())
    norm_doc = " ".join(raw_doc.split())
    return len(norm_quote) >= 12 and norm_quote in norm_doc

If verify_grounding() returns False, your code catches the hallucination deterministically in 0.1 ms and flags the field for review! Even better, clicking that quote in your UI scrolls the user straight to the exact highlighted sentence in the PDF!


4. Cascade & Intent Routing: Frontier Quality at 1/6th the Cost

Sending 100% of production traffic to a heavyweight frontier reasoning model is like hiring a Principal Distributed Systems Architect to sort incoming physical mail. Build a 2-Tier Router / Cascade:

Tracing a 2-Tier Flash -> Frontier Model Cascade
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Fast Router Inspects Incoming Query (180ms))
Wire Telemetry:in=120 tokout=14 toklatency=180mscost=$0.00002
1→# Step 1: Fast Triage Router (Gemini Flash / GPT-4o-mini @ $0.15/1M)
2→route = classify_complexity_and_intent(user_query)
3if route.complexity == "simple" and route.confidence >= 0.90:
4 return flash_answer(user_query) # 85% of traffic (240ms!)
5else:
6 return frontier_reasoning(user_query) # 15% hard traffic!
Query A (Routine FAQ — 85% of Volume)
"How do I export my expense report to CSV?"
Router Decisioncomplexity='simple' · p=0.98
{"intent": "docs_howto", "complexity": "simple", "needs_sql_tool": false}
What's Happening: A tiny structured router call takes ~180ms and costs $0.00002 — classifying both intent (which tools/docs to load!) and difficulty!

Bonus Cost Lever: Async Batch APIs (Instant 50% Discount!)

When extracting entities from 500,000 historical PDFs, reviews, or support tickets overnight where you don't need synchronous <1s HTTP replies, OpenAI, Anthropic, and Google Gemini all offer official Batch APIs:

  • 50% flat discount on both input and output tokens!
  • Separate, much higher rate-limit pools so offline backfills never throttle your live user traffic!

5. Production SDK Code: Span-Verified Extraction & Tiered Routing

SDK:
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()

class TriageRoute(BaseModel):
  brief_reason: str
  intent: Literal["billing", "bug_report", "architecture_debug"]
  escalate_to_reasoning: bool

def smart_answer(query: str) -> str:
  # 1. Cheap, sub-250ms router on gpt-4o-mini
  route = client.responses.parse(
      model="gpt-4o-mini",
      temperature=0.0,
      instructions="Escalate ONLY if multi-step code debugging or math reconciliation is required.",
      input=query,
      text_format=TriageRoute,
  ).output_parsed

  # 2. Route to the right model tier!
  target_model = "o4-mini" if route.escalate_to_reasoning else "gpt-4o-mini"
  return client.responses.create(model=target_model, input=query).output_text

6. What Breaks in Production (War Stories)

  1. Running Offline Backfills Against Your Live Synchronous Quota: Launching asyncio.gather(*[extract(doc) for doc in ten_thousand_docs]) against your main API key immediately triggers 429 Too Many Requests (Tokens Per Minute exceeded) — taking down your live customer-facing chat! Always cap concurrency with asyncio.Semaphore(15) and push bulk jobs to the Batch API.
  2. Asking One Giant Prompt to Extract 60 Fields From a 90-Page PDF: Recall degrades sharply when extracting dozens of unrelated fields across huge documents in a single pass. Split by document section or group related fields into 2–3 focused parallel Flash calls — parallel Flash calls are both faster and far more accurate!
  3. Silent Schema Drift When Business Categories Change: Renaming "account_access" → "sso_auth" in your Pydantic enum changes historical analytics joins unless you version extractor outputs (schema_version: "v3").

Module 3.2 Mastery Check — Extraction & Model Routing

Q1.How does requiring an `exact_source_quote: str` field alongside extracted numbers help prevent hallucinations in financial/legal extraction?
Q2.Your classifier needs to assign tickets into 150 fine-grained support sub-categories. What architecture gives the highest accuracy?
Q3.When you need to classify 250,000 archived customer reviews overnight, why should you use the provider's Batch API instead of synchronous HTTP loops?
Q4.In a 2-Tier Flash -> Frontier Cascade where 85% of queries stay on a $0.15/1M Flash model and 15% escalate to a $3.00/1M Frontier model, what happens to blended input cost?

Keep Exploring: Related Lessons & Tools

All Courses →