ValueError
builtins.ValueError
Stack trace
ValueError: OpenAI API key not configured. Please set the OPENAI_API_KEY environment variable.
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
The OPENAI_API_KEY environment variable is not set in the system or runtime environment.
Set the OPENAI_API_KEY environment variable with your valid OpenAI API key before running your application.
The environment variable is set but contains an empty string or invalid key.
Verify that OPENAI_API_KEY contains a valid, non-empty API key string.
The application is running in an environment where environment variables are not loaded (e.g., missing .env loading).
Ensure your environment variables are loaded properly, for example by using python-dotenv or configuring your deployment environment correctly.
Code: broken vs fixed
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", "") 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.") 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.