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%.
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:
- Classification & Triage: Tagging tickets, moderating content, detecting user intent, routing alerts.
- Unstructured → Structured Extraction: Turning messy PDFs, invoices, call transcripts, and crash logs into clean relational rows in PostgreSQL.
- Tiered Model Routing (Cascades): Using a
$0.15 / 1MFlash/Mini model to handle 85% of traffic in220 ms, escalating only the tricky 15% to a$3.00+ / 1MFrontier / 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%:
- 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". - 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! - Calibrated Confidence Gating: Combine
logprobs(Lesson 1.3) or a rubric-basedneeds_human_review: boolflag so ambiguous edge cases route to a human queue instead of triggering wrong automation. - Taxonomy Size Limit (
<= 15–20labels 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 8BILLINGsub-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!
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:
"How do I export my expense report to CSV?"
{"intent": "docs_howto", "complexity": "simple", "needs_sql_tool": false}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
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_text6. What Breaks in Production (War Stories)
- 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 triggers429 Too Many Requests (Tokens Per Minute exceeded)— taking down your live customer-facing chat! Always cap concurrency withasyncio.Semaphore(15)and push bulk jobs to the Batch API. - 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!
- 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
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.