microsoft/semantic-kernel · error · AgentInitializationException
The OpenAI API key is required.
Error message
The OpenAI API key is required.
What it means
Raised by create_client_and_model() when OpenAISettings resolved successfully but openai_settings.api_key is empty/None. The settings object tolerates a missing key at construction, so the library does a second explicit presence check before building the AsyncOpenAI client, because an empty key would only fail later at the first API call with a cryptic auth error.
Source
Thrown at python/semantic_kernel/agents/open_ai/openai_assistant_agent.py:354
default_headers: The default headers to add to the client
kwargs: Additional keyword arguments
Returns:
An OpenAI client instance and the configured model name
"""
try:
openai_settings = OpenAISettings(
chat_model_id=ai_model_id,
api_key=api_key,
org_id=org_id,
env_file_path=env_file_path,
env_file_encoding=env_file_encoding,
)
except ValidationError as ex:
raise AgentInitializationException("Failed to create OpenAI settings.", ex) from ex
if not openai_settings.api_key:
raise AgentInitializationException("The OpenAI API key is required.")
if not openai_settings.chat_model_id:
raise AgentInitializationException("The OpenAI model ID is required.")
merged_headers = dict(copy(default_headers)) if default_headers else {}
if default_headers:
merged_headers.update(default_headers)
if APP_INFO:
merged_headers.update(APP_INFO)
merged_headers = prepend_semantic_kernel_to_user_agent(merged_headers)
client = AsyncOpenAI(
api_key=openai_settings.api_key.get_secret_value() if openai_settings.api_key else None,
organization=openai_settings.org_id,
default_headers=merged_headers,
**kwargs,
)
View on GitHub (pinned to c028a0c7dc)
Solutions
- Set OPENAI_API_KEY in your environment or .env, or pass api_key= explicitly to create_client_and_model.
- Confirm the env file path and encoding passed to env_file_path are correct so the key is actually loaded.
- If using a key vault, retrieve the secret and pass it as api_key rather than relying on env.
Example fix
# before
client, model = await OpenAIAssistantAgent.create_client_and_model(ai_model_id='gpt-4o')
# after
client, model = await OpenAIAssistantAgent.create_client_and_model(
ai_model_id='gpt-4o',
api_key=os.environ['OPENAI_API_KEY'],
) Defensive patterns
Strategy: validation
Validate before calling
import os
assert os.environ.get('OPENAI_API_KEY'), 'OPENAI_API_KEY must be set' Type guard
null
Try / catch
from semantic_kernel.exceptions.agent_exceptions import AgentInitializationException
try:
client, model = await OpenAIAssistantAgent.create_client_and_model(api_key=key, ai_model_id=mid)
except AgentInitializationException as e:
if 'API key' in str(e):
key = retrieve_secret_from_vault()
client, model = await OpenAIAssistantAgent.create_client_and_model(api_key=key, ai_model_id=mid) Prevention
- Inject secrets via env/CI, never hardcode.
- Assert key presence at startup.
- Use a vault helper to fetch keys.
When it happens
Trigger: No OPENAI_API_KEY env var and no api_key argument passed; the key is present but empty string; env file not found or not loaded so the field stays unset; SecretStr coerced from None.
Common situations: Fresh checkout without .env; CI without secrets injected; key stored under a non-default env var name; Docker container missing the env var; using Azure env vars instead of the plain OpenAI ones.
Related errors
- Failed to create OpenAI settings.
- The OpenAI model ID is required.
- Missing required 'client' in OpenAIAssistantAgent._from_dict
- model.id required when creating a new Azure AI agent
- Expected OpenAISettings, got {type(settings).__name__}
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/292dbb14333a41ae.
Report an issue: GitHub.