Getting Started with LangGraph: Build a Stateful AI Agent (Not Another Prompt Chain)
From the publisher’s feed, collected in the ZeroLabs newsroom.
Prompt chains break the moment you need branching, retries, tools, or memory.Most “agent” demos look great until the workflow stops being linear.The second you need conditional steps, loops, state, or multiple tools, a straight line turns into a mess of if/else blocks and glue code.LangGraph’s core idea is simple: model your agent as a directed graph.Nodes do work (call an LLM, run a tool, validate output).Edges decide what happens next (including branching and looping).State carries memory across steps.In this guide, you’ll build a minimal stateful agent and learn the mental model behind LangGraph — without getting lost in framework trivia.What You’ll BuildA tiny agent that:accepts a user question,routes it through an LLM/tool step,stores conversation context in state,produces a response.Then you’ll extend it with:memory + persistence (so restarts don’t wipe context),debugging/testing practices (so graphs don’t become black boxes),a clear path to multi‑agent workflows.The Core Building Blocks of LangGraph (Before We Touch Code)Before writing any code, it’s important to understand what LangGraph is really giving you.Most confusion comes from trying to map LangGraph directly to prompt chains. That mental model breaks quickly.LangGraph introduces three first‑class concepts that change how agent systems are designed: nodes, edges, and state.1) Nodes: Units of Intentional WorkA node is a single, well‑defined operation in your workflow.A node answers one question:What piece of work should happen here?Examples:call an LLM,execute a tool (search, DB query, API call),validate output,transform intermediate data.The shift: nodes do not “own the workflow”. They only read/write shared state.2) Edges: Explicit Control Flow (The Real Value)Edges define when and why a node runs after another.In many agent stacks, control flow is hidden inside prompts or scattered conditional logic.LangGraph makes flow explicit, so you can model:sequencebranchingretriesloopsfallbacksIf nodes define what can happen, edges define what is allowed to happen next.3) State: The Agent’s Memory and Coordination LayerState is not just conversation history.It’s the shared, mutable context every node can read and update:messages,routing decisions,tool outputs,counters/flags,intermediate results.Think of the state as the system of record for agent behavior.Nodes don’t talk to each other directly. They coordinate through state.The Mental Model: Nodes, Edges, and StateIf prompt chains feel like a function call, LangGraph feels like a control system.Nodes are your operators (LLM call, tool call, validation).Edges encode control flow (sequence, branch, loop, retry).State is shared memory across the graph.Once control flow is explicit, you can reason about an agent like any workflow system: branching, retries, loop caps, and state transitions.Nodes, Edges, State— the mental model anchorStep 1 — Define the State (Minimal but Useful)A practical state for a basic agent usually includes:messages (conversation history)scratch (intermediate results)meta (routing decisions, flags, counters)Keep state small and intentional. Large state becomes slow, expensive, and hard to debug.A Minimal LangGraph Workflow (End‑to‑End)Minimal LangGraph workflow with routing, tool path, and stateYou now have the mental model. Let’s make it concrete with a minimal workflow that maps directly to the three primitives:State: a shared dictionary that every node reads/writes.Nodes: small functions that do one job and update state.Edges: explicit rules that decide which node runs next.Note: The code below is intentionally conceptual. LangGraph APIs evolve across versions.This example focuses on architecture so you can map it to the current LangGraph primitives without fighting import names.1) State — the shared memory# STATE: shared memory across nodesstate = { "messages": [], # conversation history "scratch": {}, # intermediate results (tool outputs, parsed fields) "meta": { "turn": 0, "route": None, # set by the router node "max_steps": 6, "steps": 0, }}2) Nodes — small, testable units of work# NODE: capture user input into statedef node_user_input(state, user_text: str): state["messages"].append({"role": "user", "content": user_text}) state["meta"]["turn"] += 1 return state# NODE: routing decision (direct vs tool)def node_router(state): last = state["messages"][-1]["content"].lower() # Keep the heuristic simple for the minimal workflow. # In real systems, routing can be an LLM call + guardrails. needs_tool = any(k in last for k in ["search", "lookup", "docs", "reference"]) state["meta"]["route"] = "tool" if needs_tool else "direct" return state# NODE: tool execution (placeholder)def node_tool(state): query = state["messages"][-1]["content"] # Replace this with an actual tool call. tool_result = f"TOOL_RESULT({query})" state["scratch"]["tool_result"] = tool_result return state# NODE: LLM call (direct)def node_llm_direct(state): prompt = build_prompt_from(state["messages"]) # you implement answer = llm(prompt) # you implement state["messages"].append({"role": "assistant", "content": answer}) return state# NODE: LLM call (synthesis after tool)def node_llm_synthesize(state): tool_result = state["scratch"].get("tool_result", "") prompt = build_prompt_from(state["messages"], tool_result=tool_result) # you implement answer = llm(prompt) # you implement state["messages"].append({"role": "assistant", "content": answer}) return state# NODE: final response (a view of state)def node_response(state): return state["messages"][-1]["content"]3) Edges — explicit control flowInstead of hiding flow in if/else scattered across your app, define it once.# EDGES: explicit "what runs next" rulesdef next_node(current: str, state): if current == "user_input": return "router" if current == "router": return "tool" if state["meta"]["route"] == "tool" else "llm_direct" if current == "tool": return "llm_synthesize" if current in ["llm_direct", "llm_synthesize"]: return "response" return "end"4) End‑to‑end runner — execute nodes by following edgesNODES = { "user_input": node_user_input, "router": node_router, "tool": node_tool, "llm_direct": node_llm_direct, "llm_synthesize": node_llm_synthesize,}def run_workflow(user_text: str): current = "user_input" while current != "end": # Safety: avoid accidental infinite loops. state["meta"]["steps"] += 1 if state["meta"]["steps"] > state["meta"]["max_steps"]: raise RuntimeError("Workflow exceeded max steps") # Execute the current NODE. if current == "user_input": NODES[current](state, user_text) elif current in NODES: NODES[current](state) elif current == "response": return node_response(state) # Follow EDGES to choose the next NODE. current = next_node(current, state) return ""print(run_workflow("Explain LangGraph in one sentence"))print(run_workflow("Search docs for LangGraph state handling"))What this workflow teaches (without extra abstraction)State is the shared contract between nodes.Nodes are small and testable (they read/write state).Edges make control flow visible (and debuggable).Once this clicks, scaling to retries, branching, and multi‑agent graphs becomes straightforward.Upgrade: Add a Tool Step (Where Graphs Start Paying Off)Even simple agents quickly need tools: search, DB queries, function calls, and retrieval.A clean pattern is:decide whether you need a toolExecute the toolsummarize the tool output into a statesynthesize a final response.Text DiagramUser Input │ ▼[Router Node] ── yes ──► [Tool Node] ─► [LLM Synthesis] ─► Response │ └── no ─────────► [LLM Direct] ─► ResponseThis is where LangGraph stays clean while “prompt‑chain + if/else” starts to collapse.Memory & Persistence: Why State Alone Is Not EnoughState makes an agent coherent within a single execution.Persistence makes an agent reliable across deployments, restarts, and failures.Without persistence, every deployment resets your agent’s memory to zero — conversation context disappears, learned preferences vanish, and long‑running workflows silently break. In production systems, this isn’t an edge case; it’s the default failure mode.Think of the distinction this way:State answers: “What does the agent know right now?”Persistence answers: “What should the agent remember tomorrow?”Not all states deserve to be remembered. Persisting everything creates security risks, performance issues, and debugging nightmares. Persisting in nothing makes agents behave like goldfish.Practical Principles for Agent MemoryGood agent memory follows the same discipline as system design:Persist only decision‑shaping information — data that improves future behavior.Never persist raw secrets or sensitive inputs; memory leaks are harder to revoke than logs.Bound memory growth using truncation, summarization, or expiry.Ensure atomic updates when multiple workers or retries may write concurrently.What’s Worth Persisting (In Priority Order)Conversation summaries — compact, distilled context beats raw transcripts.User preferences — safe, minimal signals that guide future decisions.Stable identifiers — references, not raw personally identifiable data.Tool outputs — only when they are deterministic, reusable, and safe.Persistence is not about remembering everything. It’s about remembering the right things for the right length of time.Diagram comparing stateful vs durable memory and showing why tracing state transitions helps debuggingDebugging & Testing: Graphs Fail Differently Than ServicesGraph‑based agents don’t usually fail because of “bad prompts.” They fail because the control flow went wrong.The most common failures look like this:loops that never terminate,state accidentally overwritten in the wrong node,tool failures cascading into invalid decisions,Concurrent executions corrupting shared memory.These failures are subtle because the agent often continues running — just incorrectly. By the time someone notices, the root cause is buried several transitions back in the graph.The Minimum Testing Strategy That Actually WorksTesting graph agents means validating behavior across paths, not just outputs.At a minimum:Unit test nodes Given an input state, assert the exact state diff after execution.Integration test paths Test the happy path, tool failure path, and retry or fallback path.Enforce execution limits Add maximum iteration or step counts to prevent runaway loops.Log state changes, not entire state Debug what changed — full snapshots quickly become noise.If you use workflow observability tools (such as LangSmith), use them intentionally:visualize which path was executed,inspect individual node outputs,Track how the state evolves step by step.The goal is not prettier traces — it’s confidence that your agent behaves predictably under failure.Multi‑Agent Workflows (A Glimpse of What Comes Next)Single agents are useful when tasks are simple and mostly linear. But once problems grow beyond a narrow scope — requiring planning, information gathering, verification, and synthesis — a single agent model starts to strain.This is where multi‑agent workflows become powerful.Instead of asking one agent to do everything, the system is decomposed into specialized agents, each with a clear responsibility:One agent focuses on planning the next steps,One agent handles retrieval or external data access,One agent verifies or validates intermediate results,One agent synthesizes the final response.Each agent is simpler, easier to reason about, and easier to test. The system’s intelligence emerges not from a single large prompt, but from coordination.The key to making this work is not clever prompting — it is shared state and explicit handoffs. Agents don’t guess what others are doing. They communicate through well‑defined state updates, and control flow determines who runs next and why. LangGraph’s graph‑based model makes this coordination visible instead of implicit.In the next article, we’ll build a focused example: a two‑agent workflow where a planner agent decides what needs to be researched, and a researcher agent gathers information before handing results back. This example only works because control flow and responsibilities are explicit — exactly what LangGraph is designed for.If you’re exploring AI systems from the ground up and want clear, beginner‑friendly explanations that connect concepts to real architectures, consider following this channel. Upcoming posts will continue breaking down agent workflows, system design patterns, and practical AI concepts — step by step, without assuming prior expertise.Wrap‑Up: What LangGraph Really Gives YouLangGraph isn’t about making LLM calls easier.It’s about making agent behavior visible, predictable, and controllable.When workflows are modeled as graphs, you gain:explicit control flow instead of hidden prompt logic,state you can inspect instead of implicit memory,and workflows that evolve safely instead of collapsing into tangled conditionals.This shift matters because real agents don’t fail in demos — they fail in production. They fail when tools time out, when retries stack up, when memory grows, and when control logic becomes impossible to reason about.The real goal isn’t to build agents that seem intelligent in a single run. It’s to build agents that remain stable, debuggable, and extensible as you add tools, memory, retries, and real operational constraints.LangGraph isn’t a shortcut.It’s a structure that lets complex agent systems grow without losing control.Getting Started with LangGraph: Build a Stateful AI Agent (Not Another Prompt Chain) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.