Today, we leave the world of linear "Chains" and enter the most powerful evolution of the LangChain ecosystem: LangGraph.
If you've been following along, you've noticed that Chains always go forward: A -> B -> C. But real intelligence requires loops. Think about how you work: you write code, you run it, it fails, so you go back and fix it. That's a cycle. LangGraph is designed to let AI agents do exactly that.
π Why LangGraph?
Standard LangChain "Chains" are Directed Acyclic Graphs (DAGs). They can't loop.
LangGraph allows for cycles, which are essential for:
Self-Correction: "I tried to search Google, but got no results. I'll try a different keyword."
Multi-Agent Collaboration: "Agent A writes the code, Agent B reviews it and sends it back for edits."
Persistence: Saving the state of a conversation so you can pause and resume it days later.
ποΈ The Core Concepts
To build with LangGraph, you need to understand three things:
State: A shared "notebook" (usually a Python dictionary) that all parts of your agent can read and write to.
Nodes: Simple Python functions that take the current State, do some work, and return an update.
Edges: The "roads" between nodes. They decide which node to go to next.
π οΈ Building a Basic "Smart Assistant" Graph
Let's build a graph where the AI decides whether to use a tool or just reply.
import operator
from typing import Annotated, TypedDict, Union
from langgraph.graph import StateGraph, START, END
from langchain_openai import ChatOpenAI
# 1. Define the State
class AgentState(TypedDict):
# This stores our message history
messages: Annotated[list, operator.add]
# 2. Define a Node (The Brain)
model = ChatOpenAI(model="gpt-4o")
def call_model(state: AgentState):
response = model.invoke(state["messages"])
return {"messages": [response]}
# 3. Build the Graph
workflow = StateGraph(AgentState)
# Add our node
workflow.add_node("agent", call_model)
# Define the flow
workflow.add_edge(START, "agent")
workflow.add_edge("agent", END)
# 4. Compile it
app = workflow.compile()
# Run it!
input_state = {"messages": [("user", "Explain LangGraph in 10 words.")]}
for event in app.stream(input_state):
print(event)
β‘ The "Conditional" Edge: The Secret Sauce
The real power comes when you add a Conditional Edge. This is a function that looks at the AI's response and says:
"If the AI wants to use a tool β go to the Tools Node."
"If the AI is finished β go to END."
This creates the "Loop" that makes agents truly autonomous.
π― Day 12 Summary
Today, you caught a glimpse of the "Brain" of modern AI agents. You learned:
Chains vs. Graphs: Why cycles are necessary for complex tasks.
State Management: How agents keep track of their "thoughts."
Nodes & Edges: The building blocks of an agentic workflow.
Your Homework: Look at the code above. How would you add a "Review" node that checks the AI's answer for typos before sending it to the user?
See you tomorrow! β
Top comments (0)