Vivek's Field Notes

Lang Graph

• 19 min read

Short notes, added as I learn.

What is LangGraph?

LangGraph is a framework (from the LangChain team) for building stateful LLM apps as graphs: workflows and agents that can loop, branch, pause and resume.

You describe the app as:

1graph = StateGraph(State)
2graph.add_node("generate", generate)
3graph.add_node("check", check)
4graph.add_edge(START, "generate")
5graph.add_edge("generate", "check")
6graph.add_conditional_edges("check", lambda s: "generate" if s["bad"] else END)
7app = graph.compile()          # turns it into a runnable app
8app.invoke({"question": "…"})

The graph that code builds:

flowchart LR
  S([START]) --> G[generate]
  G --> C{check}
  C -->|bad| G
  C -->|good| E([END])

Why it exists: plain LangChain chains are a one-way pipe. Real agents need:

NeedLangGraph gives
Retry / loop until goodCycles in the graph
Choose the next step at runtimeConditional edges
Shared memory between stepsState + reducers
Remember across calls, survive crashesCheckpointers
Human approvalinterrupt()
Many agentsSubgraphs
Live outputStreaming

It is low-level: it doesn’t hide prompts or decide your agent’s logic. It is the runtime that runs your graph reliably. It works with or without LangChain.

One line: LangChain = building blocks (LLMs, prompts, tools, retrievers). LangGraph = the runtime that wires them into a stateful, looping app.

Workflow vs agent

Workflow: you write the path. The LLM fills in steps, but the order is fixed in code. input → summarize → translate → output. Predictable, cheap, easy to test.

Agent: the LLM chooses the path. It looks at the state, picks the next step or tool, and loops until it decides it’s done. input → LLM → (tool? → LLM → tool? → ...) → output. Flexible, but slower, costlier, and can loop.

WorkflowAgent
Who picks the next stepYour codeThe LLM
PathFixedDecided at runtime
Good forKnown stepsOpen-ended tasks
RiskRigidLoops, cost, surprises

Rule: use a workflow when you can draw the steps up front. Use an agent only when you can’t.

flowchart LR
  subgraph W[Workflow: your code picks the path]
    direction LR
    i1([input]) --> s1[summarize] --> s2[translate] --> o1([output])
  end
  subgraph A[Agent: the LLM picks the path]
    direction LR
    i2([input]) --> L{LLM decides}
    L -->|call tool| T[tool]
    T --> L
    L -->|done| o2([output])
  end

In LangGraph both are the same thing, a graph. A workflow uses fixed edges (add_edge). An agent uses a conditional edge where the LLM’s output picks the next node (add_conditional_edges).

LLM workflows: the 5 common patterns

An LLM workflow is a fixed series of steps where one or more steps call an LLM. Most real apps are one of these 5 patterns (or a mix):

1. Prompt chaining: the output of one LLM call is the input to the next.

flowchart LR
  T([topic]) --> O[LLM: outline] --> W[LLM: write blog] --> P[LLM: proofread] --> B([blog])

Use when the task splits cleanly into steps. You can add a check between steps.

2. Routing: classify the input first, then send it to the right specialist.

flowchart LR
  Q([query]) --> C{LLM: classify}
  C -->|refund| R[refund handler]
  C -->|tech| T[tech-support handler]
  C -->|general| G[general handler]

Use when inputs fall into clear types. In LangGraph: a conditional edge.

3. Parallelization: run independent LLM calls at the same time, then combine them.

flowchart LR
  E([essay]) --> G[LLM: grammar score]
  E --> C[LLM: clarity score]
  E --> D[LLM: depth score]
  G --> M[combine]
  C --> M
  D --> M
  M --> F([final score])

Use for speed, or for several views of the same input (voting). In LangGraph: fan-out edges + a reducer to merge the results.

4. Orchestrator–worker: one LLM plans the subtasks at runtime, workers do them, and the results are combined.

flowchart LR
  T([task]) --> O[orchestrator LLM<br/>splits into N subtasks]
  O -.->|Send| W1[worker 1]
  O -.->|Send| W2[worker 2]
  O -.->|Send| WN[worker N]
  W1 --> S[synthesizer]
  W2 --> S
  WN --> S
  S --> R([result])

