0

I am using a Node/Javascript Wrapper for OpenAI's GPT3 API. The code below outputs GPT3's answer, which to these inputs is 'Sad.'

My question is, how can I set a global variable equal to GPT3's output. That is, instead of logging it on the console, how can I get the IIFE to either:

  • Create a global variable that I can access outside the function equal to the string output of gptResponse.data.answers[0].

OR

  • Change the value of an already defined global variable to gptResponse.data.answers[0].

I intend to use this string output to pass into other functions, and such need it to be accessible globally. But, unfortunately, no matter what I've tried I haven't been able to access this string output globally.

Thank you for your help!

(async () => {
    const gptResponse = await openai.answers({
      "documents": ["Puppy A is happy.", "Puppy B is sad."],
      "question": "which puppy is happy?",
      "search_model": "ada",
      "model": "curie",
      "examples_context": "In 2017, U.S. life expectancy was 78.6 years.",
      "examples": [["What is human life expectancy in the United States?", "78 years."]],
      "max_tokens": 5,
      "stop": ["\n", "<|endoftext|>"],
    });

    console.log(gptResponse.data.answers[0);
})();
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • how will you know that the global variable has changed - global variables should be avoided – Daniel A. White Jun 24 '21 at 19:56
  • Perhaps I didn't phrase my question correctly. I just want access to the string output of the function, outside of the function. I assumed setting it to a global variable would be the solution to this but perhaps not? – Marc Roube Jun 24 '21 at 20:06
  • A global variable is one way of doing it, but as @DanielA.White suggests, you won't know when that global variable is updated. The duplicate question's answers present other solutions; don't use an IIFE but rather an actual async function, and await that function's return value. Or call a callback function with the value you receive from your asynchronous call. – Heretic Monkey Jun 24 '21 at 20:13

0 Answers0