Home >Web Front-end >JS Tutorial >Integrating Gemini AI in Angular: Building a Chat Application

Integrating Gemini AI in Angular: Building a Chat Application

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 06:30:14416browse

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

  npm install @google/generative-ai

Transforming Gemini Responses to HTML

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

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());
  }
}

Use this pipe in your template:

<span>




<hr>

<p>For more on AI and Gemini:  </p>

  • Google AI Blog
  • Google AI Platform
  • Gemini Web

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!

The above is the detailed content of Integrating Gemini AI in Angular: Building a Chat Application. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn