How can I help you?
Integrate Gemini AI with React AI AssistView component
28 Oct 202514 minutes to read
The AI AssistView component 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.
-
Syncfusion AI AssistView: Package @syncfusion/ej2-react-interactive-chat installed.
-
Marked Library: For parsing Markdown responses (
npm install marked --save).
Set Up the React Environment
Follow the Getting Started guide to configure and render the AI AssistView component in your React 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 AI AssistView
To integrate Gemini AI with the Syncfusion AI AssistView component in your application:
-
Modify the
src/App.jsfile to host the integration logic. -
Add your Gemini API key securely in the configuration:
const geminiApiKey = 'Place your API key here';import { AIAssistViewComponent } from '@syncfusion/ej2-react-interactive-chat';
import { GoogleGenerativeAI } from '@google/generative-ai';
import * as React from 'react';
import * as ReactDOM from "react-dom";
import { marked } from 'marked';
const geminiApiKey = ''; // Replace with your Gemini API key (WARNING: Do not expose API key in client-side code for production)
const genAI = new GoogleGenerativeAI(geminiApiKey);
let stopStreaming = false;
function App() {
const assistInstance = React.useRef(null);
const suggestions = [
'How do I prioritize my tasks?',
'How can I improve my time management skills?'
];
const bannerTemplate = '<div class="banner-content"><div class="e-icons e-assistview-icon"></div><h3>How can I help you today?</h3></div>';
const toolbarItemClicked = (args) => {
if (args.item.iconCss === 'e-icons e-refresh') {
assistInstance.current.prompts = [];
assistInstance.current.promptSuggestions = suggestions;
stopStreaming = true;// Stop streaming on refresh
}
};
const assistViewToolbarSettings = {
items: [{ iconCss: 'e-icons e-refresh', align: 'Right' }],
itemClicked: toolbarItemClicked
};
const streamResponse = async (response) => {
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);
assistInstance.current.addPromptResponse(htmlResponse, i === responseLength);
assistInstance.current.scrollToBottom();
}
await new Promise(resolve => setTimeout(resolve, 15)); // Delay before the next chunk
}
assistInstance.current.promptSuggestions = suggestions;
};
const onPromptRequest = (args) => {
const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' }); // Replace Your Model Name Here
model.generateContent(args.prompt)
.then(result => {
const responseText = result.response.text().trim() || 'No respons received.';
stopStreaming = false;
streamResponse(responseText);
})
.catch(error => {
assistInstance.current.addPromptResponse('⚠️ Something went wrong while connecting to the AI service. Please check your API key or try again later.');
stopStreaming = true;
});
};
const handleStopResponse = () => {
stopStreaming=true;
};
return (
<AIAssistViewComponent
id="aiAssistView"
ref={assistInstance}
promptRequest={onPromptRequest}
promptSuggestions={suggestions}
bannerTemplate={bannerTemplate}
toolbarSettings={assistViewToolbarSettings}
stopRespondingClick={handleStopResponse}
/>
);
}
ReactDOM.render(<App />, document.getElementById('container'));import { AIAssistViewComponent, ToolbarItemClickArgs } from '@syncfusion/ej2-react-interactive-chat';
import { GoogleGenerativeAI, GenerateContentResult } from '@google/generative-ai';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { marked } from 'marked';
const geminiApiKey: string = ''; // Replace with your Gemini API key (WARNING: Do not expose API key in client-side code for production)
const genAI: GoogleGenerativeAI = new GoogleGenerativeAI(geminiApiKey);
let stopStreaming = false;
function App() {
const assistInstance = React.useRef<AIAssistViewComponent | null>(null);
const suggestions: string[] = [
'How do I prioritize my tasks?',
'How can I improve my time management skills?'
];
const bannerTemplate: string = '<div class="banner-content"><div class="e-icons e-assistview-icon"></div><h3>How can I help you today?</h3></div>';
const toolbarItemClicked = (args: ToolbarItemClickArgs): void => {
if (args.item.iconCss === 'e-icons e-refresh') {
if (assistInstance.current) {
assistInstance.current.prompts = [];
assistInstance.current.promptSuggestions = suggestions;
stopStreaming = true;
}
}
};
const assistViewToolbarSettings = {
items: [{ iconCss: 'e-icons e-refresh', align: 'Right' }],
itemClicked: toolbarItemClicked
};
const streamResponse = async (response: string): Promise<void> => {
let lastResponse: string = '';
const responseUpdateRate: number = 10;
let i: number = 0;
const responseLength: number = response.length;
while (i < responseLength && !stopStreaming) {
lastResponse += response[i];
i++;
if (i % responseUpdateRate === 0 || i === responseLength) {
const htmlResponse: string = marked.parse(lastResponse) as string;
assistInstance.current.addPromptResponse(htmlResponse, i === responseLength);
assistInstance.current.scrollToBottom();
}
await new Promise(resolve => setTimeout(resolve, 15)); // Delay before the next chunk
}
if (assistInstance.current) {
assistInstance.current.promptSuggestions = suggestions;
}
};
const onPromptRequest = (args: { prompt: string }): void => {
const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' }); // Replace Your Model Name Here
model.generateContent(args.prompt)
.then((result: GenerateContentResult) => {
const responseText: string = result.response.text().trim() || 'No response received.';
stopStreaming = false;
streamResponse(responseText);
})
.catch((error: unknown) => {
assistInstance.current.addPromptResponse('⚠️ Something went wrong while connecting to the AI service. Please check your API key or try again later.');
stopStreaming = true;
});
};
const handleStopResponse = (): void => {
stopStreaming = true;
};
return (
<AIAssistViewComponent
id="aiAssistView"
ref={assistInstance}
promptRequest={onPromptRequest}
promptSuggestions={suggestions}
bannerTemplate={bannerTemplate}
toolbarSettings={assistViewToolbarSettings}
stopRespondingClick={handleStopResponse}
/>
);
}
ReactDOM.render(<App />, document.getElementById('container'));