Communicating with the API in vanilla js (no server side stuff)

Hey, new user here, so sorry if my question is bad or misunderstands something about the OpenAI API.

Is there any way of communicating with the OpenAI API in plain vanilla JavaScript without using node.js. If so, any tutorials out there?

Best
Andreas

1 Like

Thanks! Do you happen to know any tutorials or similar that you could point me to that show communication with the OpenAI API in plain vanilla JavaScript?

1 Like

hey just search fecth api in js

But to hide your Openai secret key you need to find something, and if you know let us know
and if you still find difficulty let us know

1 Like

Right, it is for a quick demo, so currently okay with not hiding the secret key. Of course I would need a solution for that later, but one thing at a time.

Fetch is what I am looking for, although. I still find it tricky, would there be some sample code to look at somewhere? Or could someone throw together a really basic example?

For instance, I can see that the CURL to communicate with openAI is:

curl https://api.openai.com/v1/engines/davinci/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "prompt": "", "temperature": 0.7, "max_tokens": 64, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0 }'

What would a fetch request look like for this?

function OpenaiFetchAPI() {
    console.log("Calling GPT3")
    var url = "https://api.openai.com/v1/engines/davinci/completions";
    var bearer = 'Bearer ' + YOUR_TOKEN
    fetch(url, {
        method: 'POST',
        headers: {
            'Authorization': bearer,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            "prompt": "Once upon a time",
            "max_tokens": 5,
            "temperature": 1,
            "top_p": 1,
            "n": 1,
            "stream": false,
            "logprobs": null,
            "stop": "\n"
        })


    }).then(response => {
        
        return response.json()
       
    }).then(data=>{
        console.log(data)
        console.log(typeof data)
        console.log(Object.keys(data))
        console.log(data['choices'][0].text)
        
    })
        .catch(error => {
            console.log('Something bad happened ' + error)
        });

}
3 Likes

Awesome, thanks so much :star_struck:
Really appreciate the help!

1 Like

Anyone could explain why this fails to parse json when streaming completion?

  /**
   * Stream OpenAI completion
   * @param{string} prompt
   * @param{any} parameters
   */
  async* streamCompletion(prompt: string,
      parameters: any): any {
    const r = await fetch(`${openAiEndpoint}/${parameters.model}/completions`, {
      method: "POST",
      body: JSON.stringify({
        "prompt": prompt,
        "temperature": parameters.temperature,
        "max_tokens": parameters.maxTokens,
        "top_p": parameters.topP,
        "frequency_penalty": parameters.frequencyPenalty,
        "presence_penalty": parameters.presencePenalty,
        "stop": parameters.stop,
        "stream": true,
      }),
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": `Bearer ${openAiKey}`,
      },
    });
    for await (const chunk of r.body) {
      console.log(chunk.toString());
      if (chunk.toString().includes("error")) throw Error(chunk.toString());
      if (chunk.toString().includes("DONE")) return;
      // Sometimes fail parsing JSON here :/
      const data = JSON.parse(chunk.toString().replace("data: ", ""));
      if (!data.choices || data.choices.length === 0) continue;
      yield data.choices[0].text;
    }
  }
1 Like

The parameters seem correct :confused:

{"topP":1,"presencePenalty":0.03,"stop":["\"\"\"","\"\""],"temperature":0.7,"maxTokens":1000,"model":"davinci","frequencyPenalty":0.07}}

Actually have several outputs and suddenly fail to parse JSON

Thanks a lot for this!

1 Like

No problem here to help if you need any help just ping me.

1 Like