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

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