microsoft/semantic-kernel · critical · ServiceInitializationError

Failed to create OpenAI settings.

Error message

Failed to create OpenAI settings.

What it means

Raised as ServiceInitializationError during OpenAIRealtimeWebRTC construction when the OpenAISettings pydantic model fails validation. The constructor builds settings from api_key, org_id, ai_model_id, env_file_path, and env_file_encoding, then catches pydantic.ValidationError and re-wraps it. The original ValidationError is available in ex.__cause__.

Source

Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_realtime.py:98

            env_file_encoding (str | None): The encoding of the environment settings file. (Optional)
            kwargs: Additional arguments.
                This can include:
                kernel (Kernel): the kernel to use for function calls
                plugins (list[object] or dict[str, object]): the plugins to use for function calls
                settings (OpenAIRealtimeExecutionSettings): the settings to use for the session
                chat_history (ChatHistory): the chat history to use for the session
                Otherwise they can also be passed to the context manager.
        """
        try:
            openai_settings = OpenAISettings(
                api_key=api_key,
                org_id=org_id,
                realtime_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.realtime_model_id:
            raise ServiceInitializationError("The OpenAI realtime model ID is required.")
        if audio_track:
            kwargs["audio_track"] = audio_track
        super().__init__(
            audio_output_callback=audio_output_callback,
            ai_model_id=openai_settings.realtime_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.REALTIME,
            default_headers=default_headers,
            client=client,
            **kwargs,
        )


# region Websocket

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Inspect ex.__cause__ (the pydantic.ValidationError) to see which field(s) failed validation and why
  2. Fix the specific field validation error reported by pydantic (e.g., provide a non-empty api_key)
  3. Ensure the .env file at env_file_path exists and contains valid entries if relying on it
  4. Construct OpenAISettings directly in a try/except to get clearer error messages before passing to the service

Example fix

# before
service = OpenAIRealtimeWebRTC(audio_track=track)  # may fail if settings invalid
# after — construct settings explicitly to catch validation early
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
try:
    settings = OpenAISettings(api_key=os.environ['OPENAI_API_KEY'])
except ValidationError as e:
    print(e.errors())  # inspect specific field errors
    raise
service = OpenAIRealtimeWebRTC(audio_track=track, api_key=settings.api_key.get_secret_value())
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, realtime_model_id=ai_model_id)
except ValidationError as e:
    for err in e.errors():
        print(f'Field {err["loc"]}: {err["msg"]}')
    raise

Try / catch

from semantic_kernel.exceptions.service_exceptions import ServiceInitializationError

try:
    service = OpenAIRealtimeWebRTC(audio_track=track)
except ServiceInitializationError as e:
    if 'Failed to create OpenAI settings' in str(e):
        logger.error('Settings validation failed: %s', e.__cause__)
        raise

Prevention

When it happens

Trigger: Constructing OpenAIRealtimeWebRTC when the OpenAISettings pydantic validator rejects the input — e.g., api_key fails a field validator, or a combination of fields violates a model-level constraint in OpenAISettings.

Common situations: Passing an empty or malformed api_key string that fails pydantic field validation; providing conflicting settings values (e.g., both env_file_path pointing to a missing file with no fallback); a pydantic model_validator on OpenAISettings rejecting the combination of inputs.

Related errors


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