Getting Started with the OpenAI API and Node.js/JavaScript

This is a growing collection of tutorials for learning how to use the OpenAI API with Node.js/JavaScript. If you’re new to programming (or new to Node) and want to learn how to use Node.js/JavaScript with the OpenAI API - hopefully these tutorials will help.

Tutorials

Stay tuned - more to come!

21 Likes

I love how simple it is to get started with the OpenAI API using the Playground. But if you want to go beyond the Playground you’re going to need to write some code. If you’re not a programmer, that might seem intimidating. But no worries, learning to use the API in code is easier than you might think.

Over the coming weeks, I plan to post as many Node.js/JavaScript examples as possible. I’m also going to provide code examples with as few lines as possible to keep it easy to follow. If you have any specific examples you’d like to see, let me know. If you have any questions, post them here and I’ll try my best to answer them as quickly as possible. Lastly, no question is too basic. The goal here is to make getting started as comfortable, easy, and hopefully fun!

What you’ll need

I’ll be doing all the examples in replit.com and they’ll be posted here. If you’re not familiar with Replit.com it’s on online code editor and development environment that runs 100% in your browser. So, it’s super simple to get start with and there is no software to install or configure. So, the only thing you really need is your OpenAI API Key.

9 Likes

Getting Started with Replit.com and Node.js for calling the OpenAI API

To create a simple node.js app that calls the OpenAI API using Replit.com complete the following steps:

  1. Create an account on Replit.com if you don’t have one already. The free account is all you need.

  2. Create a new Node.js repl (projects are called repls on replit.com) and name it openai-examples-node.

  3. Add your OpenAI API key as an environment variable by doing the following:

    • Click on the Secrets icon on the left menu (the padlock)

    • Enter OPENAI_API_KEY in the key field

    • Enter your OpenAI API key in the value field

    • CLick the Add new secret button

    IMPORTANT: Using environment variable keeps your API key private. The code will get the key value from an environment variable. This is important because your OpenAI API Key should never be shared. To learn more about using secrets / environment variables in a repl see the documentation.

  4. Create a new file named index.js and copy the following code into it.

const axios = require('axios');
const apiKey = process.env.OPENAI_API_KEY;
const client = axios.create({
    headers: { 'Authorization': 'Bearer ' + apiKey }
});

const params = {
  "prompt": "Once upon a time", 
  "max_tokens": 10
}

client.post('https://api.openai.com/v1/engines/davinci/completions', params)
  .then(result => {
    console.log(params.prompt + result.data.choices[0].text);
}).catch(err => {
  console.log(err);
});
  1. Create or open a file named .replit and add or update it with the following.
language = "nodejs"
run = "node index.js"

NOTE: The .replit file is used to define what happens when the Run button is clicked in the Replit.com IDE. In this example we’ve set it to run the index.js file using node.

  1. Click the ‘Run’ button in the replit.com IDE (on the top of the editor) and view the results.

The code in the file index.js calls the OpenAI completions endpoint with the prompt Once upon a time. The response from the API will show up in the console pane of the Replit.com IDE.

That’s it! You just coded your first Node.js app that calls the OpenAI API. This is a simple first example but stay tuned - more to come.

For qustions about this example or any getting started question you can post them in the OpenAI Community Forum here.

6 Likes

Content Filtering

This is a super quick example/tutorial for implementing content filtering with the OpenAI API and Node.js/JavaScript. This is just the very basics. I’ll follow up with an example that is a bit more real-world.

NOTE: This tutorial is part of a series. If you have not read the getting started post you should check that one out first.

Steps

  1. log in to Replit.com
  2. Open the openai-examples-node repl that you created in the getting started tutorial.
  3. Create a new file named filter.js
  4. Copy the following code into the filter.js file.
const axios = require('axios');

const input = "What religion are you?";

const params = JSON.stringify({
  "prompt": `<|endoftext|>${input}\n--\nLabel:`,
  "max_tokens": 1,
  "temperature": 0,
  "top_p": 0
});

const config = {
  method: 'post',
  url: 'https://api.openai.com/v1/engines/content-filter-alpha-c4/completions',
  headers: { 
    'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`, 
    'Content-Type': 'application/json'
  },
  data : params
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});
  1. Update the .replit file with the following
