KeyError
langgraph.exceptions.StateGraphKeyError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
graph.run()
File "/usr/local/lib/python3.9/site-packages/langgraph/core.py", line 128, in run
state_value = self.state[state_key]
KeyError: 'user_input' Why it happens
LangGraph's StateGraph requires all referenced state keys to be present in its internal state dictionary before execution. If a key is missing, typically because it was never initialized or set, the graph raises a KeyError indicating the absent key. This usually happens when the state setup is incomplete or a required input was not provided.
Detection
Add assertions or logging before graph execution to verify all required state keys exist in the state dictionary, catching missing keys early and preventing runtime crashes.
Causes & fixes
The required state key was never initialized or set before running the StateGraph.
Initialize all required state keys with default or input values before calling graph.run(), ensuring the state dictionary contains every key the graph expects.
A typo or mismatch in the state key name between the graph definition and the provided state dictionary.
Verify that all state keys used in the graph exactly match the keys in the state dictionary, including case sensitivity and spelling.
Conditional logic in the graph expects a key only under certain conditions, but the key is missing when those conditions occur.
Add conditional checks or default values for optional keys, or refactor the graph logic to ensure keys are always set before access.
Code: broken vs fixed
from langgraph import StateGraph
graph = StateGraph()
# Missing initialization of 'user_input' key
result = graph.run() # This line raises KeyError: 'user_input' import os
from langgraph import StateGraph
# Initialize environment or inputs
os.environ['USER_INPUT'] = 'Hello'
graph = StateGraph()
graph.state['user_input'] = os.environ['USER_INPUT'] # Fixed: set required state key
result = graph.run()
print(result) # Runs without KeyError Workaround
Wrap the graph.run() call in try/except KeyError, catch the missing key error, log the missing key name, and set a default value before retrying execution.
Prevention
Design your application to always initialize and validate all required state keys before graph execution, and use schema validation or type hints to enforce state completeness.