Unlike parallelization, the subtasks are not known in advance (e.g. “edit every file that needs a change”). In LangGraph: the Send API to spawn workers.

5. Evaluator–optimizer: one LLM generates, another critiques, and it loops until it’s good enough.

flowchart LR
  S([START]) --> G[LLM: generate]
  G --> E{LLM: evaluate}
  E -->|not good: feedback| G
  E -->|good, or tries >= 3| X([END])

Use when there are clear criteria and iteration helps (writing, translation, SQL fixing). In LangGraph: a loop with a max-iterations guard.

PatternShapeLangGraph feature
Prompt chainingStraight lineadd_edge
RoutingOne-of-N branchadd_conditional_edges
ParallelizationFan-out / fan-inParallel edges + reducer
Orchestrator–workerDynamic fan-outSend
Evaluator–optimizerLoopConditional edge back + limit

When even these aren’t flexible enough (the steps can’t be drawn up front), you use an agent: an LLM calling tools in a loop and deciding each step.

These patterns are from Anthropic’s “Building effective agents” post.

The 5 patterns in LangGraph code

llm is any chat model. The code shows only the graph wiring, so each snippet stays short.

1. Prompt chaining

 1class S(TypedDict):
 2    topic: str
 3    outline: str
 4    blog: str
 5
 6def make_outline(s): return {"outline": llm.invoke(f"Outline for: {s['topic']}").content}
 7def write_blog(s):   return {"blog": llm.invoke(f"Write a blog from:\n{s['outline']}").content}
 8
 9g = StateGraph(S)
10g.add_node("outline", make_outline)
11g.add_node("write", write_blog)
12g.add_edge(START, "outline")
13g.add_edge("outline", "write")
14g.add_edge("write", END)

2. Routing

1def classify(s):
2    return {"kind": llm.invoke(f"Answer refund, tech or general: {s['q']}").content.strip()}
3
4g.add_node("classify", classify)
5g.add_conditional_edges("classify", lambda s: s["kind"],
6                        {"refund": "refund", "tech": "tech", "general": "general"})

3. Parallelization

 1class S(TypedDict):
 2    essay: str
 3    scores: Annotated[list[int], operator.add]   # reducer: merges the parallel writes
 4    final: float
 5
 6def grammar(s): return {"scores": [score(s["essay"], "grammar")]}
 7def clarity(s): return {"scores": [score(s["essay"], "clarity")]}
 8def depth(s):   return {"scores": [score(s["essay"], "depth")]}
 9def combine(s): return {"final": sum(s["scores"]) / len(s["scores"])}
10
11for n, fn in [("grammar", grammar), ("clarity", clarity), ("depth", depth)]:
12    g.add_node(n, fn)
13    g.add_edge(START, n)        # fan-out
14    g.add_edge(n, "combine")    # fan-in: combine waits for all three

4. Orchestrator–worker

 1from langgraph.types import Send
 2
 3class S(TypedDict):
 4    task: str
 5    subtasks: list[str]
 6    results: Annotated[list[str], operator.add]
 7    answer: str
 8
 9def plan(s):   return {"subtasks": split_into_subtasks(s["task"])}       # LLM decides N
10def assign(s): return [Send("worker", {"sub": t}) for t in s["subtasks"]]
11def worker(w): return {"results": [llm.invoke(w["sub"]).content]}
12def synth(s):  return {"answer": "\n".join(s["results"])}
13
14g.add_node("plan", plan)
15g.add_node("worker", worker)
16g.add_node("synth", synth)
17g.add_edge(START, "plan")
18g.add_conditional_edges("plan", assign, ["worker"])   # spawn N workers at runtime
19g.add_edge("worker", "synth")

5. Evaluator–optimizer

 1class S(TypedDict):
 2    task: str
 3    draft: str
 4    feedback: str
 5    ok: bool
 6    tries: int
 7
 8def generate(s):
 9    d = llm.invoke(f"{s['task']}\nFix this feedback: {s['feedback']}").content
