TutorialsLangGraphmulti-agent workflowAI agent orchestrationLangGraph tutorial

Building a Multi-Agent Workflow with LangGraph: A Hands-On Tutorial

Build a multi-agent workflow with LangGraph: define shared state, add researcher and reviewer nodes, and route with a bounded conditional loop. Full Python tutorial.

Why Multi-Agent Workflows Need Real Orchestration

Most multi-agent systems start the same way: a couple of prompt-chained scripts, a while loop that calls an LLM until "done," and a growing pile of string concatenation. It works in a notebook. Then you add a third agent, a retry path, and a human approval step, and the thing collapses. You can't tell which agent produced which output, loops run forever on ambiguous tasks, and there's no clean way to pause and resume a run that takes twenty minutes.

The problem isn't the model. It's the lack of explicit control flow. When agent transitions live inside prompt text, you've traded determinism for vibes.

This tutorial fixes that. You'll build a working two-agent workflow — a researcher that drafts content and a reviewer that critiques it — with a conditional loop that sends work back for revision until it's approved. Along the way you'll see how LangGraph models agents as a state machine, which makes routing inspectable, loops bounded, and runs resumable.

Prerequisites: Python 3.10+, the langgraph package (pip install langgraph), the langchain-openai package for the example model client (pip install langchain-openai), and an LLM API key. The examples use an OpenAI-compatible client, but any chat model with a LangChain wrapper works. (See also: setting up a Python LLM development environment.)

What LangGraph Adds to the Multi-Agent Toolbox

LangGraph is, in its own documentation's framing, a low-level orchestration framework. That phrase matters. It doesn't ship a prebuilt "agent" that hides its reasoning behind a black box. Instead, it gives you primitives — graphs, typed state, nodes, and edges — to express exactly how your agents hand off work.

Contrast that with two common alternatives:

  • Sequential chains are easy to write but rigid. Every run follows the same path, so there's no way to say "revise this if it's weak."
  • Free-form ReAct loops are flexible but unpredictable. The model decides when to stop, which in practice produces runaway loops, skipped steps, and traces that are hard to audit.

LangGraph sits between them. You get explicit control flow (the graph defines every legal transition), inspectable state (you can read the shared state at any step), and routing as a plain Python function (the next node is chosen by code that inspects state, not by a prompt). Note the precise claim: the router itself is deterministic, but it reads fields that a model may have written. You still own the judgment calls — you've just moved them into code you can test and bound.

It's also model-agnostic. LangGraph integrates with LangChain components if you want them — message types, tool wrappers, retrievers — but nothing forces you to use the wider ecosystem. The core graph is just functions and a state dictionary. (See also: choosing an LLM framework for production agents.)

The mental shift: stop thinking of agents as chatbots that talk to each other, and start thinking of them as nodes in a state machine that read and write a shared record.

The Architecture: Graphs, State, and Nodes

A LangGraph workflow is a state machine. Nodes are functions that transform state. Edges define which node runs next. A compiled graph is an executable object you invoke with an initial state.

State as the Contract Between Agents

Every agent in the graph reads from and writes to a single shared state object. Define it as a TypedDict (or a Pydantic model if you want validation). This type is the contract: each node knows exactly which fields it can rely on and which it's responsible for producing.

Fields that accumulate over time — like a message history — use reducer functions. Instead of overwriting a list, a reducer merges new items into it. LangGraph ships with add_messages for exactly this, so conversation history grows naturally across nodes rather than being clobbered on each write. One detail worth knowing: add_messages expects LangChain message objects (anything deriving from BaseMessage), not raw strings, so seed your state with a HumanMessage. (See also: managing shared state in agentic systems.)

Nodes, Edges, and Conditional Routing

Nodes are ordinary Python functions with the signature (state) -> dict. They return a partial update that gets merged into the shared state.

Edges come in two flavors. Regular edges are fixed transitions — node A always goes to node B. Conditional edges call a router function that inspects the current state and returns the name of the next node. That router is where you encode business logic like "approved → publish" or "not approved → revise."

You declare an entry point with the built-in START sentinel (where execution begins) and route to the built-in END sentinel when the workflow is complete.

A diagram showing the researcher node and reviewer node connected by a conditional edge, with a loop
A diagram showing the researcher node and reviewer node connected by a conditional edge, with a loop

Hands-On: Building a Research-and-Review Agent Workflow

Time to build. The workflow: a researcher drafts an answer to a query, a reviewer critiques it, and a router either ends the run or sends it back for revision — capped at a fixed number of attempts.

Step 1 — Define the Shared State Schema

Start with the contract. The state carries the conversation, the current draft, the reviewer's feedback, an approval flag, and a revision counter.

from typing import Annotated, TypedDict
from langgraph.graph.message import add_messages

class AgentState(TypedDict):
    messages: Annotated[list, add_messages]  # accumulates
    draft: str
    review_feedback: str
    approved: bool
    revision_count: int

The Annotated[list, add_messages] line attaches the reducer, so messages appends instead of overwriting. The other fields use default last-write-wins semantics, which is what you want for single-value fields like draft.

