Module 6 Lesson 2: Graph-Based Agent Architecture
Designing the flowchart of intelligence. Understanding nodes, edges, and state transitions.
Graph-Based Architecture: The Flowchart Brain
When we build a LangGraph agent, we are acting more like a Systems Architect than a prompt engineer. We are defining the "Shapes" (Nodes) and the "Arrows" (Edges) of the application.
1. The Three Components
A. The State (The Schema)
This is a shared dictionary (or Pydantic model) that all nodes can read from and write to.
- Example:
{"messages": [], "is_authorized": False}
B. Nodes (The Work)
A node is just a Python function. It takes the Current State as input, performs an action (like calling an LLM), and returns the Modified State.
- Example:
def call_model(state): ... return {"messages": [new_msg]}
C. Edges (The Path)
Edges connect the nodes.
- Fixed Edges: "From Node A, always go to Node B."
- Conditional Edges: "From Node A, if X is true go to Node B, otherwise go to Node C."
2. Thinking in "State Transitions"
Every step of the agent's life is a transition from State_N to State_N+1.
graph LR
S1[Start] -- "Input" --> N1[Node: Prompt LLM]
N1 -- "Output" --> S2[State Updated]
S2 -- "Is Tool Call?" --> N2[Node: Run Python Tool]
N2 -- "Result" --> S3[State Updated]
S3 -- "Is Goal Met?" --> Finish[End]
3. Benefits of Graph Design
A. Modular Logic
You can write a "Security" node once and use it in 10 different agent graphs. You just "Plug it in" with an edge.
B. Controlled Loops
You can program an edge like this:
if loop_count > 5: return END
This prevents the agent from ever looping infinitely, because the code (the edge) has priority over the LLM.
C. Checkpointing
Because every state transition is explicit, you can save the state to a database between every node. If the server crashes during Node 2, you can reload the state and restart exactly at Node 2.
4. Code Concept: Defining the Graph
from langgraph.graph import StateGraph, END
# 1. State definition
class MyState(TypedDict):
messages: Annotated[list, add_messages]
# 2. Build the Graph
workflow = StateGraph(MyState)
# 3. Add Nodes
workflow.add_node("agent", call_model)
workflow.add_node("action", call_tool)
# 4. Add Edges
workflow.set_entry_point("agent")
workflow.add_conditional_edges("agent", should_continue)
workflow.add_edge("action", "agent")
# 5. Compile
app = workflow.compile()
Key Takeaways
- State is the shared memory of the entire graph.
- Nodes are functional units that mutate the state.
- Edges define the flow and the "Control Logic."
- Graphs transform agents from "Unpredictable Loops" into Predictable State Machines.