10    return {"draft": d, "tries": s["tries"] + 1}
11
12def evaluate(s):
13    v = judge(s["draft"])                 # LLM with structured output: ok + feedback
14    return {"ok": v.ok, "feedback": v.feedback}
15
16g.add_edge(START, "generate")
17g.add_edge("generate", "evaluate")
18g.add_conditional_edges("evaluate",
19    lambda s: END if s["ok"] or s["tries"] >= 3 else "generate")
20
21app.invoke({"task": "...", "feedback": "", "tries": 0})

State and data points

State: the shared memory of one graph run. Every node can read it, and nodes update it as the run moves forward. Think of it as a dict that travels through the graph.

Data points: the individual keys inside the state. Each one is a piece of info the workflow needs to remember.

1class EssayState(TypedDict):
2    essay: str          # data point: the input
3    feedback: str       # data point: written by the "review" node
4    score: int          # data point: written by the "grade" node

So: state = the container, data points = what’s in it.

Workflow state: how state moves through a run

The state is passed from node to node. Each node adds or changes its data points, so the state fills up as the workflow runs:

1START        {essay: "…", feedback: "",       score: 0}
2  ↓ review   returns {feedback: "good flow"}
3             {essay: "…", feedback: "good flow", score: 0}
4  ↓ grade    returns {score: 8}
5             {essay: "…", feedback: "good flow", score: 8}
6END          → this final state is what invoke() returns

StateGraph

A graph where every node reads one shared state and returns only the keys it changes.

Reducers: how a returned key is merged

A reducer is a function (old_value, new_value) -> merged_value. A node returns an update like {"steps": ["b"]}, and LangGraph calls the reducer of steps to merge it into the state. Each key has its own reducer, set in the state definition with Annotated[type, reducer].

1class State(TypedDict):
2    answer: str                                # override
3    steps: Annotated[list[str], operator.add]  # append

Classic bug: forget the reducer on a list and each node wipes the history. When two nodes run in parallel and write the same key, you need a reducer, or LangGraph raises an error.

Step by step

1state:        {steps: ["a"]}
2node returns: {steps: ["b"]}
3reducer:      operator.add(["a"], ["b"])  →  ["a", "b"]
4new state:    {steps: ["a", "b"]}

Without the reducer, the new state would be {steps: ["b"]}, and "a" is lost.

Common reducers

ReducerMergeUse for
none (default)new replaces oldCurrent answer, a flag, a counter you set
operator.addold + new (lists); old + new (numbers, so it sums)Logs, results from parallel workers, totals
add_messagesAppend messages; replace a message with the same idChat history (MessagesState uses it)
custom functionanything you writeDedupe, keep the max, merge dicts

Custom reducer

Any function with two arguments works:

1def merge_dict(old: dict, new: dict) -> dict:
2    return {**old, **new}                       # new keys win
3
4def keep_last_5(old: list, new: list) -> list:
5    return (old + new)[-5:]                     # bounded history
6
7class State(TypedDict):
8    meta: Annotated[dict, merge_dict]
9    recent: Annotated[list[str], keep_last_5]

Chat state with add_messages

1from langgraph.graph import MessagesState     # = {"messages": Annotated[list, add_messages]}
2
3def chatbot(s: MessagesState):
4    return {"messages": [llm.invoke(s["messages"])]}   # return only the new message

Rules to remember

Is LangChain stateless?

Mostly, yes. A LangChain chain is stateless.

1chain = prompt | llm | parser
2chain.invoke({"q": "My name is Vivek"})
3chain.invoke({"q": "What's my name?"})   # doesn't know

Memory in LangChain = you keep the chat history yourself and resend it each call. The old ConversationBufferMemory classes did this for you, and they’re deprecated now.

Caveat: newer LangChain (v1) builds its agents (create_agent) on the LangGraph runtime. Those agents can have state, but the state comes from LangGraph, not from the chain.

Does LangChain have a key-value store?

Yes, but not a shared workflow state.

  1. Dict passed down a chain. In prompt | llm | parser, each step gets the previous step’s output. RunnablePassthrough.assign(x=...) adds keys to it. Key-value, but it only flows forward in one pipe.
  2. Memory classes. Chat history only (deprecated).
  3. BaseStore / InMemoryStore. A real key-value store (mset, mget), used for caching embeddings or storing docs. A utility, not workflow state.

LangChain vs LangGraph: state

