LangGraph explained: state, nodes and edges, with a 30-line example
LangGraph is a Python and JavaScript library for building agents as graphs: you write each step as a function, connect the steps with edges, and LangGraph runs them while carrying a shared state between them. Its own docs call it “a low-level orchestration framework and runtime for long-running, stateful agents”.1
Why a graph instead of a loop
A simple AI agent is a while-loop around a model call. That works until a client asks: where did it go wrong, can a person approve this step, and can it pick up after a crash? A graph answers those questions because every step has a name and every change to the state is recorded. The docs list what you get: hand-coded and model-driven steps in one graph, saved state so a run can resume after a failure or pause, pausing for a person to inspect or edit state, memory across sessions, and streaming of events as the graph runs.1 LangGraph does not require LangChain.1
The four ideas
| Idea | What it is | In the example |
|---|---|---|
| State | The shared data the graph carries, usually a TypedDict. Each node returns only the keys it changes; by default an update overwrites the old value2 | question, draft, tries, log |
| Node | A plain function that takes the state and returns an update2 | write, check |
| Edge | Runs one node after another; START is the entry and the run ends at END2 | START to write, write to check |
| Conditional edge | A routing function reads the state and returns the next node, which is how you build branches and loops2 | check goes back to write until the draft cites a source |
One more term: a reducer decides how updates to a key combine. With operator.add, a list key appends instead of being overwritten.2 The log key below uses it.
A tested example
This graph drafts an answer, checks that it cites a source, and retries up to three times. The model call is replaced by a plain function so you can run it with no API key. We ran it with langgraph 1.2.24 after pip install -U langgraph.1
import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
question: str
draft: str
tries: int
log: Annotated[list[str], operator.add] # reducer: append, don't overwrite
def write(state):
# In a real agent this is an LLM call. Here it improves on each try.
draft = "Refunds take 7 days." if state["tries"] == 0 else "Refunds take 7 days [policy.pdf, p2]."
return {"draft": draft, "tries": state["tries"] + 1, "log": [f"write #{state['tries'] + 1}"]}
def check(state):
return {"log": ["check: " + ("cited" if "[" in state["draft"] else "no source")]}
def route(state):
if "[" in state["draft"]:
return "done"
return "retry" if state["tries"] < 3 else "done"
g = StateGraph(State)
g.add_node("write", write)
g.add_node("check", check)
g.add_edge(START, "write")
g.add_edge("write", "check")
g.add_conditional_edges("check", route, {"retry": "write", "done": END})
app = g.compile()
out = app.invoke({"question": "How long do refunds take?", "draft": "", "tries": 0, "log": []})
print(out["draft"])
print(out["log"])
Output:
Refunds take 7 days [policy.pdf, p2].
['write #1', 'check: no source', 'write #2', 'check: cited']
Swap the body of write for a real model call and you have the core of a RAG answerer that refuses to ship an uncited answer. The tries limit matters: LangGraph also caps runs with a recursion limit and raises GraphRecursionError when a loop runs too long.2
What to add for production
- A checkpointer. Pass one to
compile()and completed steps are saved, so a resumed run does not repeat them.2 - Human approval. Interrupts pause the graph so a person can check the state before a risky step, such as sending an email or changing a record.1
- Evals and traces. A graph makes each step testable on its own. Measure it with evals and watch it with tracing.
When not to use it
If the steps never change order, a plain function calling the model twice is easier to read. Reach for a graph when there are branches, loops, people in the loop or runs that must survive a restart. Our agent vs workflow guide covers that choice.
The Zero to FDE roadmap builds an agent by hand first, then rebuilds it as an agent graph, so you know what the library is doing for you. The course is self-paced and written: there are no live classes, mentors or certificate.
Zero to FDE is a self-paced 16-week course, ₹2,999 once, with a 7-day full refund. Week 1 is free, and one Week 4 lesson is free if you already write backend code. It has no live classes, no mentors and no accredited certificate.
Sources
Zero to FDE is a 16-week path, for working engineers and AIML graduates, to the work Forward Deployed Engineers do: backend basics, LLMs, RAG, agents, evaluation and deployment, with a shipped deliverable every week. Week 1 is free and complete, no card needed.
Start Week 1 freeMore from the blog
- Forward Deployed Engineer jobs in 2026: what the data says
- What is RAG? Retrieval-augmented generation, explained with working code
- What is an AI agent? The agent loop, explained with code
- AI engineer roadmap 2026: what to learn, and in what order
- Will AI replace software engineers? What the data says in 2026
- Forward Deployed Engineer courses in India (2026): fees, format and how they compare
- Forward Deployed Engineer vs ML engineer: which AI role fits you?
- Forward Deployed Engineer salary in India: what the 2026 data says for 2027
- Forward Deployed Engineer interview questions: the six rounds and how to answer
- Why Forward Deployed Engineer is a smart next move for a software engineer
- Forward Deployed Engineer certification in 2026: what exists, what it costs, and what employers check
- Forward Deployed Engineer skills: what 1,000 job posts ask for
- Forward Deployed Engineer vs Solutions Engineer: the real difference
- Forward Deployed Engineer resume: what to put on one page
- Forward Deployed Software Engineer (FDSE): what the Palantir title means
- Forward deployed AI engineer, AI deployment engineer, FDE: the titles explained
- Prompt injection explained: what it is and how to defend against it
- Context engineering explained: beyond prompt engineering
- RAG vs fine-tuning: which one to use, and when
- LLM evals explained: how to test a system that gives different answers
- LLM observability explained: traces, cost and what to log
- Tool calling explained: how an LLM uses your functions
- What is MCP? The Model Context Protocol explained
- AI agent vs workflow: which one does your problem need?
- AI engineer vs ML engineer: what each one does
- AI engineer interview questions: 25 that test whether you have built anything
- What is a vector database? Explained with a 30-line example
- EY now hires Forward Deployed Engineers for audit. The role is leaving the AI labs
- Randstad: 90% of Indian employers are growing tech teams for AI. What it means for engineers
- AI agent memory explained: short-term vs long-term, with a tested example
- LLM cost optimization: prompt caching, batching and model routing, with the numbers
- Structured outputs from an LLM: JSON schema, validation and retries
- Embeddings explained: vectors, cosine similarity and dimensions
- Data engineer to AI engineer: what carries over and what to learn
- AWS launches a Forward Deployed Engineering Competency, with Infosys, TCS and Coforge among 22 launch partners
- Forward Deployed Architect: what the role is, certifications and courses
- Persistent launches a Forward Deployed Engineering program with Microsoft, a day after NIIT's FDE talent blueprint
- How to become an AI engineer in India: the route depends on where you start
- Self-paced Forward Deployed Engineer courses in India under ₹10,000 (and under ₹3,000)
- AWS and OpenAI will jointly staff forward deployed engineering teams inside customer environments
- Backend developer to AI engineer: what carries over and what to learn
- Claude now runs on premises in customers' own data centers through AWS AI Factories
- Agentic AI courses compared: four free options, and what a course must make you build
- AWS: attacks on AI systems grew about 800% in 2026, and an AI agent broke into a decoy MCP server in 12.7 minutes