microsoft/semantic-kernel · error · ServiceResponseException

{type(self)} service failed to complete the prompt

Error message

{type(self)} service failed to complete the prompt

What it means

Raised as ServiceResponseException in _send_completion_request when the OpenAI SDK raises a BadRequestError whose code is NOT 'content_filter' — i.e., a 400 error for any other reason (malformed request, unsupported parameters, invalid model name, token-limit violations). It wraps the original BadRequestError as the cause.

Source

Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_handler.py:100

            settings_dict = settings.prepare_settings_dict()
            if self.ai_model_type == OpenAIModelTypes.CHAT:
                assert isinstance(settings, OpenAIChatPromptExecutionSettings)  # nosec
                self._handle_structured_output(settings, settings_dict)
                if settings.tools is None:
                    settings_dict.pop("parallel_tool_calls", None)
                response = await self.client.chat.completions.create(**settings_dict)
            else:
                response = await self.client.completions.create(**settings_dict)

            self.store_usage(response)
            return response
        except BadRequestError as ex:
            if ex.code == "content_filter":
                raise ContentFilterAIException(
                    f"{type(self)} service encountered a content error",
                    ex,
                ) from ex
            raise ServiceResponseException(
                f"{type(self)} service failed to complete the prompt",
                ex,
            ) from ex
        except Exception as ex:
            raise ServiceResponseException(
                f"{type(self)} service failed to complete the prompt",
                ex,
            ) from ex

    async def _send_embedding_request(self, settings: OpenAIEmbeddingPromptExecutionSettings) -> list[Any]:
        """Send a request to the OpenAI embeddings endpoint."""
        try:
            response = await self.client.embeddings.create(**settings.prepare_settings_dict())

            self.store_usage(response)
            return [x.embedding for x in response.data]
        except Exception as ex:
            raise ServiceResponseException(

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Inspect the wrapped BadRequestError (ex.__cause__) for the exact API error message and code
  2. Verify the model name is valid and the parameters you set are supported by that specific model
  3. Remove or adjust unsupported parameters (e.g., drop temperature for o1-family models)
  4. Validate tool/function JSON schemas against the OpenAI function-calling spec before sending

Example fix

# before — o1 model does not support temperature
settings = OpenAIChatPromptExecutionSettings(ai_model_id='o1-preview', temperature=0.7)
# after
settings = OpenAIChatPromptExecutionSettings(ai_model_id='o1-preview')  # no temperature
Defensive patterns

Strategy: try-catch

Validate before calling

SUPPORTED_PARAMS = {'gpt-4o': {'temperature', 'max_tokens', 'tools', 'tool_choice', 'response_format'}}
model = settings.ai_model_id
if model in SUPPORTED_PARAMS:
    for key in settings.prepare_settings_dict():
        if key not in SUPPORTED_PARAMS[model] and key not in {'model', 'messages', 'stream'}:
            logger.warning(f'Parameter {key} may not be supported by {model}')

Try / catch

from openai import BadRequestError
from semantic_kernel.exceptions import ServiceResponseException

try:
    response = await service.get_chat_message_content(...)
except ServiceResponseException as e:
    if isinstance(e.__cause__, BadRequestError):
        logger.error('OpenAI rejected request: %s (code=%s)', e.__cause__.message, e.__cause__.code)
        # adjust parameters based on the error and retry

Prevention

When it happens

Trigger: Sending a completion/chat request with parameters the OpenAI API rejects: specifying a model name that doesn't exist, max_tokens exceeding the model's limit, incompatible tool/function schemas, unsupported response_format, or deprecated parameters for the requested model.

Common situations: Switching to a new model (e.g., o1) that doesn't support certain parameters like temperature; passing tool definitions with invalid JSON schemas; setting max_tokens beyond the model's context window; using parameters valid for one model family on another.

Related errors


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