AzureOpenAIContentFilterError
azure.openai.error.AzureOpenAIContentFilterError
Stack trace
azure.openai.error.AzureOpenAIContentFilterError: The request was blocked by Azure OpenAI content filter due to policy violation.
at azure.openai._client._send_request (azure/openai/_client.py:123)
at azure.openai._client.ChatCompletion.create (azure/openai/_client.py:234)
at app.py:45 Why it happens
Azure OpenAI applies a content filter to detect and block requests containing disallowed or sensitive content based on Microsoft's policy. When the input prompt or generated output triggers this filter, the API returns a content filter error with HTTP 403 status.
Detection
Monitor API responses for AzureOpenAIContentFilterError exceptions or HTTP 403 status codes with content filter messages to catch blocked requests before they cause downstream failures.
Causes & fixes
Input prompt contains disallowed or sensitive content triggering the Azure content filter.
Review and sanitize the input prompt to remove or rephrase content that violates Azure OpenAI content policies.
Generated output contains content flagged by the Azure content filter.
Add stricter prompt instructions to avoid generating disallowed content or implement post-processing filters to detect and handle flagged outputs.
Using an Azure OpenAI deployment with strict content filtering enabled by default.
Check your Azure OpenAI deployment settings and consider adjusting content filter sensitivity or using a deployment with relaxed filtering if policy compliant.
Code: broken vs fixed
from azure.openai import OpenAI
import os
client = OpenAI(deployment_id=os.environ['AZURE_DEPLOYMENT_ID'], endpoint=os.environ['AZURE_ENDPOINT'], api_key=os.environ['AZURE_API_KEY'])
response = client.chat.completions.create(
deployment_id=os.environ['AZURE_DEPLOYMENT_ID'],
messages=[{"role": "user", "content": "Some disallowed content here"}]
) # This line triggers AzureOpenAIContentFilterError from azure.openai import OpenAI, AzureOpenAIContentFilterError
import os
client = OpenAI(deployment_id=os.environ['AZURE_DEPLOYMENT_ID'], endpoint=os.environ['AZURE_ENDPOINT'], api_key=os.environ['AZURE_API_KEY'])
try:
response = client.chat.completions.create(
deployment_id=os.environ['AZURE_DEPLOYMENT_ID'],
messages=[{"role": "user", "content": "Please provide a safe and policy-compliant prompt."}]
) # Fixed: sanitized prompt and added error handling
print(response.choices[0].message.content)
except AzureOpenAIContentFilterError as e:
print(f"Content filter blocked the request: {e}") Workaround
Catch AzureOpenAIContentFilterError exceptions and implement fallback logic such as prompting the user to revise input or logging the incident for manual review.
Prevention
Design prompts carefully to avoid disallowed content, validate inputs before sending to Azure OpenAI, and monitor API responses to handle content filter blocks proactively.