KeyError
builtins.KeyError
Stack trace
Traceback (most recent call last):
File "app.py", line 15, in <module>
output = response['completion'] # KeyError here
KeyError: 'completion' Why it happens
The Ollama Python library returns a response dictionary whose keys may differ depending on the model or API version. If the code assumes a fixed key like 'completion' but the response uses a different key or nested structure, accessing the missing key raises a KeyError.
Detection
Add logging of the full response dictionary before accessing keys, or use dict.get() with a fallback to detect missing keys before the code crashes.
Causes & fixes
The response dictionary key 'completion' does not exist because the API returned a different key or nested structure.
Inspect the actual response keys by printing the full response and update your code to access the correct key path.
Using an outdated Ollama Python library version incompatible with the current API response format.
Upgrade the Ollama Python library to the latest version that matches the API response structure.
The API call failed or returned an error response without the expected keys.
Check for error fields in the response before accessing keys and handle error cases gracefully.
Code: broken vs fixed
import ollama
import os
response = ollama.chat(model="llama2", messages=[{"role": "user", "content": "Hello"}])
print(response['completion']) # KeyError if 'completion' key missing import ollama
import os
response = ollama.chat(model="llama2", messages=[{"role": "user", "content": "Hello"}])
print(response.get('completion', response)) # Fixed: safely access key or print full response Workaround
Wrap the key access in try/except KeyError, log the full response, and parse the correct key manually as a fallback.
Prevention
Always validate and log API responses before accessing keys; use schema validation or response parsing libraries to handle evolving API formats.