openai-php / client

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
MIT License
4.6k stars 468 forks source link

Unable to access the API, apparently due to an authorization issue #208

Closed MastaBaba closed 10 months ago

MastaBaba commented 10 months ago

I use the following basic code:

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Load your project's composer autoloader (if you aren't already doing so).
require_once(__DIR__ . '/vendor/autoload.php');

$api_key = "{{key}}";

$yourApiKey = getenv($api_key);
$client = OpenAI::client($yourApiKey);

$result = $client->completions()->create([
    'model' => 'text-davinci-003',
    'prompt' => 'PHP is',
]);

echo $result['choices'][0]['text']; 

This results in the following error:

Fatal error: Uncaught OpenAI\Exceptions\ErrorException: 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://platform.openai.com/account/api-keys. in {{folder}}/openai/vendor/openai-php/client/src/Transporters/HttpTransporter.php:131 Stack trace: #0 {{folder}}/openai/vendor/openai-php/client/src/Transporters/HttpTransporter.php(57): OpenAI\Transporters\HttpTransporter->throwIfJsonError(Array, '{\n "error": ...') #1 {{folder}}/openai/vendor/openai-php/client/src/Resources/Completions.php(33): OpenAI\Transporters\HttpTransporter->requestObject(Object(OpenAI\ValueObjects\Transporter\Payload)) #2 {{folder}}/openai/index2.php(17): OpenAI\Resources\Completions->create(Array) #3 {main} thrown in {{folder}}/openai/vendor/openai-php/client/src/Transporters/HttpTransporter.php on line 131

What am I doing wrong?

The key I use I created a good hour ago.

pb30 commented 10 months ago

The error message is pretty clear. Do you have API key set as an environment variable? If not you’re overwriting the variable.

$api_key = "{{key}}";

$yourApiKey = getenv($api_key);
$client = OpenAI::client($yourApiKey);
gehrisandro commented 10 months ago

Hi @MastaBaba

I agree to @pb30. If you still think it is a problem with the package, do not hesitate to get back on this one.

MastaBaba commented 10 months ago

Thanks both.

Apologies for my being dim. I am not familiar with calling environment variables in PHP code.

But, also, doesn't this mean that what is in 'Get Started' actually lacks somehow setting an environment variable?

The following code works:

$api_key = "{{key}}";
$client = OpenAI::client($api_key);

$result = $client->completions()->create([
    'model' => 'text-davinci-003',
    'prompt' => 'PHP is',
]);

echo $result['choices'][0]['text']; 

Thanks