0

I'm trying to recreate an idea using OpenAI Api with react.

I'm using the official OpenAI Documentation here but got stuck and I'm hoping someone is able to help.

The idea is to have an simple text-input and a button on a page. Reciving the user's prompt and sending the information to the OpenAI Api.

OnClick to the button I'm handling everything within the handleSubmit function which looks like this:

const config = new Configuration({
    apiKey: "API_KEY_IS_HERE",
})

const handleSubmit = async (e) => {
    e.preventDefault()
    setState('loading...')
    
    const openai = new OpenAIAPI(config)
    const res = await openai.createImage({
      prompt: prompt,
      n: 1,
      size: "256×256",
    })

    const url = res.data.data[0].url
    console.log(url)
    console.log('clicked: ' + prompt)
}

which clicking the button and calling the function handleSubmit now I'm getting an error

Uncaught TypeError: openai__WEBPACK_IMPORTED_MODULE_1__.OpenAIAPI is not a constructor

besides putting the api key directly into the source code instead of env variables (testing and playing around locally) nothing seems out of the ordernary to me.

Thank you for any input!

edit:

imports:

import { useEffect, useState } from "react"
import { Configuration, OpenAIAPI } from "openai"

versions:

"openai": "^3.1.0"
"react": "^18.2.0"

1 Answer 1

1

It could be webpack complaining about how openai package is imported. Could you show us the lines of code that import.

Also it seems from a glance at the documentation that it is supposed to be:

OpenAIApi and not OpenAIAPI

Case matters :D

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, sorry for the missing info. aparently, that solved the issue and I'm now at my next error message ^^ thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.