microsoft/semantic-kernel · error · AgentInitializationException

The OpenAI API key is required.

Error message

The OpenAI API key is required.

What it means

Raised by setup_resources() after OpenAISettings is built but openai_settings.api_key is falsy. The API key is mandatory for any authenticated call to the OpenAI Responses API, so construction of the client is aborted. The key can come from the api_key argument or the OPENAI_API_KEY environment variable; neither was present or valid.

Source

Thrown at python/semantic_kernel/agents/open_ai/openai_responses_agent.py:436

            default_headers: The default headers to add to the client
            kwargs: Additional keyword arguments

        Returns:
            An OpenAI client instance and the configured Response model name
        """
        try:
            openai_settings = OpenAISettings(
                responses_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.responses_model_id:
            raise AgentInitializationException("The OpenAI Responses 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

  1. Set OPENAI_API_KEY in your environment or .env file (e.g. export OPENAI_API_KEY=sk-...).
  2. Pass api_key explicitly: setup_resources(api_key='sk-...').
  3. Verify the value is non-empty and is being read from the correct env file path/env_file_encoding.
  4. Switch to create_client() which applies the same check.

Example fix

// before
client, model = OpenAIResponsesAgent.setup_resources()

// after
client, model = OpenAIResponsesAgent.setup_resources(api_key='sk-...')
Defensive patterns

Strategy: validation

Validate before calling

import os
key = os.environ.get('OPENAI_API_KEY')
if not key:
    raise SystemExit('OPENAI_API_KEY is not set')

Type guard

def has_api_key() -> bool:
    import os
    return bool(os.environ.get('OPENAI_API_KEY'))

Try / catch

from semantic_kernel.exceptions.agent_exceptions import AgentInitializationException
try:
    client, model = OpenAIResponsesAgent.setup_resources()
except AgentInitializationException as e:
    if 'API key' in str(e):
        # prompt for / load the key
        ...
    raise

Prevention

When it happens

Trigger: Calling setup_resources() without an api_key argument and with no OPENAI_API_KEY environment variable set, or with the variable set to an empty string. Also when the key is supplied but the settings layer strips/ignores it.

Common situations: Fresh checkout with no .env file, CI runners that don't forward secrets, a renamed env var, or a container that lost its environment. The SecretStr field reports as falsy when its inner value is empty.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/9550c41d591d8cc6. Report an issue: GitHub.