September 13, 2024 No Comments

Introduction

In the ever-evolving landscape of cloud computing, automating routine tasks and integrating intelligent agents into applications can significantly enhance productivity and efficiency. Amazon Bedrock, a fully managed service for building, training, and deploying machine learning models, offers powerful capabilities to create and deploy intelligent agents. One such application is leveraging a Bedrock Agent, enriched with a comprehensive knowledge base, and integrating it into an AWS Lambda function.

This blog will guide you through the process of creating a Bedrock Agent, equipping it with a robust knowledge base, and seamlessly invoking it within a Lambda function. By the end of this tutorial, you’ll have a deeper understanding of how to utilize Amazon Bedrock to build intelligent agents and deploy them in serverless environments, unlocking new possibilities for automation and intelligent task management in your AWS infrastructure.

Whether you’re a developer looking to enhance your applications with AI capabilities or an IT professional aiming to streamline operations, this step-by-step guide will provide you with the insights and practical knowledge needed to get started with Bedrock Agents and AWS Lambda. Let’s dive in and explore how to create, configure, and deploy a Bedrock Agent with a knowledge base, and invoke it within a Lambda function for a smarter, more efficient cloud ecosystem.

Prerequisites

  • AWS Account
  • IAM User Access or root user access
  • S3 bucket for storing the Knowledge-base data source

Step 1: Create a bedrock Agent

  • Navigate to the AWS Bedrock service.
  • From the AWS services menu, select Bedrock Service and expand the menu on the welcome page.
  • Click on “Agents” under Builder Tools to access the Create Agent page.
  • Click “Create Agent”, complete the pop-up form, and then click “Create” to proceed to the Edit Agent page.
  • Choose the model that aligns with your use case and provide an introduction for the agent.
  • Click “Save & Exit” to be redirected to the Show Agent Details page, where you can view the Agent ID, ARN, and other agent details.
  • To create aliases, scroll to the bottom of the page and click “Create” in the Aliases section.
  • Complete the form and click “Create Alias”, then copy the Alias ID.

Step 2: Create a knowledge base

  • From the left navigation pane, select “Knowledge Base” to be redirected to the Create Knowledge Base page.
  • In the Knowledge Bases section, select “Create Knowledge Base”. Ensure you are logged in with an IAM user instead of the root user, and that the user has permissions for S3, Lambda, and Bedrock.
  • On the Provide Knowledge Base Details page, set up the following configurations:
    • In the Knowledge Base Details section, change the default name and provide a description for your knowledge base.
    • In the IAM Permissions section, choose an AWS Identity and Access Management (IAM) role that grants Amazon Bedrock permission to access other AWS services. You can either let Amazon Bedrock create the service role or select the option to create and use a new service role.
    • (Optional) Add tags to your knowledge base.
  • Select “Next”.
  • On the Set Up Data Source page, provide the information for the data source you will use for the knowledge base:
    • (Optional) Change the default data source name.
    • Select “Current Account” or “Other Account” for the data source location.
    • Provide the S3 URI of the object containing the files for the data source that you prepared. If you select another account, you may need to update the other account’s Amazon S3 bucket policy, AWS KMS key policy, and the current account’s Knowledge Base role.
  • Select “Next”.
  • On the Review and Create page, check the configuration and details of your knowledge base. Choose “Edit” in any section that needs modification. When you are satisfied, select “Create Knowledge Base”.
  • The time it takes to create the knowledge base depends on the amount of data you provide. When the knowledge base creation is complete, the status changes to “Ready”.
  • Go to the Knowledge Bases section to view your newly created knowledge base in the list.
  • Click on the knowledge base name, go to the Data Source section, and select “Sync” to synchronize your data source.

Step 3: Integrate Bedrock agent with Knowledge Base

  • From the left panel, go to the Agent section and select the agent you created. Click “Edit” in the Agent Builder.
  • Next, go to the Knowledge Bases section and click the “Add” button.
  • Select the knowledge base you want to integrate and write the instructions on how the knowledge base will work. Click the “Next” button.
  • Click the “Prepare” button and test some questions in the Test Agent panel to ensure the integration is working correctly.

