KeyError
builtins.KeyError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
output = prompt_template.format(**inputs) # KeyError occurs here
KeyError: 'missing_variable' Why it happens
Haystack prompt templates require all variables referenced in the template string to be present in the input dictionary. If a variable is missing, Python's string formatting raises a KeyError. This usually happens when the input data does not match the template placeholders exactly.
Detection
Add validation to check that all required variables exist in the input dictionary before formatting the prompt template to catch missing keys early.
Causes & fixes
Input dictionary lacks a variable referenced in the prompt template string
Ensure the input dictionary passed to the prompt template includes all variables named in the template exactly, including case sensitivity.
Typo or mismatch in variable names between the prompt template and input keys
Double-check and align variable names in the prompt template and input dictionary to be identical.
Dynamic generation of input dictionary missing keys due to logic errors
Add logging or assertions to verify the input dictionary keys before passing to the prompt template.
Code: broken vs fixed
from haystack.nodes import PromptTemplate
prompt_template = PromptTemplate(template="Hello, {name}! Your order {order_id} is ready.")
inputs = {"name": "Alice"}
# This line raises KeyError because 'order_id' is missing
output = prompt_template.format(**inputs)
print(output) import os
from haystack.nodes import PromptTemplate
prompt_template = PromptTemplate(template="Hello, {name}! Your order {order_id} is ready.")
inputs = {"name": "Alice", "order_id": "12345"} # Added missing variable
output = prompt_template.format(**inputs) # Fixed: all variables provided
print(output) Workaround
Wrap the prompt formatting call in try/except KeyError, log the missing key, and provide a default or fallback value to avoid crashing.
Prevention
Implement input validation that asserts all required prompt template variables are present before formatting, and use static typing or schema validation for input data.