How to Use OpenAI API in JavaScript

Arva Rangwala

Suppose you’re a developer looking to integrate cutting-edge Artificial General Intelligence models like GPT-3 into your apps or web services with JavaScript. In that case, our API can help you bridge the gap between your work and the OpenAI server. This allows you to leverage OpenAI research without spending millions of dollars and makes your work more efficient.

This article’ll show you how to use OpenAI’s latest AI capabilities. OpenAI recently unveiled the GPT-4 model for developers to use. If you’re starting an OpenAI project or just starting with OpenAI, consider using GPT-4, as GPT-3 will be discontinued next year.

How to Get Started with an OpenAI API Key

These are the first steps to using the OpenAI API in JavaScript. To begin, you need an OpenAI API key.

  1. Visit the OpenAI Platform in your browser.
  2. Log in with your OpenAI credentials or continue using Google or Microsoft authentication.
    1. If you don’t have an OpenAI account, create one. You will need to verify your email and mobile number. After that, set up your OpenAI account with a profile picture, name, date of birth, and other requirements.
  3. Obtain your OpenAI API by visiting the OpenAI platform.
  4. Click on your profile, which appears in the screen’s upper-right corner.
  5. Next, click on Your Profile and then select the View API Key.
  6. Create a new Secret Key by clicking on Create new Secret Key, giving it a name, and saving the API key. Once created, you can’t view it again.
  7. That’s it!

Setting Up Your JavaScript Developer Environment

To get started, you’ll need to set up your development environment. For this tutorial, we’ll use Microsoft Visual Studio as the code editor, but feel free to use whichever code editor you prefer.

