Search code examples
node.jsopenai-api

Run OpenAI API document example in Node: where do I put sample code?


Objective: HTML input form that sends a prompt to openai's API and returns a message.

Completed Successfully:

  • Form on page that calls the route /api
  • Post endpoint defined in a routes file: 'api.js'
  • Endpoint returns to the web page the expected success message ({msg:"hello world"}).

Dev Environment:

  • I am using Express with no framework (the example on openai is React, which I npm installed and worked successfully, but now I want to add openai to my existing project).

Question: How do I call openai?

Per the documentation page: https://beta.openai.com/docs/api-reference/authentication

Step 1: npm install openai

Step 1 completed: The openai folder is in the node_modules folder, as expected.

Step 2 in docs:

import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
    organization: "org-sdfds34dsf",
    apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.listEngines();

Step 2 questions

  • Where do I put this code? If I put it in the route, I get a: SyntaxError: Cannot use import statement outside a module error
  • How do I trigger running the openai API endpoint call from within my route?

Solution

  • I think problem is how you are importing modules

    Use

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

    Instead of

    import { Configuration, OpenAIApi } from "openai";