HelpBot Assistant

How can I help you?

Integrate Gemini AI with Angular AI AssistView component

7 Nov 20258 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-angular-interactive-chat installed.

  • Angular CLI: For project setup and execution.

  • Marked Library: For parsing Markdown responses (npm install marked --save).

Set Up the Angular Environment

Follow the Getting Started guide to configure and render the AI AssistView component in your Angular application using Angular CLI.

Install Dependencies

To install the marked library, run npm install marked --save in your project directory to add it as a dependency in your package.json file.

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 AI AssistView

To integrate Gemini AI with the Syncfusion AI AssistView component in your Angular application:

  • Modify the a standalone app.component.ts file to host the integration logic.

  • Add your Gemini API key securely in the configuration:

const geminiApiKey = 'Place your API key here';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent, AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { PromptRequestEventArgs } from '@syncfusion/ej2-interactive-chat';
import { marked } from 'marked';

@Component({
  standalone: true,
  imports: [AIAssistViewModule],
  selector: 'app-root',
  template: `
    <div ejs-aiassistview #aiassist (promptRequest)="onPromptRequest($event)" [promptSuggestions]="suggestions"
      [toolbarSettings]="toolbarSettings" (stopRespondingClick)="handleStopResponse()">
      <ng-template #bannerTemplate>
        <div class="banner-content">
          <div class="e-icons e-assistview-icon"></div>
          <h3>AI Assistance</h3>
          <div>To get started, provide input or choose a suggestion.</div>
        </div>
      </ng-template>
    </div>
  `
})

export class AppComponent {
  @ViewChild('aiassist') aiAssistView!: AIAssistViewComponent;
  // Initialize Gemini API
  private geminiApiKey: string = ''; // Replace with your Gemini API key
  private stopStreaming: boolean = false;

  public suggestions: string[] = [
    'What are the best tools for organizing my tasks?',
    'How can I maintain work-life balance effectively?'
  ];

  public toolbarSettings = {
    items: [{ iconCss: 'e-icons e-refresh', align: 'Right', tooltip: 'Clear Prompts' }],
    itemClicked: () => {
      this.aiAssistView.prompts = [];
      this.aiAssistView.promptSuggestions = this.suggestions;
      this.stopStreaming = true; // Stop streaming on refresh
    }
  };

  public onPromptRequest = async (args: PromptRequestEventArgs) => {
    const modelName = 'gemini-2.5-flash'; // Select the Gemini model (update model name as needed)
    const url = `https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent?key=${this.geminiApiKey}`;
    const requestBody = {
      contents: [{ parts: [{ text: args.prompt || 'Hi' }] }]
    };

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      const fullResponse = data.candidates[0].content.parts[0].text || '';
      this.stopStreaming = false; // Reset stopStreaming for new request
      this.streamResponse(fullResponse);

    } catch (error) {
      console.error('Error fetching from Gemini API:', error);
      this.aiAssistView.addPromptResponse(
        '⚠️ Something went wrong while connecting to the AI service. Please check your API key, network connection, or try again later.'
      );
      this.stopStreaming = true; // Ensure streaming stops on error
    }
  }

  // Stream AI response in chunks
  private async streamResponse(response: string): Promise<void> {
    let lastResponse = "";
    const responseUpdateRate = 20; // Adjust for smoother or faster updates
    let i = 0;
    const responseLength = response.length;

    while (i < responseLength && !this.stopStreaming) {
      lastResponse += response[i];
      i++;

      if (i % responseUpdateRate === 0 || i === responseLength) {
        const htmlResponse = marked.parse(lastResponse);

        this.aiAssistView.addPromptResponse(htmlResponse, i !== responseLength);
        this.aiAssistView.scrollToBottom();
      }
      await new Promise(resolve => setTimeout(resolve, 15)); 
    }
    this.aiAssistView.promptSuggestions = this.suggestions;
  }

  public handleStopResponse(): void {
    this.stopStreaming = true;
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));