Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

47.8 KB
Raw Blame
#!/usr/bin/env python3
"""
Test OpenAI Moderation Guardrail
"""

import json
import os
from pathlib import Path
from typing import Final


from unittest.mock import MagicMock, patch

import httpx
import pytest
import respx

import litellm
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.llms.openai.workload_identity import _workload_identity_auth
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.common_utils.callback_utils import get_logging_caching_headers
from litellm.proxy.guardrails.guardrail_hooks.openai import (
    initialize_guardrail as initialize_openai_moderation_guardrail,
)
from litellm.proxy.guardrails.guardrail_hooks.openai.moderations import (
    OpenAIModerationGuardrail,
)
from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLER, InMemoryGuardrailHandler
from litellm.proxy.guardrails.init_guardrails import init_guardrails_v2
from litellm.types.guardrails import Guardrail, LitellmParams, SupportedGuardrailIntegrations
from litellm.types.llms.openai import OpenAIModerationResponse, OpenAIModerationResult


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_init():
    """Test OpenAI moderation guardrail initialization"""
    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
        )

        assert guardrail.guardrail_name == "test-openai-moderation"
        assert guardrail.api_key == "test-key"
        assert guardrail.model == "omni-moderation-latest"
        assert guardrail.api_base == "https://api.openai.com/v1"


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_adds_to_litellm_callbacks():
    """Test that OpenAI moderation guardrail adds itself to litellm callbacks during initialization"""
    import litellm
    from litellm.proxy.guardrails.guardrail_hooks.openai import (
        initialize_guardrail as openai_initialize_guardrail,
    )
    from litellm.types.guardrails import (
        Guardrail,
        LitellmParams,
        SupportedGuardrailIntegrations,
    )

    # Clear existing callbacks for clean test
    original_callbacks = litellm.callbacks.copy()
    litellm.logging_callback_manager._reset_all_callbacks()

    try:
        with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
            guardrail_litellm_params = LitellmParams(
                guardrail=SupportedGuardrailIntegrations.OPENAI_MODERATION,
                api_key="test-key",
                model="omni-moderation-latest",
                mode="pre_call",
            )
            guardrail = openai_initialize_guardrail(
                litellm_params=guardrail_litellm_params,
                guardrail=Guardrail(
                    guardrail_name="test-openai-moderation",
                    litellm_params=guardrail_litellm_params,
                ),
            )

            # Check that the guardrail was added to litellm callbacks
            assert guardrail in litellm.callbacks
            assert len(litellm.callbacks) == 1

            # Verify it's the correct guardrail
            callback = litellm.callbacks[0]
            assert isinstance(callback, OpenAIModerationGuardrail)
            assert callback.guardrail_name == "test-openai-moderation"
    finally:
        # Restore original callbacks
        litellm.logging_callback_manager._reset_all_callbacks()
        for callback in original_callbacks:
            litellm.logging_callback_manager.add_litellm_callback(callback)


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_safe_content():
    """Test OpenAI moderation guardrail with safe content via apply_guardrail"""
    from litellm.types.utils import GenericGuardrailAPIInputs

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
        )

        # Mock safe moderation response
        mock_response = OpenAIModerationResponse(
            id="modr-123",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=False,
                    categories={
                        "sexual": False,
                        "hate": False,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.001,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.001,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": [],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        with patch.object(guardrail, "async_make_request", return_value=mock_response):
            # Test apply_guardrail with safe content using structured_messages
            inputs = GenericGuardrailAPIInputs(
                structured_messages=[
                    {"role": "user", "content": "Hello, how are you today?"}
                ]
            )

            result = await guardrail.apply_guardrail(
                inputs=inputs,
                request_data={
                    "messages": [
                        {"role": "user", "content": "Hello, how are you today?"}
                    ]
                },
                input_type="request",
            )

            # Should return the original inputs unchanged
            assert result == inputs


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_apply_guardrail():
    """Test OpenAI moderation guardrail apply_guardrail method (unified guardrail interface)"""
    from litellm.types.utils import GenericGuardrailAPIInputs

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
        )

        # Mock safe moderation response
        mock_response = OpenAIModerationResponse(
            id="modr-123",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=False,
                    categories={
                        "sexual": False,
                        "hate": False,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.001,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.001,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": [],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        with patch.object(guardrail, "async_make_request", return_value=mock_response):
            # Test apply_guardrail with texts (embeddings-style input)
            inputs = GenericGuardrailAPIInputs(
                texts=["Hello, how are you?", "What is the weather?"]
            )

            result = await guardrail.apply_guardrail(
                inputs=inputs,
                request_data={},
                input_type="request",
            )

            # Should return inputs unchanged (moderation doesn't modify, only blocks)
            assert result == inputs


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_harmful_content():
    """Test OpenAI moderation guardrail with harmful content via apply_guardrail"""
    from litellm.types.utils import GenericGuardrailAPIInputs

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
        )

        # Mock harmful moderation response
        mock_response = OpenAIModerationResponse(
            id="modr-123",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=True,
                    categories={
                        "sexual": False,
                        "hate": True,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.95,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.001,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": ["text"],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        with patch.object(guardrail, "async_make_request", return_value=mock_response):
            # Test apply_guardrail with harmful content using structured_messages
            inputs = GenericGuardrailAPIInputs(
                structured_messages=[
                    {"role": "user", "content": "This is hateful content"}
                ]
            )

            # Should raise HTTPException
            from fastapi import HTTPException

            with pytest.raises(HTTPException) as exc_info:
                await guardrail.apply_guardrail(
                    inputs=inputs,
                    request_data={
                        "messages": [
                            {"role": "user", "content": "This is hateful content"}
                        ]
                    },
                    input_type="request",
                )

            assert exc_info.value.status_code == 400
            assert "Violated OpenAI moderation policy" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_streaming_safe_content():
    """Test OpenAI moderation guardrail with streaming safe content via UnifiedLLMGuardrails"""
    from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (
        UnifiedLLMGuardrails,
    )

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
            event_hook="post_call",
        )
        unified_guardrail = UnifiedLLMGuardrails()

        # Mock safe moderation response
        mock_response = OpenAIModerationResponse(
            id="modr-123",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=False,
                    categories={
                        "sexual": False,
                        "hate": False,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.001,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.001,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": [],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        # Mock streaming chunks
        async def mock_stream():
            # Simulate streaming chunks with safe content
            chunk1 = MagicMock()
            chunk1.model = "gpt-4"
            chunk1.choices = [MagicMock()]
            chunk1.choices[0].delta = MagicMock()
            chunk1.choices[0].delta.content = "Hello "
            chunk1.choices[0].finish_reason = None
            chunk1.choices[0].index = 0

            chunk2 = MagicMock()
            chunk2.model = "gpt-4"
            chunk2.choices = [MagicMock()]
            chunk2.choices[0].delta = MagicMock()
            chunk2.choices[0].delta.content = "world"
            chunk2.choices[0].finish_reason = None
            chunk2.choices[0].index = 0

            # Last chunk with finish_reason
            chunk3 = MagicMock()
            chunk3.model = "gpt-4"
            chunk3.choices = [MagicMock()]
            chunk3.choices[0].delta = MagicMock()
            chunk3.choices[0].delta.content = "!"
            chunk3.choices[0].finish_reason = "stop"
            chunk3.choices[0].index = 0

            for chunk in [chunk1, chunk2, chunk3]:
                yield chunk

        # Mock for stream_chunk_builder
        mock_model_response = MagicMock()
        mock_model_response.choices = [MagicMock()]
        mock_model_response.choices[0].message = MagicMock()
        mock_model_response.choices[0].message.content = "Hello world!"

        with (
            patch.object(guardrail, "async_make_request", return_value=mock_response),
            patch(
                "litellm.llms.openai.chat.guardrail_translation.handler.stream_chunk_builder",
                return_value=mock_model_response,
            ),
        ):
            user_api_key_dict = UserAPIKeyAuth(
                api_key="test", request_route="/chat/completions"
            )
            request_data = {
                "messages": [{"role": "user", "content": "Hello, how are you today?"}],
                "guardrail_to_apply": guardrail,
                "metadata": {"guardrails": ["test-openai-moderation"]},
            }

            # Test streaming hook with safe content via UnifiedLLMGuardrails
            result_chunks = []
            async for (
                chunk
            ) in unified_guardrail.async_post_call_streaming_iterator_hook(
                user_api_key_dict=user_api_key_dict,
                response=mock_stream(),
                request_data=request_data,
            ):
                result_chunks.append(chunk)

            # Should return all chunks without blocking
            assert len(result_chunks) == 3


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_streaming_harmful_content():
    """Test OpenAI moderation guardrail with streaming harmful content via UnifiedLLMGuardrails"""
    from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (
        UnifiedLLMGuardrails,
    )

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
            event_hook="post_call",
        )
        unified_guardrail = UnifiedLLMGuardrails()

        # Mock harmful moderation response
        mock_response = OpenAIModerationResponse(
            id="modr-123",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=True,
                    categories={
                        "sexual": False,
                        "hate": True,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.95,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.001,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": ["text"],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        # Mock streaming chunks with harmful content
        async def mock_stream():
            # First chunk - no finish_reason
            chunk1 = MagicMock()
            chunk1.model = "gpt-4"
            chunk1.choices = [MagicMock()]
            chunk1.choices[0].delta = MagicMock()
            chunk1.choices[0].delta.content = "This is "
            chunk1.choices[0].finish_reason = None
            chunk1.choices[0].index = 0

            # Last chunk - with finish_reason to signal end of stream
            chunk2 = MagicMock()
            chunk2.model = "gpt-4"
            chunk2.choices = [MagicMock()]
            chunk2.choices[0].delta = MagicMock()
            chunk2.choices[0].delta.content = "harmful content"
            chunk2.choices[0].finish_reason = "stop"
            chunk2.choices[0].index = 0

            for chunk in [chunk1, chunk2]:
                yield chunk

        # Mock for stream_chunk_builder - use real litellm types so isinstance checks pass
        from litellm.types.utils import ModelResponse
        import litellm

        mock_model_response = ModelResponse(
            id="mock-response",
            model="gpt-4",
            choices=[
                litellm.Choices(
                    index=0,
                    message=litellm.Message(
                        role="assistant",
                        content="This is harmful content",
                    ),
                    finish_reason="stop",
                )
            ],
        )

        with (
            patch.object(guardrail, "async_make_request", return_value=mock_response),
            patch(
                "litellm.llms.openai.chat.guardrail_translation.handler.stream_chunk_builder",
                return_value=mock_model_response,
            ),
        ):
            user_api_key_dict = UserAPIKeyAuth(
                api_key="test", request_route="/chat/completions"
            )
            request_data = {
                "messages": [{"role": "user", "content": "Generate harmful content"}],
                "guardrail_to_apply": guardrail,
                "metadata": {"guardrails": ["test-openai-moderation"]},
            }

            # Chunks have already been flushed by end-of-stream moderation, so
            # the block surfaces as the in-stream error frame, not a raise.
            import json as _json

            result_chunks = []
            async for chunk in unified_guardrail.async_post_call_streaming_iterator_hook(
                user_api_key_dict=user_api_key_dict,
                response=mock_stream(),
                request_data=request_data,
            ):
                result_chunks.append(chunk)

            frame = result_chunks[-1]
            assert isinstance(frame, bytes)
            text = frame.decode()
            assert text.startswith("data: ")
            assert "Violated OpenAI moderation policy" in text
            payload = _json.loads(text[len("data: ") :])
            assert payload["error"]["code"] == "400"


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_logs_full_response_safe_content():
    """Test that safe content logs the full moderation response (categories, scores)
    in StandardLoggingGuardrailInformation, not just 'allow'."""
    from litellm.types.utils import GenericGuardrailAPIInputs

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
        )

        mock_response = OpenAIModerationResponse(
            id="modr-123",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=False,
                    categories={
                        "sexual": False,
                        "hate": False,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.002,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.003,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": [],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        with patch.object(guardrail, "async_make_request", return_value=mock_response):
            inputs = GenericGuardrailAPIInputs(
                structured_messages=[{"role": "user", "content": "Hello, how are you?"}]
            )
            request_data = {"metadata": {}}

            await guardrail.apply_guardrail(
                inputs=inputs,
                request_data=request_data,
                input_type="request",
            )

            guardrail_info_list = request_data["metadata"][
                "standard_logging_guardrail_information"
            ]
            assert len(guardrail_info_list) == 1

            info = guardrail_info_list[0]
            assert info["guardrail_name"] == "test-openai-moderation"
            assert info["guardrail_status"] == "success"

            # Full moderation response, NOT "allow"
            guardrail_resp = info["guardrail_response"]
            assert isinstance(guardrail_resp, dict)
            assert guardrail_resp["results"][0]["flagged"] is False
            assert "category_scores" in guardrail_resp["results"][0]

            # Internal key cleaned up (.pop())
            assert "_openai_moderation_response" not in request_data["metadata"]


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_logs_full_response_harmful_content():
    """Test that harmful content logs guardrail_intervened status with the full
    moderation response, not just the exception string."""
    from litellm.types.utils import GenericGuardrailAPIInputs

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
        )

        mock_response = OpenAIModerationResponse(
            id="modr-456",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=True,
                    categories={
                        "sexual": False,
                        "hate": True,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.95,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.001,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": ["text"],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        with patch.object(guardrail, "async_make_request", return_value=mock_response):
            inputs = GenericGuardrailAPIInputs(
                structured_messages=[{"role": "user", "content": "Hateful content"}]
            )
            request_data = {"metadata": {}}

            from fastapi import HTTPException

            with pytest.raises(HTTPException):
                await guardrail.apply_guardrail(
                    inputs=inputs,
                    request_data=request_data,
                    input_type="request",
                )

            guardrail_info_list = request_data["metadata"][
                "standard_logging_guardrail_information"
            ]
            info = guardrail_info_list[0]
            assert info["guardrail_status"] == "guardrail_intervened"

            # Full moderation response, NOT stringified exception
            guardrail_resp = info["guardrail_response"]
            assert isinstance(guardrail_resp, dict)
            assert guardrail_resp["results"][0]["flagged"] is True
            assert guardrail_resp["results"][0]["category_scores"]["hate"] == 0.95

            # Internal key cleaned up by _process_error (.pop())
            assert "_openai_moderation_response" not in request_data["metadata"]


@pytest.mark.asyncio
async def test_openai_moderation_post_call_request_data_passthrough():
    """Test that post-call guardrail info flows through to the real request_data
    via the unified guardrail dispatcher (Bug 1 fix)."""
    from unittest.mock import AsyncMock

    from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (
        UnifiedLLMGuardrails,
    )
    from litellm.types.utils import ModelResponse

    import litellm

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
            event_hook="post_call",
        )
        unified_guardrail = UnifiedLLMGuardrails()

        mock_mod_response = OpenAIModerationResponse(
            id="modr-789",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=False,
                    categories={
                        "sexual": False,
                        "hate": False,
                        "harassment": False,
                        "self-harm": False,
                        "violence": False,
                    },
                    category_scores={
                        "sexual": 0.001,
                        "hate": 0.002,
                        "harassment": 0.001,
                        "self-harm": 0.001,
                        "violence": 0.001,
                    },
                    category_applied_input_types={
                        "sexual": [],
                        "hate": [],
                        "harassment": [],
                        "self-harm": [],
                        "violence": [],
                    },
                )
            ],
        )

        llm_response = ModelResponse(
            id="chatcmpl-test",
            model="gpt-4",
            choices=[
                litellm.Choices(
                    index=0,
                    message=litellm.Message(role="assistant", content="Hello world"),
                    finish_reason="stop",
                )
            ],
        )

        request_data = {
            "messages": [{"role": "user", "content": "Hello"}],
            "guardrail_to_apply": guardrail,
            "metadata": {"guardrails": ["test-openai-moderation"]},
        }

        mock_make_request = AsyncMock(return_value=mock_mod_response)
        with patch.object(guardrail, "async_make_request", mock_make_request):
            await unified_guardrail.async_post_call_success_hook(
                data=request_data,
                user_api_key_dict=UserAPIKeyAuth(
                    api_key="test", request_route="/chat/completions"
                ),
                response=llm_response,
            )

        mock_make_request.assert_called_once()

        # Guardrail info in the REAL request_data (not a throwaway). The unified hook
        # seeds litellm_metadata, so read the bucket the resolver names rather than
        # assuming "metadata"; the spend log reads it the same way.
        from litellm.litellm_core_utils.core_helpers import (
            get_metadata_variable_name_from_kwargs,
        )

        bucket = request_data[get_metadata_variable_name_from_kwargs(request_data)]
        guardrail_info_list = bucket.get("standard_logging_guardrail_information")
        assert guardrail_info_list is not None
        assert isinstance(guardrail_info_list[0]["guardrail_response"], dict)
        assert "results" in guardrail_info_list[0]["guardrail_response"]


def test_openai_moderation_process_response_metadata_none_edge_case():
    """
    Test that _process_response anchors the metadata dict back into
    request_data when metadata is None, so pop() doesn't operate on a
    temporary and the moderation response is correctly logged.
    """
    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
            event_hook="post_call",
        )

        mod_dict = {"id": "modr-test", "model": "omni-moderation-latest", "results": []}

        # Simulate apply_guardrail having stashed the response but metadata
        # was None initially — apply_guardrail anchors it, so metadata is a
        # real dict with the stashed key by the time _process_response runs.
        request_data = {"metadata": {"_openai_moderation_response": mod_dict}}

        guardrail._process_response(
            response={"inputs": {}},
            request_data=request_data,
        )

        # Full moderation dict should be logged, not "allow"
        info_list = request_data["metadata"].get(
            "standard_logging_guardrail_information"
        )
        assert info_list is not None
        assert info_list[0]["guardrail_response"] == mod_dict

        # Internal key should have been cleaned up by pop()
        assert "_openai_moderation_response" not in request_data["metadata"]


def test_openai_moderation_process_error_metadata_none_edge_case():
    """
    Test that _process_error anchors the metadata dict back into
    request_data when metadata starts as None (or {}), so pop() doesn't
    operate on a temporary.
    """
    from fastapi import HTTPException

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test-openai-moderation",
            event_hook="post_call",
        )

        mod_dict = {
            "id": "modr-test",
            "model": "omni-moderation-latest",
            "results": [{"flagged": True, "categories": {"hate": True}}],
        }

        # metadata is None — exercises the or {} anchor
        request_data: dict = {"metadata": None}

        # Simulate stashing the response then calling _process_error
        # (normally apply_guardrail stashes, then the decorator calls
        # _process_error on HTTPException)
        # First anchor metadata like apply_guardrail does:
        metadata = request_data.get("metadata") or {}
        request_data["metadata"] = metadata
        metadata["_openai_moderation_response"] = mod_dict

        exc = HTTPException(status_code=400, detail="Violated policy")
        with pytest.raises(HTTPException):
            guardrail._process_error(
                e=exc,
                request_data=request_data,
            )

        # Full moderation dict should be logged, not the exception
        info_list = request_data["metadata"].get(
            "standard_logging_guardrail_information"
        )
        assert info_list is not None
        assert info_list[0]["guardrail_response"] == mod_dict
        assert info_list[0]["guardrail_status"] == "guardrail_intervened"

        # Internal key cleaned up
        assert "_openai_moderation_response" not in request_data["metadata"]


@pytest.mark.asyncio
async def test_openai_moderation_logs_violation_categories_harmful_content():
    """Flagged content surfaces only the violated category names in
    StandardLoggingGuardrailInformation.violation_categories, so OTEL can index
    a short ``guardrail_violation_categories`` attribute instead of the full
    response blob (LIT-3801)."""
    from fastapi import HTTPException

    from litellm.types.utils import GenericGuardrailAPIInputs

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(guardrail_name="test-openai-moderation")

        mock_response = OpenAIModerationResponse(
            id="modr-violations",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=True,
                    categories={
                        "sexual": False,
                        "hate": False,
                        "self-harm": True,
                        "self-harm/intent": True,
                        "violence": True,
                    },
                    category_scores={
                        "sexual": 0.0001,
                        "hate": 0.0001,
                        "self-harm": 0.97,
                        "self-harm/intent": 0.98,
                        "violence": 0.35,
                    },
                    category_applied_input_types={},
                )
            ],
        )

        with patch.object(guardrail, "async_make_request", return_value=mock_response):
            request_data = {"metadata": {}}
            with pytest.raises(HTTPException):
                await guardrail.apply_guardrail(
                    inputs=GenericGuardrailAPIInputs(
                        structured_messages=[{"role": "user", "content": "harmful"}]
                    ),
                    request_data=request_data,
                    input_type="request",
                )

        info = request_data["metadata"]["standard_logging_guardrail_information"][0]

        # Only the flagged categories, never the unflagged ones or the scores
        assert info["violation_categories"] == [
            "self-harm",
            "self-harm/intent",
            "violence",
        ]


@pytest.mark.asyncio
async def test_openai_moderation_no_violation_categories_safe_content():
    """Safe content carries no violation_categories key, so the short attribute
    is absent rather than empty on allowed requests (LIT-3801)."""
    from litellm.types.utils import GenericGuardrailAPIInputs

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(guardrail_name="test-openai-moderation")

        mock_response = OpenAIModerationResponse(
            id="modr-safe",
            model="omni-moderation-latest",
            results=[
                OpenAIModerationResult(
                    flagged=False,
                    categories={"hate": False, "violence": False},
                    category_scores={"hate": 0.001, "violence": 0.002},
                    category_applied_input_types={},
                )
            ],
        )

        with patch.object(guardrail, "async_make_request", return_value=mock_response):
            request_data = {"metadata": {}}
            await guardrail.apply_guardrail(
                inputs=GenericGuardrailAPIInputs(
                    structured_messages=[{"role": "user", "content": "hi"}]
                ),
                request_data=request_data,
                input_type="request",
            )

        info = request_data["metadata"]["standard_logging_guardrail_information"][0]
        assert "violation_categories" not in info


def test_openai_moderation_build_tracing_detail_non_dict_responses():
    """Non-dict guardrail responses (the "allow" sentinel, a raw Exception) yield
    no tracing detail so logging never crashes when no moderation call ran."""
    assert OpenAIModerationGuardrail._build_tracing_detail("allow") is None
    assert OpenAIModerationGuardrail._build_tracing_detail(ValueError("boom")) is None


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_streaming_defaults():
    """Defaults match the unified dispatcher: sampled in-stream, every 5th chunk."""
    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(guardrail_name="test")
        assert guardrail.streaming_end_of_stream_only is False
        assert guardrail.streaming_sampling_rate == 5


@pytest.mark.asyncio
async def test_openai_moderation_guardrail_streaming_overrides():
    """Constructor-level overrides for the two streaming flags are stored on self."""
    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail = OpenAIModerationGuardrail(
            guardrail_name="test",
            streaming_end_of_stream_only=False,
            streaming_sampling_rate=3,
        )
        assert guardrail.streaming_end_of_stream_only is False
        assert guardrail.streaming_sampling_rate == 3


@pytest.mark.asyncio
async def test_openai_moderation_initialize_guardrail_forwards_streaming_flags():
    """initialize_guardrail forwards streaming knobs from litellm_params (extra='allow')."""
    import litellm
    from litellm.proxy.guardrails.guardrail_hooks.openai import (
        initialize_guardrail as openai_initialize_guardrail,
    )
    from litellm.types.guardrails import (
        Guardrail,
        LitellmParams,
        SupportedGuardrailIntegrations,
    )

    litellm.logging_callback_manager._reset_all_callbacks()
    try:
        with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
            litellm_params = LitellmParams(
                guardrail=SupportedGuardrailIntegrations.OPENAI_MODERATION,
                api_key="test-key",
                model="omni-moderation-latest",
                mode="post_call",
                streaming_end_of_stream_only=False,
                streaming_sampling_rate=2,
            )
            guardrail = openai_initialize_guardrail(
                litellm_params=litellm_params,
                guardrail=Guardrail(
                    guardrail_name="test-openai-moderation",
                    litellm_params=litellm_params,
                ),
            )

            assert guardrail.streaming_end_of_stream_only is False
            assert guardrail.streaming_sampling_rate == 2
    finally:
        litellm.logging_callback_manager._reset_all_callbacks()


@pytest.mark.asyncio
@pytest.mark.parametrize(("input_type", "stage"), [("request", "pre_call"), ("response", "post_call")])
async def test_openai_moderation_records_moderation_id_as_scan_metadata(input_type: str, stage: str):
    """Each moderation call's id is exposed with the guardrail name, stage and provider that produced it."""
    payload: Final = {
        "id": f"modr-{stage}",
        "model": "omni-moderation-latest",
        "results": [{"flagged": False, "categories": {}, "category_scores": {}, "category_applied_input_types": {}}],
    }
    http_client: Final = AsyncHTTPHandler()
    http_client.client = httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload)))

    with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
        guardrail: Final = OpenAIModerationGuardrail(guardrail_name="openai-mod")
    guardrail.async_handler = http_client
    request_data: Final[dict[str, object]] = {"metadata": {}}

    await guardrail.apply_guardrail(inputs={"texts": ["hello"]}, request_data=request_data, input_type=input_type)

    headers: Final = get_logging_caching_headers(request_data)
    assert headers is not None
    assert headers["x-litellm-guardrail-scan-id"] == f"modr-{stage}"
    assert json.loads(headers["x-litellm-guardrail-scan-metadata"]) == [
        {"guardrail": "openai-mod", "stage": stage, "provider": "openai_moderation", "scan_id": f"modr-{stage}"}
    ]


