1

I am getting an error for the following PHP code:

$curl = curl_init("https://api.openai.com/v1/engines/davinci/completions");

$data = array(
  'prompt' => 'how many sundays in 2023',
  'max_tokens' => 256,
  'temperature' => 0.7,
  'model' => 'text-davinci-003'
);

curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer sk-MY-API-KEY']);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$result = curl_exec($curl);
curl_close($curl);

$result = json_decode($result);
print $result->choices[0]->text;

I correctly provided the API Key, but getting this error:

Error message: 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)

Rok Benko
  • 14,265
  • 2
  • 24
  • 49
Susan
  • 13
  • 6

1 Answers1

0

All Engines endpoints are deprecated.

Deprecated

This is the correct Completions endpoint:

https://api.openai.com/v1/completions

Working example

If you run test.php the OpenAI API will return the following completion:

string(23) "

This is indeed a test"

test.php

<?php
    $ch = curl_init();

    $url = 'https://api.openai.com/v1/completions';

    $api_key = 'sk-xxxxxxxxxxxxxxxxxxxx';

    $post_fields = '{
        "model": "text-davinci-003",
        "prompt": "Say this is a test",
        "max_tokens": 7,
        "temperature": 0
    }';

    $header  = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ];

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    curl_close($ch);

    $response = json_decode($result);
    var_dump($response->choices[0]->text);
?>
Rok Benko
  • 14,265
  • 2
  • 24
  • 49
  • Changed the URL as you suggested, but still getting this error: "message": "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), "type": "invalid_request_error", – Susan Jan 23 '23 at 14:03
  • *Start experimenting with $18 in free credit that can be used during your first 3 months.* – Rok Benko Jan 23 '23 at 14:11
  • I have enough credits and my API key is correct and active. But still it doesn't work. – Susan Jan 23 '23 at 14:22
  • What if you revoke the current and issue a new API key? – Rok Benko Jan 23 '23 at 14:29
  • Also, see: https://stackoverflow.com/questions/75050771/php-curl-open-ai-remove-the-quotes-from-post-data. – Rok Benko Jan 23 '23 at 14:38