
Implementing the State and Logic Nodes
Cross the threshold into implementation. Learn how to write the Python functions for each node and how to manage state transitions in the capstone project.
Implementing the State and Logic Nodes
In the previous lesson, we designed the blueprint. Now, we build the walls. In LangGraph, every node is just a Python function that takes the State as input and returns the modified State.
In this lesson, we will implement the logic for our Research, Architect, and Runner nodes.
1. The Research Node (Gathering Facts)
This node behaves like the Search Agent we saw in Module 9.
async def research_node(state: ProjectState):
query = state["task"]
# Simulated Tool Call (Module 9)
findings = f"Results for {query}: The library uses the 'init()' method to start."
return {"research_notes": findings}
2. The Architect Node (Writing Code)
This node takes the research and generates the solution.
async def architect_node(state: ProjectState):
notes = state["research_notes"]
iteration = state["iteration_count"] + 1
# Simple Logic (In production, this would be an LLM call)
if iteration == 1:
code = "print('Hello World') # Intentional Bug"
else:
code = "import time; print('Fixed Logic')"
return {"proposed_code": code, "iteration_count": iteration}
3. The Runner Node (The Critic)
This node validates the work of the Architect.
async def runner_node(state: ProjectState):
code = state["proposed_code"]
# Check for the intentional bug
if "# Intentional Bug" in code:
return {"execution_result": "FAIL: Syntax Error"}
return {"execution_result": "PASS"}
4. Binding the Tool to the Graph
In Module 9, we learned that nodes can execute tools. Here, the research_node is a wrapper for a search tool. It is important to handle Tool Failures (Module 13) at this stage to prevent the entire graph from crashing.
5. State Persistence during Nodes
Because we are using a Checkpointer (Module 3), if the server crashes right after the research_node completes, LangGraph will resume at the architect_node. This "Durable" execution is what makes our capstone project production-ready.
Summary and Mental Model
Think of each node as a Specialized Employee in an office.
- The Researcher finds the book.
- The Architect writes the report.
- The Critic (Runner) checks for typos.
- Each one takes the "Internal Mail Folder" (The State), adds their part, and passes it to the next desk.
Exercise: Node Logic
- Self-Correction: Modify the
architect_nodelogic so that it reads theexecution_result. If the result is "FAIL", the node should change its strategy. - State Management: Why is it better to return
{"research_notes": ...}instead of the entire state dictionary? - Async: Why should we use
async deffor nodes that talk to external APIs or databases? Ready to see them move? Next lesson: Testing and Iterating on the Graph.