2

Call chatgpt api from angular

 1 month ago
source link: https://www.dotnetoffice.com/2024/04/direct-call-chatgpt-api-from-angular.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

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

Share this


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK