Core Concepts
A LangGraph workflow consists of:- State: The data structure that flows through your graph
- Nodes: Functions that process the state
- Edges: Connections between nodes that define the flow
- Graph: The compiled workflow that orchestrates execution
Creating a Simple Graph
from langgraph.graph import MessagesState
class AgentState(MessagesState):
# Add additional fields as needed
context: str
def node_a(state: State) -> dict:
return {"text": state["text"] + "a"}
def node_b(state: State) -> dict:
return {"text": state["text"] + "b"}
graph.add_node("node_a", node_a)
graph.add_node("node_b", node_b)
from langgraph.graph import START, END
# Direct edge from START to first node
graph.add_edge(START, "node_a")
# Sequential flow
graph.add_edge("node_a", "node_b")
# End the graph
graph.add_edge("node_b", END)
Conditional Edges
Use conditional edges to create dynamic routing based on state:Working with Tools
Integrate tools using the prebuiltToolNode:
State Reducers
UseAnnotated types to define how state updates are merged:
add_messages reducer intelligently merges message lists:
- Appends new messages by default
- Updates existing messages by ID
- Handles message deletion with
RemoveMessage
Multi-Agent Patterns
Create graphs with multiple agents by adding nodes for each agent:Best Practices
- Keep nodes focused: Each node should handle a single responsibility
- Use type hints: Define clear state schemas for better IDE support
- Test incrementally: Build and test your graph one node at a time
- Visualize your graph: Use
graph.compile().get_graph().print_ascii()to debug - Handle errors gracefully: Add error handling in your node functions
Next Steps
- Learn about State Management for advanced state patterns
- Explore Persistence to save and resume graph execution
- Add Interrupts for human-in-the-loop workflows