OpenAI NodeJS Full Guide

Introduction

OpenAI NodeJS Full Guide
OpenAI NodeJS Full Guide

We will cover an OpenAI NodeJS Full Guide.

Did you know that you can use Javascript to generate content for you?

We will break down this in the following sections:

  • Why Javascript is suitable for generating content for you
  • How to send commands to the openai engine
  • Some working examples to get you started

I have used this technology successfully in various projects, and it works very well and has saved me a ton of trouble and time debugging things.

We will go point by point on getting you up and running in less than 5mins; having some background programming knowledge in Javascript is helpful if you want to fine-tune our code, but you don’t need to start generating content.

This complete guide should cover all your questions on using Javascript on using OpenAI.

All code and examples of how to do this can be found in the Github link.

Why Use Javascript To Generate Content

In this section, I’d like to cover some reasons to generate content using OpenAI in Javascript. This may or may not apply to your use case, so feel free to skip this section if you know what you are doing and want to get into the coding part.

  • Javascript allows you to scrape the data and run analytics on it programmatically.
  • You can include this data as part of a viewer or news aggregator
  • You may want ask questions and answered programmatically using Javascript
  • You can set up alerting and other triggers based on conditions such as article keywords etc
  • You can automate some form of article classification based on tags and content

The list above is by no means, but it explains why some people may want to perform questions or content generation using Javascript programmatically.

How To Setup Javascript For OpenAI

How To Install Node and Yarn

The first step we will be doing is to set up the NodeJS environment that we will use to run our application. If you don’t have NodeJS and Yarn installed in your system I recommend checking these links to get started with those in your system:

If you have those installed in your system you can check the versions that you have by running the following commands:

$ node -v
v18.7.0

$ yarn -v
1.22.19

In order to ensure compatibility with this guide I recommend you use at least the versions listed above or greater than them. This will allow you to work by copying directly the things from the Git repo and this article.

How To Install NodeJS Library Dependencies For OpenAI

The first step we need to do is make a directory and initialize our yarn packages there. In order to do this we will be calling the yarn init command and passing -2 so it uses version 2 structure which is faster and can parallelize package installation.

$ yarn init -2
➤ YN0000: Retrieving https://repo.yarnpkg.com/3.2.2/packages/yarnpkg-cli/bin/yarn.js
➤ YN0000: Saving the new release in .yarn/releases/yarn-3.2.2.cjs
➤ YN0000: Done in 0s 330ms
{
  name: 'nodejs-openai',
  packageManager: '[email protected]'
}

This initializes our repo and creates a baseline from which now we can start installing packages that we will be using in this project. So the next step is to install two packages we need here:

  • Typescript
  • OpenAI

This can be shown in the command below:

$ yarn add typescript openai
➤ YN0000: ┌ Resolution step
➤ YN0000: └ Completed in 0s 269ms
➤ YN0000: ┌ Fetch step
....
➤ YN0000: └ Completed
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed
➤ YN0000: Done in 0s 384ms

How To Install Development Dependencies For NodeJS

As it can be seen above we successfully installed both package dependencies, now we can proceed into installing our development dependencies that we will use in our app. The most important one is our node types so we code completion works in Visual Code alongside we will also use ts-node compiler to produce Javascript files from Typescript files.

This can be seen in the command below:

$ yarn add -D @types/node ts-node
➤ YN0000: ┌ Resolution step
➤ YN0000: └ Completed in 2s 565ms
➤ YN0000: ┌ Fetch step
➤ YN0013: │ diff@npm:4.0.2 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ make-error@npm:1.3.6 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ ts-node@npm:10.9.1 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ v8-compile-cache-lib@npm:3.0.1 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ yn@npm:3.1.1 can't be found in the cache and will be fetched from the remote registry
➤ YN0000: └ Completed in 0s 586ms
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed
➤ YN0000: Done in 3s 179ms

How To Configure TSC For NodeJS

Finally we also need to do a final step and this is initialize the Node Typescript pseudo compiler system with some options that are good to have. Also we will be defining our source and binary directories in the command below.

$ yarn tsc --init --rootDir src --outDir ./bin --esModuleInterop --lib ES2022 --module commonjs --noImplicitAny true

Created a new tsconfig.json with:                                                                                                       TS
  target: es2016
  module: commonjs
  lib: es2022
  outDir: ./bin
  rootDir: src
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true

If you notice above we also specified our default Typescript library version which in this case the latest one is ES2022, depending on which year you are seeing this on you can adjust accordingly. For now the output defaults to ES2016 so it’s compatible with various versions of Javascript.

Now that all of our dependencies and libraries are installed we can proceed into implementing some code.

