Node.js: The requested module 'openai' does not provide an export named 'Configuration'

Hi guys,

My workflow was allright a few hours ago.
All I’ve changed is the number of “timeout”. Changed from 180 to 300.
Then this node of OpenAI (Node.js) failed.

SyntaxError: The requested module ‘openai’ does not provide an export named ‘Configuration’

Error: SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'
    at handleError (/var/task/common.js:38:40)
    at Runner.runUserCode (file:///var/task/lambda_handler.mjs:866:9)
    at async Runner.run (file:///var/task/lambda_handler.mjs:697:5)
    at async Runtime.handler (file:///var/task/lambda_handler.mjs:914:22)

part of my code

import { Configuration, OpenAIApi } from "openai"
import { encode, decode } from "gpt-3-encoder"

export default defineComponent({
  props: {
    openai: {
      type: "app",
      app: "openai",
    }
  },
  async run({steps, $}) {

    const language = steps.decide_language_fullname.$return_value
    const transcript = steps.create_transcription.$return_value.transcription
    const maxTokens = 2000

    const openAIkey = this.openai.$auth.api_key
    const configuration = new Configuration({
      apiKey: openAIkey,
    });
    const openai = new OpenAIApi(configuration);
...

Can someone please help?

Hi @ghiou123,

I’m sorry for the trouble you’re experiencing. It looks like you’re trying to use the openai package directly in your Pipedream component. Pipedream has a built-in integration with OpenAI, so you don’t need to import the openai package or use the Configuration and OpenAIApi classes.

Instead, you can use the @pipedream/platform package’s axios function to make API requests to OpenAI. Here’s an example of how you can modify your code:

import { axios } from "@pipedream/platform";

export default defineComponent({
  props: {
    openai: {
      type: "app",
      app: "openai",
    },
  },
  async run({ steps, $ }) {
    const language = steps.decide_language_fullname.$return_value;
    const transcript = steps.create_transcription.$return_value.transcription;
    const maxTokens = 2000;

    const openAIkey = this.openai.$auth.api_key;

    // Replace this with the appropriate OpenAI API endpoint and method
    const url = "https://api.openai.com/v1/your_endpoint";
    const method = "POST";

    const response = await axios($, {
      method,
      url,
      headers: {
        Authorization: `Bearer ${openAIkey}`,
      },
      // Add any required data for the API request
      data: {
        language,
        transcript,
        maxTokens,
      },
    });

    // Process the response as needed
    // ...
  },
});

Replace the url and method variables with the appropriate OpenAI API endpoint and HTTP method for your use case. Also, make sure to include any required data for the API request in the data property.

I hope this helps! If you have any further questions or need assistance, please let me know.
I’m a bot powered by Pipedream and GPT-4. I’m still learning, so please double check my answers and code! Learn how to build your own.

I called OpenAIApi.createChatCompletion function.
How do I call this function with your suggestion - using built in axios?

openai didn’t update their platform.openai.com but on GitHub,
refer to this: GitHub - openai/openai-node: The official Node.js / Typescript library for the OpenAI API

it no longer support ‘Configuration’ class,
instead, the code should be like below,

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: 'my api key', // defaults to process.env["OPENAI_API_KEY"]
});

Hey I’m having a similar problem, trying to get different types of written docs summarized, using the Thomas Frank method shared here: Summarize text from a PDF

I literally have no idea why this exact snippet of code:

import { Configuration, OpenAIApi } from "openai"
import { encode, decode } from "gpt-3-encoder"

export default defineComponent({
  props: {
    openai: {
      type: "app",
      app: "openai",
    }
  },
  async run({steps, $}) {

    // Import the transcript from the previous step
    const transcript = steps.Extract_pdf_text.$return_value

    // Set the max number of input tokens
    const maxTokens = 2000

    // Initialize OpenAI
    const openAIkey = this.openai.$auth.api_key
    const configuration = new Configuration({
      apiKey: openAIkey,
    });
    const openai = new OpenAIApi(configuration);

    // Split the transcript into shorter strings if needed, based on GPT token limit
    function splitTranscript(encodedTranscript, maxTokens) {
      const stringsArray = []
      let currentIndex = 0

      while (currentIndex < encodedTranscript.length) {
        let endIndex = Math.min(currentIndex + maxTokens, encodedTranscript.length)

        // Find the next period
        while (endIndex < encodedTranscript.length && decode([encodedTranscript[endIndex]]) !== ".") {
          endIndex++
        }

        // Include the period in the current string
        if (endIndex < encodedTranscript.length) {
          endIndex++
        }

        // Add the current chunk to the stringsArray
        const chunk = encodedTranscript.slice(currentIndex, endIndex)
        stringsArray.push(decode(chunk))

        currentIndex = endIndex
      }

      return stringsArray
    }

    const encoded = encode(transcript)

    const stringsArray = splitTranscript(encoded, maxTokens)
    const result = await sendToChat(stringsArray)
    return result

    // Function to send transcript string(s) to Chat API
    async function sendToChat (stringsArray) {

      const resultsArray = []

      for (let arr of stringsArray) {

        // Define the prompt
        const prompt = `Analyze the PDF text provided below, then provide the following:
Key "title:" - add a title.
Key "summary" - create a summary.
Key "main_points" - add an array of the main points. Limit each item to 100 words, and limit the list to 10 items.

Ensure that the final element of any array within the JSON object is not followed by a comma.

Transcript:
        
        ${arr}`

        let retries = 3
        while (retries > 0) {
          try {
            const completion = await openai.createChatCompletion({
              model: "gpt-3.5-turbo",
              messages: [{role: "user", content: prompt}, {role: "system", content: `You are an assistant that only speaks JSON. Do not write normal text.

Example formatting:

{
    "title": "Notion Buttons",
    "summary": "A collection of buttons for Notion",
    "main_points": [
        "item 1",
        "item 2",
        "item 3"
    ]
}
              `}],
              temperature: 0.2
            });

            resultsArray.push(completion)
            break
          } catch (error) {
            if(error.response && error.response.status === 500) {
              retries--
              if (retries == 0) {
                throw new Error("Failed to get a response from OpenAI Chat API after 3 attempts.")
              }
              console.log("OpenAI Chat API returned a 500 error. Retrying...")
            } else {
              throw error
            }
          }
        }

      }

      return resultsArray
    }

  },
})

No clue why this works in the case of doing the audio transcription, but when i try to PDF extraction it has the error

Error

SyntaxError: The requested module ‘openai’ does not provide an export named ‘Configuration’

I see your message above about ‘axios’ but no matter how many times I try to build, it fails.

Specifically talking about this code:
import { Configuration, OpenAIApi } from “openai”
import { encode, decode } from “gpt-3-encoder”

export default defineComponent({
props: {
openai: {
type: “app”,
app: “openai”,
}
},
async run({steps, $}) {

// Import the transcript from the previous step
const transcript = steps.Extract_pdf_text.$return_value

// Set the max number of input tokens
const maxTokens = 2000

// Initialize OpenAI
const openAIkey = this.openai.$auth.api_key
const configuration = new Configuration({
  apiKey: openAIkey,
});
const openai = new OpenAIApi(configuration);

// Split the transcript into shorter strings if needed, based on GPT token limit
function splitTranscript(encodedTranscript, maxTokens) {
  const stringsArray = []
  let currentIndex = 0

  while (currentIndex < encodedTranscript.length) {
    let endIndex = Math.min(currentIndex + maxTokens, encodedTranscript.length)

    // Find the next period
    while (endIndex < encodedTranscript.length && decode([encodedTranscript[endIndex]]) !== ".") {
      endIndex++
    }

    // Include the period in the current string
    if (endIndex < encodedTranscript.length) {
      endIndex++
    }

    // Add the current chunk to the stringsArray
    const chunk = encodedTranscript.slice(currentIndex, endIndex)
    stringsArray.push(decode(chunk))

    currentIndex = endIndex
  }

  return stringsArray
}

const encoded = encode(transcript)

const stringsArray = splitTranscript(encoded, maxTokens)
const result = await sendToChat(stringsArray)
return result

// Function to send transcript string(s) to Chat API
async function sendToChat (stringsArray) {

  const resultsArray = []

  for (let arr of stringsArray) {

    // Define the prompt
    const prompt = `Analyze the PDF text provided below, then provide the following:

Key “title:” - add a title.
Key “summary” - create a summary.
Key “main_points” - add an array of the main points. Limit each item to 100 words, and limit the list to 10 items.

Ensure that the final element of any array within the JSON object is not followed by a comma.

Transcript:

    ${arr}`

    let retries = 3
    while (retries > 0) {
      try {
        const completion = await openai.createChatCompletion({
          model: "gpt-3.5-turbo",
          messages: [{role: "user", content: prompt}, {role: "system", content: `You are an assistant that only speaks JSON. Do not write normal text.

Example formatting:

{
“title”: “Notion Buttons”,
“summary”: “A collection of buttons for Notion”,
“main_points”: [
“item 1”,
“item 2”,
“item 3”
]
}
`}],
temperature: 0.2
});

        resultsArray.push(completion)
        break
      } catch (error) {
        if(error.response && error.response.status === 500) {
          retries--
          if (retries == 0) {
            throw new Error("Failed to get a response from OpenAI Chat API after 3 attempts.")
          }
          console.log("OpenAI Chat API returned a 500 error. Retrying...")
        } else {
          throw error
        }
      }
    }

  }

  return resultsArray
}

},
})

Since they have updated the code from v3 to v4 in the github you shared I updated the code and it successfully runs… looks like this.

import OpenAI from ‘openai’;
import { encode, decode } from “gpt-3-encoder”;

export default defineComponent({
props: {
openai: {
type: “app”,
app: “openai”,
}
},
async run({steps, $}) {
const transcript = steps.Extract_pdf_text.$return_value;
const maxTokens = 2000;

const openAIkey = this.openai.$auth.api_key;
const openai = new OpenAI({
  apiKey: openAIkey
});

function splitTranscript(encodedTranscript, maxTokens) {
  const stringsArray = [];
  let currentIndex = 0;

  while (currentIndex < encodedTranscript.length) {
    let endIndex = Math.min(currentIndex + maxTokens, encodedTranscript.length);

    // Find the next period
    while (endIndex < encodedTranscript.length && decode([encodedTranscript[endIndex]]) !== ".") {
      endIndex++;
    }

    // Include the period in the current string
    if (endIndex < encodedTranscript.length) {
      endIndex++;
    }

    // Add the current chunk to the stringsArray
    const chunk = encodedTranscript.slice(currentIndex, endIndex);
    stringsArray.push(decode(chunk));

    currentIndex = endIndex;
  }

  return stringsArray;
}

const encoded = encode(transcript);
const stringsArray = splitTranscript(encoded, maxTokens);
const result = await sendToChat(stringsArray);
return result;

async function sendToChat(stringsArray) {
  const resultsArray = [];

  for (let arr of stringsArray) {
    const prompt = `Analyze the PDF text provided below, then provide the following:

Key “title:” - add a title.
Key “summary” - create a summary.
Key “main_points” - add an array of the main points. Limit each item to 100 words, and limit the list to 10 items.

Ensure that the final element of any array within the JSON object is not followed by a comma.

Transcript:

${arr}`;

    let retries = 3;
    while (retries > 0) {
      try {
        const completion = await openai.chat.completions.create({
          model: "gpt-3.5-turbo",
          messages: [{
            role: "user",
            content: prompt
          }, {
            role: "system",
            content: `You are an assistant that only speaks JSON. Do not write normal text.

Example formatting:

{
“title”: “Notion Buttons”,
“summary”: “A collection of buttons for Notion”,
“main_points”: [
“item 1”,
“item 2”,
“item 3”
]
}`
}],
temperature: 0.2
});

        resultsArray.push(completion.choices[0].message);
        break;
      } catch (error) {
        if (error instanceof OpenAI.APIError) {
          if (error.status === 500) {
            retries--;
            if (retries == 0) {
              throw new Error("Failed to get a response from OpenAI Chat API after 3 attempts.");
            }
            console.error("OpenAI Chat API returned a 500 error. Retrying...");
          }
        } else {
          console.log(error);
        }
      }
    }
  }

  return resultsArray;
}

},
});

1 Like