Building Agents with LangGraph
LangGraph provides more control over agent workflows using a graph-based approach:
Stateful Agent with Conditional Logic
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
from langchain_openai import ChatOpenAI
class AgentState(TypedDict):
messages: list
next_step: str
research_data: str
draft: str
final_output: str
llm = ChatOpenAI(model="gpt-4")
def research_node(state: AgentState) -> AgentState:
"""Gather information from various sources."""
query = state["messages"][-1]
# Simulate research
research = llm.invoke(f"Research this topic thoroughly: {query}")
return {"research_data": research.content, "next_step": "write"}
def write_node(state: AgentState) -> AgentState:
"""Write content based on research."""
draft = llm.invoke(
f"Based on this research:\n{state['research_data']}\n\n"
f"Write a comprehensive article."
)
return {"draft": draft.content, "next_step": "review"}
def review_node(state: AgentState) -> AgentState:
"""Review and decide if content needs revision."""
review = llm.invoke(
f"Review this article for accuracy and completeness. "
f"Respond with 'APPROVE' if good, or 'REVISE: [feedback]' if not.\n\n"
f"{state['draft']}"
)
if "APPROVE" in review.content:
return {"final_output": state["draft"], "next_step": "end"}
else:
return {"next_step": "write"} # Loop back to rewrite
def route_next(state: AgentState) -> str:
if state["next_step"] == "end":
return END
return state["next_step"]
# Build the graph
graph = StateGraph(AgentState)
graph.add_node("research", research_node)
graph.add_node("write", write_node)
graph.add_node("review", review_node)
graph.set_entry_point("research")
graph.add_edge("research", "write")
graph.add_edge("write", "review")
graph.add_conditional_edges("review", route_next)
app = graph.compile()
# Run
result = app.invoke({
"messages": ["Write an article about quantum computing in 2025"],
"next_step": "research",
"research_data": "",
"draft": "",
"final_output": ""
})
print(result["final_output"])