microsoft/semantic-kernel · error · ServiceInitializationError
Failed to create OpenAI settings.
Error message
Failed to create OpenAI settings.
What it means
Raised in OpenAITextEmbedding.__init__ when the underlying OpenAISettings pydantic model fails validation. The original pydantic ValidationError is chained as __cause__, so the concrete field-level reasons (type coercion, malformed .env values, etc.) live on the cause, not in this message. All OpenAISettings fields are Optional, so this wrapper triggers only on an actual validation failure, not on a missing model id.
Source
Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_text_embedding.py:63
org_id (str | None): The optional org ID to use. If provided will override,
the env vars or .env file value.
default_headers (Mapping[str,str] | None): 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,
embedding_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.embedding_model_id:
raise ServiceInitializationError("The OpenAI embedding model ID is required.")
super().__init__(
ai_model_id=openai_settings.embedding_model_id,
api_key=openai_settings.api_key.get_secret_value() if openai_settings.api_key else None,
ai_model_type=OpenAIModelTypes.EMBEDDING,
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 chained cause: except ServiceInitializationError as e: print(e.__cause__.errors()) to see the failing field
- Validate the .env file syntax and the OPENAI_* values it defines
- Ensure api_key is passed as a str and env_file_encoding matches the file (default utf-8)
- Construct OpenAISettings() directly in a REPL to reproduce and read the raw ValidationError before wiring it into the service
Example fix
# before service = OpenAITextEmbedding(api_key=12345) # raises ServiceInitializationError: Failed to create OpenAI settings. # after service = OpenAITextEmbedding(api_key="sk-...", ai_model_id="text-embedding-3-small")
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, embedding_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 = OpenAITextEmbedding(api_key=api_key)
except ServiceInitializationError as e:
cause = e.__cause__
fields = cause.errors() if cause is not None else []
raise RuntimeError(f"OpenAI settings invalid: {fields}") from e Prevention
- Always inspect e.__cause__.errors() for the failing field
- Keep api_key as a str and .env files utf-8 encoded
- Build OpenAISettings() in isolation first when debugging
When it happens
Trigger: Constructing OpenAITextEmbedding with an argument pydantic cannot coerce (e.g. api_key of an unexpected type), or with an env_file_path that points to a .env file whose values fail field validation, or when KernelBaseSettings rejects a value during env-var binding.
Common situations: A .env file has a syntax error or a quoted/whitespace value that breaks SecretStr parsing; the API key is loaded from a secret manager in a non-string form; a pydantic version upgrade tightened coercion; env_file_encoding does not match the file's actual encoding.
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/4438700e182dd298.
Report an issue: GitHub.