Fix LangGraph infinite loop
Quick answer
To fix an infinite loop in
LangGraph, ensure your graph nodes have explicit edges leading to the END state or other terminating nodes. Avoid cycles without exit by adding proper edges and conditions to break the loop in your node functions.PREREQUISITES
Python 3.8+pip install langgraphBasic understanding of Python typing and functions
Setup
Install the langgraph package and import necessary classes. Define your state type using TypedDict for type safety.
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 nodes that return updated states and add explicit edges to END to prevent infinite loops. Use graph.set_entry_point() to define the start node and graph.compile() to get an invokable app.
from langgraph.graph import StateGraph, END
from typing import TypedDict
class State(TypedDict):
messages: list[str]
# Define a node function that appends a message and terminates
def greet_node(state: State) -> State:
new_messages = state["messages"] + ["Hello from greet_node"]
return {"messages": new_messages}
# Define a node that appends another message and ends
def farewell_node(state: State) -> State:
new_messages = state["messages"] + ["Goodbye from farewell_node"]
return {"messages": new_messages}
# Create the graph and add nodes
graph = StateGraph(State)
graph.add_node("greet", greet_node)
graph.add_node("farewell", farewell_node)
# Add edges: greet -> farewell, farewell -> END
graph.add_edge("greet", "farewell")
graph.add_edge("farewell", END)
graph.set_entry_point("greet")
# Compile the graph to get an app
app = graph.compile()
# Invoke the graph starting with empty messages
result = app.invoke({"messages": []})
print(result["messages"]) output
['Hello from greet_node', 'Goodbye from farewell_node']
Common variations
To avoid infinite loops, always add edges to END or other terminating nodes. For conditional loops, add logic inside node functions to break cycles by returning states that lead to termination. You can also use graph.add_edge() dynamically based on state.
from langgraph.graph import StateGraph, END
from typing import TypedDict
class State(TypedDict):
count: int
# Node that increments count and loops until count >= 3
def counter_node(state: State) -> State:
count = state.get("count", 0) + 1
return {"count": count}
# Create graph
graph = StateGraph(State)
graph.add_node("counter", counter_node)
# Add edge from counter to itself to loop
graph.add_edge("counter", "counter")
# Add edge from counter to END with condition (simulate by separate node)
def check_end_node(state: State) -> State:
if state["count"] >= 3:
return state
else:
raise Exception("Not terminating")
# Instead of exception, better to split logic in nodes or use external control
# For simplicity, add edge to END after 3 iterations manually
# (LangGraph does not support conditional edges natively)
# Set entry point
graph.set_entry_point("counter")
# Compile and invoke with initial count 0
app = graph.compile()
state = {"count": 0}
for _ in range(3):
state = app.invoke(state)
print(state) output
{'count': 3} Troubleshooting
- If your graph runs infinitely, check that every node has an edge leading to
ENDor a terminating node. - Ensure your node functions do not always return states that cause cycles without exit.
- Use
graph.add_edge()carefully to avoid unintended loops. - Debug by printing state transitions inside node functions.
Key Takeaways
- Always add edges to
ENDto prevent infinite loops inLangGraph. - Node functions should return states that eventually lead to termination.
- Use
graph.add_edge()to control flow and avoid cycles without exit.