Q&A-2Model an agent workflow as a graph.
Answer
What I'd say first
Model it as a directed graph over one shared, typed state object. Nodes are agent invocations; edges are data and control dependencies. The state is the only channel between agents: no agent calls another directly. That one decision buys replay, budget accounting, and a single place to hang limits.
Assumptions: the agent set is known at build time, the task may need iterative refinement, and each run has a hard budget.
Four things the model must pin down:
- Node contract: typed input/output, owner, deadline, retry policy, terminal criteria.
- Guards: conditional edges that read state and pick the next node. All branching lives here, never inside an agent.
- Joins: a node with several incoming edges waits for all of them; quorum joins need custom logic.
- Cycles: allowed, but every cycle needs a progress condition plus hard caps on depth, wall-clock, tokens and cost.
Concrete instantiation: a five-agent research pipeline:
| Node | In → Out | Owner | Deadline | Retry | Terminal criteria |
|---|---|---|---|---|---|
| Planner | query:str → plan:list[str] | orchestrator | 2s | 1 | plan non-empty |
| Retriever | plan → docs:list[Doc] | search-agent | 5s | 2 | docs ≥ 3 |
| Summarizer | docs → summary:str | summarizer-agent | 6s | 1 | len(summary) > 100 |
| Critic | summary → score:float | critic-agent | 2s | 0 | score ∈ [0,1] |
| Writer | summary → final:str | writer-agent | 4s | 1 | final non-empty |
Edge critic → retriever is conditional: retry while score < 0.8 and retries < 2.
LangGraph 0.2.x
import operator
from typing import Annotated, Literal, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
class State(TypedDict):
query: str
plan: list[str]
docs: list[str]
summary: str
score: float
retries: int
cost_usd: Annotated[float, operator.add] # each node returns its delta
final: str
def planner(state: State) -> dict: ...
def retriever(state: State) -> dict: ... # returns {"docs": ..., "retries": state["retries"] + 1}
def summarizer(state: State) -> dict: ...
def critic(state: State) -> dict: ...
def writer(state: State) -> dict: ...
def route_critic(state: State) -> Literal["writer", "retriever"]:
if state["score"] >= 0.8 or state["retries"] >= 2:
return "writer"
return "retriever"
g = StateGraph(State)
for name, fn in [("planner", planner), ("retriever", retriever),
("summarizer", summarizer), ("critic", critic), ("writer", writer)]:
g.add_node(name, fn)
g.add_edge(START, "planner")
g.add_edge("planner", "retriever")
g.add_edge("retriever", "summarizer")
g.add_edge("summarizer", "critic")
g.add_conditional_edges("critic", route_critic, {"writer": "writer", "retriever": "retriever"})
g.add_edge("writer", END)
app = g.compile(checkpointer=MemorySaver())
app.invoke(
{"query": "...", "retries": 0, "cost_usd": 0.0},
config={"recursion_limit": 10, "configurable": {"thread_id": "run-1"}},
)Two things the framework will not do for you: it does not enforce token or cost caps (check state["cost_usd"] in a guard node, or raise from a callback), and it does not increment your retry counter. A node has to write it, or the guard reads a constant forever.
Trace (hypothetical figures)
| # | Node | in/out tok | s | $ | note |
|---|---|---|---|---|---|
| 1 | planner | 150/200 | 1.2 | 0.003 | |
| 2 | retriever | 500/100 | 2.5 | 0.005 | retries→1 |
| 3 | summarizer | 2000/300 | 3.0 | 0.015 | |
| 4 | critic | 300/50 | 0.8 | 0.002 | score 0.70 → retry |
| 5 | retriever | 600/120 | 2.8 | 0.006 | retries→2 |
| 6 | summarizer | 2200/320 | 3.2 | 0.016 | |
| 7 | critic | 320/50 | 0.9 | 0.002 | score 0.85 → writer |
| 8 | writer | 400/500 | 2.0 | 0.008 | |
| total | 8110 | 16.4 | 0.057 | 8 supersteps |
recursion_limit counts supersteps, not loop iterations, and the cycle here is three nodes long. One more retry would add three supersteps and raise GraphRecursionError before the retry counter fired. Size it as 1 + max_loop_iters × cycle_length + 1.
Alternatives
- DAG: trivially parallel, no replay ambiguity, but cannot express retry or refinement.
- State machine: explicit states and transitions; readable at five states, unmanageable at thirty.
- Blackboard: agents read/write a shared workspace opportunistically; most flexible, hardest to bound or debug.
Use the graph when the agent set is known, you need deterministic replay, and you want hard limits. Don't use it when agents must discover their own collaborators: that needs a supervisor spawning subgraphs, or a blackboard.
Failure modes
- Runaway cycle: no progress condition. Detect via
GraphRecursionError, or node execution count (retriever runs > 3). - Retry storm: retries without backoff. Detect via cost/min > $0.10, or > 5 retries in 60s.
- Join deadlock: fan-in waits on a branch that errored and was swallowed. Detect via node pending > 30s with no active upstream.
- State clobbering: two parallel branches write the same key with no reducer; last write wins silently. Detect by asserting the expected key set, or declare
Annotated[list, operator.add]. - Orphaned work: cancellation doesn't propagate. Detect via nodes still emitting after the parent is cancelled.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.