Using Javascript to get OpenAI to generate textarea content

55 Views Asked by At

Is there a simple way to get OpenAI to take a prompt from one text area and post the answer to another textarea using only html and javascript?

<html>
<body>
 <h1>OpenAI Text Generator</h1>

 <textarea id="prompt-text-field"></textarea>

 <button type="button" id="generate-text">Generate Text</button>

 <textarea id="response-text-field"></textarea>

 <script>
  // Create an OpenAI client
  const client = new OpenAI({
   apiKey: "YOUR_API_KEY",
   endpointURL: "https://api.openai.com/v1/engines"
  });

  // Add an event listener to the button
  document.getElementById("generate-text").addEventListener("click", async () => {
   // Get the text from the prompt
   const prompt = document.getElementById("prompt-text-field").value;

   // Generate the text
   const response = await client.createCompletion({
    engine: "davinci",
    prompt,
    maxTokens: 100
   });

   // Add the text to the response text field
   document.getElementById("response-text-field").value = response.choices[0].text;
  });
 </script>
</body>
</html>

I replaced the api key and tried this but it isn't working. Am I missing something?

0

There are 0 best solutions below