Edit

Share via


Work with Azure OpenAI content filtering in a .NET app

This article demonstrates how to handle content filtering concerns in a .NET app. Azure OpenAI Service includes a content filtering system that works alongside core models. This system works by running both the prompt and completion through an ensemble of classification models aimed at detecting and preventing the output of harmful content. The content filtering system detects and takes action on specific categories of potentially harmful content in both input prompts and output completions. Variations in API configurations and application design might affect completions and thus filtering behavior.

The Content Filtering documentation provides a deeper exploration of content filtering concepts and concerns. This article provides examples of how to work with content filtering features programmatically in a .NET app.

Prerequisites

Configure and test the content filter

To use the sample code in this article, you need to create and assign a content filter to your OpenAI model.

  1. Create and assign a content filter to your provisioned model.

  2. Add the Azure.AI.OpenAI NuGet package to your project.

    dotnet add package Azure.AI.OpenAI
    

    Or, in .NET 10+:

    dotnet package add Azure.AI.OpenAI
    
  3. Create a simple chat completion flow in your .NET app using the AzureOpenAiClient. Replace the YOUR_MODEL_ENDPOINT and YOUR_MODEL_DEPLOYMENT_NAME values with your own.

    using Azure.AI.OpenAI;
    using Azure.Identity;
    using Microsoft.Extensions.AI;
    
    IChatClient client =
        new AzureOpenAIClient(
            new Uri("YOUR_MODEL_ENDPOINT"),
            new DefaultAzureCredential()).GetChatClient("YOUR_MODEL_DEPLOYMENT_NAME").AsIChatClient();
    
    try
    {
        ChatResponse completion = await client.GetResponseAsync("YOUR_PROMPT");
    
        Console.WriteLine(completion.Messages.Single());
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
    
  4. Replace the YOUR_PROMPT placeholder with your own message and run the app to experiment with content filtering results. If you enter a prompt the AI considers unsafe, Azure OpenAI returns a 400 Bad Request code. The app prints a message in the console similar to the following:

The response was filtered due to the prompt triggering Azure OpenAI's content management policy...