HomeBlogHow to Build a Multi-Agent AI...

Engineering Guide · 8 min read · September 19, 2026

How to Build a Multi-Agent AI System Using LangGraph

Single-prompt agent loops break down once a workflow spans multiple domains, stateful approvals, and flaky APIs. This guide walks through building deterministic, inspectable multi-agent systems in LangGraph with typed state, bounded retries, and isolated tool access.

Author
Smit Desai
Published
September 19, 2026
Read time
8 min read
Topic
AI & Agents
Services
Custom Web · Mobile Apps · All Services

Single-agent prototypes feel magical until you hand them real operational work. Give one LLM prompt twelve tools across billing, CRM updates, and document extraction, and failure modes multiply fast: the model calls write endpoints with half-baked arguments, forgets step two after a long tool output, or burns forty seconds looping on a rate-limited API.

Splitting one overloaded prompt into specialized agents only helps if coordination is explicit. Letting three autonomous bots chat back and forth in freeform prose creates unpredictable token bills and impossible-to-reproduce bugs.

LangGraph solves this by treating multi-agent orchestration as a state machine—a directed graph with typed shared state, explicit transitions, and persistent checkpoints. Whether you are mapping out an automation phase in your AI agents software roadmap or writing Python workers today, graph-based orchestration keeps complex workflows debuggable.


Single-Agent Loops vs. Directed State Graphs

Before adding multiple agents, be honest about whether you actually need them. A single structured LLM call followed by plain code is almost always faster and cheaper when the workflow is linear.

Where Monolithic Prompts Break Down

Multi-agent graphs earn their keep when three conditions show up together:

  1. Conflicting tool permissions: Research needs broad read access, while execution needs strict write validation.
  2. Long-running or interruptible steps: A workflow must pause for webhook callbacks or human sign-off and resume safely.
  3. Distinct verification roles: One step drafts SQL, email copy, or code, and a separate verifier checks policy or syntax against rules the drafter shouldn't override.

Modeling Workflows as Explicit Nodes and Edges

In LangGraph, every capability is a node (a Python function reading and returning state deltas), and control flow lives in edges. Plain Python nodes handle deterministic tasks like fetching database rows or checking quotas, while agent nodes handle reasoning with scoped tool sets.


Defining Shared State Schemas and Checkpointing

The biggest mistake developers make with multi-agent systems is passing unstructured message blobs between agents. When downstream nodes have to re-parse English paragraphs to guess what happened upstream, errors compound silently.

Define an explicit TypedDict or Pydantic state contract where structured outputs sit alongside conversation history:

from typing import Annotated, Literal, TypedDict
from operator import add
from langgraph.graph import StateGraph, END
from langgraph.checkpoint.memory import MemorySaver


class SupportWorkflowState(TypedDict):
    ticket_id: str
    customer_tier: Literal["free", "pro", "enterprise"]
    intent: str
    retrieved_policy: list[str]
    draft_reply: str
    verification_passed: bool
    step_count: int
    audit_log: Annotated[list[str], add]


def triage_node(state: SupportWorkflowState) -> dict:
    # Replace with structured-output LLM classifier in production
    is_billing = "refund" in state["ticket_id"].lower()
    intent = "billing_refund" if is_billing else "technical_issue"
    return {
        "intent": intent,
        "step_count": state["step_count"] + 1,
        "audit_log": [f"triaged:{intent}"],
    }


def policy_research_node(state: SupportWorkflowState) -> dict:
    # Deterministic lookup or scoped RAG node (no write tools attached)
    policies = ["Enterprise refunds under $200 auto-eligible within 14 days."]
    return {
        "retrieved_policy": policies,
        "step_count": state["step_count"] + 1,
        "audit_log": ["policy_loaded"],
    }


def draft_and_verify_node(state: SupportWorkflowState) -> dict:
    draft = f"Reviewed policy for {state['intent']}: {state['retrieved_policy'][0]}"
    passed = len(state["retrieved_policy"]) > 0
    return {
        "draft_reply": draft,
        "verification_passed": passed,
        "step_count": state["step_count"] + 1,
        "audit_log": [f"verified:{passed}"],
    }

In production, swap MemorySaver for a PostgreSQL checkpointer so state survives worker restarts, container deploys, and multi-hour human approval pauses.


Routing, Tool Isolation, and Bounded Retries

Once your state schema is strict, routing logic becomes plain, testable Python rather than wishful prompting.

Conditional Edges Over Freeform Agent Handoffs

Instead of letting a researcher agent decide in prose whether to talk to billing or compliance, evaluate structured state fields inside a dedicated router function:

def route_after_verification(state: SupportWorkflowState) -> str:
    if state["step_count"] >= 8:
        return "escalate_human"
    if not state["verification_passed"]:
        return "escalate_human"
    return END


