Home >Web Front-end >JS Tutorial >Creating a Chatbot with JavaScript and Gemini AI: creating the backend

Creating a Chatbot with JavaScript and Gemini AI: creating the backend

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 09:26:35865browse

Save! o

Continuing the creation of our chatbot with Javascript and Gemini AI, we will add the "backend" of the project. Last time we created the frontend, with HTML, CSS and Javascript, where we guaranteed that the user interface will reflect a conversation between the user and the chatbot.

Now we need to create a server, configuring a route with express.js to communicate with the Gemini API. Let's go!

Installing project dependencies

Well, we're going to need express.js, the Google Gemini SDK and to protect our API key I'm going to install dotenv to work with environment variables.

npm install @google/generative-ai express dotenv

Now we are ready to create our server adopting best practices such as using local environment variables to protect private data.

To do this, we will create a file in the project root folder called server.js. In this file we will start by importing the dependencies and configuring the necessary resources.

const express = require("express");
require("dotenv").config();
const { GoogleGenerativeAI } = require("@google/generative-ai");

const app = express();
const port = 3000;

const genAI = new GoogleGenerativeAI(process.env.GOOGLE_GEMINI_API_KEY);

app.use(express.static("public"));

app.use(express.json());

This code configures express to serve static files from the "public" folder and accepts requests with JSON payload. That's why we put the index.html, styles.css and script.js files in this folder. We also configured the application to run on port 3000.

We use the @google/generative-ai library to integrate the Gemini API, authenticating it with a key stored in an environment variable called GOOGLE_GEMINI_API_KEY.

But where do we get this API Key? That's what we're going to find out now.

Gemini API Key

Obtaining the key

To get a Gemini API key, I recommend that you are logged into an "@gmail.com" account. After that, access this link and you will see a screen like this:

Criando um Chatbot com JavaScript e Gemini AI: criando o backend

Click the "Create API key" button, indicate a project in which you will use this key and you're done. Your key will appear below and you will be able to view it and even copy it to take the next step.

Protecting your API key

Now in your project, create a file with the name .env.local or just .env in the root folder of your project. In this file put your API key as follows:

GOOGLE_GEMINI_API_KEY="sua-chave-vai-aqui"

Now save your file and that's it. If you did the previous step correctly, your API key will be working.

PS: pay attention to the plan that appears in your API key. Gemini offers a free plan with a limited amount of tokens that your key can return. If you want a greater amount of tokens, consider subscribing to a paid plan. We will use the free plan, which, although limited, will allow us to exchange some messages with the chatbot.

Creating the /chat route

Now with the dependencies configured and the API key in hand, let's open the doors of possibilities of what we can do with artificial intelligence.

In the server.js file we will create the /chat route:

npm install @google/generative-ai express dotenv

Our route is of the POST type, as you will receive a message in the body, precisely the message from the user who will interact with the chat. So, with this message we use a little defensive programming (it doesn't hurt anyone to be careful lol) and check that we don't have a message. If we don't, an error is returned as a response and a message is thrown.

If we have the message, then we will send it as a prompt for the model we choose, as follows:

const express = require("express");
require("dotenv").config();
const { GoogleGenerativeAI } = require("@google/generative-ai");

const app = express();
const port = 3000;

const genAI = new GoogleGenerativeAI(process.env.GOOGLE_GEMINI_API_KEY);

app.use(express.static("public"));

app.use(express.json());

As this communication is an asynchronous process, we will use try/catch to handle the response. First I define the Gemini model that will be used (you can check a list of models at this link). In this case I opted for gemini-1.5-flash.

The second step is to start the chat. So with model.startChat() I can start communication with Gemini, configuring the maximum number of tokens I want in the response (in this case 100 tokens per response).

Now we wait for this response after sending the message to the model with chat.sendMessage(message). When we have the response, we will return it to the person who made the request, converting the text format returned by the model to JSON.

And last but not least, if we have an error we can use it within catch to throw this error in the console, and also returning a status 500, making life easier for the client who is consuming this "mini api". Beauty?

Now we just need to indicate where our "mini api" will run with the code snippet below:

GOOGLE_GEMINI_API_KEY="sua-chave-vai-aqui"

Our api will run on the port we specified at the beginning. The complete server.js code is shown below:

app.post("/chat", async (req, res) => {
  const { message } = req.body;

  if (!message) {
    return res.status(400).json({ error: "Mensagem não pode estar vazia." });
  }

  //...
});

Testing the chatbot

Now the most awaited moment has arrived, to test our chatbot. To do this, let's open a terminal and type the following command:

try {
    const model = genAI.getGenerativeModel({
      model: "gemini-1.5-flash",
    });

    const chat = model.startChat({
      history: [],
      generationConfig: { maxOutputTokens: 100 },
    });

    const result = await chat.sendMessage(message);
    res.json({ response: result.response.text() });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Erro ao processar mensagem." });
  }

You should receive the following message in the terminal after running this command:

app.listen(port, () => {
  console.log(`Servidor rodando em http://localhost:${port}`);
});

Now by accessing the url http://localhost:3000 and writing a message in the input and pressing the send button, the AI ​​responds to your message and it is shown on the screen.

Criando um Chatbot com JavaScript e Gemini AI: criando o backend

Very cool, right?

Conclusion

With this we finish creating a chatbot using JavaScript and the Google Gemini API. We saw how to create the frontend from scratch, apply styles, manipulate the DOM. We created a server with express.js, used the Gemini API, configured a POST route to communicate with the application client and were able to talk to the AI ​​through our own interface, developed by ourselves.


But that's not all you can do. We can customize and configure this chatbot for different tasks, from being a language assistant, to a virtual teacher who answers your questions about mathematics or programming, it will depend on your creativity.

Turning an AI into a personalized assistant involves training the model, more about the way you want it to respond and behave than about the code itself.

We'll explore some of this in a future article.

See you then!

The above is the detailed content of Creating a Chatbot with JavaScript and Gemini AI: creating the backend. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn