How can I help you?
Integrate Gemini AI with JavaScript Inline AI Assist control
24 Mar 202611 minutes to read
The Inline AI Assist control integrates with Google’s Gemini API to deliver intelligent conversational interfaces. It leverages advanced natural language understanding to interpret user input, maintain context throughout interactions, and provide accurate, relevant responses. By configuring secure authentication and data handling, developers can unlock powerful AI-driven communication features that elevate user engagement and streamline support experiences.
Prerequisites
Before starting, ensure you have the following:
-
Node.js: Version 16 or higher with npm.
-
Google Account: For generating a Gemini API key.
-
Marked Library: For parsing Markdown responses (
npm install marked --save).
Set Up the Environment
Follow the Getting Started guide to configure and render the Inline AI Assist control in your application.
Install Dependencies
Install the required packages:
- Google Generative AI SDK:
npm install @google/generative-ai- Marked Library:
npm install marked --saveGenerate API Key
-
Access Google AI Studio: Instructs users to sign into Google AI Studio with a Google account or create a new account if needed.
-
Navigate to API Key Creation: Go to the
Get API Keyoption in the left-hand menu or top-right corner of the dashboard. Click theCreate API Keybutton. -
Project Selection: Choose an existing Google Cloud project or create a new one.
-
API Key Generation: After project selection, the API key is generated. Users are instructed to copy and store the key securely, as it is shown only once.
Security Note: Advises against committing the API key to version control and recommends using environment variables or a secret manager in production.
Configure Gemini AI with Inline AI Assist
Modify the index.js file to integrate the Gemini API with the Inline AI Assist control.
- Add your Gemini API key securely in the configuration:
var geminiApiKey = 'Place your API key here';// Initialize Gemini API
var geminiApiKey = ''; // Replace with your real Gemini API key
var stopStreaming = false;
// Initializes the Inline AI Assist control
var inlineAIAssist = new ej.interactivechat.InlineAIAssist({
promptRequest: onPromptRequest,
inlineToolbarSettings: {
itemClick: function (args) {
if (args.item.iconCss === 'e-icons e-inline-stop') {
handleStopResponse();
}
}
},
relateTo: '#summarizeBtn',
responseSettings: {
itemSelect: function (args) {
if (args.command.label === 'Accept') {
var editable = document.getElementById('editableText');
if (editable) {
editable.innerHTML = '<p>' + inlineAIAssist.prompts[inlineAIAssist.prompts.length - 1].response + '</p>';
}
inlineAIAssist.hidePopup();
}
else if (args.command.label === 'Discard') {
inlineAIAssist.hidePopup();
}
}
}
});
// Stream AI response in chunks
async function streamResponse(response) {
var lastResponse = "";
var responseUpdateRate = 10;
var i = 0;
var responseLength = response.length;
while (i < responseLength && !stopStreaming) {
lastResponse += response[i];
i++;
if (i % responseUpdateRate === 0 || i === responseLength) {
var htmlResponse = marked.parse(lastResponse);
inlineAIAssist.addResponse(htmlResponse, i === responseLength);
}
await new Promise(resolve => setTimeout(resolve, 15));
}
}
// Handle user prompt: call Gemini model
function onPromptRequest(args) {
var model = 'gemini-2.5-flash'; // Select the Gemini model (update model name as needed)
var url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${geminiApiKey}`;
var requestBody = {
contents: [{ parts: [{ text: args.prompt }]}]
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
var fullResponse = data.candidates[0].content.parts[0].text;
stopStreaming = false;
streamResponse(fullResponse);
})
.catch(function(error) {
inlineAIAssist.addResponse(
'⚠️ Something went wrong while connecting to the AI service. Please check your API key or try again later.'
);
stopStreaming = true;
});
}
function handleStopResponse() {
stopStreaming = true;
}
inlineAIAssist.appendTo('#defaultInlineAssist');
var summarizeBtn = document.querySelector('#summarizeBtn');
if (summarizeBtn) {
summarizeBtn.addEventListener('click', function () {
inlineAIAssist.showPopup();
});
}<!DOCTYPE html>
<html lang="en">
<head>
<title>EJ2 Inline AI Assist</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="TypeScript Inline AI Assist Control" />
<meta name="author" content="Syncfusion" />
<link href="index.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/33.1.44/ej2-base/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/33.1.44/ej2-interactive-chat/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/33.1.44/ej2-inputs/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/33.1.44/ej2-buttons/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/33.1.44/ej2-navigations/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/33.1.44/ej2-notifications/styles/material.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="systemjs.config.js"></script>
<style>
#editableText {
width: 100%;
min-height: 120px;
max-height: 300px;
overflow-y: auto;
font-size: 16px;
padding: 12px;
border-radius: 4px;
border: 1px solid;
}
</style>
</head>
<body>
<div id='loader'>Loading....</div>
<div id='container' style="height: 350px; width: 650px;">
<button id="summarizeBtn" class="e-btn e-primary" style="margin-bottom: 10px;">Content Summarize</button>
<div id="editableText" contenteditable="true">
<p>Inline AI Assist component provides intelligent text processing capabilities that enhance user productivity. It leverages advanced natural language processing to understand context and deliver precise suggestions. Users can seamlessly integrate AI-powered features into their applications.</p>
<p>With real-time response streaming and customizable prompts, developers can create interactive experiences. The component supports multiple response modes including inline editing and popup-based interactions.</p>
</div>
<div id="defaultInlineAssist"></div>
</div>
</body>
</html>