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 key (usually 'chat_history') to exist in its internal buffer or memory variables. If the key is missing due to incorrect initialization, manual clearing, or mismatched key names, a KeyError is raised when accessing or loading memory variables.
Detection
Add logging around memory variable access and assert the presence of expected keys like 'chat_history' before usage to catch missing keys early.
Causes & fixes
Memory key 'chat_history' is missing because ConversationBufferMemory was not properly initialized.
Ensure ConversationBufferMemory is instantiated with the default or correct memory_key parameter and that the buffer is initialized before use.
Custom memory_key parameter passed to ConversationBufferMemory does not match the key accessed in code.
Align the memory_key parameter in ConversationBufferMemory with the key your code expects to access, or update your code to use the configured key.
Memory buffer was manually cleared or reset, removing the expected key.
Avoid manually clearing the internal buffer or reinitialize the memory object properly before accessing memory variables.
Code: broken vs fixed
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
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 initialize the buffer with an empty list or default value if the key is missing.
Prevention
Always configure and document the memory_key parameter consistently across your app and avoid manual buffer manipulation to keep memory keys intact.