LangGraph & State Machines
Building cyclical, stateful agent workflows with graph-based state machines.
Why LangGraph?
Traditional agent executors are "while loops" that run until a stopping condition. They are hard to debug, hard to control, and prone to infinite loops. LangGraph models agent workflows as state machines (directed graphs).
Core Concepts
- State: A Python dict or Pydantic model holding the current context. Passed between nodes.
- Nodes: Functions that receive state, perform actions (LLM call, API call), and return updated state.
- Edges: Rules dictating which node runs next.
- Conditional Edges: Dynamic routing based on state — enables loops and branching.
Human-in-the-Loop (HITL)
LangGraph can pause execution and wait for human approval before proceeding. Combined with a durable Checkpointer (Postgres), execution state is saved before destructive actions. This unlocks native approval workflows for payments, deployments, and refunds.
DSPy: Compile Prompts, Don't Hack Them
Senior engineers use frameworks like DSPy to treat prompts as learnable parameters. DSPy separates logical execution from instructions, dynamically compiling and optimizing the highest-accuracy few-shot combinations against test schemas.
Code Example
LangGraph with conditional routing and human-in-the-loop.
1from langgraph.graph import StateGraph, END
2from typing import TypedDict
3
4class AgentState(TypedDict):
5 messages: list[str]
6 needs_human_review: bool
7
8def llm_node(state: AgentState):
9 return {"messages": ["LLM: I propose deleting the database."]}
10
11def tool_node(state: AgentState):
12 return {"messages": ["Tool: Action Executed."]}
13
14def should_continue(state: AgentState):
15 if state.get("needs_human_review"):
16 return "human_review"
17 return "tools"
18
19workflow = StateGraph(AgentState)
20workflow.add_node("llm", llm_node)
21workflow.add_node("tools", tool_node)
22
23workflow.set_entry_point("llm")
24workflow.add_conditional_edges("llm", should_continue, {
25 "human_review": END,
26 "tools": "tools"
27})
28workflow.add_edge("tools", END)
29
30app = workflow.compile()
31result = app.invoke({"messages": [], "needs_human_review": False})Use Cases
Common Mistakes
Interview Insight
Relevance
High - Most enterprise agent systems use graph-based state machines.