LangChain chainLangGraph
Data flowOutput → next input, one directionOne shared state that every node reads and writes
State inside one runOnly the dict in the pipeTyped state with data points
State across runsNoneYes, with a checkpointer
Loops / branchesHardBuilt in (conditional edges)
Merge rule per keyNoneReducers (override or append)

Main reason LangGraph exists: LangChain can store data, but it has no single state that lives through loops, branches and restarts.

Sequential vs event-driven execution

Sequential execution (LangChain chains): steps run in a fixed line, one after another. Step 2 always runs after step 1, and the order is set when you build the chain.

flowchart LR
  I([input]) --> P[prompt] --> L[llm] --> O[parser] --> X([output])

Simple and predictable, but it can’t go back (no loops) and it can’t decide at runtime which step comes next.

Event-driven execution (LangGraph): a node runs because something happened, not because it’s next in a list. The “event” is a state update: when a node finishes and writes to the state, that message triggers the nodes connected to it.

flowchart LR
  S([START]) --> G[generate_sql]
  G -->|writes state| V{validate}
  V -->|invalid: loop back| G
  V -->|valid| R[run_query]
  R --> X([END])

How LangGraph runs it (based on Google’s Pregel model):

  1. Run in super-steps. In each step, all nodes that received a message run, possibly in parallel.
  2. Their state updates are merged using the reducers.
  3. The updates trigger the next set of nodes.
  4. The run stops when no node is triggered (it reaches END) or the recursion limit is hit.
SequentialEvent-driven
What starts a stepIts position in the chainA message / state update reaching it
OrderFixed at build timeDecided at runtime
LoopsNoYes
Parallel nodesOnly special casesNatural (same super-step)
Used byLangChain chainsLangGraph

Note: a “sequential workflow” in LangGraph (START → a → b → END) still runs event-driven. It just happens to have one path.

Execution model (how a graph actually runs)

compile()

graph.compile() checks the graph (no orphan nodes, edges point to real nodes) and turns it into a Pregel app: a runnable object with invoke, stream and ainvoke. You can’t run a StateGraph before you compile it.

The pieces inside

Nodes never call each other. They only read channels and write channels. This is message passing.

One super-step = 3 phases

flowchart LR
  P[1. PLAN<br/>which nodes are triggered?] --> E[2. EXECUTE<br/>run them in parallel<br/>on the same snapshot]
  E --> U[3. UPDATE<br/>merge writes via reducers<br/>save checkpoint]
  U -->|nodes triggered| P
  U -->|none triggered| X([return state])

Example: START → a → (b, c in parallel) → d → END

StepRunsSeesAfter the update
0input—input written to the channels
1ainputa’s writes applied
2b, c togetherthe state after ab’s and c’s writes merged by the reducers
3dthe state after b and cd’s writes applied
—nothing triggered—stop, return the state

Rules that come from this

Streaming = watching the steps

app.stream(input, stream_mode=...) emits output as the steps run:

ModeEmits
valuesThe full state after each step
updatesOnly what each node wrote
messagesLLM tokens as they’re produced
debugEverything (tasks, checkpoints)
LangGraphDistributed systems
Super-stepBSP superstep (Pregel, Giraph)
End-of-step updateA barrier
ReducerMerge function / CRDT
Checkpoint per stepSnapshot / write-ahead log
Step all-or-nothingA transaction

Checkpoints

A checkpoint is a saved snapshot of the state, taken after every super-step. A checkpointer is the thing that saves the snapshots (in memory, SQLite, Postgres, Redis…).

This is how LangGraph gets state across runs. Without a checkpointer, the state dies when invoke() returns.

1from langgraph.checkpoint.memory import InMemorySaver
2
3app = graph.compile(checkpointer=InMemorySaver())
4
5cfg = {"configurable": {"thread_id": "user-42"}}
6app.invoke({"messages": ["My name is Vivek"]}, cfg)
7app.invoke({"messages": ["What's my name?"]}, cfg)   # remembers: same thread
flowchart LR
  subgraph T1[thread_id = user-42]
    direction LR
    c0[(ckpt step 0<br/>input)] --> c1[(ckpt step 1)] --> c2[(ckpt step 2)] --> c3[(ckpt step 3<br/>latest)]
  end
  c1 -.->|time travel: fork from here| f2[(new branch)]
  subgraph T2[thread_id = user-7]
    direction LR
    d0[(ckpt step 0)] --> d1[(ckpt step 1<br/>latest)]
  end

