microsoft/semantic-kernel · critical · ServiceInitializationError

Failed to create OpenAI settings.

Error message

Failed to create OpenAI settings.

What it means

Raised as ServiceInitializationError during OpenAITextCompletion construction when the OpenAISettings pydantic model fails validation. The constructor builds settings with api_key, org_id, text_model_id, env_file_path, and env_file_encoding, then catches pydantic.ValidationError and re-wraps it with the __cause__ chain preserved.

Source

Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_text_completion.py:60

            org_id (str | None): The optional org ID to use. If provided will override,
                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)
        """
        try:
            openai_settings = OpenAISettings(
                api_key=api_key,
                org_id=org_id,
                text_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 openai_settings.text_model_id:
            raise ServiceInitializationError("The OpenAI text model ID is required.")
        super().__init__(
            ai_model_id=openai_settings.text_model_id,
            service_id=service_id,
            api_key=openai_settings.api_key.get_secret_value() if openai_settings.api_key else None,
            org_id=openai_settings.org_id,
            ai_model_type=OpenAIModelTypes.TEXT,
            default_headers=default_headers,
            client=async_client,
        )

    @classmethod
    def from_dict(cls, settings: dict[str, Any]) -> "OpenAITextCompletion":
        """Initialize an Open AI service from a dictionary of settings.

        Args:
            settings: A dictionary of settings for the service.

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Inspect ex.__cause__ (pydantic.ValidationError) for field-level error details
  2. Fix the specific failing field — typically api_key or a settings combination constraint
  3. Construct OpenAISettings standalone to get clearer error messages before the service call
  4. Verify env_file_path and env_file_encoding are correct if loading from a .env file

Example fix

# before
service = OpenAITextCompletion()  # may raise if settings invalid
# after — construct settings explicitly
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
try:
    settings = OpenAISettings(api_key=os.environ['OPENAI_API_KEY'], text_model_id='gpt-3.5-turbo-instruct')
except ValidationError as e:
    print(e.errors())
    raise
service = OpenAITextCompletion(api_key=settings.api_key.get_secret_value(), ai_model_id=settings.text_model_id)
Defensive patterns

Strategy: validation

Validate before calling

from pydantic import ValidationError
from semantic_kernel.connectors.ai.open_ai import OpenAISettings

try:
    _ = OpenAISettings(api_key=api_key, org_id=org_id, text_model_id=ai_model_id)
except ValidationError as e:
    for err in e.errors():
        logger.error('Field %s: %s', err['loc'], err['msg'])
    raise

Try / catch

from semantic_kernel.exceptions.service_exceptions import ServiceInitializationError

try:
    service = OpenAITextCompletion()
except ServiceInitializationError as e:
    if 'Failed to create OpenAI settings' in str(e):
        logger.error('Text completion settings invalid: %s', e.__cause__)
        raise

Prevention

When it happens

Trigger: Constructing OpenAITextCompletion when OpenAISettings fails pydantic validation — invalid api_key, conflicting field values, or a model-level validator rejecting the combination of inputs.

Common situations: Passing an empty or malformed api_key; .env file at env_file_path does not exist and no fallback is available; pydantic model_validator on OpenAISettings rejects the field combination (e.g., neither api_key nor a valid token source is provided).

Related errors


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