Build Responsible AI with Amazon Bedrock Guardrails and .NET

Introduction

Generative AI creates human-like content that must align with organizational standards and safety guidelines. Amazon Bedrock Guardrails helps organizations implement customized safeguards for their AI applications by filtering harmful content, blocking denied topics, and removing sensitive information.

The ApplyGuardrail API enables content validation without invoking foundation models. This API offers three key benefits.

  1. Evaluate text against your defined rules, including topic avoidance, content filters, and PII detection
  2. Validate data at any point in your application flow, from user input to final output
  3. Assess content without calling foundation models, giving you control over your application's security workflow

In this article, you will learn to implement the Amazon Bedrock ApplyGuardrail API in a .NET console application to validate the content and ensure compliance with responsible AI policies.

Pre-requisites

  1. An AWS account with Amazon Bedrock access permissions.
  2. Visual Studio 2022.
  3. Install and set up the AWS Toolkit for Visual Studio.
  4. Install or update to the latest version of the AWS CLI (version 2.x or later).
  5. Get credentials to grant programmatic access.
  6. Create a guardrail with denied topics.
     Amazon Bedrock

Steps Involved

Create a .NET Console Application in Visual Studio 2022 to implement the ApplyGuardrail API.

  1. Launch Visual Studio 2022.
  2. Select File -> New -> Project.
  3. Choose the Console App template. Click Next.
  4. Enter the project name and click Next.
  5. Select the .NET 8.0 framework and click Create.
  6. Add the following NuGet packages.
    AWSSDK.BedrockRuntime
  7. Replace Program.cs content.
    using Amazon;
    using Amazon.BedrockRuntime;
    using Amazon.BedrockRuntime.Model;
    using System.Text.Json;
    
    namespace BedrockApplyGuardrailAPIDemo
    {
        internal class Program
        {
            static async Task Main(string[] args)
            {
                // Configure AWS credentials and region
                var region = RegionEndpoint.USEast1; // Change this to your preferred region
    
                // Create Bedrock Runtime client
                var bedrockRuntimeClient = new AmazonBedrockRuntimeClient(region);
    
                // Set up the request
                var applyGuardrailRequest = new ApplyGuardrailRequest
                {
                    GuardrailIdentifier = "eecv****vc0a", // Replace with your actual guardrail ID
                    GuardrailVersion = "1", // Replace with your actual guardrail version
                    Source = "INPUT", // or "OUTPUT" depending on your use case
                    Content = new List<GuardrailContentBlock>
                    {
                        new GuardrailContentBlock
                        {
                            Text = new GuardrailTextBlock
                            {
                                Text = "How to harm someone?"
                            }
                        }
                    }
                };
    
                try
                {
                    // Call the ApplyGuardrail API
                    var response = await bedrockRuntimeClient.ApplyGuardrailAsync(applyGuardrailRequest);
    
                    // Print the ApplyGuardrailResponse as JSON
                    Console.WriteLine(JsonSerializer.Serialize(response));
    
                    // Process the response
                    Console.WriteLine($"Action: {response.Action}");
                    Console.WriteLine($"Usage: {JsonSerializer.Serialize(response.Usage)}");
    
                    if (response.Outputs.Count > 0)
                    {
                        Console.WriteLine("Outputs:");
                        foreach (var output in response.Outputs)
                        {
                            Console.WriteLine(output.Text);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No outputs (Guardrails did not intervene)");
                    }
    
                    if (response.Assessments.Count > 0)
                    {
                        Console.WriteLine("Assessments:");
                        foreach (var assessment in response.Assessments)
                        {
                            Console.WriteLine(JsonSerializer.Serialize(assessment));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
    
  8. Run and validate the implementation.
    ApplyGuardrailResponse: 
    
    {
        "Action": {
            "Value": "GUARDRAIL_INTERVENED"
        },
        "Assessments": [
            {
                "ContentPolicy": null,
                "ContextualGroundingPolicy": null,
                "InvocationMetrics": {
                    "GuardrailCoverage": {
                        "Images": null,
                        "TextCharacters": {
                            "Guarded": 20,
                            "Total": 20
                        }
                    },
                    "GuardrailProcessingLatency": 287,
                    "Usage": {
                        "ContentPolicyUnits": 0,
                        "ContextualGroundingPolicyUnits": 0,
                        "SensitiveInformationPolicyFreeUnits": 0,
                        "SensitiveInformationPolicyUnits": 1,
                        "TopicPolicyUnits": 1,
                        "WordPolicyUnits": 1
                    }
                },
                "SensitiveInformationPolicy": null,
                "TopicPolicy": {
                    "Topics": [
                        {
                            "Action": {
                                "Value": "BLOCKED"
                            },
                            "Name": "violence",
                            "Type": {
                                "Value": "DENY"
                            }
                        }
                    ]
                },
                "WordPolicy": null
            }
        ],
        "GuardrailCoverage": {
            "Images": null,
            "TextCharacters": {
                "Guarded": 20,
                "Total": 20
            }
        },
        "Outputs": [
            {
                "Text": "Sorry, the model cannot answer this question."
            }
        ],
        "Usage": {
            "ContentPolicyUnits": 0,
            "ContextualGroundingPolicyUnits": 0,
            "SensitiveInformationPolicyFreeUnits": 0,
            "SensitiveInformationPolicyUnits": 1,
            "TopicPolicyUnits": 1,
            "WordPolicyUnits": 1
        },
        "ResponseMetadata": {
            "RequestId": "bd252f13-b1f6-4a53-87cb-dfe18664fde4",
            "Metadata": {},
            "ChecksumAlgorithm": 0,
            "ChecksumValidationStatus": 0
        },
        "ContentLength": 889,
        "HttpStatusCode": 200
    }
    

Output

Output

Additional Resources

  1. Use the ApplyGuardrail API in your application
  2. Examples of ApplyGuardrail API use cases
  3. AWS SDK for .NET

Conclusion

In this article, you learned how to implement Amazon Bedrock ApplyGuardrail API in a C# .NET console application. This solution helps validate content and ensure responsible AI practices in your applications.

Up Next
    Ebook Download
    View all
    Learn
    View all