Amazon Bedrock Knowledge Base Query in .NET Console App

Introduction

In this article, you'll learn how to query an Amazon Bedrock knowledge base and generate responses using a .NET console application. For demonstration purposes, we'll use an Amazon S3 bucket named wikiworldarchive24072024 as the data source. This bucket contains a collection of documents that we'll query. You can refer to the documentation for detailed instructions on connecting an Amazon S3 bucket to the Amazon Bedrock knowledge base.

Amazon Bedrock

Prerequisites

  1. Create an AWS account and log in. Ensure the IAM user you use has sufficient permissions to make necessary AWS service calls and manage AWS resources.
  2. Download and install the AWS Command Line Interface (CLI).
  3. Configure the AWS CLI.
  4. Download and install Visual Studio or Visual Studio Code.
  5. Download and install .NET 8.0 SDK
  6. Ensure that your IAM user or role has the necessary permissions to create and manage knowledge bases in Amazon Bedrock.

Tools

Visual Studio 2022

Steps Involved

Perform the following steps to create a .NET console application in Visual Studio 2022 to query an Amazon Bedrock knowledge base and generate a response based on the retrieved results. Refer to this documentation for the RetrieveAndGenerate request syntax.

  1. Open Visual Studio 2022.
  2. Click File -> New -> Project.
  3. Select the Console App template. Click Next.
  4. Enter the project name and click Next.
  5. Select the .NET 8.0 framework. Click Create.
  6. Add the following NuGet packages.
    AWSSDK.BedrockAgentRuntime
  7. Open Program. cs and replace the code with the following.
    using Amazon;
    using Amazon.BedrockAgentRuntime;
    using Amazon.BedrockAgentRuntime.Model;
    
    namespace AmazonBedrockQueryKB
    {
        internal class Program
        {
            static async Task Main(string[] args)
            {
                string modelArn = "anthropic.claude-3-sonnet-20240229-v1:0";
                string knowledgeBaseId = "YY5QKQM0HV";
                string queryText = "What are some famous historical sites and landmarks in France?";
    
                var client = new AmazonBedrockAgentRuntimeClient(RegionEndpoint.USEast1);
    
                try
                {
                    var request = new RetrieveAndGenerateRequest
                    {
                        Input = new RetrieveAndGenerateInput
                        {
                            Text = queryText,
                        },
                        RetrieveAndGenerateConfiguration = new RetrieveAndGenerateConfiguration
                        {
                            KnowledgeBaseConfiguration = new KnowledgeBaseRetrieveAndGenerateConfiguration
                            {
                                KnowledgeBaseId = knowledgeBaseId,
                                ModelArn = modelArn
                            },
                            Type = RetrieveAndGenerateType.KNOWLEDGE_BASE
                        }
                    };
    
                    var response = await client.RetrieveAndGenerateAsync(request);
    
                    if (response.Citations.Count > 0 && response.Citations[0].RetrievedReferences.Count > 0)
                    {
                        var context = response.Citations[0].RetrievedReferences[0].Content.Text;
                        var docUrl = response.Citations[0].RetrievedReferences[0].Location.S3Location.Uri;
    
                        Console.WriteLine($"Context used: {context}");
                        Console.WriteLine($"Source Document: {docUrl}");
                    }
                    else
                    {
                        Console.WriteLine("No Context available.");
                    }
                }
                catch (AmazonBedrockAgentRuntimeException ex)
                {
                    // Handle specific exceptions related to AWS SDK
                    Console.WriteLine($"AWS Error: {ex.Message}");
                }
                catch (Exception ex)
                {
                    // Handle other potential exceptions
                    Console.WriteLine($"General Error: {ex.Message}");
                }
            }
        }
    }
    
  8. Press F5 to run the application. You will receive a response if the query in the code pertains to Germany, as the relevant document is available in the Amazon S3 bucket. If you query about countries not covered in the documents stored in the Amazon S3 bucket, the response will indicate "No Context available."

Summary

This article describes how to create a .NET console application to query an Amazon Bedrock knowledge base and generate the response based on the retrieved results in Visual Studio 2022.


Similar Articles