Skip to main content
Intelligent Chatbots Gemini With JavaScript

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 API
  • mainModule.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.

Leave a Reply

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