0
const gptResponse = await openai
      .createCompletion({
        model: "davinci",
        prompt,
        max_tokens: 60,
        temperature: 0.9,
        presence_penalty: 0,
        frequency_penalty: 0.5,
        best_of: 1,
        n: 1,
        stream: false,
        stop: ["\n", "\n\n"]
      })
      .catch((err) => {
        console.log(err); 

        return { data: { choices: [{ text: "" }] } };
      });

    const response = gptResponse.data.choices[0]?.text;

Why do I get the error 'gptResponse.data.choices' is possibly 'undefined'.ts(18048)?

wolfdmon
  • 1
  • 1
  • 1

3 Answers3

1

I did some investigation and found an answer to your question:

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

const configuration = new Configuration({
  apiKey: "your_key",
});
const openai = new OpenAIApi(configuration);

const response = openai.createCompletion({
  model: "text-davinci-002",
  prompt: "#JavaScript to Python:\nJavaScript: \ndogs = [\"bill\", \"joe\", \"carl\"]\ncar = []\ndogs.forEach((dog) >  temperature: 0",
  max_tokens: 64,
  top_p: 1.0,
  frequency_penalty: 0.0,
  presence_penalty: 0.0,
}).then((res) => {console.log(res.data.choices[0].text)});

Simply use .then()

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
GoatCedric
  • 11
  • 1
  • Same error 'res.data.choices' is possibly 'undefined'.ts(18048). When I use ? to prevent the error it says Property 'text' does not exist on type 'number[]'.ts(2339). – wolfdmon Oct 05 '22 at 12:28
1

Using express res.body(200).send({bot: response.data.choices[0].text})

app.post('/', async(req, res) => {
    try {
        const prompt = req.body.prompt
        const response = await openai.createCompletion({
            model: "text-davinci-003",
            prompt: `${prompt}`,
            temperature: 0,
            max_tokens: 1000,
            top_p: 1,
            frequency_penalty: 0.5,
            presence_penalty: 0,
        });
        res.body(200).send({
            bot: response.data.choices[0].text
        })
    } catch (error) {
        
    }
})
Lotpite
  • 336
  • 2
  • 4
0

I had a similar error where the system couldn't extract text from data.choices[0]. I had only in two cases, in the first case the start text was not set in the openai.createCompletion({promt: "text"}) settings, in the second case the openai.createCompletion({stream: true}) was turned on in true mode so text in data.choices[0] was separated broken into symbols and words.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31