High severity beginner · Fix: 2-5 min

KeyError

builtins.KeyError

What this error means
Haystack raises a KeyError when a prompt template references a variable not provided in the input dictionary.

Stack trace

traceback
Traceback (most recent call last):
  File "app.py", line 42, in <module>
    output = prompt_template.format(**inputs)  # KeyError occurs here
KeyError: 'missing_variable'
QUICK FIX
Verify and include all variables referenced in the prompt template in the input dictionary before formatting.

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

1

Input dictionary lacks a variable referenced in the prompt template string

✓ Fix

Ensure the input dictionary passed to the prompt template includes all variables named in the template exactly, including case sensitivity.

2

Typo or mismatch in variable names between the prompt template and input keys

✓ Fix

Double-check and align variable names in the prompt template and input dictionary to be identical.

3

Dynamic generation of input dictionary missing keys due to logic errors

✓ Fix

Add logging or assertions to verify the input dictionary keys before passing to the prompt template.

Code: broken vs fixed

Broken - triggers the error
python
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)
Fixed - works correctly
python
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)
Added the missing 'order_id' key to the input dictionary so the prompt template can format without KeyError.

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.

Python 3.9+ · haystack >=1.0.0 · tested on 1.15.0
Verified 2026-04
Verify ↗

Community Notes

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