How To Send OpenAI Commands In JavaScript

Now that we have the environment setup and everything is working fine we will proceed into implementing some code that does our first use case. The first thing we need to do is basically connect to OpenAI and send a command to it and see if it works.

As with all services OpenAI uses a API interface that lets you communicate with it. Via this API you can request things from it and get responses based on what you asked for. In our case we will be firstly ensuring this simple use case is functional and works.

To test this we are going to simply ask OpenAI a few general questions and see if it answers them for us. Subsequently lets go ahead and get started with this.

The code outlined below demonstrates this first use-case we just discussed:

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

const openAIConfig = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
});

const openAIEngine = new OpenAIApi(openAIConfig);
const openAIModel = 'text-davinci-002';

const questionToAsk1 = 'Who is Nikola Tesla?';
const questionToAsk2 = 'When was Nikola Tesla born?';

async function 
sendOpenAICommand(command: string)
{
    let res;
    console.log('Asking OpenAI: ', command);
    res = await openAIEngine.createCompletion({
        model: openAIModel,
        prompt: command
    });
    return res.data.choices[0].text;
}

(async () => {
    let res: string;
    res = await sendOpenAICommand(questionToAsk1);
    console.log(res);
    res = await sendOpenAICommand(questionToAsk2);
    console.log(res);
})();

Now that we have a baseline code lets go ahead and analyze and see what we’ve done above:

  • The first thing we do is import and initialize our library
    • To import we simply use the require to include the package we installed using Yarn which is the OpenAI library
    • We then call the configuration function that OpenAI uses to load our API key which is set in the environment. We will show below when we execute this how this gets initialized.
  • Next we implement an asynchronous function called sendOpenAICommand. This function basically tells OpenAI that we want to request some information from it and see what it gives us back as a response. Two important parameters need to be passed on here:
    • Model: This is the OpenAI model to use, in our case we will be going with DaVinci engine. There’s other ones too that you can find in OpenAI’s website referenced at the conclusion below.
    • Prompt: This is basically the question we will be asking OpenAI on what to answer for us.
  • Finally we test our use case by asking two questions for OpenAI which will be shown in the output of execution below and see what results it returned to us.

How To Ask Questions To OpenAI Using Javascript

So executing the OpenAI ask question example we did we see the following output:

$ OPENAI_API_KEY=REPLACE_WITH_YOUR_API_KEY yarn ts-node nodejs-openai-ask-command.ts

Asking OpenAI:  Who is Nikola Tesla?
Nikola Tesla was an inventor and electrical engineer whose work in the late

Asking OpenAI:  When was Nikola Tesla born?
1856

So let’s see what happened above, we basically asked OpenAI two questions on Nikola Tesla such as his birth date and who he was known for. It has accurately pulled the right answers for us. This has successfully demonstrated our first goal which is interacting with OpenAI and getting some answers for it.

How To Generate An Article Using OpenAI In Javascript

Now that we did a proof of concept on interacting with OpenAI we are going to proceed and do a little more advanced example. The second example we will be demonstrating is how we can use OpenAI to generate an article for us automatically without writing anything.

Having said that lets proceed and see the new code that basically takes a title for us and generates topics and from those topics we can go ahead and write paragraphs and sections on them.

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

const openAIConfig = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
});

const openAIEngine = new OpenAIApi(openAIConfig);
const openAIModel = 'text-davinci-002';

const topic = 'Nuclear Fusion';
const title = 'Methodologies for nuclear fusion';

async function 
openAIgenerateHeadings(topic: string): Promise<string>
{
    let res;
    console.log('Generating headings on: ', topic);
    res = await sendOpenAICommand('Generate headings on: '+topic);
    return res;
}

async function 
openAIgenerateParagraph(title: string): Promise<string>
{
    let res;
    console.log('Generate paragraphs on: ', title);
    res = await sendOpenAICommand('Write an essey on: '+title);
    return res;
}

async function 
sendOpenAICommand(command: string): Promise<string>
{
    let res;
    res = await openAIEngine.createCompletion({
        model: openAIModel,
        prompt: command,
        max_tokens: 1024
    });
    return res.data.choices[0].text;
}

(async () => {
    let res: string;
    res = await openAIgenerateHeadings(topic);
    console.log(res);
    res = await openAIgenerateParagraph(title);
    console.log(res);
})();

