KeyError
builtins.KeyError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
document = index.docstore['nonexistent_key'] # KeyError raised here
KeyError: 'nonexistent_key' Why it happens
LlamaIndex maintains a document store mapping keys to documents. When code attempts to retrieve a document by a key that was never added or has been deleted, Python raises a KeyError. This usually means the key is misspelled, the document was never indexed, or the index was not properly saved and loaded.
Detection
Add checks using 'key in index.docstore' before access or wrap access in try/except KeyError to log missing keys and avoid crashes.
Causes & fixes
Attempting to access a document key that was never added to the index.
Verify the key exists in the document store before access or ensure the document was indexed properly.
The document store was not saved or loaded correctly, causing missing keys.
Ensure the index is saved and loaded using LlamaIndex's save_to_disk and load_from_disk methods properly.
Typo or mismatch in the document key string used for retrieval.
Double-check the key string for exact spelling and case sensitivity matching the stored keys.
Code: broken vs fixed
from llama_index import GPTSimpleVectorIndex
index = GPTSimpleVectorIndex.load_from_disk('index.json')
doc = index.docstore['missing_key'] # KeyError here import os
from llama_index import GPTSimpleVectorIndex
index = GPTSimpleVectorIndex.load_from_disk('index.json')
key = 'missing_key'
if key in index.docstore:
doc = index.docstore[key]
print('Document found:', doc)
else:
print(f'Key "{key}" not found in document store.') # Fixed: check key existence before access Workaround
Wrap document store access in try/except KeyError, then log the missing key and optionally return a default value or trigger re-indexing.
Prevention
Always validate keys before access and ensure documents are indexed and persisted correctly using LlamaIndex's save/load methods to keep the document store consistent.