Showing posts with label OpenAI. Show all posts
Showing posts with label OpenAI. Show all posts

Call chatgpt api from angular

Angular is a frontend framework that allows you to build web applications, and you can use it to make HTTP requests to external APIs, including the ChatGPT API. 

To call the ChatGPT API from Angular, you would typically use Angular's built-in HttpClient module to send HTTP requests to the API endpoint. Here's a basic example of how you might do this: 

First, make sure you have Angular CLI installed. If not, you can install it using npm:

npm install -g @angular/cli


Create a new Angular project:

ng new my-chatgpt-app


Navigate to your project directory:
cd my-chatgpt-app

Generate a new service to handle API calls:
ng generate service chatgpt


In your service file (chatgpt.service.ts), import HttpClient and inject it into your service constructor:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ChatGptService {
  private apiUrl = 'https://api.openai.com/v1/chat/completions'; // Example API endpoint

  constructor(private http: HttpClient) { }

  getChatResponse(prompt: string): Observable<any> {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY' // Replace YOUR_API_KEY with your actual API key
    };

    const body = {
      prompt: prompt,
      max_tokens: 150
    };

    return this.http.post<any>(this.apiUrl, body, { headers });
  }
}



Replace 'https://api.openai.com/v1/chat/completions' with the actual URL of the ChatGPT API endpoint you want to call.
Replace 'YOUR_API_KEY' with your actual ChatGPT API key.
Now, you can use this service in your Angular components to make API calls. For example, in your component file (app.component.ts), you can inject the ChatGptService and call the getChatResponse method:
import { Component } from '@angular/core';
import { ChatGptService } from './chatgpt.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private chatGptService: ChatGptService) {}

  ngOnInit() {
    this.chatGptService.getChatResponse('Hello, GPT!').subscribe(response => {
      console.log(response);
    });
  }
}



Here we are printing data to the console, you can print it in an HTML page as well.





----------------------

ChatGPT is now available in the Azure OpenAI Service

In this article we will see about ChatGPT is now available in Azure OpenAI Service

If you are new to ChatGPT then previously we discussed OpenAI and we have seen how to create a ChatGTP application using OpenAI, 

For more please follow the below link 👇

Now ChatGPT is available in Azure Open AI service as well, it is introduced and announced by Microsoft on 9th march 2023.

Now developers and the business team will be able to integrate the Open AI’s ChatGPT modes into their cloud applications, which enables communication in other apps and services.

Now the business team can use ChatGPT to customize the queries as per the customer feedback and can help in applications to send automated emails and so many others.

As per Microsoft's announcement Azure OpenAI, users now can start to access the preview of ChatGPT today, with the pricing set of $0.002 for the 1,000 tokens, now the billing for all the ChatGPT service starts on March 13th as part of the Azure OpenAI.

Developers need to apply for special access, as the Azure OpenAI Services requires registration and it is currently only available for Microsoft-managed customers and partners.

With the help of Azure OpenAI Service, more than 1,000 customers are applying the advanced AI model, including the Dall-E 2, GPT-3.5, Codex, and many other large language models to innovate in new ways, now the developers use OpenAI’s ChatGPT in the enhancement of PowerBI, MicrosoftTeams, GitHub, etc.

Now all the big and small levels of organizations are using the Azure OpenAI Services to achieve their business value, Microsoft also working internally to combine the large language models with the OpenAI and the AI-optimized infrastructure of Azure to introduce new experiences across the customer and products ex.

  • GitHub Copilot leverages AI models in the Azure OpenAI Service to give benefits to developers to enhance the code with its AI pair programmer.
  • Microsoft Teams Premium includes the intelligent recap and the AI-generated chapters to help the teams, individuals, and organizations become more productive.
  • Microsoft Viva Sales is the new AI-powered seller experience that offers suggested email content and data-driven insights to help the sales teams to focus on selling products to customers.
  • Microsoft Bing introduced the AI-powered chat option to enhance the consumer's search experience.

above are just a few examples of how Microsoft openAI is helping organizations to transform in AI models.

So in the future, AI will definitely change the way of work, and also improve the organization's growth with Open A.

Below are a couple of the Links given by Microsoft through that we can start working with Azure OpenAI services.

Getting started with the Azure OpenAI Service


    ---------------------------------------------------------------------------------------

    Integrate OpenAI with .NET Core and Angular15 | ChatGPT Completions In .NET Core Web API & Angular15

    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");
                }
            }
        }
    }
    C#

    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");
    C#

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

    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>
    JavaScript

    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'
            });
        }
    }
    JavaScript

    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,





    ----------------------------------------------------------------