ChatGPT Completions In .NET Core Web API And Angular 15

Hello everyone, Here we are going to discuss, how to integrate OpenAI with .Net Core and Angular 15.

ChatGPT Completions In .NET Core Web API & Angular15

ChatGPT (Generative Pre-trained Transformer) is the chatbot developed by OpenAI on November 30, 2022.

Previously we discussed OpenAI and we have seen how to create a ChatGTP application using OpenAI, 

For more please follow the below link ๐Ÿ‘‡

Step 1. Create an OpenAI account

First, we need to create an OpenAI account; you can follow the below link to how to create an OpenAI account.

Step 2. Get the OpenAI API key

Login to your OpenAI account and click on profile (personal, right-hand side) and click on view API

ChatGPT Completions In .NET Core Web API & Angular15

Once you click on View API Keys, you will "Create a new secret key, once you click on it an API key will generate in the Popup window, and you can copy it for using it in the application.

ChatGPT Completions In .NET Core Web API & Angular15

 

ChatGPT Completions In .NET Core Web API & Angular15

Now open Visual Studio 2022 and create an ASP.Net Core web API project like below

ChatGPT Completions In .NET Core Web API & Angular15

ChatGPT Completions In .NET Core Web API & Angular15

Give additional information as per your requirement.

ChatGPT Completions In .NET Core Web API & Angular15

Once the project is created, now go to the NuGet package manager and add the OpenAI package like below

ChatGPT Completions In .NET Core Web API & Angular15

Now right-click on the Controller folder and add a new controller Called OpenAI and write the below code in it

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OpenAI_API.Completions;
using OpenAI_API;
namespace OpenAIApp.Controllers {
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OpenAI: ControllerBase {
        [HttpGet]
        public async Task < IActionResult > GetData(string input) {
            string apiKey = "Your API Key";
            string response = "";
            OpenAIAPI openai = new OpenAIAPI(apiKey);
            CompletionRequest completion = new CompletionRequest();
            completion.Prompt = input;
            completion.Model = "text-davinci-003";
            completion.MaxTokens = 4000;
            var output = await openai.Completions.CreateCompletionAsync(completion);
            if (output != null) {
                foreach(var item in output.Completions) {
                    response = item.Text;
                }
                return Ok(response);
            } else {
                return BadRequest("Not found");
            }
        }
    }
}

Now click on the program.cs class and add the cors origin like below,

builder.Services.AddCors(options => {
    options.AddPolicy(name: "AllowOrigin", policy => {
        policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
});
app.UseCors("AllowOrigin");

ChatGPT Completions In .NET Core Web API & Angular15

When you will run this application, we will see our API in swagger and our API is ready to use in angular.

ChatGPT Completions In .NET Core Web API & Angular15

Now we need to create the Angular 15 application, you can follow the below link for the same

Once the angular 15 application is created, now open the app.component.ts file and add the below code

import { Component } from '@angular/core';
import { OpenAIService } from './open-ai.service';
 
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    searchTxtVal: string = '';
    showOutput: boolean = false;
    output: string = '';
    isLoading: boolean = false;
    constructor(private service: OpenAIService) {}
    getResult() {
        this.isLoading = true;
        this.output = "";
        this.service.getData(this.searchTxtVal).subscribe(data => {
            this.output = data as string;
            this.showOutput = true;
            this.isLoading = false;
        })
    }
}

Add the below code in app.component.html file

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div class="text-center">
  <div class="panel-default">
    <div class="panel-body">ChatGPT Completions In the ASP.NET Core Web API</div>
    <div class="panel-body">
      <div class="col-sm-8">
        <input type="text" [(ngModel)]="searchTxtVal" class="form-control" autocomplete="off" placeholder="Enter your question" />
      </div>
      <div class="col-sm-2" style="margin-left: -60px;">
        <button (click)="getResult()">Get Result</button>
      </div>
      <div class="col-sm-12 mt-5" *ngIf="showOutput">
        {{output}}
      </div>
      <div class="col-sm-12 mt-5" *ngIf="isLoading">
        <p style="color: red;">Loading...</p>
      </div>
    </div>
  </div>
</div>

Now create a service file with the below command, here service name is "OpenAI"

Ng g s openAI

And write the below code in the openAI.service.ts file

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import{ Observable} from 'rxjs';
 
@Injectable({
    providedIn: 'root'
})
export class OpenAIService {
    constructor(private http: HttpClient) {}
    getData(input: string): Observable < any > {
        return this.http.get('https://localhost:7285/api/OpenAI/GetData?input=' + input, {
            responseType: 'text'
        });
    }
}

In the above the Url path is "'https://localhost:7285", you need to replace the port, which you are looking at locally, once you run your .Net Core application.

Now add this service reference in the app.model.ts file in the provider array and apart from it we need to add the FormsModule and HttpClientModule like below

ChatGPT Completions In .NET Core Web API & Angular15

Now when you will run your angular 15 application, you will see UI like below

ChatGPT Completions In .NET Core Web API & Angular15

Here, now you can write your query and click on the getResult button, you will see the output below

ChatGPT Completions In .NET Core Web API & Angular15

The output will be like below

ChatGPT Completions In .NET Core Web API & Angular15

This is the way we can integrate the OpenAI with our angular application.

Below is the video, on how we can integrate OpenAI with our angular application practically,