Intelligent Chatbots: How To Integrate AI Gemini With JavaScript
source link: https://www.js-tutorials.com/javascript-tutorial/intelligent-chatbots-how-to-integrate-ai-gemini-with-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Intelligent Chatbots: How To Integrate AI Gemini With JavaScript
In this tutorial, we will explore how to integrate Google Gemini AI with JavaScript to create intelligent chatbots. The Gemini is Google’s latest family of large language models.
The fastest way to start using Gemini is with Google AI Studio, a web-based tool that lets you prototype and run prompts right in your browser.
Google Gemini AI
Google Gemini AI represents the latest family of large language models developed by Google’s DeepMind. It excels in tasks such as language generation, understanding, and overall natural language processing.
Create Chatbot Using Google Gemini
Let’s go through the integration process to use Google Gemini AI to build a chatbot.
Prerequisites:
Make sure you meet the following prerequisites before beginning the integration process:
- Basic Knowledge of JavaScript: Familiarity with JavaScript fundamentals is essential for implementing and understanding the integration.
- Gemini API Key: Obtain an API key from Google AI Studio, which will be used to authenticate requests to the Gemini API.
There are the following files participate in this tutorial:
index.html
: Contains the HTML structure for the chatbot user interface.script.js
: This file is responsible for handling user input and making requests to the Gemini APImainModule.js
: Configures the Gemini-pro module and establishes the connection to the Gemini API.
Step 1: Obtain the API Key from Google AI Studio
Let’s create an APIKEY for our project, we follow the following process to obtain Gemini API Key:
- Log in to Google AI Studio.
- Navigate to the API Key section and create a new API key for your project.
- Copy the generated API key, as it will be used in the integration.
Import and Configure the Model in mainModule.js
Create a mainModule.js
file and add the following code to configure the Gemini-pro module and establish the connection to the Gemini API.
// mainModule.js import { GoogleGenerativeAI } from "@google/generative-ai"; const API_KEY = "YOUR_API_KEY"; // Paste your API key here const genAI = new GoogleGenerativeAI(API_KEY); const model = genAI.getGenerativeModel({ model: "gemini-pro" }); // Export the 'model' variable for use in other modules export { model };
Replace “YOUR_API_KEY” with the API key obtained from Google AI Studio.
Create the UI for the Chatbot in index.html
Create or open the index.html
file and update it with the following code to set up the HTML structure for the chatbot UI.
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Gemini with JavaScript</title> <link rel="stylesheet" href="style.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Google Fonts Link For Icons --> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+ Symbols+Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" /> <script type="importmap"> { "imports": { "@google/generative-ai": "https://esm.run/@google/generative-ai" } } </script> </head> <body> <!-- Chats container --> <div class="chat-container"></div> <!-- Typing container --> <div class="typing-container"> <div class="typing-content"> <div class="typing-textarea"> <textarea id="chat-input" spellcheck="false" placeholder="Enter a prompt here" required></textarea> <span id="send-btn" class="material-symbols-rounded">send</span> </div> </div> </div> <!-- Import the mainModule.js file --> <script type="module" src="mainModule.js"></script> <!-- Import the main JavaScript file --> <script type="module" src="script.js" defer></script> </body> </html>
Get a Response from Gemini API in script.js
Create a script.js
file and add the following code to handle user input and make requests to the Gemini API.
// script.js import { model } from "./mainModule.js"; const chatInput = document.querySelector("#chat-input"); const sendButton = document.querySelector("#send-btn"); const chatContainer = document.querySelector(".chat-container"); const getChatResponse = async () => { const userText = chatInput.value.trim(); const pEle = document.createElement("p"); try { const result = await model.generateContent(userText); const response = await result.response.text(); pEle.textContent = response.trim(); } catch (error) { pEle.classList.add("error"); pEle.textContent = "Oops! Something went wrong while retrieving the response. Please try again."; } chatContainer.appendChild(pEle); } chatInput.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && window.innerWidth > 800) { e.preventDefault(); getChatResponse(); } }); const handleAPI = () => { const userText = chatInput.value.trim(); if (!userText) return; chatInput.value = ""; // Clear the input field const html = `<div class="chat-content"> <div class="chat-body-inner"> <img src="images/user.png" alt="user-img"> <p>${userText}</p> </div> </div>`; chatContainer.innerHTML += html; getChatResponse(); } sendButton.addEventListener("click", handleAPI);
Run the Application
Save your changes and open the index.html
file in your favorite web browser. You can see a simple chatbot interface that interacts with the Gemini API to provide responses based on user input.
Conclusion:
It’s an exciting possibility for developers to create intelligent and interactive chatbots. I have created a simple chatbot to get query responses from Gemini API. You can enhance UI as per your needs. There is one possibility to manage the env variable, You can use dotenv package to manage the app env variable.
Recommend
-
142
Gemini's Story I have no secret of success but hard work.
-
163
The Full Treble Project for MI5 Gemini Brought to you by Jflte DevConnection Team #include /* * Your warranty is now void. * * We're not responsible for…
-
61
「流」这个概念在开发中非常常见,在 java 语言里我们熟知InputStream和OutputStream,node 中有WriteStream和ReadStream,cpp 里也有 stre...
-
55
前文 一些「流与管道」的小事 - Gemini’s Story 介绍了一些关于流的概念问题,今天我们来看看一个也许是 Android 程序员非常熟悉的库 —— okio
-
27
How to link the JavaScript Scheduler component to a date picker that can change the visible date.
-
5
TellephantBuild chatbots and integrate with WhatsApp, Google, Facebook
-
2
Files Permalink Latest commit message Commit time
-
4
How Seach Engine Can Integrate AI Chatbots in the Future?Over the past years, Artificial Intelligence (AI) has changed the lives of individuals and businesses, for the better. The boom in the tech in...
-
4
Building Intelligent Chatbots: Enhancing User Experience with Natural Language ProcessingThis blog post summarizes the key points from Priyamvada’s (SE, GeekyAnts) presentation at the All Things AI Mee...
-
4
Install AI Models, LLMs and Integrate Chatbots with Linux Hello, fellow Linux enthusiasts! I’m excited to embark on this journey with you, exploring the fascinating realm of Artificial Intelligence (AI) on our favorite oper...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK