High severity beginner · Fix: 2-5 min

KeyError

builtins.KeyError

What this error means
LangChain's ConversationBufferMemory raises KeyError when expected memory keys are missing or incorrectly referenced in the conversation state.

Stack trace

traceback
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'
QUICK FIX
Verify and set the correct memory_key parameter when creating ConversationBufferMemory and avoid manual buffer clearing.

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

1

Memory key 'chat_history' is missing because ConversationBufferMemory was not properly initialized.

✓ Fix

Ensure ConversationBufferMemory is instantiated with the default or correct memory_key parameter and that the buffer is initialized before use.

2

Custom memory_key parameter passed to ConversationBufferMemory does not match the key accessed in code.

✓ Fix

Align the memory_key parameter in ConversationBufferMemory with the key your code expects to access, or update your code to use the configured key.

3

Memory buffer was manually cleared or reset, removing the expected key.

✓ Fix

Avoid manually clearing the internal buffer or reinitialize the memory object properly before accessing memory variables.

Code: broken vs fixed

Broken - triggers the error
python
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
print(memory.load_memory_variables({}))  # KeyError: 'chat_history'
Fixed - works correctly
python
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key='chat_history')  # Explicitly set memory_key
print(memory.load_memory_variables({}))  # Works without KeyError
Explicitly setting the memory_key to 'chat_history' ensures the key exists in the buffer, preventing KeyError on access.

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.

Python 3.9+ · langchain-core >=0.1.0 · tested on 0.2.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.