Build a Multi-Agent Lead Qualification Pipeline: A Step-by-Step Tutorial
Build a multi-agent lead qualification pipeline in LangGraph. Enrich, score, and route inbound leads with a full audit trail.
Why Single-Prompt Lead Classifiers Stall Out
Inbound leads can be enriched, scored, and routed quickly — with a full audit trail of every decision — if you stop asking one prompt to do three jobs. This tutorial walks engineers and AI practitioners through building a multi-agent lead qualification pipeline in LangGraph. It assumes you've already shipped a single-prompt lead classifier, watched its agreement with your best SDR plateau, and concluded the ceiling isn't the model. It's the architecture.
Why Multi-Agent Systems Beat a Single Prompt for Lead Qualification
A single prompt that enriches, judges, and routes a lead conflates three different kinds of work. Enrichment is retrieval. Scoring is judgment against a rubric. Routing is deterministic policy. When all three live in one context window, you can't tell whether a bad outcome came from stale firmographic data, a misapplied rubric, or a routing rule that fired on the wrong field. Debugging means re-reading a 2,000-token prompt and guessing.
Separation of concerns fixes this. Each agent gets one job, one eval suite, and one failure surface. When routing accuracy drops, you test the routing agent in isolation. When scores drift, you diff the rubric against a labeled sample. The blast radius of any change is one node, not the whole pipeline.
There's a cost argument too. Extraction work — resolving a domain, pulling headcount, detecting a tech stack — runs fine on a small, cheap model. You reserve the stronger, more expensive model for the scoring step where judgment actually matters. A single mega-prompt forces you to pay frontier prices for lookup tasks.
The Three Failure Modes of Single-Agent Lead Scoring
- Hallucinated firmographics. The model invents a headcount or funding round because the context implied one should exist. With no separate enrichment step, nothing contradicts it.
- Score drift with no traceability. Scores shift week to week as you tweak the prompt, and you have no per-lead rationale to explain why a "hot" lead went cold.
- Silent routing errors. A lead gets misrouted and nobody notices until a rep complains — because routing logic was buried in prose, not expressed as inspectable rules.
Architecture Overview: Three Agents, One Observer, Shared State
The pipeline has three working agents — Enrichment, Scoring, and Routing — plus a QA/Audit observer (strongly recommended). No agent calls another directly. Instead, a typed state object flows through a LangGraph StateGraph, and each node reads what it needs and writes its output back to state.
A note on terminology: the QA/Audit component is an observer node, not an LLM agent. It snapshots state and runs deterministic checks. Calling it an "agent" invites a fair question about why you'd pay a model to do bookkeeping — so we won't.
In prose: a raw lead enters the Enrichment Agent, which writes structured firmographic data to state. The Scoring Agent reads that data plus the ICP rubric and writes a score, rationale, and confidence. The Routing Agent reads score, confidence, and segment, then writes a destination and the triggering rule. The QA/Audit observer sits alongside, snapshotting state at each transition so you can replay any decision. A conditional edge off the Routing node sends low-confidence leads to a human-review branch instead of auto-routing.
Agent Roles and Handoff Contracts
Every handoff is a schema boundary. Define input and output schemas per agent, and validate state at each node entry rather than letting a downstream agent improvise around missing fields.
- Enrichment: in →
lead_raw; out →enrichment(typed, with per-source provenance and confidence). - Scoring: in →
lead_raw+enrichment; out →score,rationale,confidence. - Routing: in →
score+confidence+enrichment.segment; out →route,route_rule. - QA/Audit: in → full state snapshot; out →
audit_logentries and anomaly flags.
Step 1 — Define the Shared State Schema
The state object is the contract between agents, so treat it like an API. Version it, and bump the version whenever a field's meaning changes.
Use Pydantic rather than TypedDict for the state. A TypedDict gives you static type hints but performs no runtime validation — a node can happily write score="high" and nothing complains until the routing agent chokes. Pydantic models validate on assignment boundaries and produce a usable error when a contract is violated.
from pydantic import BaseModel, Field
from typing import Literal, Optional
class LeadState(BaseModel):
schema_version: str = "1.0.0" # bump on any field-meaning change
lead_raw: dict # inbound payload — immutable
enrichment: Optional[dict] = None # firmographics + per-source provenance
score: Optional[int] = Field(default=None, ge=0, le=100)
rationale: Optional[str] = None
confidence: Optional[float] = Field(default=None, ge=0.0, le=1.0)
route: Optional[Literal["ae", "sdr", "nurture", "disqualify", "review"]] = None
route_rule: Optional[str] = None
audit_log: list[dict] = Field(default_factory=list)
Keep lead_raw immutable — never let an agent overwrite the inbound payload. Everything derived goes in its own field. That single rule makes replays and audits trivial: you can always reconstruct what the system saw versus what it concluded. (Related: versioning strategies for LLM pipelines.)
When wiring nodes, validate on entry. LangGraph passes a dict; convert and check before doing work:
def validate_state(state: dict) -> LeadState:
return LeadState.model_validate(state) # raises on contract violation
Step 2 — Build the Enrichment Agent
The Enrichment Agent is a tool-calling loop. Give it a small model and a narrow toolset: firmographic lookup, domain resolution, and tech-stack detection. Each tool returns a typed result with a source label and a timestamp.
Timeout and fallback behavior matter more than enrichment coverage. If your firmographic provider times out, the agent should degrade — mark the field as unavailable, lower the enrichment confidence, and let scoring proceed with a flag. Never let a vendor outage crash the pipeline or, worse, silently substitute a guessed value.
Cache aggressively. Enrichment results for a given domain are stable for days. A keyed cache on normalized domain (strip www., lowercase, resolve redirects once) turns repeat-domain lookups into near-zero-latency hits and keeps your p95 inside the latency budget. The cost win scales with your repeat-domain share, so measure that hit rate before quoting savings.
Step 3 — Build the Scoring Agent
The Scoring Agent reads lead_raw and enrichment and writes score, rationale, and confidence. This is the node where you spend on a stronger model, because rubric judgment is where quality actually varies.
Two rules make scoring trustworthy:
Score against an explicit rubric, not vibes. Encode the ICP as weighted criteria (e.g., company size 30%, industry fit 30%, tech-stack match 25%, engagement signal 15%) and have the model return a per-criterion subscore. The aggregate is then arithmetic you control, not a number the model made up. This also gives you a rationale you can show a rep.
Treat self-reported confidence as a weak signal. When a model says "confidence: 0.9," that number is poorly calibrated — models tend to be overconfident on inputs they've seen patterns for and underconfident on genuinely novel ones. Two practical mitigations: (a) derive confidence from enrichment completeness — if half the fields are unavailable, cap confidence — and (b) validate calibration offline against a labeled sample by binning predictions and comparing stated confidence to observed accuracy. If a bin says 0.9 and only 70% are correct, you have a calibration problem, not a model problem.
def scoring_node(state: dict) -> dict:
s = validate_state(state)
result = score_lead(s.lead_raw, s.enrichment, rubric=ICP_RUBRIC)
# Cap confidence when enrichment is partial
conf = min(result.confidence, enrichment_ceiling(s.enrichment))
return {"score": result.score, "rationale": result.rationale, "confidence": conf}
Step 4 — Build the Routing Agent
Routing is deterministic policy. Use an LLM here only if rules genuinely require reading unstructured text; otherwise a plain function is cheaper, faster, and testable. Either way, every route must carry the rule that fired in route_rule, so the audit trail explains the decision.
A rule set that uses the confidence signal:
def routing_node(state: dict) -> dict:
s = validate_state(state)
if s.confidence is not None and s.confidence < 0.6:
return {"route": "review", "route_rule": "low_confidence_manual_review"}
if s.score >= 80:
return {"route": "ae", "route_rule": "score_gte_80"}
if s.score >= 50:
return {"route": "sdr", "route_rule": "score_50_to_79"}
if s.enrichment and s.enrichment.get("segment") == "enterprise":
return {"route": "nurture", "route_rule": "enterprise_low_score_nurture"}
return {"route": "disqualify", "route_rule": "score_lt_50"}
The review route is the human-in-the-loop branch. In LangGraph, model it as a conditional edge to a node that pauses the graph (an interrupt) and resumes when a human resolves it — this is the concrete reason to use LangGraph rather than a hand-rolled chain.
Step 5 — Add the QA/Audit Observer
The observer is a lightweight node (or callback) that snapshots state at each transition and appends to audit_log. Keep it deterministic: it should flag anomalies (score present but rationale empty; route fired without a route_rule; enrichment confidence below threshold) and never call a model. This is your replay and debugging substrate — when a "hot" lead goes cold, you read the log, not the prompt.
Step 6 — Wire the Graph in LangGraph
Assemble the nodes into a StateGraph, add the conditional edge for human review, and compile. Keep the graph shallow; the value is in the isolated nodes, not in a clever topology.
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
def build_graph():
g = StateGraph(dict) # state passed as dict; each node validates via Pydantic
g.add_node("enrich", enrichment_node)
g.add_node("score", scoring_node)
g.add_node("route", routing_node)
g.add_node("audit", audit_node)
g.add_node("human_review", human_review_node)
g.add_edge(START, "enrich")
g.add_edge("enrich", "score")
g.add_edge("score", "route")
g.add_conditional_edges(
"route",
lambda s: "human_review" if s["route"] == "review" else "audit",
{"human_review": "human_review", "audit": "audit"},
)
g.add_edge("human_review", "audit")
g.add_edge("audit", END)
# A checkpointer is what enables replay and human-in-the-loop resume.
return g.compile(checkpointer=MemorySaver())
The checkpointer is not optional in production: it's what lets you replay a decision and resume an interrupted human_review node.
Step 7 — Evaluate Each Agent in Isolation
The whole point of separation is per-agent eval suites. Build them before you tune prompts.
- Enrichment: precision/recall on a labeled set of domains against ground-truth firmographics. Track
unavailablerate separately — a high rate is a vendor problem, not a model problem. - Scoring: rank correlation between model scores and SDR-qualified outcomes on a held-out sample; calibration curves per confidence bin.
- Routing: confusion matrix against human-routed labels; track the
reviewrate, since a rising review rate means confidence is degrading upstream. - End-to-end: agreement with your best SDR on the final route, plus the share of decisions that were auto-routed versus reviewed.
Production Hardening
- Idempotency. Key each run on a hash of
lead_raw+schema_version. Re-delivered webhooks should not re-score or double-route. - Bounded retries. Wrap tool calls in retries with exponential backoff and a hard cap; a hung vendor call should trip the timeout fallback from Step 2, not stall the graph.
- Cost and latency envelope. Set an explicit per-lead budget (e.g., a small-model enrichment pass plus one frontier scoring call) and alert when p95 exceeds it. Cache hit rate on repeat domains is the biggest lever.
- Schema versioning discipline. Bump
schema_versionon any field-meaning change and reject state whose version the running code doesn't understand — a silent mismatch between a stored audit log and current code is the hardest bug to diagnose.
The Takeaway
The ceiling on lead qualification isn't the model — it's the architecture. Give each job its own node, its own schema, and its own eval suite; spend on the model only where judgment matters; and let a checkpointered graph give you replay and human review for free. You'll debug one node at a time instead of re-reading a 2,000-token prompt, and you'll be able to explain every routing decision to the rep who has to act on it.