microsoft/semantic-kernel · error · ServiceInitializationError

Failed to create OpenAI settings.

Error message

Failed to create OpenAI settings.

What it means

Raised by OpenAIChatCompletion.__init__ when OpenAISettings construction throws a pydantic ValidationError. The settings model (non-Azure) validates api_key (SecretStr|None), org_id (str|None), chat_model_id (str|None). If any field receives a value that fails type coercion, pydantic raises ValidationError which is wrapped here as ServiceInitializationError.

Source

Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_chat_completion.py:62

                the env vars or .env file value.
            default_headers: The default headers mapping of string keys to
                string values for HTTP requests. (Optional)
            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

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Inspect the chained ValidationError for the specific field and constraint that failed.
  2. Pass api_key as a plain string (str), not a SecretStr or bytes.
  3. Verify .env file syntax and encoding (default utf-8).
  4. Ensure OPENAI_API_KEY and OPENAI_ORG_ID are set to valid strings in the environment.

Example fix

# before (api_key passed as SecretStr)
from pydantic import SecretStr
service = OpenAIChatCompletion(
    ai_model_id='gpt-4o',
    api_key=SecretStr('sk-...'),
)
# after (plain string)
service = OpenAIChatCompletion(
    ai_model_id='gpt-4o',
    api_key='sk-...',
)
Defensive patterns

Strategy: try-catch

Validate before calling

import os

api_key = os.environ.get('OPENAI_API_KEY')
if not api_key or not isinstance(api_key, str):
    raise ValueError(
        'OPENAI_API_KEY must be set to a non-empty string in the environment or .env file.'
    )

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:
    cause = e.__cause__
    if cause:
        print(f'Settings validation failed: {cause}')
    raise

Prevention

When it happens

Trigger: Constructing OpenAIChatCompletion with a malformed .env file, an api_key of the wrong type (e.g. bytes), or an OPENAI_API_KEY environment variable with an incompatible value. Since most fields are str|None, type errors are uncommon but can arise from corrupt env files or passing SecretStr where str is expected.

Common situations: Corrupted .env file with invalid dotenv syntax; OPENAI_API_KEY set to an empty string in CI; env_file_encoding mismatch; passing api_key as a SecretStr object rather than a plain string; OPENAI_ORG_ID set to a non-string value in config management tools.

Related errors


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