{"record":{"id":"9407a15fbf73f983","repo":"microsoft/semantic-kernel","slug":"failed-to-create-openai-settings-9407a1","errorCode":null,"errorMessage":"Failed to create OpenAI settings.","messagePattern":"Failed to create OpenAI settings\\.","errorType":"exception","errorClass":"ServiceInitializationError","httpStatus":null,"severity":"critical","filePath":"python/semantic_kernel/connectors/ai/open_ai/services/open_ai_text_completion.py","lineNumber":60,"sourceCode":"            org_id (str | None): The optional org ID to use. If provided will override,\n                the env vars or .env file value.\n            default_headers: The default headers mapping of string keys to\n                string values for HTTP requests. (Optional)\n            async_client (Optional[AsyncOpenAI]): An existing client to use. (Optional)\n            env_file_path (str | None): Use the environment settings file as a fallback to\n                environment variables. (Optional)\n            env_file_encoding (str | None): The encoding of the environment settings file. (Optional)\n        \"\"\"\n        try:\n            openai_settings = OpenAISettings(\n                api_key=api_key,\n                org_id=org_id,\n                text_model_id=ai_model_id,\n                env_file_path=env_file_path,\n                env_file_encoding=env_file_encoding,\n            )\n        except ValidationError as ex:\n            raise ServiceInitializationError(\"Failed to create OpenAI settings.\", ex) from ex\n        if not openai_settings.text_model_id:\n            raise ServiceInitializationError(\"The OpenAI text model ID is required.\")\n        super().__init__(\n            ai_model_id=openai_settings.text_model_id,\n            service_id=service_id,\n            api_key=openai_settings.api_key.get_secret_value() if openai_settings.api_key else None,\n            org_id=openai_settings.org_id,\n            ai_model_type=OpenAIModelTypes.TEXT,\n            default_headers=default_headers,\n            client=async_client,\n        )\n\n    @classmethod\n    def from_dict(cls, settings: dict[str, Any]) -> \"OpenAITextCompletion\":\n        \"\"\"Initialize an Open AI service from a dictionary of settings.\n\n        Args:\n            settings: A dictionary of settings for the service.","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/ai/open_ai/services/open_ai_text_completion.py#L42-L78","documentation":"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.","triggerScenarios":"Constructing OpenAITextCompletion when OpenAISettings fails pydantic validation — invalid api_key, conflicting field values, or a model-level validator rejecting the combination of inputs.","commonSituations":"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).","solutions":["Inspect ex.__cause__ (pydantic.ValidationError) for field-level error details","Fix the specific failing field — typically api_key or a settings combination constraint","Construct OpenAISettings standalone to get clearer error messages before the service call","Verify env_file_path and env_file_encoding are correct if loading from a .env file"],"exampleFix":"# before\nservice = OpenAITextCompletion()  # may raise if settings invalid\n# after — construct settings explicitly\nfrom semantic_kernel.connectors.ai.open_ai import OpenAISettings\ntry:\n    settings = OpenAISettings(api_key=os.environ['OPENAI_API_KEY'], text_model_id='gpt-3.5-turbo-instruct')\nexcept ValidationError as e:\n    print(e.errors())\n    raise\nservice = OpenAITextCompletion(api_key=settings.api_key.get_secret_value(), ai_model_id=settings.text_model_id)","handlingStrategy":"validation","validationCode":"from pydantic import ValidationError\nfrom semantic_kernel.connectors.ai.open_ai import OpenAISettings\n\ntry:\n    _ = OpenAISettings(api_key=api_key, org_id=org_id, text_model_id=ai_model_id)\nexcept ValidationError as e:\n    for err in e.errors():\n        logger.error('Field %s: %s', err['loc'], err['msg'])\n    raise","typeGuard":null,"tryCatchPattern":"from semantic_kernel.exceptions.service_exceptions import ServiceInitializationError\n\ntry:\n    service = OpenAITextCompletion()\nexcept ServiceInitializationError as e:\n    if 'Failed to create OpenAI settings' in str(e):\n        logger.error('Text completion settings invalid: %s', e.__cause__)\n        raise","preventionTips":["Construct and validate OpenAISettings independently before constructing the text completion service","Log pydantic ValidationError.errors() for actionable field-level diagnostics"],"tags":["openai","text-completion","configuration","pydantic-validation"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}