Can't connect to API in Angular

I have this error which appear and disappear time to time, but those days that’s every day :
You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://beta.openai.com.

And so my Angular application doesn’t work properly anymore.
Here is my call to the API :

try {
    const body = {
      "model": "text-davinci-003",
      "prompt": ask,
      "temperature": 0.7,
      "max_tokens": 10000,
      "top_p": 1,
      "frequency_penalty": 0.0,
      "presence_penalty": 0.0
    }
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${environment.OPENAI_SECRET_KEY}`
    });
    const completion: any = await this.http.post("https://api.openai.com/v1/completions", body, { headers }).toPromise();
    this.response = completion.choices[0].text as string;
    this.articleService.updateArticle(this.createdArticleId, this.generateText(this.response));
    console.log(completion);
    console.log(completion.choices[0].text);
  } catch (error: any) {
    if (error.response) {
      console.log(error.response.status);
      console.log(error.response.data);
    } else {
      console.log(error.message);
    }
    this.connectToAPI(ask, true);
  }

Before I was using the properly method with npm install of openai packages (which was working 1 time on 2), but today I changed for this way to have the APIKEY in the header, but that didn’t help…

If someone have an idea, I would be very great full, because I already watch many link on Google, but nothing did ! (and StackOverflow too)

1 Like

can you try api with beta
Beta completions

Please note that for this code to work, you will also need to import the HttpHeaders class from the @angular/common/http package and the environment file should be in the same directory as this file.

Example Only:

import { environment } from './environment';

Please make sure that the path to the environment file is correct, otherwise, the code will not be able to find the file and will throw an error.

Hello, thanks but your link sends to a 404 error

Yes, everything is well configured, I well import the environment and HttpHeaders !