Groundedness detection through Content Safety is not working

Gebru, J (Jonathan) 0 Reputation points
2025-09-20T13:15:29.5566667+00:00

Hi,

Content safety's groundedness detection is not working, when I run my code I receive the following output constantly

{

"ungroundedDetected": false,

"ungroundedPercentage": 0,

"ungroundedDetails": []

}

Also when running an example within AI foundry (the ungrounded example) I see that it doesn't catch the ungroundednes (See attached picture)

User's image

This is Azure's own example.

Azure AI Content Safety
Azure AI Content Safety
An Azure service that enables users to identify content that is potentially offensive, risky, or otherwise undesirable. Previously known as Azure Content Moderator.
{count} votes

1 answer

Sort by: Most helpful
  1. Manas Mohanty 13,340 Reputation points Moderator
    2025-10-31T15:58:35.8933333+00:00

    Hi Gebru, J (Jonathan)

    Have got below working code for groundedness detection from product group.

    and Issue has been addressed in Portal UI too.

    Tested East Us2 and Germany West Central

    #
    # Copyright (c) Microsoft. All rights reserved.
    # To learn more, please visit the documentation - Quickstart: Azure Content Safety: https://aka.ms/acsstudiodoc
    #
    
    import enum
    import requests
    import os
    
    
    class TaskType(enum.Enum):
        SUMMARIZATION = "SUMMARIZATION"
        QNA = "QNA"
    
    
    class DomainType(enum.Enum):
        MEDICAL = "MEDICAL"
        GENERIC = "GENERIC"
    
    
    class ResourceType(enum.Enum):
        AZUREOPENAI = "AzureOpenAI"
    
    
    class LLMResource:
        def __init__(self, openai_endpoint, openai_deployment_name):
            self.llm_resource={
                "resourceType": ResourceType.AZUREOPENAI.value,
                "azureOpenAIEndpoint": openai_endpoint,
                "azureOpenAIDeploymentName": openai_deployment_name
            }
    
    def detect_groundness_body(
        domain: DomainType,
        task_type: TaskType,
        content_text: str,
        grounding_sources: list,
        query: str,
        reasoning: bool,
        llm_resource: LLMResource
    ) -> dict:
        """
        Builds the request body for the Content Safety API request.
    
        Args:
        - task_type (TaskType): The type of task to be analyzed.
        - content_text (str): The content to analyze.
        - groundingSources (list): The grounding sources to be analyzed.
        - query (str): The query to be analyzed.
        - reasoning (ReasoningType): Specifies whether to use the reasoning feature.
        - llm_resource (llmResource):GPT resources to provide an explanation.
    
        Returns:
        - dict: The request body for the Content Safety API request.
        """
        body = {
            "domain": domain.value,
            "task": task_type.value,
            "text": content_text,
            "groundingSources": grounding_sources,
            "Reasoning": reasoning
        }
        # For task type "QnA", the query value needs to be re-added.
        if task_type == TaskType.QNA:
            body["qna"] = {"query": query}
        # For reasoning true, the body needs add llmResource.
        if reasoning == True:
            body["llmResource"] = llm_resource.llm_resource
        return body
    
    
    def detect_groundness_result(
        data: dict,
        url: str,
        subscription_key: str
    ):
        """
        Retrieve the Content Safety API request result.
    
        Args:
        - data (dict): The body data sent in the request.
        - url (str): The URL address of the request being sent.
        - subscription_key (str): The subscription key value corresponding to the request being sent.
    
        Returns:
        - response: The request result of the Content Safety API.
        """
        headers = {
            "Content-Type": "application/json",
            "Ocp-Apim-Subscription-Key": subscription_key
        }
    
        # Send the API request
        response = requests.post(url, headers=headers, json=data)
        return response
    
    
    if __name__ == "__main__":
        # Replace with your own subscription_key and endpoint
        subscription_key = "<Key>"
        endpoint = "https://<aifoundryname>.services.ai.azure.com/"
    
        if not subscription_key or not endpoint:
            raise ValueError("Environment variables AACS_SUBSCRIPTION_KEY and AACS_ENDPOINT must be set.")
    
        api_version = "2024-09-15-preview"
    
        # Set according to the actual task category.
        domain = DomainType.GENERIC
        task_type = TaskType.QNA
    
        grounding_sources = [
            "The HR policy states that bank tellers earn between $14 and $16 per hour.",
            "Last month, her paycheck indicated $15/hour."
        ]
        query = "How much does she currently get paid per hour at the bank?"
    
    
        # Set reasoning type[True or False].
        reasoning = False
        # GPT resources to provide an explanation
        openai_endpoint = "https://tesgpt5nano.cognitiveservices.azure.com/"
        deployment_name = "gpt-4o"
        llm_resource_instance = LLMResource(openai_endpoint=openai_endpoint, openai_deployment_name=deployment_name)
    
        content_text_to_test = [
            "She earns $15 per hour at the bank.",
            "She earns $20 per hour at the bank.",
            "She earns $160 per hour at the bank.",
            "Water boils at 100 degrees."
        ]
    
        for content_text in content_text_to_test:
            print(f"\nTesting content: {content_text}")
            # Build the request body
            data = detect_groundness_body(domain=domain, task_type=task_type, content_text=content_text,
                                        grounding_sources=grounding_sources, query=query, reasoning=reasoning, llm_resource=llm_resource_instance)
    
            # Set up the API request
            url = f"{endpoint}/contentsafety/text:detectGroundedness?api-version={api_version}"
    
            # Send the API request
            response = detect_groundness_result(data=data, url=url, subscription_key=subscription_key)
    
            # Handle the API response
            if response.status_code == 200:
                result = response.json()
                print("Groundedness result:", result)
            else:
                print("Error:", response.status_code, response.text)
    #
    # Copyright (c) Microsoft. All rights reserved.
    # To learn more, please visit the documentation - Quickstart: Azure Content Safety: https://aka.ms/acsstudiodoc
    
    
    

    Thank you for your inputs

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.