{"record":{"id":"596e5248157b573b","repo":"BerriAI/litellm","slug":"violated-openai-moderation-policy","errorCode":null,"errorMessage":"Violated OpenAI moderation policy","messagePattern":"Violated OpenAI moderation policy","errorType":"http","errorClass":"HTTPException","httpStatus":400,"severity":"error","filePath":"litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py","lineNumber":161,"sourceCode":"        if result.flagged:\n            # Build detailed violation information\n            violated_categories: Final = []\n            if result.categories:\n                for category, is_violated in result.categories.items():\n                    if is_violated:\n                        violated_categories.append(category)\n\n            violation_details: Final = {\n                \"violated_categories\": violated_categories,\n                \"category_scores\": result.category_scores or {},\n            }\n\n            verbose_proxy_logger.warning(\n                \"OpenAI Moderation: Content flagged for violations: %s\",\n                violation_details,\n            )\n\n            raise HTTPException(\n                status_code=400,\n                detail={\n                    \"error\": \"Violated OpenAI moderation policy\",\n                    \"moderation_result\": violation_details,\n                },\n            )\n\n    @log_guardrail_information\n    async def apply_guardrail(\n        self,\n        inputs: GenericGuardrailAPIInputs,\n        request_data: dict,\n        input_type: Literal[\"request\", \"response\"],\n        logging_obj: Optional[\"LiteLLMLoggingObj\"] = None,\n    ) -> GenericGuardrailAPIInputs:\n        \"\"\"\n        Apply OpenAI moderation guardrail using the unified guardrail interface.\n","sourceCodeStart":143,"sourceCodeEnd":179,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py#L143-L179","documentation":"Intentional content block from OpenAIModerationGuardrail._check_moderation_result: the moderation model flagged the text in one or more categories, and the guardrail (running in blocking mode) rejects the request/response with HTTP 400. The detail includes which categories fired and the full category_scores for auditability.","triggerScenarios":"Pre-call moderation of prompts containing violence/self-harm/hate/sexual content matched by omni-moderation-latest; post-call streaming hook flagging a generated chunk; borderline content newly caught after OpenAI updates moderation models or thresholds","commonSituations":"User-generated content apps surfacing the raw 400 to end users; test fixtures containing edgy text that trips categories; legitimate content (medical, security research) being over-flagged by category thresholds","solutions":["Catch the 400 client-side and degrade gracefully using violated_categories to tailor the message","For legitimate content being over-flagged, pre-filter or rephrase at the application layer, or run the guardrail in log-only mode for those routes","Review category_scores — near-threshold scores indicate borderline content you may choose to allow by switching to custom threshold handling","Keep human-review flows for false positives rather than bypassing moderation entirely"],"exampleFix":"# before: error propagates raw\ntry:\n    r = client.chat.completions.create(**params)\nexcept Exception:\n    abort(500)\n\n# after: handle the moderation block specifically\nfrom openai import BadRequestError\ntry:\n    r = client.chat.completions.create(**params)\nexcept BadRequestError as e:\n    body = e.response.json()\n    if body.get(\"error\") == \"Violated OpenAI moderation policy\":\n        cats = body[\"moderation_result\"][\"violated_categories\"]\n        return f\"Content blocked ({', '.join(cats)}). Please rephrase.\", 400\n    raise","handlingStrategy":"try-catch","validationCode":"null  # moderation verdict is server-side; clients cannot pre-classify without reimplementing the model","typeGuard":null,"tryCatchPattern":"from openai import BadRequestError\n\ntry:\n    r = client.chat.completions.create(**params)\nexcept BadRequestError as e:\n    body = e.response.json()\n    if body.get(\"error\") == \"Violated OpenAI moderation policy\":\n        cats = body[\"moderation_result\"][\"violated_categories\"]\n        return respond_block_page(cats)\n    raise","preventionTips":["Convert the 400 into category-aware user messaging instead of retrying — the same input will fail again","Log category_scores to spot systematic false positives and take them to policy review","Keep fixtures with known-flaggy strings in your test suite to assert your block-handling path works"],"tags":["openai-moderation","guardrails","content-filter","policy-block","http-400"],"backgroundTag":"content-blocked-by-policy","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}