Add Generative AI to a JavaScript Web App

Learn how to integrate genAI with minimal code changes using JS, Cognito credentials to invoke the Amazon Bedrock API in a React single page app.

Elizabeth Fuentes
Amazon Employee
Published Feb 20, 2024
Last Modified May 9, 2024
This article was written in colaboration Enrique Rodriguez

šŸšØšŸšØšŸšØšŸšØšŸšØ This blog is outdated, check the new version Add Generative AI to a JavaScript Web App 2.0 šŸšØšŸšØšŸšØšŸšØšŸšØšŸšØ

Integrating generative AI into existing applications presents challenges. Many developers have limited experience in training foundations models, but the aim is to integrate generative AI capabilities with minimal code changes.
To solve this, we created an application that integrates the power of generative AI with a call to the Amazon Bedrock API from a web application such SPA built with JavaScript and react framework. With no middleware, lowering the barrier for incorporating AI generation through minimal code integration.
In this blog you will learn how to use Amazon Cognito credentials and IAM Roles to invoke Amazon Bedrock API in a react-based application with JavaScript and the CloudScape design system. You will deploy all the resources and host the app using AWS Amplify.
Authentication
Authentication

How Does This Application Work?

In the repository of this application, you will find the code ready to deploy the backend and frontend.
āœ… Backend: An Amazon Cognito User Pool and Identity Pool, with an AWs Identity and Access Managemen Role (IAM Role) that contains the policy with the permissions to invoke Amazon Bedrock.
Check "Integrating Amazon Cognito authentication and authorization with web and mobile apps" guide and can invoke API operations for users authentication and authorization.
This permissions can be customized here: IAM Role Code
āœ… Frontend: a reactjs single page application (SPA) and CloudScape design system.
This application comprises 2 demos:
  • Chat with Amazon Bedrock
  • Knowledge Bases for Amazon Bedrock
    Ā 
Demos menu
Demos Menu
All demos have in common the use of the BedrockRuntimeClient or BedrockAgentRuntimeClient to invoke the Bedrock or BedrockAgent service for a conversational interaction. The BedrockAgentClient is also used to list current Bedrock KnowledgeBases deployed in the same account.
Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs) along with a broad set of capabilities that you need to build generative AI applications.

An instance of a Large Language Model

To use a LLM in your application (for instance anthropic.claude-instant-v1) you create instance of Bedrock Class from Langchain. You need to specify the region, streaming responses, and API credentials from the user pool authentication. For model arguments, you specify the model to sample up to 1000 tokens and for more creative and freedom of generation use a temperature of 1.
Code --> llmLib.js
We'll walk you through each demo group to highlight their differences.

First: Chat With Amazon Bedrock

Chat Q&A
Chat Q&A
Here you will talk directly with the Large Language Model (LLM) implemented by the Bedrock API through a chain, in two different ways:
- Chat Q&A: Send prompt input request and the model answer with a generated output.
Chat Q&A
Chat Q&A
Ā - Chat with Memory: Send prompt input request along with the with previous messages (if they exist) and the model responds with a generated output. This implementation uses local memory.
Chat with Memory
Chat with Memory
This chat is built with a ConversationChain with Buffer Memory to store and get past dialogs. There are other types of memory, learn more in Working With Your Live Data Using LangChain.
To set up this demo, it is necessary to instantiate the Bedrock library for Lagnchain, ConservationChain to manage the conversation and BufferMemory to invoke memory usage.
Why humanPrefix: "H"?
Anthropic Claude has been trained to understand the prompt in terms of Human: and Assistant: indicators. For memory you use "H:" to identify the human part (instead of Human:) to prevent model confusion on where the last Human instrucition starts.
The chain will look at chat_history key in the memory to get past dialogs, hence you use that key as memoryKey in BufferMemory.

Second: Knowledge Bases for Amazon Bedrock