builder = StateGraph(SupportWorkflowState)
builder.add_node("triage", triage_node)
builder.add_node("research", policy_research_node)
builder.add_node("verify", draft_and_verify_node)
builder.add_node("escalate_human", lambda s: {"audit_log": ["escalated_to_operator"]})

builder.set_entry_point("triage")
builder.add_edge("triage", "research")
builder.add_edge("research", "verify")
builder.add_conditional_edges(
    "verify",
    route_after_verification,
    {"escalate_human": "escalate_human", END: END},
)
builder.add_edge("escalate_human", END)

graph = builder.compile(checkpointer=MemorySaver())

Preventing Infinite Loops with Step Budgets

Every cycle in a graph—such as Drafter -> Reviewer -> Drafter—needs a hard loop counter in state. Never rely on the model deciding "I have tried three times." Enforce max_revisions and step_count in code, and treat tool execution timeouts cleanly so a transient HTTP 502 from a third-party API goes through backoff rather than re-running expensive reasoning tokens. Following least-privilege tool scoping guidelines from the OWASP Top 10 for LLM Applications also ensures a read-only triage node can never accidentally invoke a state-mutating tool.


Multi-Agent Coordination Patterns Compared

Choosing the simplest topology that fits your constraints saves latency, token cost, and debugging time:

Pattern Control Mechanism Predictability Latency & Cost Ideal Use Case
Single Tool-Calling Agent One prompt loops over tools Low–Medium Low Simple Q&A with 2–4 read-only lookups
Deterministic Graph + LLM Nodes Code-defined edges; LLMs only at leaf tasks High Low–Medium Triage, extraction, policy checks, ETL pipelines
Supervisor-Worker Graph Supervisor node routes dynamically between specialist agents Medium Medium–High Multi-domain research, complex report synthesis
Evaluator-Optimizer Loop Generator node paired with strict critic node and max retries High (with cap) Medium SQL/code generation, compliance-checked drafting

Notice that Deterministic Graph + LLM Nodes handles roughly eighty percent of business automation reliably. Reserve dynamic supervisor routing for open-ended tasks where the execution sequence genuinely cannot be known up front.


Observing, Replaying, and Testing Graph Runs

An agent graph without per-node observability is a black box. When a workflow goes wrong in staging or production, your team needs to see which node changed which field and why.

Per-Node Trace Logging and Token Accounting

Emit structured logs (or OpenTelemetry spans) on every node entry and exit containing thread_id, node_name, latency in milliseconds, model name, and prompt/completion token counts as recommended in the OpenAI platform documentation. Attach a cost ceiling per thread_id so runaway inputs abort gracefully before draining API quotas.

Deterministic Mocking for CI Pipelines

Because LangGraph nodes are regular Python functions, you can test routing, retry caps, and checkpoint recovery in pytest without hitting live LLM endpoints on every commit. Mock the LLM wrapper with fixture responses to verify that invalid schemas, tool errors, and step-limit breaches route to escalate_human 100% of the time, then run a smaller live evaluation suite nightly against real models.


Putting Multi-Agent Workflows into Production with SmitDev

Turning a LangGraph prototype into a reliable backend service takes queue workers, database checkpointing, API streaming, and clean operator dashboards. At SmitDev, we build and integrate production agent systems across Python/FastAPI, Laravel, and Next.js—backed by 170+ shipped case studies for startups and engineering teams worldwide.

Whether you need architectural review through AI agent consulting, a dedicated hourly or daily senior developer at $55/day (8–9 hours/day), or ongoing $1,999/month delivery capacity, we embed directly into your repo and ship tested code.

Ready to move an agent workflow out of notebooks and into production? Contact SmitDev with your architecture goals and constraints.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Agentic Engineering

AI Agents & Automation Consulting

Deploy schema-validated AI agents, RAG pipelines, and CRM/support automation with predictable token and latency budgets.

Interactive Tool · Scope & Budget

SaaS & AI Cost Calculator

Estimate development timeline, MVP phases, and build costs across $55/day sprints or $1,999/month dedicated delivery.

01 — Frequently asked questions

ai & agents

Why use LangGraph instead of a single ReAct agent loop?

A single ReAct loop forces one prompt to manage every tool schema, business rule, and recovery path. LangGraph separates responsibilities into explicit graph nodes with typed state and deterministic edges, making workflows testable and bounded.

How do you prevent multi-agent systems from getting stuck in infinite handoff loops?

Track an explicit step_count or iteration counter inside your shared graph state and enforce a hard ceiling inside conditional routing functions. When the budget expires, route to a deterministic fallback or human-review node.

Should every node in LangGraph call an LLM?

No. Keep deterministic work—such as schema validation, SQL queries, API retries, and policy checks—in plain Python nodes. Reserve LLM calls strictly for classification, synthesis, or unstructured reasoning.

Can LangGraph pause a workflow and resume hours later after human approval?

Yes. With a persistent checkpointer backed by PostgreSQL or Redis, LangGraph saves serialized graph state at interrupt points and resumes cleanly from the exact node once an operator submits approval.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.