language = "nodejs"
run = "node filter.js"
  1. Review the results in the console pane. You should see a result similar to the following example.
{
    "id":"cmpl-2mAPQo53gUzavAtWFBRiTaJIU3uN8",
    "object":"text_completion",
    "created":1617832432,
    "model":"toxicity-double-18",
    "choices":[{"text":"1","index":0,"logprobs":null,"finish_reason":"length"}]
}

The choices array in the json response contains the results from the content filter. In the example above, the text value is 1. The value could be one of the following:

0 – Safe – Nothing about the text seems potentially offensive or unsafe
1 – Sensitive - Sensitive topics might include text with, political, religious, race, or nationality related content.
2 – Unsafe - The text contains language that some would consider mean, hurtful, explicit, offensive, profane, prejudiced, or hateful. Or language that most would consider NSFW (Not Safe for Work), or language that might portray certain groups/people in a harmful manner.

That’s it for now. Let me know if you have any questions.

For details about content filtering see the OpenAI docs here.

3 Likes

This is awesome, @stevet, thank you!!

2 Likes

Thanks, @bram! more to come over the next few days.

3 Likes

Simple Search

Here is a super simple example of how to call the search endpoint usng Node.js/JavaScript. For details about the search endpoint see the OpenAI Docs.

NOTE: This tutorial is part of a series. If you have not read the getting started post you should check that one out first.

Steps

  1. log in to Replit.com
  2. Open the openai-examples-node repl that you created in the getting started tutorial.
  3. Create a new file named simple-search.js
  4. Copy the following code into the simple-search.js file.
const axios = require('axios');
const apiKey = process.env.OPENAI_API_KEY;
const client = axios.create({
  headers: { 'Authorization': 'Bearer ' + apiKey }
});

const params = {
  "documents": ["plane", "boat", "spaceship", "car"],
  "query": "A vehicle with wheels"
}

client.post('https://api.openai.com/v1/engines/davinci/search', params)
  .then(result => {
    console.log(result.data);
  }).catch(err => {
    console.log(err);
  });

  1. Update the .replit file with the following
language = "nodejs"
run = "node simple-search.js"
  1. Review the results in the console pane. You should see a result similar to the following example.
{
  object: 'list',
  data: [
    { object: 'search_result', document: 0, score: 57.427 },
    { object: 'search_result', document: 1, score: 46.697 },
    { object: 'search_result', document: 2, score: 93.986 },
    { object: 'search_result', document: 3, score: 179.054 }
  ],
  model: 'davinci:2020-05-03'
}

The params object contains an array of documents and a query string. The search endpoint ranks the documents by how semantically similar they are to the query. The results contain an array of objects with a reference to each document (0 = the first document - plane in our example) and a score. The highest score for our example is document 3 (car) which makes sense because the query was A vehicle with wheels.

Let me know if you have any questions!

1 Like

Thanks @stevet! I’m wrapping my head around GPT-3 as a web developer and these examples are very helpful. Thank you very much for sharing. :+1:

1 Like

Thanks for the comment @rich! If you have any questions as you get into it let me know and I’ll do my best to help.

1 Like

I found some issue with the API when i tried using in the post request you have .

