LangGraph: A Guide to Building Stateful AI Agents
LangGraph is a powerful framework for building complex AI agent workflows using stateful graphs. It allows for structured, conditional, and parallel execution of tasks, making it ideal for sophisticated AI applications.
1. Setting Up LangGraph
Installation
To install LangGraph, run the following command:
pip install langgraph
Import Required Modules
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
2. Creating a Basic LangGraph Agent
Define the State
The state defines the agent’s conversation history:
class State(TypedDict):
messages: Annotated[list, add_messages]
Build the Graph
Creating a stateful graph involves defining nodes and connecting them with edges:
graph_builder = StateGraph(State)
def chatbot(state: State):
# Implement LLM logic here
llm_response = "Hello! How can I assist you?"
return {"messages": [llm_response]}
graph_builder.add_node("chatbot", chatbot)
graph_builder.add_edge(START, "chatbot")
graph_builder.add_edge("chatbot", END)
# Compile the graph
graph = graph_builder.compile()
3. Adding Tools and Conditional Logic
Define External Tools
You can integrate tools such as web search or API calls:
from langchain_community.tools.tavily_search import TavilySearchResults
tool = TavilySearchResults(max_results=2)
tools = [tool]
Create a Tool Node
from langgraph.prebuilt import ToolNode, tools_condition
tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node)
Add Conditional Edges
Using conditional logic, the agent can decide whether to invoke a tool:
graph_builder.add_conditional_edges(
"chatbot",
tools_condition,
{
"tools": "tools",
"end": END
}
)
graph_builder.add_edge("tools", "chatbot")
4. Running the LangGraph Agent
To invoke the agent, provide a message input:
from langchain.schema import HumanMessage
messages = [HumanMessage(content="Your query here")]
result = graph.invoke({"messages": messages})
print(result['messages'][-1].content)
5. Advanced Features
1. State Persistence
LangGraph allows saving and restoring agent states, making it ideal for long-running tasks.
2. Graph Visualization
You can visualize the graph structure with:
graph.draw_ascii()
Or generate an image representation:
graph.draw_mermaid_png("graph.png")
3. Parallel Execution
LangGraph supports parallel execution of API calls, improving efficiency for complex workflows.
6. Summary
LangGraph provides a structured approach to AI workflows, offering stateful graphs, conditional execution, and parallel processing. It is a powerful tool for building robust AI agents.
References
With this guide, you can start building sophisticated AI workflows using LangGraph!