InputKeyNotFoundError
langchain.memory.base.InputKeyNotFoundError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
output = chain.run(inputs)
File "/usr/local/lib/python3.9/site-packages/langchain/chains/base.py", line 123, in run
return self.invoke(inputs)
File "/usr/local/lib/python3.9/site-packages/langchain/chains/base.py", line 150, in invoke
raise InputKeyNotFoundError(f"Input key '{key}' not found in inputs")
langchain.memory.base.InputKeyNotFoundError: Input key 'user_input' not found in inputs Why it happens
LangChain chains and memory components expect specific input keys to be present in the inputs dictionary. If the inputs passed to the chain do not include a required key defined in the memory's input_key or the chain's input_keys, this error is raised. It often happens when the prompt template or memory expects a key that the caller did not provide.
Detection
Add validation before calling the chain to assert all required input keys exist in the inputs dictionary, or catch InputKeyNotFoundError and log missing keys for debugging.
Causes & fixes
The inputs dictionary passed to the chain is missing the key specified in memory's input_key.
Ensure the inputs dictionary includes the exact key name expected by the memory's input_key parameter.
Mismatch between the prompt template input variables and the keys provided in inputs.
Align the prompt template input variables with the keys in the inputs dictionary passed to the chain.
Using a memory or chain configuration that expects a default input_key but the caller provides a different key name.
Explicitly set the memory's input_key parameter to match the key name used in the inputs dictionary.
Code: broken vs fixed
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
import os
memory = ConversationBufferMemory(input_key='user_input')
chain = ConversationChain(memory=memory)
inputs = {'input': 'Hello!'}
output = chain.run(inputs) # This line raises InputKeyNotFoundError
print(output) import os
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory(input_key='user_input')
chain = ConversationChain(memory=memory)
inputs = {'user_input': 'Hello!'} # Fixed: key matches memory.input_key
output = chain.run(inputs)
print(output) # Works without error Workaround
Wrap the chain.run call in try/except InputKeyNotFoundError, then log the missing key and provide a default or fallback input key to continue execution.
Prevention
Define and document all required input keys clearly in your chain and memory configurations, and validate inputs before calling chains to ensure all keys are present.