client.post(‘https://api.openai.com/v1/engines/davinci/completions’, completionParmas) …

Shouldnt this be params as that is the name you defined? So it should be

client.post(‘https://api.openai.com/v1/engines/davinci/completions’, params) …

I changed the name to params and it worked fine.

1 Like

Hey @Steph you’re right! Typo that slipped by me. I fixed it in the example code. Thanks so much for pointing that out!

1 Like

Also if you are trying out this using a simple js file with no backend. Axion is globally defined once you add their cdn script on your html

You need to include this before the line where you are importing your js file

Then you really dont need to add this
const axios = require(‘axios’);

Just comment it out and all works well.

Hope this helps

1 Like

Thanks again, @Steph good point/suggestion.

Classifications Endpoint

This example show how to call the classifications endpoint using using Node.js/JavaScript. For details about the classifications endpoint see the OpenAI Docs.

NOTE: This tutorial is part of a series. If you have not read the getting started post you should check that one out first.

Steps

  1. log in to Replit.com
  2. Open the openai-examples-node repl that you created in the getting started tutorial.
  3. Create a new file named classifications-endpoint.js
  4. Copy the following code into the classifications-endpoint.js file.
const axios = require('axios');
const examples = [
                  ["The service was super quick. I love that.","Good"],
                  ["Would not go back.","Poor"],
                  ["I tried the chicken and cranberry pizza...mmmm!","Good"],
                  ["There were no signs indicating cash only!","Poor"],
                  ["I was disgusted. There was a hair in my food.","Poor"],
                  ["The waitress was a little slow but friendly.","Neutral"]
                ]

const client = axios.create({
  headers: {
    'Authorization': 'Bearer ' + process.env.OPENAI_API_KEY
  }
});

const endpoint = "https://api.openai.com/v1/classifications";

const params = {
  "query": "I'm never going to this place again",
  "examples": examples,
  "model": "curie"
}

client.post(endpoint, params)
  .then(result => {
    console.log(params.query + '\nLABEL:' + result.data.label);
  }).catch(err => {
    console.log(err);
  });

  1. Update the .replit file with the following
language = "nodejs"
run = "node classifications-endpoint.js"
  1. Review the results in the console pane. You should see a result similar to the following example.
I'm never going to this place again
LABEL:Poor

The examples array is being used for the example classifications. You can change the examples and labels in that array, along with the query to try different classifications.

Let me know if you have any questions!

1 Like

File Upload

This example show how to upload a jsonl file to the Files endpoint using using Node.js/JavaScript. This example is posting a file for the classifications endpoint. You can change the file purpose in step 2 of the code below. The purpose can be, search, answers, or classifications. See the see the OpenAI Docs for details.

For the example code to work, you’ll also need to create a file named reviews.jsonl and add data for the classifications endpoint. Here is some sample data you can use for testing.


{"text": "i love this place", "label": "Good", "metadata": {"id":"1"}}

{"text": "i hate this place", "label": "Poor", "metadata": {"id":"2"}}

{"text": "i have no opinion", "label": "Neutral", "metadata": {"id":"3"}}

NOTE: This tutorial is part of a series. If you have not read the getting started post you should check that one out first.

Steps

  1. log in to Replit.com

  2. Open the openai-examples-node repl that you created in the getting started tutorial.

  3. Create a new file named file-upload.js

  4. Copy the following code into the file-upload.js file.


// 1. Require a few libraries that will be used

const fs = require('fs');

const axios = require('axios');

const FormData = require('form-data');

// 2. Get the data file ready for the http post

const data = new FormData();

data.append('purpose', 'classifications');

data.append('file', fs.createReadStream('reviews.jsonl'));

// 3. Set http request parameters for axios

const params = {

method: 'post',

url: 'https://api.openai.com/v1/files',

headers: {

'Authorization': 'Bearer ' + process.env.OPENAI_API_KEY,

...data.getHeaders()

},

data : data

};

// 4. Call the openai api and log results to the console

axios(params)

.then(function (response) {

console.log(JSON.stringify(response.data));

})

.catch(function (error) {

console.log(error);

});

  1. Update the .replit file with the following

language = "nodejs"

run = "node file-upload.js"

  1. Review the results in the console pane. You should see a result similar to the following example.

{
  "id":"file-ZMHNItHRzrkYbIf19mutOvlR",
  "object":"file",
  "bytes":215,
  "created_at":1618832808,
  "filename":"reviews.jsonl",
  "purpose":"classifications",
  "status":"uploaded",
  "status_details":null
}

The id value is what you’ll need from the response to use the file with the search, classifications, or answers endpoint.

Let me know if you have any questions!

4 Likes

Really amazing work here @stevet

2 Likes

Hi @m-a.schenk - that is a very good point and one I need to make clearer. The .replit file is used to create an entry point for the app with a run command for example:

run = "node index.js"

If your .replit file contained the previous command and your index.js file called the API using a key stored as an environment variable - YES the request will use your key.

However, only the file referenced in the run command within the .replit file can be run on a public REPL. So, I would recomend making sure that the run command in the .replit file dosen’t contain code that calls the API (other than when you’re testing), or sign up for a Replit.com paid account that lets you have private repls. I think that is like $7/month.

Thanks again for bringing this up - it’s a very important point and I’m going to clarify that in the post about using replit.

1 Like

My pleasure and no worries at all. Having an input for the API key that doesn’t store the value might be a good way to go.

1 Like

Looks like replit.com has changed the behavior on how the repl works now. Seems they don’t run with env variables you setup anymore unless you’re sharing an application.

thanks this helps a lot

1 Like