microsoft/semantic-kernel · error · ContentFilterAIException
{type(self)} service encountered a content error
Error message
{type(self)} service encountered a content error What it means
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.
Source
Thrown at python/semantic_kernel/connectors/ai/open_ai/services/open_ai_handler.py:96
settings: OpenAIPromptExecutionSettings,
) -> ChatCompletion | Completion | AsyncStream[ChatCompletionChunk] | AsyncStream[Completion]:
"""Execute the appropriate call to OpenAI models."""
try:
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())
View on GitHub (pinned to c028a0c7dc)
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
Example fix
# before
response = await service.get_chat_message_content(chat_history=history, settings=settings)
# after — pre-moderate then call
moderation = await client.moderations.create(input=user_text)
if moderation.results[0].flagged:
return 'Content blocked by moderation policy.'
response = await service.get_chat_message_content(chat_history=history, settings=settings) Defensive patterns
Strategy: try-catch
Validate before calling
from openai import AsyncOpenAI
async def input_is_safe(client: AsyncOpenAI, text: str) -> bool:
result = await client.moderations.create(input=text)
return not result.results[0].flagged Try / catch
from semantic_kernel.connectors.ai.open_ai.exceptions.content_filter_ai_exception import ContentFilterAIException
try:
response = await service.get_chat_message_content(...)
except ContentFilterAIException as e:
logger.warning('Content filtered by OpenAI: %s', e)
return safe_fallback_message Prevention
- Run user input through the OpenAI Moderation API before the completion call
- Log filtered prompts to identify systematic false positives or abuse patterns
When it happens
Trigger: 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'.
Common situations: Processing untrusted user input that contains prohibited content; aggressive system prompts; jailbreak attempts in production; testing with edge-case prompts that trip moderation.
Related errors
- Run failed with status: `{response.Status}` for agent `{agen
- {type(self)} service failed to complete the prompt
- OPENAI_API_KEY is not set.
- OPENAI_API_KEY is not set.
- OPENAI_API_KEY is not set.
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/6083e7a228fcdcdd.
Report an issue: GitHub.