Step 4: Create Lambda Function and Invoke bedrock agent

  • Navigate to the Lambda service from the AWS services menu and click “Create Function”.
  • Provide a name for your function and select the runtime, such as Python 3.12 or another Python version.
  • Click “Create Function” to be redirected to the code editor for the Lambda function.
  • In the code editor, write the following code:
				
					import json
import boto3
import re

AWS_ACCESS_KEY = <Your_Access_Key>
AWS_SECRET_KEY = <Your_Secret_Key>
REGION_NAME = <bedrock_agent_region>
def bedrock_call(userPrompt):
    print(userPrompt)
    bedrock = boto3.client(service_name='bedrock-agent-runtime', region_name=REGION_NAME, aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY)

    try:
        # Invoking the bedrock agent
        response = bedrock.invoke_agent(
            agentAliasId=<Your AliasID>,
            agentId=<Your AgentID>,
            enableTrace=True,
            endSession=False,
            inputText=userPrompt,
            sessionId=<SessionID>
        )
        print("Response of agent request:", response)
        event_stream = response['completion']
        final_answer = None

        # Parse the event stream to get the final answer
        try:
            for event in event_stream:
                if 'chunk' in event:
                    data = event['chunk']['bytes']
                    print(f"data==>{data}")
                    try:
                        final_answer = data.decode('utf8')
                    except:
                        final_answer = data.decode()
                    final_answer = final_answer.replace('\n','\\n')
                    final_answer = final_answer.replace('\t','\\t')
                
                    if final_answer and final_answer.strip():
                        # Print the result verbatim
                        print("Final Answer",final_answer)
                        response = final_answer
                    else:
                        response = "The result does not contain any information."
                        print("Error: The result does not contain any information.")
                        
                elif 'trace' in event:
                    print(event['trace'])
                    json.dumps(event['trace'], indent=2)
                else:
                    raise Exception("unexpected event.", event)
        except Exception as e:
            print(e)
            raise Exception("unexpected event.", e)
        return response
    except Exception as e:
        print("unexpected event.", e)
        return "Internal Server Error."
    
def lambda_handler(event, context):
    try:
        body = event.get('body', '{}')
        body_json = json.loads(body)
        userPrompt =  body_json.get('inputText', None)
    except:
        return {
            'statusCode': 400,
            'body': json.dumps({'error': 'Invalid JSON'})
        }
    response = bedrock_call(userPrompt)
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps(response)
    }

				
			

Step 5: Create the Function URL and testing

  • Navigate to the created Lambda function, click on “Configuration”, and go to the “Function URL” tab.
  • Click on the “Create Function URL” button, select “None” for authentication type, and click “Save”.
  • Copy the generated Function URL.
  • Go to the “General Configuration” tab to increase the request timeout.
  • Click on the “Edit” button, set the timeout from 1 minute to 15 minutes, and click “Save”.
  • We can use cURL or Postman request for testing.

1. Using cURL request

				
					curl --location 'URL' \
--header 'Content-Type: application/json' \
--data '{
    			"inputText": "Tell Me about pragnakalp."
}'

				
			

2. Using Postman request

  • Open Postman and create a new request.
    • Select the POST method and paste the Function URL in the URL section.
    • Go to the “Body” section, select “raw”, and choose “JSON” format.
				
					{
    “inputText”: “input_value”
}

				
			
  • Click “Send” to test the Lambda function and invoke the Bedrock agent.
  • Ensure to replace “input_value” and URL with the input and function URL your Bedrock agent requires.

Conclusion

Integrating AWS Bedrock with a knowledge base and invoking it through a Lambda function provides a robust solution for automating and enhancing various tasks. By following the steps outlined in this blog post, you have learned how to create a Bedrock agent, set up a knowledge base, integrate the agent with the knowledge base, and use a Lambda function to invoke the agent. These steps ensure that your agent can efficiently process and respond to queries using the rich data stored in your knowledge base.

Testing the setup with Postman further validates that the integration works seamlessly, allowing you to leverage the full potential of AWS services. This setup not only enhances the capabilities of your applications but also optimizes your workflow by utilizing powerful AWS tools.

Write a comment

Your email address will not be published. Required fields are marked *

Want to talk to an Expert Developer?

Our experts in Generative AI, Python Programming, and Chatbot Development can help you build innovative solutions and scale your business faster.