Newbie help needed using React app to call OpenAI API

Hi,
I am trying to create a simple react app to learn how to use OPenAI API.
I have a simple form that takes the input as a user query and then return the output in a JSON format.

When I try simple query like :
“give me JSON output of US software engineer salaries from 1990 to 2000 on a yearly basis”

I get this output:

{"id":"cmpl-70cgCqLnm0iohb9trpeWbKl2esyTZ","object":"text_completion","created":1680383040,"model":"text-davinci-003","choices":[{"text":"\n\n[\n  {\n    \"Year\": 1990,\n    \"","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":17,"completion_tokens":16,"total_tokens":33}}

It seems incomplete and not correct. Does anyone know what I might be doing wrong?

Here is my code:

import React, { useState } from 'react';
const ChatForm = () => {
  const [prompt, setPrompt] = useState('');
  const [response, setResponse] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();

    const requestOptions = {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`
      },
      body: JSON.stringify({ prompt })
    };

    const response = await fetch('https://api.openai.com/v1/engines/text-davinci-003/completions', requestOptions);
    const data = await response.json();
    setResponse(JSON.stringify(data));
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Enter a prompt:
        <input type="text" value={prompt} onChange={(event) => setPrompt(event.target.value)} />
      </label>
      <button type="submit">Submit</button>

      {response && (
        <div>
          <h2>Response</h2>
          <pre>{response}</pre>
        </div>
      )}
    </form>
  );
};

export default ChatForm;

I’d recommend to use OpenAI’s official node package on NPM. Guide for how to use it here. Looks like you are getting a response (the code below is your test response) but not sure what your prompt was?

"text":"\n\n[\n  {\n    \"Year\": 1990,\n    \""
1 Like

Thanks @Jofri I will look into the guide.
My prompt was this:
“give me JSON output of US software engineer salaries from 1990 to 2000 on a yearly basis”

Have you specified the number of tokens. It shouldn’t matter but try adding max_tokens = 4000 as an input parameter

1 Like