Integrate the OpenAI library, set up your environment, and then execute the code.

Step 1. Set up your environment.

If Error: Follow these steps, highlighted or skip these steps

The error "File C:\Program Files\nodejs\npm.ps1 cannot be loaded because running scripts is disabled on this system" means your PowerShell execution policy is set to restrict script execution. To fix this, you need to temporarily change the execution policy to allow scripts to run, then change it back to a more restrictive setting for security.

Here's how to resolve it.

If No Error, continue these steps.

Step 2. Write your JavaScript code.

JavaScript

const OpenAI = require("openai");

require("dotenv").config();

Create an OpenAI client.

JavaScript

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

Interact with the OpenAI API.

JavaScript

async function runCompletion() {
  const completion = await openai.chat.completions.create({
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      {
        role: "user",
        content: "Translate the following English text to French: {your text here}",
      },
    ],
    model: "gpt-3.5-turbo",
  });

  console.log(completion.choices[0].message.content);
}

runCompletion();

Step 3. Run your code.

Run the JavaScript

How to get the API Keys?

https://platform.openai.com/api-keys

Log in to Chat GPT.

ChatGPT

Here's a more detailed breakdown.