Module 6 Wrap-up: Migrating to the Graph
Hands-on: Convert a simple LangChain AgentExecutor into a controlled LangGraph workflow.
Module 6 Wrap-up: The Graph Evolution
You have learned why we use graphs (Cycles + Control). Now, we are going to do the most important engineering task of this course: Converting an old-school LangChain agent into a Modern LangGraph.
Hands-on Exercise: The Conversion
Take the "Stock Analyst" agent from Module 4 and wrap it in a graph that includes a Loop Guard (prevention of more than 3 steps).
1. Requirements
pip install langgraph
2. The Code
Create a file langgraph_conversion.py:
from typing import Annotated, TypedDict, Union
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END, add_messages
from langchain_core.messages import BaseMessage, HumanMessage
# 1. DEFINE STATE
class AgentState(TypedDict):
messages: Annotated[list[BaseMessage], add_messages]
# 2. DEFINE THE AGENT NODE
llm = ChatOpenAI(model="gpt-4o", temperature=0)
def call_model(state: AgentState):
response = llm.invoke(state["messages"])
return {"messages": [response]}
# 3. DEFINE THE ROUTING LOGIC
def should_continue(state: AgentState):
last_message = state["messages"][-1]
# If the model wants to call a tool, we would route to 'tools'
# For this simple exercise, we just check if the model is done
if "FINAL" in last_message.content:
return "end"
return "continue"
# 4. BUILD THE GRAPH
workflow = StateGraph(AgentState)
workflow.add_node("agent", call_model)
workflow.set_entry_point("agent")
workflow.add_conditional_edges(
"agent",
should_continue,
{
"continue": "agent",
"end": END
}
)
# 5. COMPILE AND RUN
app = workflow.compile()
inputs = {"messages": [HumanMessage(content="Explain agentic AI in 3 words. End with FINAL")]}
for output in app.stream(inputs):
print(output)
3. What Changed?
- Unlike the
AgentExecutor, we now have full visibility into the message flow. - We can easily inject a new node between
agentandendto verify the output. - We have a clear schema (
AgentState) for our data.
Module 6 Summary
- LangGraph solves the problems of infinite loops and lack of control in standard agents.
- Cycles allow agents to learn and retry.
- Nodes are modular, testable Python functions.
- Conditional Edges take over the "Decision Making" from the LLM, increasing reliability.
Coming Up Next...
In Module 7, we go deep into Advanced LangGraph Patterns. We will learn how to handle Parallelism, Human Approval Nodes, and complex Conditional Routing.
Module 6 Checklist
- I can explain why a DAG is not sufficient for an iterative agent.
- I understand the relationship between Nodes, Edges, and State.
- I have successfully run the
langgraph_conversion.pyscript. - I can identify where a "Guard Node" would fit in a graph.
- I understand that LangGraph is about making "Explicit" what was once "Implicit."