@pytest.mark.asyncio
async def test_openai_moderation_responses_api_input_field():
    from litellm.types.utils import GenericGuardrailAPIInputs

    flagged_moderation: Final = {
        "id": "modr-123",
        "model": "omni-moderation-latest",
        "results": [
            {
                "flagged": True,
                "categories": {"violence": True, "hate": False},
                "category_scores": {"violence": 0.95, "hate": 0.1},
                "category_applied_input_types": None,
            }
        ],
    }
    http_client: Final = AsyncHTTPHandler()
    http_client.client = httpx.AsyncClient(
        transport=httpx.MockTransport(lambda _: httpx.Response(200, json=flagged_moderation))
    )

    openai_mod: Final = OpenAIModerationGuardrail(
        guardrail_name="openai-moderation-test",
        api_key="fake-key-for-testing",
        model="omni-moderation-latest",
    )
    openai_mod.async_handler = http_client

    with pytest.raises(Exception, match="Violated OpenAI moderation policy") as texts_error:
        await openai_mod.apply_guardrail(
            inputs=GenericGuardrailAPIInputs(texts=["I want to hurt people"]),
            request_data={"model": "gpt-4o", "input": "I want to hurt people"},
            input_type="request",
        )
    assert "Violated OpenAI moderation policy" in str(texts_error.value)

    with pytest.raises(Exception, match="Violated OpenAI moderation policy") as responses_error:
        await openai_mod.apply_guardrail(
            inputs=GenericGuardrailAPIInputs(
                structured_messages=[{"role": "user", "content": "I want to hurt people"}]
            ),
            request_data={
                "model": "gpt-4o",
                "input": [{"role": "user", "content": "I want to hurt people"}],
            },
            input_type="request",
        )
    assert "Violated OpenAI moderation policy" in str(responses_error.value)

    with pytest.raises(Exception, match="Violated OpenAI moderation policy") as chat_error:
        await openai_mod.apply_guardrail(
            inputs=GenericGuardrailAPIInputs(
                structured_messages=[{"role": "user", "content": "I want to hurt people"}]
            ),
            request_data={
                "model": "gpt-4o",
                "messages": [{"role": "user", "content": "I want to hurt people"}],
            },
            input_type="request",
        )
    assert "Violated OpenAI moderation policy" in str(chat_error.value)


