{"record":{"id":"6083e7a228fcdcdd","repo":"microsoft/semantic-kernel","slug":"type-self-service-encountered-a-content-error","errorCode":null,"errorMessage":"{type(self)} service encountered a content error","messagePattern":"(.+?) service encountered a content error","errorType":"exception","errorClass":"ContentFilterAIException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/connectors/ai/open_ai/services/open_ai_handler.py","lineNumber":96,"sourceCode":"        settings: OpenAIPromptExecutionSettings,\n    ) -> ChatCompletion | Completion | AsyncStream[ChatCompletionChunk] | AsyncStream[Completion]:\n        \"\"\"Execute the appropriate call to OpenAI models.\"\"\"\n        try:\n            settings_dict = settings.prepare_settings_dict()\n            if self.ai_model_type == OpenAIModelTypes.CHAT:\n                assert isinstance(settings, OpenAIChatPromptExecutionSettings)  # nosec\n                self._handle_structured_output(settings, settings_dict)\n                if settings.tools is None:\n                    settings_dict.pop(\"parallel_tool_calls\", None)\n                response = await self.client.chat.completions.create(**settings_dict)\n            else:\n                response = await self.client.completions.create(**settings_dict)\n\n            self.store_usage(response)\n            return response\n        except BadRequestError as ex:\n            if ex.code == \"content_filter\":\n                raise ContentFilterAIException(\n                    f\"{type(self)} service encountered a content error\",\n                    ex,\n                ) from ex\n            raise ServiceResponseException(\n                f\"{type(self)} service failed to complete the prompt\",\n                ex,\n            ) from ex\n        except Exception as ex:\n            raise ServiceResponseException(\n                f\"{type(self)} service failed to complete the prompt\",\n                ex,\n            ) from ex\n\n    async def _send_embedding_request(self, settings: OpenAIEmbeddingPromptExecutionSettings) -> list[Any]:\n        \"\"\"Send a request to the OpenAI embeddings endpoint.\"\"\"\n        try:\n            response = await self.client.embeddings.create(**settings.prepare_settings_dict())\n","sourceCodeStart":78,"sourceCodeEnd":114,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/ai/open_ai/services/open_ai_handler.py#L78-L114","documentation":"Raised as ContentFilterAIException in _send_completion_request when the OpenAI SDK raises a BadRequestError whose code attribute equals 'content_filter'. This indicates the OpenAI content-moderation system blocked the prompt or completion. Semantic Kernel re-wraps it as a domain-specific ContentFilterAIException to distinguish it from other 400 errors.","triggerScenarios":"Sending a prompt that triggers OpenAI's content filter — the input or generated output contains content that violates OpenAI's usage policies, causing the API to return a 400 with code 'content_filter'.","commonSituations":"Processing untrusted user input that contains prohibited content; aggressive system prompts; jailbreak attempts in production; testing with edge-case prompts that trip moderation.","solutions":["Sanitize or pre-filter user input before sending it to the model","Add a retry with a rephrased or truncated prompt if the filter is a false positive","Review OpenAI's moderation guidelines and adjust your application's content policy accordingly","Consider using the OpenAI Moderation API to pre-screen input before the completion call"],"exampleFix":"# before\nresponse = await service.get_chat_message_content(chat_history=history, settings=settings)\n# after — pre-moderate then call\nmoderation = await client.moderations.create(input=user_text)\nif moderation.results[0].flagged:\n    return 'Content blocked by moderation policy.'\nresponse = await service.get_chat_message_content(chat_history=history, settings=settings)","handlingStrategy":"try-catch","validationCode":"from openai import AsyncOpenAI\n\nasync def input_is_safe(client: AsyncOpenAI, text: str) -> bool:\n    result = await client.moderations.create(input=text)\n    return not result.results[0].flagged","typeGuard":null,"tryCatchPattern":"from semantic_kernel.connectors.ai.open_ai.exceptions.content_filter_ai_exception import ContentFilterAIException\n\ntry:\n    response = await service.get_chat_message_content(...)\nexcept ContentFilterAIException as e:\n    logger.warning('Content filtered by OpenAI: %s', e)\n    return safe_fallback_message","preventionTips":["Run user input through the OpenAI Moderation API before the completion call","Log filtered prompts to identify systematic false positives or abuse patterns"],"tags":["openai","content-filter","content-moderation","bad-request"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-14T10:17:34.591Z"}