microsoft/semantic-kernel · error · ServiceInitializationError
Failed to create OpenAI settings.
Error message
Failed to create OpenAI settings.
What it means
Raised in OpenAITextToImage.__init__ when the OpenAISettings pydantic model fails validation. The real pydantic ValidationError is chained on __cause__ with the failing fields. All OpenAISettings fields are Optional, so this wrapper is hit only on an actual validation error, not a missing model id.
Source
Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_text_to_image.py:58
org_id: 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: An existing client to use. (Optional)
env_file_path: Use the environment settings file as
a fallback to environment variables. (Optional)
env_file_encoding: The encoding of the environment settings file. (Optional)
"""
try:
openai_settings = OpenAISettings(
api_key=api_key,
org_id=org_id,
text_to_image_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_to_image_model_id:
raise ServiceInitializationError("The OpenAI text to image model ID is required.")
super().__init__(
ai_model_id=openai_settings.text_to_image_model_id,
api_key=openai_settings.api_key.get_secret_value() if openai_settings.api_key else None,
ai_model_type=OpenAIModelTypes.TEXT_TO_IMAGE,
org_id=openai_settings.org_id,
service_id=service_id,
default_headers=default_headers,
client=async_client,
)
@classmethod
def from_dict(cls: type[T_], settings: dict[str, Any]) -> T_:
"""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
- Inspect the cause: except ServiceInitializationError as e: print(e.__cause__.errors())
- Fix .env OPENAI_* syntax and quoting
- Pass api_key as a str and confirm env_file_encoding
- Build OpenAISettings(text_to_image_model_id=...) alone to surface the raw error
Example fix
# before service = OpenAITextToImage(api_key=object()) # raises ServiceInitializationError: Failed to create OpenAI settings. # after service = OpenAITextToImage(ai_model_id="dall-e-3", api_key="sk-...")
Defensive patterns
Strategy: try-catch
Validate before calling
from semantic_kernel.connectors.ai.open_ai.settings.open_ai_settings import OpenAISettings
try:
OpenAISettings(api_key=api_key, text_to_image_model_id=ai_model_id)
except Exception as e:
raise ValueError(f"OpenAISettings invalid: {e}") from e Type guard
from pydantic import ValidationError
from semantic_kernel.connectors.ai.open_ai.settings.open_ai_settings import OpenAISettings
def settings_are_valid(**kwargs) -> bool:
try:
OpenAISettings(**kwargs)
return True
except ValidationError:
return False Try / catch
from semantic_kernel.exceptions.service_exceptions import ServiceInitializationError
try:
service = OpenAITextToImage(api_key=api_key)
except ServiceInitializationError as e:
fields = e.__cause__.errors() if e.__cause__ is not None else []
raise RuntimeError(f"OpenAI settings invalid: {fields}") from e Prevention
- Read e.__cause__.errors() for the failing field
- Keep .env values correctly quoted
- Pass api_key as str
When it happens
Trigger: Constructing OpenAITextToImage with a value pydantic cannot coerce, or an env_file_path whose .env contents fail field validation, or an env var binding rejected by KernelBaseSettings.
Common situations: Broken .env quoting/whitespace; api_key supplied as a non-string; env_file_encoding mismatch; pydantic upgrade that stops auto-coercing.
Related errors
- Failed to create OpenAI settings.
- Failed to create OpenAI settings.
- Failed to create Copilot Studio Agent settings: {exc}
- Failed to create Azure OpenAI settings: {exc}
- Failed to validate Google AI settings: {e}
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/45d9b1d418477149.
Report an issue: GitHub.