How to beginner · 3 min read

How to add edges to LangGraph

Quick answer
To add edges to a LangGraph in LangChain, use the add_edge() method specifying the source and target node IDs along with optional edge metadata. This method connects nodes and builds relationships within the graph structure programmatically.

PREREQUISITES

  • Python 3.8+
  • pip install langchain>=0.2
  • Basic familiarity with LangChain graph concepts

Setup

Install LangChain if you haven't already and import the necessary classes to create and manipulate a LangGraph.

bash
pip install langchain>=0.2

Step by step

Create a LangGraph instance, add nodes, then add edges between nodes using add_edge(). The example below demonstrates this with simple string node IDs and edge labels.

python
from langchain.graphs import LangGraph

# Initialize the graph
graph = LangGraph()

# Add nodes
graph.add_node("node1", data={"label": "Node 1"})
graph.add_node("node2", data={"label": "Node 2"})

# Add an edge from node1 to node2
graph.add_edge("node1", "node2", data={"relation": "connects_to"})

# Print edges to verify
print(graph.edges())
output
[('node1', 'node2', {'relation': 'connects_to'})]

Common variations

You can add edges with different metadata or use complex node objects instead of strings. Async graph operations are not typical but you can batch add edges in loops. Different graph backends may support additional edge attributes.

python
nodes = ["A", "B", "C"]
for node in nodes:
    graph.add_node(node)

# Add multiple edges with weights
graph.add_edge("A", "B", data={"weight": 5})
graph.add_edge("B", "C", data={"weight": 3})

print(graph.edges())
output
[('node1', 'node2', {'relation': 'connects_to'}), ('A', 'B', {'weight': 5}), ('B', 'C', {'weight': 3})]

Troubleshooting

If add_edge() raises a KeyError, ensure both source and target nodes exist in the graph before adding the edge. Use add_node() first. Check for typos in node IDs.

Key Takeaways

  • Use add_edge(source, target, data) to connect nodes in a LangGraph.
  • Always add nodes before adding edges to avoid errors.
  • Edge metadata can store relationship details like labels or weights.
Verified 2026-04
Verify ↗