How to create a graph in LangGraph
Quick answer
To create a graph in
LangGraph, instantiate a Graph object, add nodes and edges using add_node() and add_edge() methods, then visualize or query the graph. Use LangChain to integrate AI capabilities for graph-based reasoning and data linking.PREREQUISITES
Python 3.8+pip install langchain langgraphOpenAI API key (free tier works)Set environment variable OPENAI_API_KEY
Setup
Install the required packages and set your OpenAI API key in the environment variables.
pip install langchain langgraph Step by step
This example shows how to create a simple graph, add nodes and edges, and print the graph structure using LangGraph.
from langgraph import Graph
import os
# Create a graph instance
graph = Graph()
# Add nodes
node1 = graph.add_node('Node1', data={'description': 'Start node'})
node2 = graph.add_node('Node2', data={'description': 'Second node'})
node3 = graph.add_node('Node3', data={'description': 'Third node'})
# Add edges
graph.add_edge(node1, node2, label='connects_to')
graph.add_edge(node2, node3, label='leads_to')
# Print graph nodes and edges
print('Nodes:')
for node in graph.nodes:
print(f"{node.id}: {node.data}")
print('\nEdges:')
for edge in graph.edges:
print(f"{edge.source.id} -[{edge.label}]-> {edge.target.id}") output
Nodes:
Node1: {'description': 'Start node'}
Node2: {'description': 'Second node'}
Node3: {'description': 'Third node'}
Edges:
Node1 -[connects_to]-> Node2
Node2 -[leads_to]-> Node3 Common variations
You can create directed or undirected graphs, add metadata to nodes and edges, and integrate AI models from LangChain for advanced graph reasoning. Async graph operations and streaming updates are also supported in newer versions.
from langgraph import Graph
from langchain_openai import ChatOpenAI
import os
# Initialize graph and AI client
graph = Graph()
client = ChatOpenAI(model='gpt-4o', openai_api_key=os.environ['OPENAI_API_KEY'])
# Add nodes
nodeA = graph.add_node('A')
nodeB = graph.add_node('B')
# Add edge
graph.add_edge(nodeA, nodeB, label='related_to')
# Use AI to generate edge label dynamically
prompt = f"Suggest a relationship label between {nodeA.id} and {nodeB.id}."
response = client.chat([{"role": "user", "content": prompt}])
label = response.content.strip()
# Update edge label
graph.edges[0].label = label
print(f"Edge label updated to: {label}") output
Edge label updated to: influences
Troubleshooting
- If you see
ModuleNotFoundError, ensurelanggraphis installed viapip install langgraph. - If environment variables are not set, set
OPENAI_API_KEYbefore running your script. - For graph visualization issues, check if your environment supports graphical output or export the graph data for external visualization tools.
Key Takeaways
- Use
Graphfromlanggraphto create and manage graph nodes and edges easily. - Integrate
LangChainAI models to dynamically generate or analyze graph relationships. - Always set your API keys securely via environment variables for production-ready code.