Lets analyze the code above and see how this differs from what we previously did.

  • First the loading and initialization of the library is similar to the previous example that we did
  • Once the code initializes we implement two helper functions:
    • openAIgenerateHeadings: The headings function basically takes a command and generates some titles which we can later expand with the second helper function to write paragraphs on.
      • One thing we define here that’s important is a max token parameter that we previously did not use. By default OpenAI limits how much information it gives you back as a response. Since in the previous example length wasn’t an issue we were able to get away with the default value which at the time of this writing it is 256 tokens. In these examples since we need a lot more data to be returned to us in the form of an essay we will bump this value up to 1024. Note if you want longer content you can do this by adjusting accordingly higher just keep a note that currently there’s an upper limit of 4000 tokens per request.
      • We will be using our helper function the sendOpenAICommand we implemented in the previous example but in this case the command is slightly different to basically request headings instead of asking a question.
    • openAIgenerateParagraph:
      • This function works identical to the previous one but with the additional information that we slightly adjust what we ask for the OpenAI engine in our command prompt as it can be seen in the code.
  • Finally putting it all together we can take the response form the first command which gives us the heading on the topic we selected and pipe into our paragraphs section one by one and see what it gives back to us. To avoid chewing through my tokens here I basically gave it a random topic related to Nuclear Fusion, but you can easily use the string returned from the first one split it up by section and ask it to generate an essay.

The response for each comes in a very creative way by the OpenAI engine so lets see how this works by executing it.

$ OPENAI_API_KEY=REPLACE_WITH_YOUR_API_KEY yarn ts-node nodejs-openai-generate-article.ts

Generating headings on:  Nuclear Fusion

- The Energy of the Future
- How It Works
- The Benefits

Generate paragraphs on:  Methodologies for nuclear fusion power
The possibility of nuclear fusion has been a topic of scientific interest for over a century now. Even though it has been proven to be a viable source of energy, the challenge lies in harnessing it for practical purposes. There are many different approaches being researched in order to achieve this, each with its own advantages and disadvantages.
The most common approach to nuclear fusion is magnetic confinement. This involves using magnetic fields to confine the hot plasma that is required for fusion reactions. The most well-known example of this is the Tokamak. This approach has the potential to produce large amounts of energy, but the necessary technology is not yet well developed.
Another promising approach is inertial confinement. This uses high-powered lasers to compress and heat a small fuel pellet, causing fusion to occur. This has the advantage of being relatively simple and could be scaled up to provide power on a commercial scale. However, the technology is still in its early stages and needs further development.
A less well-known option is muon-catalyzed fusion. This uses muons, particles that are similar to electrons but heavier, to catalyze fusion reactions. This could potentially be a very efficient way to achieve fusion, but it is still in the early stages of research.
All of these different approaches to nuclear fusion have their own advantages and disadvantages. Ultimately, it is up to researchers to decide which one is most promising and worth pursuing.

As it can be seen above the first call gives us headings on basically Nuclear fusion. Those are the baseline to basically be expanded by the second question which is us asking the OpenAI engine to write methodologies for our nuclear fusion power section.

Checking the output above the result seems somewhat interesting. In this case since it’s a very well known and researched topic it has worked well but this is not always the case with OpenAI. Basically sometimes I found you need to give it very specific information on it to generate good titles for you and I can prove this with an example.

Lets take for example the keyword Apple. This can be translated by OpenAI in two different things:

  • Apple – The fruit
  • Apple – The technology company

Which one do you want it to give information about? It’s all dependent on the context you ask. But what if that context is also generated by the OpenAI engine from the headings we asked it. Well then you need to be explicit on your initial topic of selection so if you were to ask for headings lets say on Apple the technology company it will be less confusing to the OpenAI engine and it will be able to give you more targeted information.

As you can tell there’s a lot of gotchas that you get from experience on using AI technologies. The general rule for me is to be very specific or at least as specific as I possibly can initially without the use of AI.

Conclusion

We were able to go over this OpenAI NodeJS Full Guide in an easy to explain manner with examples. Hopefully, I answered any questions you may have and helped you get started on your quest to generating content automatically using JavaScript.

Please drop me a cheer below if you found this helpful and think it may have helped you. I would appreciate it.

If you have any questions or comments, please post them below or send me a note on my Twitter. I check periodically and try to answer them in the priority they come in. Also, if you have any corrections, please let me know, and I’ll update the article with new updates or mistakes I made.

Would you consider using NodeJS to interface with OpenAI or you prefer the OpenAI playground?

I use this extensively for many projects when I want to generate content, since I love Python I have implemented the same thing in Python in a more elaborate way you can check the link below about it. However I know a lot of my projects are written in NodeJS and Javascript so I had to port a lot of my code over. In this article I used the fundamentals for you to get started and implement your own OpenAI content.

If you would like to find more articles related to OpenAI and NodeJS:

You can find information about relevant projects referenced in this article in the list below:

Leave a Comment

Your email address will not be published. Required fields are marked *