Step 2 — Build the Researcher Agent Node

The researcher reads the original query from messages, calls the model with a research prompt, and writes the result to draft. It also bumps revision_count so the router can enforce a cap.

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

def researcher_node(state: AgentState) -> dict:
    query = state["messages"][0].content
    feedback = state.get("review_feedback", "")

    prompt = f"Research and write a thorough answer to: {query}"
    if feedback:
        prompt += f"\n\nIncorporate this reviewer feedback:\n{feedback}"

    response = llm.invoke(prompt)
    return {
        "draft": response.content,
        "revision_count": state.get("revision_count", 0) + 1,
    }

Two things to notice. First, the node returns a partial update — just the fields it changed. Second, the feedback branch makes the same node handle both the initial draft and every revision, so you don't duplicate logic.

Step 3 — Build the Reviewer Agent Node

The reviewer reads the draft and returns structured feedback plus an approval decision.

import json

def reviewer_node(state: AgentState) -> dict:
    prompt = (
        "Review the following draft for accuracy and completeness. "
        "Respond with JSON: {\"approved\": bool, \"feedback\": str}.\n\n"
        f"Draft:\n{state['draft']}"
    )
    response = llm.invoke(prompt)
    try:
        result = json.loads(response.content)
    except json.JSONDecodeError:
        # Fail closed: treat unparseable reviews as "not approved"
        result = {"approved": False, "feedback": "Reviewer output was unparseable; revise."}
    return {
        "approved": bool(result.get("approved", False)),
        "review_feedback": result.get("feedback", ""),
    }

The try/except is not boilerplate. Models intermittently wrap JSON in prose or code fences; a reviewer that crashes on a stray backtick will take down the whole run. Failing closed keeps the loop moving and surfaces the problem in review_feedback.

Step 4 — Write the Router and Assemble the Graph

The router is where the loop is bounded. It ends the run on approval, ends it when the revision cap is hit, and otherwise routes back to the researcher.

from langgraph.graph import StateGraph, START, END

MAX_REVISIONS = 3

def route_after_review(state: AgentState) -> str:
    if state.get("approved"):
        return END
    if state.get("revision_count", 0) >= MAX_REVISIONS:
        return END  # cap reached: stop even if unapproved
    return "researcher"

builder = StateGraph(AgentState)
builder.add_node("researcher", researcher_node)
builder.add_node("reviewer", reviewer_node)

builder.add_edge(START, "researcher")
builder.add_edge("researcher", "reviewer")
builder.add_conditional_edges("reviewer", route_after_review, ["researcher", END])

graph = builder.compile()

The add_conditional_edges call takes the source node, the router function, and the set of possible destinations. Passing the destination list explicitly lets LangGraph validate the graph at compile time, so a typo in a returned node name fails fast instead of at runtime.

Step 5 — Invoke the Graph

Seed the state and run it. The initial messages must contain message objects, not strings.

from langchain_core.messages import HumanMessage

initial_state = {
    "messages": [HumanMessage(content="Explain how LangGraph bounds agent loops.")],
    "draft": "",
    "review_feedback": "",
    "approved": False,
    "revision_count": 0,
}

final_state = graph.invoke(initial_state)
print(final_state["approved"], final_state["revision_count"])
print(final_state["draft"])

You now have a workflow where every transition is code you can read, the loop can't exceed MAX_REVISIONS, and the full state is available for logging or evaluation after each run.

Step 6 — Make Runs Resumable with a Checkpointer

The intro promised resumability; here's the one line that delivers it. Compile the graph with a checkpointer and invoke it with a thread_id. LangGraph then persists state after each node, so a long run can be paused and resumed — or inspected mid-flight — by reusing the same thread.

from langgraph.checkpoint.memory import MemorySaver

graph = builder.compile(checkpointer=MemorySaver())
config = {"configurable": {"thread_id": "run-001"}}
final_state = graph.invoke(initial_state, config=config)

MemorySaver is in-process and fine for development. For anything you need to survive a restart, swap in a durable checkpointer (for example, a SQLite- or Postgres-backed one) — the graph code stays the same.

What You Built, and Where to Take It

You built a two-agent workflow with a typed state contract, a bounded revision loop, a router that fails closed on bad reviewer output, and optional run persistence. The parts that make it production-shaped are the boring ones: the explicit revision cap, the try/except around the reviewer's JSON, and the checkpointer.

Natural next steps:

  • Human-in-the-loop approval. Insert a node between reviewer and router that pauses for a human decision using the checkpointer's interrupt support.
  • Tool-using researcher. Give the researcher node a retriever or search tool so drafts are grounded in sources, then have the reviewer check for citations.
  • Evaluation. Log each run's final state and score drafts against a rubric; the bounded loop makes those comparisons apples-to-apples.

The takeaway stands: the leverage in multi-agent systems comes from explicit control flow and a typed state contract — not from more clever prompts.

ShareX / TwitterLinkedIn
← Back to Learn