Zero Labs
Industry News / AI

LangGraph Agents: A Practical Guide to Building Stateful AI Workflows

Source · Towards AI By Arijit Dutta

From the publisher’s feed, collected in the ZeroLabs newsroom.

How state, nodes, edges, tools, persistence, interrupts, and deterministic control fit together in a reliable AI-agent architecture.A useful AI application often needs much more than “send a prompt, receive an answer.” It may need to classify a request, retrieve trusted data, call APIs, ask for approval, remember progress, retry after failure, and decide what should happen next.LangGraph is a low-level orchestration framework for building these stateful workflows and agents as a graph of steps. Those steps can branch, loop, persist progress, call tools, stream intermediate events, and pause for human input.The simplest mental model is: state is what the system knows, nodes do the work, and edges decide what runs next.Why orchestration mattersConsider a customer asking: “My order arrived damaged. Can I get a refund?”A production system may need to:understand the request,extract or locate an order ID,load the real order record,apply refund policy,route large refunds to a human,perform the refund exactly once, andexplain the verified result to the customer.If all of this logic is hidden inside one large function or one opaque model loop, it becomes difficult to test, observe, resume, and control. LangGraph makes the control flow explicit while still allowing model-driven decisions where they are useful.A delivery-hub analogyImagine a parcel moving through a delivery hub:State is the parcel’s label and contents: information carried through the process.Nodes are stations: inspect address, weigh parcel, request payment, load truck.Edges are conveyor choices: they determine which station comes next.Checkpoints are scanner logs: they record how far the parcel got.Interrupts are supervisor stops: work pauses until a human approves or corrects something.The analogy is useful because it makes execution steps and transitions visible. It is not exact: software nodes can run in parallel, invoke probabilistic models, revisit earlier nodes, and update only selected fields of shared state.The core LangGraph model1. State: the shared working dataState is the current snapshot of information available to graph steps. A state schema defines which fields exist and, in Python, usually their types.from typing_extensions import TypedDictclass CounterState(TypedDict): count: intIf the current state is {"count": 4}, a node can read that value and return an update such as {"count": 5}. A node does not need to return every state field.A useful rule is to keep state limited to the information required to coordinate the workflow. Treat it as shared working data, not as a dump of every temporary local variable.2. Nodes: units of workA node is executable logic. It may call a model, run deterministic code, validate output, query a service, perform a tool action, or request human input.def increment(state: CounterState): return {"count": state["count"] + 1}If count is 4, this node returns 5. Returning an explicit update gives the runtime a clean boundary for state management.This boundary is also valuable for software engineering: small nodes let you test routing separately from database access, tool execution, validation, or an LLM call.3. Edges: control flowAn edge determines which node executes next. A normal edge always follows the same transition. A conditional edge calls routing logic and chooses a destination based on state.from typing import Literaldef route(state: CounterState) -> Literal["again", "done"]: return "again" if state["count"] Conditional routing is especially useful for exact business rules. If ordinary code can determine the answer precisely, there is usually no benefit in asking an LLM to guess it.A minimal graphWith the Graph API, StateGraph is a builder. You add nodes and edges, then call compile() to produce an executable graph.from langgraph.graph import StateGraph, START, ENDbuilder = StateGraph(MyState)builder.add_node("work", work_node)builder.add_edge(START, "work")builder.add_edge("work", END)graph = builder.compile()START and END are special markers rather than business-logic nodes. START represents where input enters; END represents termination.The agent loop: model, tool, modelA tool-capable model can produce a structured request containing a tool name and arguments. The application, not the model itself, performs the real operation.messages -> model -> tool request? | no -> finish | | yes v tool -> tool result -> model -> ...The model chooses only from the tools you expose. Tool descriptions and schemas therefore become part of the agent’s interface design. A vague tool description can lead the model to call the right capability incorrectly.This is also where an important distinction appears: a workflow follows predetermined code paths, while an agent dynamically chooses actions and tool usage. Strong systems often combine the two: deterministic workflow structure around a smaller agentic region.Do not make everything agenticOne of the most practical design lessons in the source material is that an LLM does not have to control everything.A robust refund workflow might divide responsibility like this:LLM: understand a free-form customer request.Backend service: load trusted order data.Deterministic code: apply exact refund-policy rules.Human: approve a high-value refund.Refund API: move money.LLM: turn the verified outcome into a clear customer-facing response.Use models where flexible judgment adds value. Keep exact rules, permissions, and irreversible actions constrained.create_agent or custom LangGraph?The section distinguishes a higher-level agent harness from lower-level orchestration. As of the current LangChain documentation, LangChain’s create_agent is the recommended higher-level option for a familiar model-plus-tools loop and is built on LangGraph.from langchain.agents import create_agentdef get_weather(city: str) -> str: """Return weather data for a city.""" return f"Weather lookup for {city}"agent = create_agent( model="openai:gpt-5.5", tools=[get_weather], system_prompt="Use tools when needed, then answer concisely.",)result = agent.invoke({ "messages": [ {"role": "user", "content": "Weather in Kolkata?"} ]})The expected behavior is that the model can choose the weather tool, receive its returned value, and then answer the user. Exact wording depends on the configured model and provider.Use create_agent first when:your architecture is mainly the standard model-plus-tools loop,you do not need to own every graph transition, andthe prebuilt harness already matches the workflow you need.Use custom LangGraph when you need:custom state,nontrivial branching or loops,explicit multi-stage orchestration,specialized human review,subgraphs or parallel fan-out, orfine control over persistence and execution.Reducers and message stateA reducer defines how an existing state value combines with a new update. Without a special reducer, a new update commonly replaces the previous value. Some fields instead need accumulation.For example, if a list field uses concatenation, conceptually:new list = old list + incoming itemsHere + means list concatenation, not numeric addition. ["a"] + ["b"] becomes ["a", "b"].For chat-style agents, MessagesState provides a standard convenience state for maintaining a chronological sequence of user messages, model replies, tool requests, and tool results.Reducers matter even more when multiple branches update the same key. Parallel execution creates a state-design problem: simultaneous updates must have intentional merge behavior.Persistence: checkpoints and stores are not the same thingLangGraph separates two kinds of persistenceCheckpointer: saves snapshots of one thread’s graph state.Store: persists application-defined data that may be shared across threads.A checkpointer supports conversation continuity, resumption, human-in-the-loop flows, debugging or time-travel behavior, and fault recovery. A thread_id identifies which thread state to load.from langgraph.checkpoint.memory import InMemorySavercheckpointer = InMemorySaver()graph = builder.compile(checkpointer=checkpointer)config = { "configurable": { "thread_id": "user-42-chat-1" }}result = graph.invoke(input_state, config=config)InMemorySaver is useful for examples, but it loses data when the process restarts. A production system that needs durable recovery should use a persistence backend suited to its deployment.A store solves a different problem: durable application information that should not be tied to only one conversation thread.Human-in-the-loop with interruptsAn interrupt pauses graph execution and surfaces a JSON-serializable payload to the caller. This is useful when the workflow needs an approval or other external decision before continuing.from langgraph.types import interruptdef approval_node(state): approved = interrupt({ "question": "Approve refund?", "amount": state["refund_amount"], }) return {"approved": bool(approved)}To continue, the same thread is resumed with a Command(resume=...) value.The key implementation detail is easy to miss: when execution resumes, the interrupted node starts again from its beginning. That means side effects performed before interrupt() should be idempotent, or better, moved after approval.Streaming and control primitivesStreaming lets a caller observe intermediate execution instead of waiting only for the final result. Depending on the API and stream mode, the caller may observe message chunks, state snapshots or updates, custom events, and interrupts.Streaming does not make the underlying work faster; it makes progress visible sooner and can make long-running agent execution easier to debug.LangGraph also provides Command, which can combine a state update with a routing decision from inside a node. It is useful when a node naturally produces both data and control flow. The source cautions against using it everywhere: ordinary edges keep simple flows easier to read.For dynamic parallel fan-out, Send can create downstream work items with different inputs. Subgraphs can package reusable workflows, teams of agents, or specialized stages behind a clear input/output contract.A worked architecture: customer-support refund agentThe PDF’s integrated example combines the main ideas into a refund workflow. It is presented as an original teaching example rather than an official policy.State might include:messages: conversation messages,order_id: parsed order identifier,order: trusted backend order data,refund_amount: requested or computed amount,eligible: deterministic policy result,approved: human decision when needed, andrefund_id: backend identifier proving the refund occurred.START -> understand_request -> load_order -> policy_check / | \ ineligible small large | | | explain refund approval | | | END reply | ENDStep 1: understand the requestA model can turn free text such as “Please refund order A123; the item arrived damaged” into structured fields. This is a good model task because natural language varies.Step 2: load trusted order dataA deterministic service call should fetch the real order record. Do not let the model invent price, payment status, delivery state, or whether the order exists.Step 3: apply policy in codedef policy_check(state): order = state["order"] eligible = ( order["delivered"] and order["days_since_delivery"] and not order["already_refunded"] ) return {"eligible": eligible}If the order was delivered eight days ago and has not already been refunded, all three Boolean conditions are true and eligible becomes True.Step 4: route by riskIn the teaching example, eligible refunds at or below Rs. 2,000 can proceed automatically, while larger refunds require human review.def refund_route(state): if not state["eligible"]: return "reject" if state["refund_amount"] return "auto_refund" return "human_review"For eligible=True and refund_amount=1500, the route is "auto_refund". For Rs. 3,500, the route is "human_review".Step 5: request approval when requiredThe graph pauses with an interrupt containing only the information a reviewer needs: order ID, amount, reason, and relevant policy facts. The same thread_id must be reused when execution resumes.Step 6: make the side effect safeThe refund API should accept an idempotency key such as refund:: when the external service supports that pattern. Idempotent means that retrying the same logical operation does not create a duplicate refund.The returned refund_id should be stored in state so later nodes work from the verified outcome rather than from a model's assumption.Step 7: compose the customer responseThe model can turn the authoritative result into a friendly explanation. It should receive the actual status and refund identifier rather than decide whether money moved.The agentic part is language understanding or flexible tool selection. The deterministic part should include eligibility rules, permission checks, monetary side effects, and idempotency.Production engineering lessonsThe source recommends a practical implementation sequence:Define the state schema before writing nodes.Mark which facts are trusted business data versus model-generated guesses.Make each node do one testable job.Put exact rules in code; use models for interpretation, ranking, drafting, and flexible decisions.Add persistence before introducing interrupts or long-running resumable work.Make external side effects idempotent and record their identifiers.Stream useful progress to the UI without exposing hidden model reasoning.Trace, evaluate, and load-test representative paths before production rollout.Tests that catch real failuresNode unit tests: given fixed state, assert the returned update.Routing tests: verify every boundary condition, especially exact thresholds.Graph path tests: simulate common end-to-end routes without real payments.Tool contract tests: verify schemas, authorization, timeouts, and error mapping.Resume tests: interrupt, restart if feasible, then resume using the same thread.Idempotency tests: repeat a side-effect node and confirm only one real operation occurs.Evaluation tests: for model-driven steps, use a curated dataset and measurable pass/fail criteria.Common implementation mistakesOne giant node that hides parsing, retrieval, validation, and side effects.Storing secrets or huge raw objects in graph state without need.Letting an LLM enforce exact policy or authorization rules.Using in-memory persistence in production and assuming it survives restarts.Performing a payment, email, or database side effect before an interrupt without idempotency.Infinite or expensive loops with no termination strategy.Tool descriptions that omit units, allowed values, or failure semantics.Seven common LangGraph misunderstandings1. “LangGraph is an LLM.”It is not. LangGraph orchestrates execution. A graph can call models from different providers, or it can contain no model at all.2. “Every node is an AI agent.”A node is simply a function or runnable step. It may be deterministic code, a service call, a model call, or a human-input step.3. “State means chat history.”Messages are one possible state field. State is the graph’s broader working snapshot: IDs, flags, structured results, counters, approvals, trusted data, and more.4. “A checkpointer and a store are the same memory mechanism.”They solve different problems. A checkpointer persists thread-scoped graph snapshots; a store holds application-defined information that may be shared across threads.5. “create_agent replaced LangGraph."create_agent is a higher-level LangChain harness built on LangGraph. Custom LangGraph remains useful when lower-level orchestration control is required.6. “An interrupt resumes from the exact Python instruction after interrupt()."The interrupted node starts again from its beginning when resumed. That is why side-effect placement and idempotency matter.7. “More autonomy always means a better agent.”More freedom is not automatically better. Give the model flexibility only where it creates value; constrain exact rules, permissions, and irreversible actions.A memory technique: SNERState = what the system currently knows.Nodes = work that uses or changes that knowledge.Edges = what runs next.Runtime = persistence, streaming, interrupts, retries, and execution behavior.Picture a railway map: the train carries state, stations are nodes, tracks are edges, switches are conditional routes, station logs are checkpoints, and a red signal is an interrupt.Final takeawayLangGraph is useful when agent behavior must be explicit and operationally reliable. Its value is not that every step becomes “AI.” Its value is that you can combine probabilistic model decisions with deterministic software engineering in one visible execution model.Start with the smallest abstraction that fits. If a simple model-plus-tools loop is enough, a higher-level agent harness may be the better choice. If you need custom state, nontrivial branching, durable execution, human approval, carefully controlled side effects, or multi-stage orchestration, custom LangGraph gives you the lower-level control to design those behaviors directly.State remembers. Nodes work. Edges route. Checkpoints save. Interrupts ask humans. Tools act on the outside world.ReferencesLangGraph overviewLangGraph Agents: A Practical Guide to Building Stateful AI Workflows was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.