


Creating a Chatbot with JavaScript and Gemini AI: creating the backend
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:
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

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

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

Undress AI Tool
Undress images for free

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











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.