What checkpoints give you:

FeatureHow
Memory (chatbots)The next invoke on the same thread loads the last state
Fault toleranceA crash mid-run resumes from the last checkpoint instead of starting over
Human-in-the-loopPause before a node (interrupt), wait for a human, resume later
Time travelget_state_history(cfg) lists old checkpoints, and you can replay or fork from any of them
Debuggingget_state(cfg) shows the exact state at any point

Production: InMemorySaver is lost on restart and isn’t shared between pods. Use SqliteSaver locally and PostgresSaver behind a FastAPI service on K8s, so any pod can resume any thread.

Dist-sys link: this is the same idea as a write-ahead log / snapshot. Save after each step, and on failure replay from the last good point.

Human in the loop (HITL)

HITL = the graph pauses at a point, waits for a human to approve, edit or reject, then resumes from the same spot.

Use it before anything risky or irreversible: running SQL on prod, sending an email, a payment, deleting data.

It needs a checkpointer. The pause is just “save the state and stop”. The resume loads that checkpoint, maybe hours later, maybe on another pod.

 1from langgraph.types import interrupt, Command
 2
 3def approve_sql(state):
 4    decision = interrupt({"sql": state["sql"]})   # pause here, send sql to the human
 5    return {"approved": decision == "yes"}
 6
 7app = graph.compile(checkpointer=checkpointer)
 8cfg = {"configurable": {"thread_id": "t1"}}
 9
10app.invoke({"question": "top 5 customers"}, cfg)   # runs, stops at interrupt
11# ... show the SQL to the human in the UI ...
12app.invoke(Command(resume="yes"), cfg)             # continues with decision = "yes"

Flow:

sequenceDiagram
  participant App as FastAPI app
  participant G as Graph
  participant CP as Checkpointer
  participant H as Human
  App->>G: invoke(question, thread_id=t1)
  G->>G: generate_sql
  G->>CP: interrupt() in approve_sql, save state
  G-->>App: paused, here is the SQL
  App->>H: show SQL
  H-->>App: approve
  App->>G: invoke(Command(resume="yes"), thread_id=t1)
  CP-->>G: load saved state
  G->>G: approve_sql reruns, gets "yes"
  G->>G: run_query
  G-->>App: answer

Common patterns:

PatternHuman does
Approve / rejectYes or no before an action
Edit stateFix the SQL or the draft, then continue
Review tool callCheck the tool name and args before it runs
Give inputAnswer a question the agent asked

Gotchas:

Subgraphs

A subgraph = a compiled graph used as a node inside another graph. Like a function call: the parent graph calls it, it runs its own steps, and it returns updates.

Why use one:

Way 1: shared keys, added directly as a node

If the parent and child share state keys, just add the compiled subgraph as a node.

1class State(TypedDict):
2    question: str
3    sql: str
4
5sql_agent = sql_builder.compile()        # child graph, also uses question/sql
6
7parent = StateGraph(State)
8parent.add_node("sql_agent", sql_agent)  # the whole graph is one node
9parent.add_edge(START, "sql_agent")

Shared keys flow in and out automatically. Keys only the child has stay inside the child.

Way 2: different state, called from a node function

If the schemas differ, wrap the subgraph in a node and map the state yourself.

1def call_rag(state: ParentState):
2    out = rag_graph.invoke({"query": state["question"]})  # parent → child
3    return {"context": out["docs"]}                       # child → parent
flowchart LR
  S([START]) --> R{router}
  R --> SQL
  R --> RAG
  subgraph SQL[SQL agent subgraph]
    direction LR
    g[generate_sql] --> v{validate}
    v -->|retry| g
  end
  subgraph RAG[RAG agent subgraph]
    direction LR
    q[retrieve from Qdrant] --> a[grade docs]
  end
  SQL --> A[answer]
  RAG --> A
  A --> X([END])

Notes:

#Blog #Langgraph #LLM #Agents #Notes