DEV Community

Lesego Letimela
Lesego Letimela

Posted on

OpenAI API Requests in JavaScript 2023

Ok so I recently tried my hand at using the OpenAI api for the first time and discovered, the recent migration from v3 to v4.
The version change introduces syntax and breaking changes. If you are in the process of migrating check this out.

Make sure you have an API key for OpenAI, as it is required for the client.

Installing openai-node

First, install the openai-node package using npm:
npm install openai

Basic Query in JavaScript

Create an app.js file.

In this example we're using an environment variable for our API key using the dotenv package. You can also hardcode the key, but it's not recommended.

require("dotenv").config();

Next we'll bring in the OpenAI package:

const OpenAI = require('openai');
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY, // This is also the default, can be omitted
});

Okay now we can start consulting the api...

Making a Request

I'm using the free-tier gpt-3.5-turbo model. The model will return an object with a choices key, with a nested message(s) array.
The array will have at least one object with a role and content.

Let's get a poem about the future of web development from gpt-3.5-turbo.

async function getPoem() {
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
// content is hard coded but can come dynamically from user
messages: [
{ role: 'user', content: 'generate a short
poem about the future of web development' },
],
});
// Log first response
console.log(response.choices[0]);
}

This returns an object with role: 'assistant' and the generated response under the key content. So to log only the assistants response,

console.log(response.choices[0].content

And that's it for the most basic of requests from OpenAI GPT API's using the openai-node client. Now everytime we run the getPoem function, our assistant will create a new poem about the future of web development.

Top comments (0)