High severity beginner · Fix: 2-5 min

KeyError

builtins.KeyError

What this error means
The Ollama Python client code tries to access a missing key in the response dictionary, causing a KeyError.

Stack trace

traceback
Traceback (most recent call last):
  File "app.py", line 15, in <module>
    output = response['completion']  # KeyError here
KeyError: 'completion'
QUICK FIX
Print the full response dict and replace direct key access with response.get('completion') or correct key path.

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

1

The response dictionary key 'completion' does not exist because the API returned a different key or nested structure.

✓ Fix

Inspect the actual response keys by printing the full response and update your code to access the correct key path.

2

Using an outdated Ollama Python library version incompatible with the current API response format.

✓ Fix

Upgrade the Ollama Python library to the latest version that matches the API response structure.

3

The API call failed or returned an error response without the expected keys.

✓ Fix

Check for error fields in the response before accessing keys and handle error cases gracefully.

Code: broken vs fixed

Broken - triggers the error
python
import ollama
import os

response = ollama.chat(model="llama2", messages=[{"role": "user", "content": "Hello"}])
print(response['completion'])  # KeyError if 'completion' key missing
Fixed - works correctly
python
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
Changed direct dict key access to use .get() with fallback to avoid KeyError and reveal actual response structure.
⚠

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.

Python 3.9+ · ollama >=0.1.0 · tested on 0.3.0
Verified 2026-04
Verify ↗

Community Notes

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