microsoft/semantic-kernel · error · ServiceInitializationError
The OpenAI API key is required.
Error message
The OpenAI API key is required.
What it means
Raised by OpenAIChatCompletion.__init__ after settings creation succeeds. The check is 'if not async_client and not openai_settings.api_key' — meaning an API key is only required when no pre-built AsyncOpenAI client was supplied. The api_key is sourced from the constructor argument or the OPENAI_API_KEY environment variable. Without either a client or a key, the service cannot authenticate to the OpenAI API.
Source
Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_chat_completion.py:65
async_client (Optional[AsyncOpenAI]): An existing client to use. (Optional)
env_file_path (str | None): Use the environment settings file as a fallback
to environment variables. (Optional)
env_file_encoding (str | None): The encoding of the environment settings file. (Optional)
instruction_role (str | None): The role to use for 'instruction' messages, for example,
"""
try:
openai_settings = OpenAISettings(
api_key=api_key,
org_id=org_id,
chat_model_id=ai_model_id,
env_file_path=env_file_path,
env_file_encoding=env_file_encoding,
)
except ValidationError as ex:
raise ServiceInitializationError("Failed to create OpenAI settings.", ex) from ex
if not async_client and not openai_settings.api_key:
raise ServiceInitializationError("The OpenAI API key is required.")
if not openai_settings.chat_model_id:
raise ServiceInitializationError("The OpenAI model ID is required.")
super().__init__(
ai_model_id=openai_settings.chat_model_id,
api_key=openai_settings.api_key.get_secret_value() if openai_settings.api_key else None,
org_id=openai_settings.org_id,
service_id=service_id,
ai_model_type=OpenAIModelTypes.CHAT,
default_headers=default_headers,
client=async_client,
instruction_role=instruction_role,
)
@classmethod
def from_dict(cls, settings: dict[str, Any]) -> "OpenAIChatCompletion":
"""Initialize an Open AI service from a dictionary of settings.
View on GitHub (pinned to c028a0c7dc)
Solutions
- Set OPENAI_API_KEY in your environment or .env file to your API key from https://platform.openai.com/api-keys.
- Pass api_key= explicitly in the constructor: OpenAIChatCompletion(ai_model_id='gpt-4o', api_key='sk-...').
- Pass a pre-built AsyncOpenAI client via async_client= to bypass key resolution entirely.
- Verify your .env file is discoverable by passing env_file_path='.env'.
Example fix
# before
service = OpenAIChatCompletion(
ai_model_id='gpt-4o',
)
# after
service = OpenAIChatCompletion(
ai_model_id='gpt-4o',
api_key='sk-...',
)
# or via env var: export OPENAI_API_KEY=sk-... Defensive patterns
Strategy: validation
Validate before calling
import os
from openai import AsyncOpenAI
api_key = os.environ.get('OPENAI_API_KEY')
if not api_key:
raise ValueError(
'OPENAI_API_KEY is not set. Provide it via environment variable, .env file, '
'the api_key= constructor argument, or an async_client= parameter.'
) Try / catch
from semantic_kernel.exceptions.service_exceptions import ServiceInitializationError
try:
service = OpenAIChatCompletion(
ai_model_id='gpt-4o',
api_key=os.environ.get('OPENAI_API_KEY'),
)
except ServiceInitializationError as e:
if 'API key is required' in str(e):
print('Set OPENAI_API_KEY, pass api_key=, or provide an async_client=')
raise Prevention
- Set OPENAI_API_KEY in your .env file during development.
- In production, inject the key via environment variable or a secrets manager.
- Pass a pre-built AsyncOpenAI client via async_client= to decouple key management from service construction.
- Validate that OPENAI_API_KEY is set at application startup before constructing any OpenAI service.
When it happens
Trigger: Constructing OpenAIChatCompletion without async_client= AND without api_key= (constructor argument) AND without OPENAI_API_KEY in the environment or .env file. This check runs after settings validation passed, so the settings object exists but its api_key field is None.
Common situations: Missing OPENAI_API_KEY env var; .env file not loaded or path incorrect; OPENAI_API_KEY set but empty string; copy-pasting sample code without configuring secrets; running in CI/Docker without injecting the key; assuming the key is optional (it is only optional if a client is provided).
Related errors
- Failed to get ephemeral token: {error_text}
- Please provide an api_key
- Failed to get a response from the chat completion service.
- API key was not specified.
- The provided reasoning effort '{textEffortLevel}' is not sup
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/73a2e0890230e750.
Report an issue: GitHub.