KeyError
builtins.KeyError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
memory.load_memory_variables({})
File "/usr/local/lib/python3.9/site-packages/langchain/memory/conversation_buffer.py", line 75, in load_memory_variables
return {self.memory_key: self.buffer}
KeyError: 'chat_history' Why it happens
ConversationBufferMemory expects a specific memory key (default 'chat_history') to store and retrieve conversation history. If this key is missing, misspelled, or overridden incorrectly, accessing it raises a KeyError. This often happens when customizing memory keys without updating all references or when initializing memory improperly.
Detection
Add logging or assertions to verify that the memory dictionary contains the expected memory_key before accessing it, or wrap calls in try/except KeyError to catch missing keys early.
Causes & fixes
Using a custom memory_key in ConversationBufferMemory but forgetting to update the prompt or chain to use the same key
Ensure the memory_key parameter is consistent across ConversationBufferMemory and any chains or prompts that access it.
Initializing ConversationBufferMemory without setting memory_key, then accessing a different key in code
Use the default memory_key 'chat_history' or explicitly set and use the same key everywhere.
Manually manipulating the memory dictionary and deleting or renaming the expected memory_key
Avoid direct manipulation of the memory dictionary or ensure the expected key is always present before access.
Code: broken vs fixed
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
# This will raise KeyError if 'chat_history' key is missing
print(memory.load_memory_variables({})) # KeyError: 'chat_history' from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key='chat_history') # Explicitly set memory_key
print(memory.load_memory_variables({})) # Works without KeyError Workaround
Wrap calls to load_memory_variables in try/except KeyError and provide a default empty buffer or initialize the missing key manually before access.
Prevention
Always explicitly set and consistently use the memory_key parameter in ConversationBufferMemory and related chains to avoid key mismatches and missing keys.