Syncfusion AI Assistant

How can I help you?

Integrate Gemini AI With TypeScript Inline AI Assist control

2 Apr 202610 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

  • Node.js: Version 16 or higher with npm.

  • Google Account: For generating a Gemini API key.

  • Syncfusion Inline AI Assist: Package @syncfusion/ej2-interactive-chat installed.

  • 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 --save

Generate API Key

  1. Access Google AI Studio: Instructs users to sign into Google AI Studio with a Google account or create a new account if needed.

  2. Navigate to API Key Creation: Go to the Get API Key option in the left-hand menu or top-right corner of the dashboard. Click the Create API Key button.

  3. Project Selection: Choose an existing Google Cloud project or create a new one.

  4. 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:
const geminiApiKey = 'Place your API key here';
import { InlineAIAssist, InlinePromptRequestEventArgs } from '@syncfusion/ej2-interactive-chat';
 import { GoogleGenerativeAI } from '@google/generative-ai';
 import { marked } from 'marked';
 
 // Initialize Gemini API
const geminiApiKey = ''; // Replace with your Gemini API key
let genAI = new GoogleGenerativeAI(geminiApiKey);
let stopStreaming = false;

// Initializes the AI Assist control
const inlineAIAssist = new InlineAIAssist({
    promptRequest: onPromptRequest,
    inlineToolbarSettings: {
        itemClick: (args: any) => {
            if (args.item.iconCss === 'e-icons e-inline-stop') {
                handleStopResponse();
            }
        }
    },
    relateTo: '#summarizeBtn',
    responseSettings: {
        itemSelect: (args: any): void => {
            if (args.command.label === 'Accept') {
                const editable = document.getElementById('editableText') as HTMLElement | null;
                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: string) {
    let lastResponse = "";
    const responseUpdateRate = 10;
    let i = 0;
    const responseLength = response.length;
    while (i < responseLength && !stopStreaming) {
        lastResponse += response[i];
        i++;
        if (i % responseUpdateRate === 0 || i === responseLength) {
            const htmlResponse = marked.parse(lastResponse);
            inlineAIAssist.addResponse(htmlResponse, i === responseLength);
        }
        await new Promise(resolve => setTimeout(resolve, 15)); // Delay for streaming effect
    }
}

// Handle user prompt: call Gemini model
async function onPromptRequest(args: InlinePromptRequestEventArgs) {
    try {
        const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' }); // Select the Gemini model (update model name as needed)
        const result = await model.generateContent(args.prompt);
        const response = result.response.text();
        stopStreaming = false;
        await streamResponse(response);
    } catch (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;
}

 // Render Inline AI Assist
inlineAIAssist.appendTo('#defaultInlineAssist');
const summarizeBtn: HTMLElement = document.querySelector('#summarizeBtn') as HTMLElement;
if (summarizeBtn) {
    summarizeBtn.addEventListener('click', () => {
        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.2.3/ej2-base/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-interactive-chat/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-inputs/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-buttons/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-navigations/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-notifications/styles/tailwind3.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>