πŸš€ Amazon Bedrock Agents for Efficient Automation 🌟

Welcome to this guide on using Amazon Bedrock Agents to simplify library management! This step-by-step tutorial will show you how to set up and use these agents to automate tasks, enhance library operations, and build a smart knowledge base. Discover how AI can make your library more efficient and effective. Ready to transform your library? Let’s get started!

 Amazon Bedrock Agents

You can find all the magic PDFs and code goodies in my GitHub treasure chest 🎩✨:

GitHub - RISING-CODER777/awsberock_agents

πŸ“œ Synopsis

In this guide, we’ll cover.

  1. 🌟 Prerequisites
  2. πŸ—οΈIntroduction to Amazon Bedrock Agents
  3. πŸ› οΈ Setting Up Your Environment
  4. πŸ“š Building a Knowledge Base
  5. πŸ”§ Creating Action Groups
  6. πŸ§ͺ Testing and Troubleshooting
  7. ❌ Unsubscribing to Avoid Costs
  8. πŸŽ‰ Conclusion

🌟 Prerequisites

Before we dive into the fun, make sure you have the following:

  1. πŸ“Œ An AWS Subscription. If you don’t have an AWS subscription, you can create a free account.
  2. πŸ“Œ Access to Claude v2. and Titan Embeddings G1 — Text v1.2. from Amazon Bedrock.
  3. πŸ“Œ Familiarity with AWS Lambda, S3, and IAM.

πŸ—οΈIntroduction

Amazon Bedrock Agents provides a framework for automating tasks and responding to queries based on library data. Key components include.

  1. Foundation Model: The AI model that processes and interprets user inputs, making sense of queries related to library inventory.
  2. Action Groups: Defined actions performed by AWS Lambda functions and described using OpenAPI schemas. They handle tasks like retrieving book details or updating inventory.
  3. Knowledge Bases: Store library data in vector format for efficient search and retrieval. They help the agent provide accurate and contextual responses.

Store library data

Agent Workflow

Agent Workflow

  1. Contextualize User Input: Validate and process user requests to understand their needs.
  2. Generate Orchestration Prompt: Create a detailed prompt using user input and metadata.
  3. Execute Actions: Based on the prompt, perform tasks such as,
    • Retrieving information
    • Updating records
    • Calling APIs or searching databases
  4. Generate Output: Produce the final response, which may include further actions or queries.

πŸ› οΈ Setting Up Your Environment

Follow these steps to create and configure a Bedrock Agent tailored for library inventory.

Create a Bedrock Agent

  1. In the Amazon Bedrock dashboard, look for Builder tools in the left navigation pane.
    Builder tools
  2. Create Agent: Click on “Create Agent,” give it a name (for example, “Agent-LibraryManagement”), and choose the foundation model as Anthropic — Claude v2.
    Create Agent
    Select Model
  3. Provide Instructions: Add instructions like “You are a helpful agent that manages book catalog inquiries, including book details, stock levels, prices, and availability.”
    Provide Instructions
  4. Click Create Agent.
  5. Let’s set aside action groups and knowledge bases for the time being.

Initial Testing

  1. Your agent may initially respond with “Sorry, I don’t have enough information” as action groups and knowledge bases are not yet configured.
    Initial Testing

πŸ“š Building a Knowledge Base

 Knowledge Base

Setting up a knowledge base is crucial for providing accurate responses. Here’s how to configure it.

Upload Data

Create an S3 Bucket

  1. Go to the S3 section from the Services menu.
  2. Click “Create bucket”.
  3. Enter a unique bucket name (e.g., “librarycatalog-kb”).
  4. Choose your preferred AWS Region and configure other settings as needed.
    AWS Region
  5. Click “Create bucket”.

Upload Files

  1. Go to your newly created bucket in the S3 dashboard.
  2. Click “Upload”.
  3. Drag and drop your CSV and PDF files, or click “Add files” to select them.
  4. Click “Upload” to transfer your files to the S3 bucket.
    Upload

File Details

  1. CSV File: Should contain fields such as Book ID, Title, Author, Genre, ISBN, and Availability.
  2. PDF File: This can include detailed descriptions or additional information about the books.

Create a Knowledge Base