In this demo, you will ask questions to the Knowledge Bases for Amazon Bedrock taking advantage of retrieval augmented generation (RAG). You must have at least one knowledge base created, do it by following Create a knowledge base guide.
Questions to the Knowledge Bases for Amazon Bedrock will be asked in two ways:
Knowledge Bases for Amazon Bedrock
Knowledge Bases for Amazon Bedrock
- Amazon Bedrock Retrieve => LLM:
Amazon Bedrock Retrieve => LLM
Amazon Bedrock Retrieve => LLM
List the knowledge bases with ListKnowledgeBasesCommandas follows:
The AmazonKnowledgeBaseRetriever Langchain class creates a retriever, an object capable to retrieve documents similar to a query from a knowledge base (in this case is a Knowledge Base from Bedrock)
The ConversationalRetrievalQAChain is instantiated with the retriever and the memory. It takes care of the memory, query the retriever and formulate the answer (with the documents) using the llm instance.
- Amazon Bedrock Retrieve & Generate:
Here you will use a complete AWS Managed RAG service. There is no need for extra packages (Langchain) or increased complexity with prompts. You will use only one API Call to BedrockAgentRuntimeClient. Also the memory is managed by the service by using a sessionId.
Amazon Bedrock Retrieve & Generate
Amazon Bedrock Retrieve & Generate
Bedrock is initialized with BedrockAgentRuntimeClient and with RetrieveAndGenerateCommand queries a knowledge base and a foundation model generates responses based on the retrieved results. In this demo Langchain is no needed.

Let's Deploy React Generative AI Application With Amazon Bedrock and AWS Javascript SDK

Step 1 - Enable AWS Amplify Hosting:

The application is built with AWS Amplify. To deploy it in your account:
  1. first fork this repo:
  1. Create a New branch: dev-branch.
  2. In Step 1 Add repository branch, select main branch and Connecting a monorepo? Pick a folder and enter reactjs-gen-ai-apps as a root directory.
    Add repository branch
    Add repository branch
  3. For the next Step, Build settings, select building-a-gen-ai-gen-ai-personal-assistant-reactjs-apps(this app) as App name, in Enviroment select Create a new envitoment and write dev.
App build and test settings
App build and test settings
  1. If there is no existing role, create a new one to service Amplify.
  2. Deploy your app.

Step 2 - Access to the App URL:

Once the application has been deployed, go to the link in the application, which is located under the white box.
Amplify Deploy
Amplify Deploy
When you enter the link, the Sing In window will appear, so you must create a Amazon Cognito User Pool User.
Sing In Window
Sing In Window

āœ… How To Create A User

In the App go to Backend environments and click on Authentication.
Backend environments
Backend environments
Then, under Authentication, click View in Cognito:
View in Cognito
View in Cognito
In the User Pool, click the name of your user pool and Create User.
Create your user and then sing in.
Note: You can create the user directly from the application by changing False hideSignUp: false in App.jsx, but this can introduce a security flaw by giving anyone access to it.

Let's Try React Generative AI Application With Amazon Bedrock Javascript SDK

Before you can use a foundation model in Amazon Bedrock, you must request access to it. Follow the step in Add model access guide.
Go to the application link and sign in with the user you created.

šŸ¤–šŸš€ Try and test the app!

āœ… Chat with Amazon Bedrock:
āœ… Ask follow-up questions, and test the model's multi-language capabilities
āœ… Query the knowledge base using the LLM to deliver the best answer
āœ… Finally consult the knowledge database directly without an intermediary

Conclusion

In this blog, you created a React web application that can directly access the Amazon Bedrock API using Amazon Cognito for authentication. Integrating generative AI services like Bedrock into a React interface securely can be achieved by leveraging AWS managed services like Cognito and AWS IAM.
With this, you can incorporate powerful Amazon Bedrock generative AI capabilities into new and existing React applications. This allows developers to focus on creating engaging conversation and RAG experiences with managed knowledge service, without the need of backend code. It also show the power of the streaming responses, that improves user experience and wait times with conversational AI.

šŸš€ Some links for you to continue learning and building:

Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.

1 Comment