In this tutorial, you’ll build a simple agent that can respond to messages and maintain state. This is the foundation for understanding how LangGraph works.
First, define the state structure for your agent. The state holds all the information that flows through your graph.
from typing_extensions import TypedDictfrom langgraph.graph import StateGraph, START, ENDclass AgentState(TypedDict): """State for the agent containing the message text.""" text: str count: int
The AgentState will track:
text: The current message text
count: Number of times the agent has processed messages
2
Create node functions
Nodes are functions that process the state. Each node receives the current state and returns updates.
def process_input(state: AgentState) -> dict: """Process the input message.""" text = state["text"] count = state.get("count", 0) # Transform the text processed_text = f"Processed: {text.upper()}" return { "text": processed_text, "count": count + 1 }def generate_response(state: AgentState) -> dict: """Generate a response based on processed input.""" text = state["text"] count = state["count"] response = f"{text} (processed {count} times)" return {"text": response}
Each function:
Takes state as input
Returns a dictionary with state updates
Can access any field from the state
3
Build the graph
Now create the graph by adding nodes and defining edges between them.
# Initialize the graphgraph = StateGraph(AgentState)# Add nodesgraph.add_node("process", process_input)graph.add_node("respond", generate_response)# Define the flowgraph.add_edge(START, "process")graph.add_edge("process", "respond")graph.add_edge("respond", END)# Compile the graphapp = graph.compile()
The graph flow:
START → process: Begin with processing
process → respond: Generate response
respond → END: Finish execution
4
Run the agent
Execute your agent with different inputs.
# First runresult = app.invoke({ "text": "hello world", "count": 0})print(result)# Output: {'text': 'Processed: HELLO WORLD (processed 1 times)', 'count': 1}# Second runresult = app.invoke({ "text": "langgraph is awesome", "count": 0})print(result)# Output: {'text': 'Processed: LANGGRAPH IS AWESOME (processed 1 times)', 'count': 1}