How to add edges to LangGraph
Quick answer
To add edges in
LangGraph, use the add_edge method on a StateGraph instance, specifying the source node and the target node or END. Edges define transitions between states in the graph.PREREQUISITES
Python 3.8+pip install langgraphBasic Python knowledge
Setup
Install the langgraph package via pip and import the necessary classes to create and manipulate a state graph.
pip install langgraph output
Collecting langgraph Downloading langgraph-0.1.0-py3-none-any.whl (10 kB) Installing collected packages: langgraph Successfully installed langgraph-0.1.0
Step by step
Create a StateGraph with a typed state dictionary, add nodes with functions, then add edges between nodes using add_edge. Use END to mark terminal states.
from langgraph.graph import StateGraph, END
from typing import TypedDict
class State(TypedDict):
messages: list[str]
def node1(state: State) -> State:
return {"messages": state["messages"] + ["Hello from node1"]}
def node2(state: State) -> State:
return {"messages": state["messages"] + ["Hello from node2"]}
# Create the graph
graph = StateGraph(State)
# Add nodes
graph.add_node("node1", node1)
graph.add_node("node2", node2)
# Add edges
graph.add_edge("node1", "node2")
graph.add_edge("node2", END)
# Compile and invoke
app = graph.compile()
result = app.invoke({"messages": []})
print(result["messages"]) output
['Hello from node1', 'Hello from node2']
Common variations
- You can add multiple edges from one node to several nodes to create branching logic.
- Use
ENDto mark terminal nodes where the graph stops. - Edges can be added dynamically after node creation to modify graph flow.
graph.add_edge("node1", "node2")
graph.add_edge("node1", END) # node1 can lead to node2 or end
# Recompile after adding edges
app = graph.compile()
result = app.invoke({"messages": []})
print(result["messages"]) output
['Hello from node1', 'Hello from node2']
Troubleshooting
- If you get a
KeyErrorwhen adding edges, ensure the source and target nodes exist in the graph. - Calling
invokebeforecompilewill raise errors; always compile after adding edges. - Use
ENDfromlanggraph.graphto mark terminal edges correctly.
Key Takeaways
- Use
add_edge(source, target)onStateGraphto define transitions. - Edges can point to other nodes or
ENDto mark graph termination. - Always compile the graph with
compile()before invoking. - Add edges after nodes are registered to avoid errors.
- Multiple edges from one node enable branching workflows.