DEV Community

KAMAL KISHOR
KAMAL KISHOR

Posted on

Integrating Gemini AI in Angular: Building a Chat Application

Integrating Gemini AI in Angular: Building a Chat Application

Artificial intelligence (AI) is revolutionizing how we interact with technology, and frontend development is no exception. Understanding AI documentation and APIs has become crucial for modern frontend developers. This article explores how to use Gemini Pro in Angular by creating a chat application. You'll learn how to integrate Gemini's capabilities and build a custom bot tailored to specific needs using prompts.

Overview

In the sample application, I created a bot trained on Angular concepts and my personal resume. The resume was extracted as text from LinkedIn, converted to an array of objects via Google AI Studio, and supplemented with prompts. Additionally, a settings form was incorporated for users to adjust bot configurations dynamically.

This tutorial assumes familiarity with ChatGPT and its integration concepts. For beginners, Google's AI Studio (https://aistudio.google.com) simplifies API integrations in JavaScript and other languages.

Why Choose Gemini Over ChatGPT?

While OpenAI’s ChatGPT is powerful, its API access involves costs and can be complex to implement. Gemini, backed by Google’s extensive AI expertise, offers a more user-friendly approach with robust documentation and features tailored for developers.

A Brief History of Google AI

Google has a long-standing history in AI innovation:

  • 2001: Machine learning was applied to improve search accuracy.
  • 2006: Google Translate emerged, later advancing with TensorFlow and DeepMind.
  • 2016: AlphaGo defeated the world's top Go players.
  • 2023: Generative AI reached new heights with Gemini.

By combining Angular's robust framework with Gemini's AI capabilities, you can create intelligent applications that seamlessly integrate AI-driven interactions.


Development Steps

1. Gemini API Integration

  • Obtain API Key: Sign up for a Google Cloud developer account.
  • Install SDK: Use Node.js (version >= 18) to install the Gemini package:
  npm install @google/generative-ai
Enter fullscreen mode Exit fullscreen mode
  • Create a Service: Implement a service to handle API calls, error handling, and response formatting.

2. Chat Interface Design

Incorporate an appealing UI with features like chat bubbles, input fields, and themes. Enhance UX using Angular animations and a spinner for delays.

3. Chat Logic Implementation

Leverage Angular's reactive programming for synchronizing user input, AI responses, and chat history. Use Gemini’s API to manage messages efficiently.

4. Enhancing User Experience

  • Predefined Questions: Add quick options for users to start conversations.
  • Personality Selection: Allow users to adjust tone, model, and API settings through a form.

Example Service: DataService

The following code demonstrates how to interact with Gemini Pro to send user messages and receive AI responses:

import { Injectable } from "@angular/core";
import { GoogleGenerativeAI, HarmBlockThreshold, HarmCategory } from "@google/generative-ai";
import { from } from "rxjs";
import { GeminiConfig } from "./chat-form";
import { API_KEY_CONF } from "../config";

@Injectable({
  providedIn: "root",
})
export class DataService {
  generateContentWithGeminiPro(
    message: string,
    history: { role: string; parts: string }[],
    geminiConfig: GeminiConfig
  ) {
    const MODEL_NAME = geminiConfig.model;
    const API_KEY = geminiConfig.apiKey || API_KEY_CONF;

    async function response() {
      const genAI = new GoogleGenerativeAI(API_KEY);
      const model = genAI.getGenerativeModel({ model: MODEL_NAME });

      const generationConfig = {
        temperature: geminiConfig.temperature,
        maxOutputTokens: 2048,
      };

      const safetySettings = [
        {
          category: HarmCategory.HARM_CATEGORY_HARASSMENT,
          threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
        },
      ];

      const chat = model.startChat({ generationConfig, safetySettings, history });
      const result = await chat.sendMessage(message);
      return result.response.text();
    }

    return from(response());
  }
}
Enter fullscreen mode Exit fullscreen mode

Transforming Gemini Responses to HTML

Gemini responses may contain special Markdown-like characters. The following Angular pipe converts them to meaningful HTML:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "convertTextToHtml",
})
export class ConvertTextToHtmlPipe implements PipeTransform {
  transform(text: string | null): string {
    if (!text) return "";
    const lines = text.split("\n").filter((line) => line.trim() !== "");
    let htmlContent = "<div>";
    let listOpened = false;

    lines.forEach((line) => {
      if (line.startsWith("* **")) {
        if (!listOpened) {
          htmlContent += "<ul>";
          listOpened = true;
        }
        htmlContent += `<li>${line.replace("* **", "").replace("**", "")}</li>`;
      } else {
        if (listOpened) {
          htmlContent += "</ul>";
          listOpened = false;
        }
        if (line.startsWith("**")) {
          htmlContent += `<h5>${line.replace(/\*\*/g, "")}</h5>`;
        } else {
          htmlContent += `<p>${line}</p>`;
        }
      }
    });

    if (listOpened) htmlContent += "</ul>";
    htmlContent += "</div>";
    return htmlContent;
  }
}
Enter fullscreen mode Exit fullscreen mode

Use this pipe in your template:

<span class="text" [innerHTML]="message.parts | convertTextToHtml"></span>
Enter fullscreen mode Exit fullscreen mode

For more on AI and Gemini:


This article highlights Gemini's potential for developers and the ease of integrating AI into frontend projects. Share your experiences or queries in the comments!

Top comments (0)