Integrating Open AI into Angular application : Step by Step Guide

Integrating Open AI into Angular application : Step by Step Guide

Greetings everyone, have you heard of the latest technology revolutionizing the world of natural language processing? It's called ChatGPT, and it's making waves in the industry. As a state-of-the-art language model developed by OpenAI, ChatGPT can understand and generate human-like text, making it a powerful tool for various applications.

Are you looking to integrate state-of-the-art language models into your web application? Look no further! I am here to guide you through the process of integrating ChatGPT into your Angular app. But that's not all, this guide is versatile and can be applied to other frameworks such as React and Vue. Whether you're a beginner or an experienced developer, this guide will provide you with all the information you need to successfully integrate ChatGPT into your web app, and take your user experience to the next level.

Note: This tutorial is not intended for production use, as it may expose your OpenAI keys through the browser's network tab.

Without further delay, let's dive right in and get started. Steps we'll follow for this guide:

  1. Install an npm package called openai.

  2. Write an angular service to configure the openAI and initialise it.

  3. Write a method to get data using the createCompletion method of the openAI npm library.

1. Installing the npm package

We'll be installing an npm package called openai.

Open a terminal within your project and run the following command to install the package:

$ npm install openai

After installing, you should see an entry for openai in the dependencies section of your package.json file.

2. Create an angular service

For the sake of organization, clarity and reusability, I recommend creating a dedicated service for handling the openai package, instead of writing the code directly in your component file. By doing so, you'll have all the openai related code in one place, and it will be easily accessible to multiple components. To generate a service using Angular CLI, you can run this command:

ng g s open-ai

This command will generate a service file for you in the project.

To begin using the openai package, we first need to import the necessary components and configure the package. The first step is to import the Configuration and OpenAIApi from the openai package. To do this, add the following line to the top of your service file:

import { Configuration, OpenAIApi } from 'openai';

Your service should now look like this:

The openai library requires configuration with your account's API key. You can generate your API key by visiting the OpenAI website. For security purposes, it's recommended to keep your API key in the environment.ts file. To initialize the configuration, add the following line in your service file:

readonly configuration = new Configuration({
  apiKey: environment.openAIToken
});

Finally, we will initialize the OpenAIApi using the configuration we just created. Here's an example of how this should be done:

readonly openai = new OpenAIApi(this.configuration);

After adding the above code, your service file should resemble the following:

3. Add the method to retrieve data from the OpenAI API.

I will be creating a method to accept a prompt as input and retrieve the corresponding response from the OpenAI API. Utilizing the async/await syntax, this method can be written as follows:

async getDataFromOpenAPI(text: string) {
    const completion = await openai.createCompletion({
      model: "text-davinci-002",
      prompt: text,
    });
    console.log(completion.data.choices[0].text);
}

As an Angular developer, I find the RxJS version to be more readable and easy to work with. To do this, we will use the from method of RxJS to convert the promise to an observable and then subscribe to it for the resulting data.

getDataFromOpenAI(text: string) {
    from(this.openai.createCompletion({
      model: "text-davinci-003",
      prompt: text,
      max_tokens: 256
    })).pipe(
      filter(resp => !!resp && !!resp.data),
      map(resp => resp.data),
      filter((data: any) => data.choices && data.choices.length > 0 && data.choices[0].text),
      map(data => data.choices[0].text)
    ).subscribe(data => {
        console.log(data);
    });
  }

The from method takes the OpenAI's completion method as input and converts it to an observable, allowing us to perform manipulation and subscribe to the result. I have only passed basic parameters such as model, prompt, and max_token in the createCompletion method of OpenAI, but you can pass a lot of parameters for more control over the generated response. You can learn more about the available parameters here.

In this case, we are only interested in the choices field received in the response from OpenAI, so I have added a few filters to ensure that we are receiving valid data and then mapped it to the appropriate fields (data.choices[0].text in this case). You can then perform the desired action with the received data.

Your final code for the service should look like this:

This is just the beginning of what openai can do for you. To unlock its full potential, be sure to explore the openai API documentation for more options and methods available. Dive deeper into the capabilities of this powerful technology and discover new ways to enhance your applications. With openai, the possibilities are endless.

Fun Fact - Did you know that the copywriting for this article was also fine-tuned by the advanced language model, chatGPT? That's right, chatGPT helped to make the language in this article more accurate, concise, and engaging.

If you encounter any difficulties during the integration process, feel free to reach out to me via the comments section or on my social media profiles. And, if you're interested, let me know in the comments if you'd like me to create a video tutorial for this.

If you are new to web development, Check out my frontend guide for 2023.

Your support in the form of a like is greatly appreciated.