Building AI-Chatbot App With ChatGPT API In Angular

Introduction

In this article, I will explain How to implement AI-Chatbot App with ChatGPT API in Angular. Furthermore, in this article, I will explain how to use OpenAPI in angular. I am also creating a demo project for better understanding.

Shot about Chat GPT

Chat GPT (Generative Pre-Training) is an unsupervised language model developed by Microsoft for conversational AI agents. The model is trained on large amounts of conversational data and can be used to generate natural language answers to users’ questions. Chat GPT is based on transformer models and is pre-trained on numerous publicly available conversational and non-conversational datasets. In addition, it is trained on internal proprietary data to improve its accuracy. Once trained, the model can generate context-sensitive responses specific to the user’s input. Chat GPT is intended to be used in everyday conversational settings and can be further tailored to applications such as customer support and virtual assistant conversations.

Prerequisites

  • Angular 13
  • HTML/Bootstrap

For this article, I have created an Angular project using Angular 13. To create an Angular project, we need to follow the following steps:

Step 1

I have created a project using the following command in the Command Prompt.

ng new chatBOT 

Step 2

Open a project in Visual Studio Code using the following commands.

cd chatBOT    
code.

Step 3

We need to install ngx bootstrap in our project using the following command in the terminal.

npm install --save bootstrap

Step 4

After installing bootstrap, we should import bootstrap in style.css.

@import '~bootstrap/dist/css/bootstrap.min.css';

To implement Chat GPT in Angular, you can follow the following steps,

  1. Install the necessary dependencies: You will need to install the @openai/api package, which is the official OpenAI API package for JavaScript/TypeScript.
  2. Create an OpenAI API key: You must sign up for the OpenAI GPT-3 API and get an API key.
  3. Set up the OpenAI API in your Angular project: In your app.module.ts file, you can import the HttpClientModule and include it in the imports array.
  4. Create a service for the OpenAI API: Create a new service file, for example openai.service.ts, where you can define a function that calls the OpenAI API with your API key and the text you want to generate.
  5. Call the OpenAI API from your Angular component: In your Angular component file, import the openai.service.ts file and call the function defined in that file with the text you want to generate.
  6. Display the generated text: You can display the generated text on the HTML template of your Angular component using string interpolation or property binding.

Here is some sample code to get you started,

Install the @openai package,

npm install openai

Sign up for the OpenAI GPT-3 API and get an API key.

Set up the OpenAI API in your app.module.ts file,

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Create a service for the OpenAI API

Create OpenAI Service in the Service folder using the following command.

ng g s openai
import { Injectable } from '@angular/core';
import { Configuration, OpenAIApi } from 'openai';

@Injectable({
  providedIn: 'root'
})
export class OpenaiService {
  private openai: OpenAIApi;
  configuration = new Configuration({
    apiKey: "Your-Key-Here",
  });

  constructor() {
    this.openai = new OpenAIApi(this.configuration);
  }
  
  generateText(prompt: string):Promise<string | undefined>{
   return this.openai.createCompletion({
        model: "text-davinci-003",
        prompt: prompt,
        max_tokens: 256
      }).then(response => {
        return response.data.choices[0].text;
      }).catch(error=>{
        return '';
      });
  }
}

Call the OpenAI API from your Angular component:

App.Component.html

<div style="margin: 30px;">
  <h1 style="text-align: center;">Chat GPT Example</h1>
  <div class="card"  *ngFor="let data of textList">
    <div class="card-header">
      <div class="input-group mb-3" >
        <input type="text" [(ngModel)]="data.text" class="form-control" placeholder="Add Your Text Here">
        <div class="input-group-append">
          <button type="button" (click)="generateText(data)" class="btn btn-primary">Generate</button>
        </div>
      </div>
    </div>
    <div class="card-body">
      <p class="card-text">{{data.response}}</p>
    </div>
  </div>
</div>

App.Component.ts

import { Component } from '@angular/core';
import { OpenaiService } from './openai.service';

export class textResponse{
  sno:number=1;
  text:string='';
  response:any='';
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  textList:textResponse[]=[{sno:1,text:'',response:''}];

  constructor(private openaiService: OpenaiService) {}

  generateText(data:textResponse) {
    this.openaiService.generateText(data.text).then(text => {
      data.response = text;
      if(this.textList.length===data.sno){
        this.textList.push({sno:1,text:'',response:''});
      }
    });
  }
}

Now Run the application using the following command,

ng serve

Building AI-Chatbot App with ChatGPT API in Angular

Summary

This is a basic example, but you can customize the OpenAI API parameters to suit your needs.