


Creating a Chatbot with JavaScript and Gemini AI: creating the backend
Jan 04, 2025 am 09:26 AMSave! 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:
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.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In JavaScript, choosing a single-line comment (//) or a multi-line comment (//) depends on the purpose and project requirements of the comment: 1. Use single-line comments for quick and inline interpretation; 2. Use multi-line comments for detailed documentation; 3. Maintain the consistency of the comment style; 4. Avoid over-annotation; 5. Ensure that the comments are updated synchronously with the code. Choosing the right annotation style can help improve the readability and maintainability of your code.

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf
