Implementing a Chat Feature in a Monaca App Using the Google Gemini API

Juan Serrano Soria
The Web Tub
Published in
4 min readMay 20, 2024

Introduction

With the growing trend of AI and machine learning, various services are being introduced by different companies. Particularly, since the release of ChatGPT, there has been much discussion on how to leverage large language models (LLMs) in businesses and applications.

This article will demonstrate how to implement a chat feature in a Monaca app using the Gemini API (formerly Bard), one of the LLMs released by Google.

Getting a Gemini API Key

1. Visit the Gemini website at https://ai.google.dev/.

2. Log in with your Google account. It’s recommended to use a Gmail account rather than a corporate account.

3. You can easily generate an API key. When generating the key, you’ll need to create or link a Google Cloud Project.

4. Obtain the API key at https://aistudio.google.com/app/u/1/apikey.

Creating a Monaca App

1. Use Monaca’s Framework7 template, which includes a chat UI component. You can find the component documentation at https://framework7.io/docs/messages.

2. Install the necessary library to use the Gemini API.

npm install @google/generative-ai

3. Initialize the Gemini API in src/js/gemini.js. Replace YOUR_GEMINI_API_KEY with the API key you obtained earlier:

import { GoogleGenerativeAI } from "@google/generative-ai";
const API_KEY = "YOUR_GEMINI_API_KEY";
const genAI = new GoogleGenerativeAI(API_KEY);
window.geminiModel = genAI.getGenerativeModel({ model: "gemini-pro"});

4. Set up routing to load the chat page at the “/chat/” path. Inside the <template> tag in src/app.f7, add:

<div id="app">
<!-- Your main view, should have "view-main" class -->
<div class="view view-main view-init safe-areas" data-url="/chat/">
</div>
</div>

In src/js/routes.js, add:

import HomePage from '../pages/home.f7';
import ChatPage from '../pages/chat.f7';
import NotFoundPage from '../pages/404.f7';

var routes = [
{
path: '/',
component: HomePage,
},
{
path: '/chat/',
component: ChatPage,
},
// Default route (404 page). MUST BE THE LAST
{
path: '(.*)',
component: NotFoundPage,
},
];

export default routes;

5. Create the chat screen by adding the following code to src/pages/chat.f7:

<template>
<div class="page">
<div class="navbar">
<div class="navbar-bg"></div>
<div class="navbar-inner sliding">
<div class="title">Gemini Chat</div>
</div>
</div>
<div class="toolbar messagebar">
<div class="toolbar-inner">
<div class="messagebar-area">
<textarea class="resizable" placeholder="Message" id="message"></textarea>
</div>
<a class="link send-link" href="#" @click=${send}>Send</a>
</div>
</div>
<div class="page-content">
<div class="page-content messages-content">
<div class="messages">
${ messages.map(message => $h`
<div class="message message-${message.role === 'user' ? 'sent' : 'received'}">
<div class="message-content">
<!-- Speech bubble with text -->
<div class="message-bubble">
<div class="message-text">${message.message}</div>
</div>
</div>
</div>
`)}
</div>
</div>
</div>
</div>
</template>
<script>
export default function (props, {$f7, $on, $update, $onMounted }) {
// JavaScript code goes here
return $render;
}
</script>

6. Initialize variables to manage chat messages and the Gemini chat object:

// Define variables used in the screen
// Message history
const messages = [];
// Gemini chat object
let chat;

7. Create the Gemini chat object when the screen loads:

// Create the chat object
$onMounted(() => {
chat = geminiModel.startChat({
history: [],
generationConfig: {
maxOutputTokens: 100,
},
});
});

8. Implement message sending functionality, which sends a request to the Gemini API and updates the messages array with the response:

// Function to send messages
const send = async (e) => {
// Compose the input message
const message = document.querySelector("#message");
const text = message.value;
if (text === "") return;
messages.push({
role: "user",
message: text,
});
$update(); // Update the view
// Get the response from Gemini
const response = await answer(text);
messages.push({
role: "system",
message: response,
});
message.value = "";
$update(); // Update the view
};

9. Create a function to send requests to the Gemini API and receive responses using the chat object:

// Function to send messages and receive responses from Gemini
// https://ai.google.dev/tutorials/web_quickstart?hl=en
const answer = async (text) => {
const result = await chat.sendMessage(text);
const response = await result.response;
return response.text();
};

Here’s an example of a chat conversation. Note that Gemini can understand the context of “it” or “that” and perform unit conversions based on previous interactions.

Managing Chat History

Gemini, like ChatGPT, can reference past conversations when generating responses if the chat history is sent along with the request. When using the chat object, the chat history is automatically stored in the chat.history property.

If you need to add past conversations from an external source, such as when reloading the page, you can add the past messages to chat.history.

Conclusion

This article demonstrated how to implement a chat feature in a Monaca app using the Gemini API. The Gemini API is easy to use in Monaca apps, thanks to the available libraries. Consider leveraging AI in your apps to help solve user problems.

You can see the full app in this repo.

For more information, visit: https://ai.google.dev/

--

--