class _ModerationsEndpointThatRecordsTheAuthorization:
    authorization: str | None = None

    def __call__(self, request: httpx.Request) -> httpx.Response:
        self.authorization = request.headers.get("Authorization")
        return httpx.Response(
            200,
            json={
                "id": "modr-federated",
                "model": "omni-moderation-latest",
                "results": [
                    {"flagged": False, "categories": {}, "category_scores": {}, "category_applied_input_types": {}}
                ],
            },
        )


@pytest.mark.asyncio
@respx.mock
async def test_openai_moderation_sends_the_federated_bearer_when_only_workload_identity_is_set(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    token_file: Final = tmp_path / "subject_token.jwt"
    token_file.write_text("subject-token")
    for name in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE"):
        monkeypatch.delenv(name, raising=False)
    for attribute in ("api_key", "openai_key", "api_base"):
        monkeypatch.setattr(litellm, attribute, None)
    monkeypatch.setenv("OPENAI_IDENTITY_PROVIDER_ID", "idp_guardrail")
    monkeypatch.setenv("OPENAI_SERVICE_ACCOUNT_ID", "user-guardrail")
    monkeypatch.setenv("OPENAI_IDENTITY_TOKEN_FILE", str(token_file))
    _workload_identity_auth.cache_clear()
    respx.post("https://auth.openai.com/oauth/token").mock(
        return_value=httpx.Response(200, json={"access_token": "guardrail-bearer", "expires_in": 3600})
    )
    endpoint: Final = _ModerationsEndpointThatRecordsTheAuthorization()
    http_client: Final = AsyncHTTPHandler()
    http_client.client = httpx.AsyncClient(transport=httpx.MockTransport(endpoint))

    guardrail: Final = OpenAIModerationGuardrail(guardrail_name="openai-mod")
    guardrail.async_handler = http_client
    response: Final = await guardrail.async_make_request("hello")

    assert response.id == "modr-federated"
    assert endpoint.authorization == "Bearer guardrail-bearer"


@pytest.mark.asyncio
@respx.mock
async def test_openai_moderation_federates_with_the_identity_in_its_own_guardrail_config(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    token_file: Final = tmp_path / "subject_token.jwt"
    token_file.write_text("subject-token")
    for name in (
        "OPENAI_API_KEY",
        "OPENAI_BASE_URL",
        "OPENAI_API_BASE",
        "OPENAI_IDENTITY_PROVIDER_ID",
        "OPENAI_SERVICE_ACCOUNT_ID",
        "OPENAI_IDENTITY_TOKEN_FILE",
    ):
        monkeypatch.delenv(name, raising=False)
    for attribute in ("api_key", "openai_key", "api_base"):
        monkeypatch.setattr(litellm, attribute, None)
    monkeypatch.setenv("GUARDRAIL_IDENTITY_PROVIDER_ID", "idp_guardrail_config")
    _workload_identity_auth.cache_clear()
    exchange: Final = respx.post("https://auth.openai.com/oauth/token").mock(
        return_value=httpx.Response(200, json={"access_token": "guardrail-config-bearer", "expires_in": 3600})
    )
    endpoint: Final = _ModerationsEndpointThatRecordsTheAuthorization()
    http_client: Final = AsyncHTTPHandler()
    http_client.client = httpx.AsyncClient(transport=httpx.MockTransport(endpoint))

    guardrail_config: Final = LitellmParams(
        guardrail=SupportedGuardrailIntegrations.OPENAI_MODERATION,
        mode="pre_call",
        openai_identity_provider_id="os.environ/GUARDRAIL_IDENTITY_PROVIDER_ID",
        openai_service_account_id="user-guardrail-config",
        openai_identity_token_file=str(token_file),
    )
    monkeypatch.setattr(litellm, "callbacks", [])
    guardrail: Final = initialize_openai_moderation_guardrail(
        litellm_params=guardrail_config,
        guardrail=Guardrail(guardrail_name="openai-mod", litellm_params=guardrail_config),
    )
    guardrail.async_handler = http_client
    await guardrail.async_make_request("hello")

    exchange_body: Final = json.loads(exchange.calls.last.request.content)
    assert exchange_body["identity_provider_id"] == "idp_guardrail_config"
    assert exchange_body["service_account_id"] == "user-guardrail-config"
    assert endpoint.authorization == "Bearer guardrail-config-bearer"


@pytest.fixture
def no_ambient_openai_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
    for name in (
        "OPENAI_API_KEY",
        "OPENAI_BASE_URL",
        "OPENAI_API_BASE",
        "OPENAI_IDENTITY_PROVIDER_ID",
        "OPENAI_SERVICE_ACCOUNT_ID",
        "OPENAI_IDENTITY_TOKEN_FILE",
    ):
        monkeypatch.delenv(name, raising=False)
    for attribute in ("api_key", "openai_key", "api_base"):
        monkeypatch.setattr(litellm, attribute, None)
    monkeypatch.setattr(litellm, "callbacks", [])


PARTIAL_IDENTITY_MODERATION: Final = {
    "guardrail": SupportedGuardrailIntegrations.OPENAI_MODERATION.value,
    "mode": "pre_call",
    "openai_identity_provider_id": "idp_without_the_rest",
}


@pytest.mark.usefixtures("no_ambient_openai_credentials")
def test_openai_moderation_with_a_partial_identity_is_a_configuration_error_naming_the_gap() -> None:
    with pytest.raises(ValueError, match="openai_service_account_id, openai_identity_token_file"):
        InMemoryGuardrailHandler().initialize_guardrail(
            guardrail={"guardrail_name": "partial-identity-mod", "litellm_params": PARTIAL_IDENTITY_MODERATION},
            source="db",
        )


@pytest.mark.usefixtures("no_ambient_openai_credentials")
def test_proxy_boot_skips_an_openai_moderation_with_a_partial_identity() -> None:
    IN_MEMORY_GUARDRAIL_HANDLER.IN_MEMORY_GUARDRAILS.clear()
    IN_MEMORY_GUARDRAIL_HANDLER.guardrail_id_to_custom_guardrail.clear()

    init_guardrails_v2(
        all_guardrails=[
            {"guardrail_name": "partial-identity-mod", "litellm_params": PARTIAL_IDENTITY_MODERATION},
            {
                "guardrail_name": "keyed-mod",
                "litellm_params": {
                    "guardrail": SupportedGuardrailIntegrations.OPENAI_MODERATION.value,
                    "mode": "pre_call",
                    "api_key": "sk-moderation",
                },
            },
        ]
    )

    booted: Final = IN_MEMORY_GUARDRAIL_HANDLER.IN_MEMORY_GUARDRAILS.values()
    assert {guardrail["guardrail_name"] for guardrail in booted} == {"keyed-mod"}