High severity beginner · Fix: 2-5 min

ValueError

builtins.ValueError

What this error means
Semantic Kernel throws a ValueError when the OpenAI API key environment variable is missing or not set correctly.

Stack trace

traceback
ValueError: OpenAI API key not configured. Please set the OPENAI_API_KEY environment variable.
QUICK FIX
Set the OPENAI_API_KEY environment variable with your OpenAI API key before running Semantic Kernel code.

Why it happens

Semantic Kernel requires the OpenAI API key to authenticate requests. If the environment variable OPENAI_API_KEY is missing or empty, the SDK raises this error to prevent unauthorized API calls.

Detection

Check for the presence of the OPENAI_API_KEY environment variable before initializing the Semantic Kernel client or making API calls.

Causes & fixes

1

The OPENAI_API_KEY environment variable is not set in the system or runtime environment.

✓ Fix

Set the OPENAI_API_KEY environment variable with your valid OpenAI API key before running your application.

2

The environment variable is set but contains an empty string or invalid key.

✓ Fix

Verify that OPENAI_API_KEY contains a valid, non-empty API key string.

3

The application is running in an environment where environment variables are not loaded (e.g., missing .env loading).

✓ Fix

Ensure your environment variables are loaded properly, for example by using python-dotenv or configuring your deployment environment correctly.

Code: broken vs fixed

Broken - triggers the error
python
from semantic_kernel import Kernel

kernel = Kernel()
# This will raise ValueError if OPENAI_API_KEY is not set
kernel.config.add_open_ai_text_completion_service("gpt-4o-mini", "")
Fixed - works correctly
python
import os
from semantic_kernel import Kernel

os.environ["OPENAI_API_KEY"] = "your_api_key_here"  # Set your API key here

kernel = Kernel()
kernel.config.add_open_ai_text_completion_service("gpt-4o-mini", os.environ["OPENAI_API_KEY"])
print("OpenAI API key configured successfully.")
Added setting of the OPENAI_API_KEY environment variable and passed it to the Semantic Kernel configuration to authenticate API calls.

Workaround

Manually pass the API key string directly to the Semantic Kernel configuration methods instead of relying on environment variables, but ensure the key is kept secure.

Prevention

Always set and verify the OPENAI_API_KEY environment variable in your deployment and development environments before initializing Semantic Kernel to avoid authentication errors.

Python 3.9+ · semantic-kernel >=0.10.0 · tested on 0.10.x
Verified 2026-04
Verify ↗

Community Notes

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