Access Knowledge Base Menu.

  1. In the AWS Console, go to the Amazon Bedrock section.
  2. Navigate to Builder tools and click on “Knowledge Base”.
    Amazon BedrockΒ section

Configure Your Knowledge Base

  1. Name Your Knowledge Base: Enter a name like “knowledge-base-library-catalog”.
    Configure Your Base
  2. Data Source Name: Enter a name for your data source.
    Data Source Name
  3. Browse for S3 URI: Click “Browse” to locate and select the S3 URI for your bucket (e.g., s3://librarycatlog-kb).
    Browse
  4. Choose Embedding Model: Select Titan Embeddings G1 — Text v1.2.
     Embedding Model
  5. Vector Database: Choose Quick Create a vector store — Recommended.
    Vector Database
  6. Click “Create” to set up the knowledge base.

Sync Knowledge Base

AWS will convert the text from your files into vector embeddings for efficient retrieval. This process ensures that your knowledge base is ready for quick and accurate responses.

In the data source, click “Sync” to start the process.

Sync

Verify Vector Store

Check OpenSearch Dashboard

  1. In the AWS Console, navigate to OpenSearch Service.
  2. Go to the Dashboard: Verify that the collections and indexes related to your knowledge base have been created and are functioning correctly.
    OpenSearch Service
    Indexes

Set Up and Test an Agent

Set Up

  1. Navigate to Agent Builder.
  2. Go to Knowledge Bases and click “Add”.
    Add
  3. Select the knowledge base you created (e.g., “knowledge-base-library-catlog”).
  4. Enter the following instruction: “This knowledge base contains a list of books available in the library. Each book has attributes such as BookID, Title, Author, Genre, Publication Year, ISBN, Available Copies, and Price.”
    BookID
  5. Click “Prepare”.

Note. Amazon Bedrock does not allow knowledge-based creation with the root account. Create an IAM user with the right permissions and enable AWS Management Console access for managing knowledge bases and related resources.

Test

  1. After preparing the agent, click “Test”.
  2. Enter queries to ensure the agent retrieves accurate information based on the knowledge base.
    Test
    Show tree

πŸ”§ Creating Action Groups

Action groups allow your agent to perform specific actions. Here’s how to set them up,

Create a Lambda Function

  1. Go to the AWS Lambda section in the AWS Management Console.
  2. Click “Create function”.
  3. Set the Function Name to “LibraryInventoryFunction”.
  4. Choose Python 3.12 as the Runtime.
  5. Select x86_64 for the Architecture.
    Basic information
  6. Click “Create function”.
  7. Navigate to the Code section of your Lambda function.
  8. Copy and paste the following code into the editor:

This Lambda function handles two API paths: /GetBooksInventory and /RestockBook. For /GetBooksInventory, it returns a hardcoded list of book details. For /RestockBook, it provides a success message. The function formats responses into JSON and handles different API paths to return appropriate data.

Save and deploy your Lambda function code.

 Lambda function code

Configure Lambda Function Permissions

  1. Navigate to the Lambda function’s Configurations section.
  2. Select Permissions.
  3. Under Resource-based policy statements, click Add permissions.
  4. In the Edit Policy Statement section
  5. Choose AWS Service: Select Other AWS services.
  6. Statement ID: Enter an identifier, e.g., st-001.
  7. Principal: Enter bedrock.amazonaws.com.
  8. Source ARN: Go to the Bedrock Agent dashboard, copy the Agent ARN, and paste it here.
  9. Action: Select lambda: InvokeFunction.
  10. Click Save to apply the changes.
    Save

Add Action Group to Agent

  1. Navigate to the Action Group in the Agent Details section.
    Agent DetailsΒ section
  2. Click on Add.
  3. Choose the action group type as Defined with API Schemas.
  4. For Action Group Invocation, select Select an existing Lambda function.
  5. In Select Lambda Function, choose LibraryCatlogFunction from the list.
    Select Lambda Function
  6. For Select API Schema, choose Define with inline OpenAPI Schema Editor.
  7. Paste the following schema.
    {
        "openapi": "3.0.0",
        "info": {
            "title": "Library Management System",
            "version": "1.0.0",
            "description": "APIs for managing book inventory in a library"
        },
        "paths": {
            "/GetBooksInventory": {
                "get": {
                    "summary": "Gets books inventory",
                    "description": "Retrieves the list of books and their available copies",
                    "operationId": "getBooksInventory",
                    "parameters": [],
                    "responses": {
                        "200": {
                            "description": "Returns the inventory of all books",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "array",
                                        "items": {
                                            "type": "object",
                                            "properties": {
                                                "bookId": {
                                                    "type": "string",
                                                    "description": "Book ID"
                                                },
                                                "title": {
                                                    "type": "string",
                                                    "description": "Book Title"
                                                },
                                                "availableCopies": {
                                                    "type": "number",
                                                    "description": "Number of available copies"
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/RestockBook": {
                "post": {
                    "summary": "Creates a Book Restock Order",
                    "description": "Creates an order to restock books in the library",
                    "operationId": "restockBook",
                    "requestBody": {
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "required": ["bookId", "quantity"],
                                    "properties": {
                                        "bookId": {
                                            "type": "string",
                                            "description": "Book ID"
                                        },
                                        "quantity": {
                                            "type": "number",
                                            "description": "Quantity to restock"
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Returns the status of the book restock order",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "status": {
                                                "type": "string",
                                                "description": "Status of the book restock order - Success or Failure"
                                            },
                                            "message": {
                                                "type": "string",
                                                "description": "Additional information about the restock operation"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

This schema defines the API paths for managing book inventory. The /GetBooksInventory endpoint retrieves book details, while the /RestockBook endpoint allows placing restock orders.

Click on Add.

πŸ§ͺ Testing and Troubleshooting

Ensure your agent is functioning correctly and troubleshoot any issues.

Test Your Agent

  1. Run Prompts: Test the agent with various prompts to verify its responses.
  2. For example, ask to Get all book inventory.
    Run Prompts
  3. Restock the book with ID B003.
    Restock
  4. Restock 3 copies of the book with ID B001.
    Restock 3 copies

Troubleshoot Errors

  1. Check for accurate information: If errors like “unknown API path” occur, verify the details provided by the agent.
    Troubleshoot Errors
  2. Inspect CloudWatch Logs: Go to CloudWatch, then Log Groups and Log Streams.
    Inspect CloudWatch Logs
  3. Verify API Endpoint Configuration: Find the API path in the relevant log stream and ensure it matches the Lambda function code.
    Verify API Endpoint
  4. In this case, verify that the /GetBooksInventory endpoint is correctly configured.
    Correctly configured

Some additional troubleshooting tips

  1. Check Permissions and Authentication: Verify that proper permissions and authentication are in place.
  2. Validate Request Format: Ensure the request format matches the expected format for the API.
  3. Confirm Knowledge Base Setup: Verify that the knowledge base and API integration are correctly set up.

Create an Alias

  1. Alias Creation: In the agent details page, create an alias for versioning and testing specific versions of your agent.
    Alias Creation
  2. Test Alias: Test the alias just like you would with a working draft to ensure it behaves as expected.

❌ Unsubscribing to Avoid Costs

Avoid Costs

Keep your costs in check by deleting unused resources and regularly reviewing your AWS account. To avoid extra charges, cancel any unneeded subscriptions in Claude v2 via AWS Marketplace.

Conclusion

You did it! πŸ‘ With Amazon Bedrock Agents, you’ve taken library management to the next level. By setting up knowledge bases and action groups, you’re now ready to automate tasks and impress users with smart responses.

Keep experimenting and tweaking to perfect your setup. Dive into the world of Amazon Bedrock Agents and see how much more efficient and fun managing your library can be. Happy building! πŸš€

Completed

If you enjoyed this blog, don’t forget to share it with your friends and colleagues.

Follow me on LinkedIn! Did you enjoy this guide? Feel free to clap and comment below!

Also any comment on anything missing or not right is very welcome. Long live the AWS Learning community πŸ€–!

Attributes and References

  1. Amazon Bedrock Agents: Create and Configure AWS Documentation
  2. Amazon Bedrock Agents: How They Work AWS Documentation
  3. Amazon Bedrock Knowledge Base: Create AWS Documentation
  4. Amazon Bedrock Knowledge Base: How It Works AWS Documentation


Similar Articles