microsoft/semantic-kernel · critical · ServiceInitializationError

Please provide an api_key

Error message

Please provide an api_key

What it means

Raised in OpenAIConfigBase when no pre-configured AsyncOpenAI client is supplied AND no api_key can be resolved. The base config logic merges default headers, then constructs a new AsyncOpenAI client — but it refuses to create one without authentication.

Source

Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_config_base.py:67

                unless the account belongs to multiple organizations.
            service_id (str): OpenAI service ID. This is optional.
            default_headers (Mapping[str, str]): Default headers
                for HTTP requests. (Optional)
            client (AsyncOpenAI): An existing OpenAI client, optional.
            instruction_role (str): The role to use for 'instruction'
                messages, for example, summarization prompts could use `developer` or `system`. (Optional)
            kwargs: Additional keyword arguments.

        """
        # Merge APP_INFO into the headers if it exists
        merged_headers = dict(copy(default_headers)) if default_headers else {}
        if APP_INFO:
            merged_headers.update(APP_INFO)
            merged_headers = prepend_semantic_kernel_to_user_agent(merged_headers)

        if not client:
            if not api_key:
                raise ServiceInitializationError("Please provide an api_key")
            client = AsyncOpenAI(
                api_key=api_key,
                organization=org_id,
                default_headers=merged_headers,
            )
        args = {
            "ai_model_id": ai_model_id,
            "client": client,
            "ai_model_type": ai_model_type,
        }
        if service_id:
            args["service_id"] = service_id
        if instruction_role:
            args["instruction_role"] = instruction_role
        super().__init__(**args, **kwargs)

    def to_dict(self) -> dict[str, str]:
        """Create a dict of the service settings."""

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Set the OPENAI_API_KEY environment variable or add it to your .env file
  2. Pass api_key explicitly: OpenAIChatCompletion(api_key='sk-...')
  3. Pass a pre-configured AsyncOpenAI client via the client= parameter if you manage your own client lifecycle

Example fix

# before
service = OpenAIChatCompletion(ai_model_id='gpt-4o')
# after
service = OpenAIChatCompletion(ai_model_id='gpt-4o', api_key=os.environ['OPENAI_API_KEY'])
Defensive patterns

Strategy: validation

Validate before calling

import os
if not os.environ.get('OPENAI_API_KEY'):
    raise EnvironmentError('OPENAI_API_KEY is not set in the environment or .env file')

Try / catch

from semantic_kernel.exceptions.service_exceptions import ServiceInitializationError

try:
    service = OpenAIChatCompletion(ai_model_id='gpt-4o')
except ServiceInitializationError as e:
    if 'api_key' in str(e):
        raise  # surface as a deployment-config issue

Prevention

When it happens

Trigger: Instantiating any OpenAI service (chat, text, embedding, realtime, etc.) that inherits OpenAIConfigBase without passing either client or api_key, and without OPENAI_API_KEY set in the environment or .env file.

Common situations: Deploying to CI/CD where the OPENAI_API_KEY secret is not injected; .env file present but key name is misspelled (e.g., OPENAI_KEY instead of OPENAI_API_KEY); local development where the .env is git-ignored and not created.

Related errors


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