Here are the steps to install the OpenAI package:

  • Start by installing the package using npm.
    • Open your terminal by pressing Ctrl + Shift + ` on your keyboard.
    • Type “npm install openai” and hit enter. A screenshot of a computer program

Description automatically generated
  • Once you install the OpenAI API Package, we can proceed with the authentication.
  • Now you can start the Setup OpenAI key, for which you do need to enter the API key.
    • export OPENAI_API_KEY=”your-api-key”
  • Start Initalizae OpenAI API by importing the OpenAI library, then Initialize it with the API key.

const OpenAI = require(‘@openai/api’);

constopenai = new OpenAI(process.env.OPENAI_API_KEY);

Now, Make an API Call for which we use the Completion.create method to generate code.

async function generateText(prompt) {

engine: “text-davinci-004”,

max_tokens: 60

}

generateText(“Translate the following English text to French: ‘Hello, how are you?'”)

.catch(error =>console.error(error));

In this code, you need to modify several things, including OpenAI key as

  • engine: Choose your GPT model
  • prompt: Gives input text to your model
  • max_token: How long you want to respond.
  • generateText: this asynchronous function takes promopt and returns the generated text from the GPT Model.
  • After you have installed the OpenAI API Package, we can authenticate your account.
  • To set up your OpenAI key, you will need to enter your API key by running the following command:
    • export OPENAI_API_KEY=”your-api-key”
  • Next, you can initialize the OpenAI API by importing the OpenAI library and initializing it with your API key:

const OpenAI = require(‘@openai/api’);

constopenai = new OpenAI(process.env.OPENAI_API_KEY);

Now, you can make an API call using the Completion.create method to generate code.

async function generateText(prompt) {

engine: “text-davinci-004”,

max_tokens: 60

}

generateText(“Translate the following English text to French: ‘Hello, how are you?'”)

.catch(error =>console.error(error));

In this code, you may need to modify several things including your OpenAI key as well as the following:

  • engine: choose your preferred GPT model
  • prompt: provides input text to your model
  • max_token: determines the length of the response
  • generateText: an asynchronous function that takes a prompt and returns the generated text from the GPT Model.

Request to the OpenAI API

To check if your API is working, We can use the following code to start making requests to the OpenAI API.

constaxios = require(“axios”);

constapiKey = “YOUR_API_KEY”;

headers: {

},

prompt,

max_tokens: 100,

.then((response) => {

})

console.log(error);

  • Completions: To make a request to the endpoint, pass the prompt.
  • max_tokens: Max number of tokens that API should return; this includes Text, Words, or punctuation marks.
  • Options: Object specifics of the header should be sent with the request.
  • Authorization: This is used to authenticate the request.
  • then() and catch(): Used to handle Api response, If it shows then() then it’s successful and if catch() it refers to request fails.

Requesting OpenAI API

To check if your API is functioning properly, you can use the following code to start making requests to the OpenAI API:

constaxios = require(“axios”);

constapiKey = “YOUR_API_KEY”;

const headers = {

};

const prompt = “”;

constmax_tokens = 100;

axios.post(“https://api.openai.com/v1/engines/davinci-codex/completions“, {

prompt,

max_tokens,

}, {

headers: {

Authorization: Bearer ${apiKey},

},

})

.then((response) => {

console.log(response.data.choices[0].text);

})

.catch((error) => {

console.log(error);

});

  • Completions: This is used to request the endpoint by passing the prompt.
  • Max_tokens: This specifies the maximum number of tokens the API should return, including text, words, or punctuation marks.
  • Options: This object specifies the headers that should be sent with the request.
  • Authorization: This is used to authenticate the request.
  • then() and catch(): These handle API responses. If it shows then(), the request was successful; if catch(), it means it failed.

OpenAI API Authentications

After finishing basic setup you can now proceed to configure OpenAI Pacakge . Let us begin with the authentication.

To initializing the pakacge you can use the following code

const{ Configuration, OpenAIApi } = require(“openai”);

const configuration = new Configuration({

});

constopenai = new OpenAIApi(configuration);

Note: You do need to modify the code with your OpenAI API key.

After successfully establishing the OpenAI API in Javascript you can now start with generate text, Translate and other stuff. You can also modify your code based on Model, Mode, Parameter like Temperature. Some of the example includes.

Generate Text

const prompt = “Once upon a time”;

console.log(response.data.choices[0].text);

Translate Text

const text = “Hello, how are you?”;

consttargetLanguage = “es”;

openai.translate({ text, sourceLanguage, targetLanguage }).then((response) => {

});

Summarize Text

const text = “The quick brown fox jumps over the lazy dog.”;

console.log(response.data.summary);

Apart from these examples code, you can get additional resources from OpenAI Documents, References, and GitHub. At the end, Do experiment with your codes and Learn Promopt Engineer, which allows you to be more specific with your results which you can do by heading over to the OpenAI Playground that lets developers test with modes, Modes, and parameters.

OpenAI API Authentication

After finishing the basic setup, you can configure the OpenAI package. Let us start with the authentication.

To initialize the package, use the following code:

const{ Configuration, OpenAIApi } = require(“openai”);

const configuration = new Configuration({

apiKey: “YOUR_OPENAI_API_KEY_HERE”,

});

constopenai = new OpenAIApi(configuration);

Note: You need to modify the code with your OpenAI API key.

After successfully establishing the OpenAI API in JavaScript, you can generate text, translate, and do other things. You can also modify your code based on the model, mode, and parameters like temperature. Here are some examples:

Generate Text

const prompt = “Once upon a time”;

console.log(response.data.choices[0].text);

Translate Text

const text = “Hello, how are you?”;

constsourceLanguage = “en”;

consttargetLanguage = “es”;

openai.translate({ text, sourceLanguage, targetLanguage }).then((response) => {

});

Summarize Text

const text = “The quick brown fox jumps over the lazy dog.”;

console.log(response.data.summary);

In addition to these example codes, you can find resources from OpenAI Documents, References, and GitHub. Finally, experiment with your codes and learn prompt engineering, which allows you to be more specific with your results. You can do this by heading to the OpenAI Playground, which lets developers test with modes, modes, and parameters.

Share This Article
Leave a comment