Skip to main content

Using replit.com

The examples here access GPT-3 by making requests to the OpenAI API. They are written in Javascript and need a Node.js environment to run. We'll be using replit.com for the runtime environment and we'll start by creating a simple node app.

Create a Simple Node.js App

To create a simple node.js app on 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). Name the repl openai-examples-node.

  3. Create a new file named .env. and add the following to it.

    OPENAI_API_KEY=replace_with_your_openai_api_key

    IMPORTANT: The purpose of the .env file is to keep 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 environment variables in a repl see the replit.com documentation.

  4. Replace the text replace_with_your_openai_api_key in the .env file with your OpenAI API key.

  5. 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);
    });
  6. 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.

  7. 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. Congrats!

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

References