3

I am using Laravel Framework 10.15.0.

I am trying to load my API-Keys the following way:

        $apiKeyOpenAI = env('OPENAI_API_KEY');
        $client = OpenAI::client($apiKeyOpenAI);

In my .env file the api key is clearly defined:

OPENAI_API_KEY=xx-xxxxxxxxxxxxxxxxxxxxxxx

However, when executing my application on the server I get that the $apiKeyOpenAI is null.

Still my .env file has the OPENAI_API_KEY in it. I checked this!

I tried to clear my cache php artisan config:clear , I still get the error:


   TypeError 

  OpenAI::client(): Argument #1 ($apiKey) must be of type string, null given, called in /var/www/demo-website/app/Console/Commands/AdminCommand.php on line 151

  at vendor/openai-php/client/src/OpenAI.php:13
      9▕ {
     10▕     /**
     11▕      * Creates a new Open AI Client with the given API token.
     12▕      */
  ➜  13▕     public static function client(string $apiKey, string $organization = null): Client
     14▕     {
     15▕         return self::factory()
     16▕             ->withApiKey($apiKey)
     17▕             ->withOrganization($organization)

  1   app/Console/Commands/AdminCommand.php:151
      OpenAI::client()

  2   app/Console/Commands/AdminCommand.php:39
      App\Console\Commands\AdminCommand::generateContentUsingOpenAI()


Any suggesitons what I am doing wrong?

I appreciate your replies!

UPDATE

After deploying to the server I need to run this script so that it seems to work:

Route::get('/clear', function() {
    Artisan::call('cache:clear');
    Artisan::call('config:clear');

    return "Cache, Config is cleared";
})->middleware(['auth', 'admin']);

When deploying this script is also automatically run:

#!/bin/sh
set -e

echo "Deploying application ..."

# Enter maintenance mode
(php artisan down) || true
    # Update codebase
    git fetch origin deploy
    git reset --hard origin/deploy

    # Install dependencies based on lock file
    composer install --no-interaction --prefer-dist --optimize-autoloader

    # Migrate database
    php artisan migrate --force

    # Note: If you're using queue workers, this is the place to restart them.
    # ...


    # Clear cache
    # php artisan optimize

    php artisan config:cache
    php artisan route:clear
    php artisan route:cache
    php artisan view:clear
    php artisan view:cache
    php artisan auth:clear-resets
    php artisan cache:clear
    php artisan config:clear

    # Generate sitemap
    # php artisan sitemap:generate

    # Reload PHP to update opcache
    echo "" | sudo -S service php8.1-fpm reload
# Exit maintenance mode
php artisan up

echo "Application deployed!"

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • Have you tried to put the key BETWEEN double quote, because the key maybe contains whitespace or whatever. – Mahmoud Mohamed Ramadan Jul 30 '23 at 23:25
  • I recommend also using **dd()** method to check what is returning from `env()`. – Mahmoud Mohamed Ramadan Jul 30 '23 at 23:32
  • @MahmoudMohamedRamadan The `env()` is returning `null`. This is what I do not get.... – Carol.Kar Aug 03 '23 at 21:44
  • ```env()``` is not a native php function. is it a Laravel function? what is env()? (in vanilla PHP we use `getenv()`) – hanshenrik Aug 12 '23 at 05:19
  • @hanshenrik Yes, `env()` is a Laravel function: https://github.com/laravel/framework/blob/10.x/src/Illuminate/Support/helpers.php#L136. It does a similar thing to PHP's `getenv()`, which is fetch an Environment Variable, but the signature is slightly different; the 2nd param is a default if the variable is not defined, so in `.env`, `EXAMPLE=foo`, calling `env('EXAMPLE', 'bar')` would return `'foo'`, or `'bar'` if `EXAMPLE=` (or otherwise missing) – Tim Lewis Aug 12 '23 at 21:56
  • @Carol.Kar are you calling `$client = OpenAI::client($apiKeyOpenAI);` within you controller constructor or some other class? can you please show show how & where you are calling `OpenAI` class in your classes? – M-Khawar Aug 16 '23 at 05:58

2 Answers2

12

Don't use env() outside of files in config/*.php. If you ever run php artisan config:cache (which should typically be done on Production as you're doing), then env() will stop working outside of those files (for most situations; env keys can still be loaded, but that is not typical for most Laravel setups). This is the reason you're having to run php artisan config:clear for env() to not return null.

Add a Key to config/app.php (or any other file in config/):

'open_ai_api_key' => env('OPENAI_API_KEY', null)

Then, when you want to use this key, use the config() helper:

$apiKeyOpenAI = config('app.open_ai_api_key');
$client = OpenAI::client($apiKeyOpenAI);

Note: app is the filename, open_ai_api_key is the array index. If you use a different file, like config/services.php, then it would be config('services.open_ai_api_key')

See the Documentation for Details:

https://laravel.com/docs/10.x/configuration#configuration-caching

If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded; therefore, the env function will only return external, system level environment variables.

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • This is actually a fundamental design flaw of Laravel not separating configuration from code. Just for additional explanation and to highlight how right your warnings about that are. Using env() within configuration files is merely a convenience feature for development. – hakre Aug 18 '23 at 08:47
1

Firstly it is consider a bad practice to use env directly in your code instead use config helper just as the link suggested. Moreover according to laravel docs it's expected behavior for env() helper to give null, once you call the config:cache command, you can no longer use the env() helper as it will not be loaded.

but just in your case where you have used env helper in your code you can try below commands

php artisan optimize:clear

or

php artisan optimize

or

php artisan config:cache

or

php artisan config:clear

if these commands does not work then you can delete the config file manually via running the below command at project's root folder

rm bootstrap/cache/config.php

Saddam
  • 1,174
  • 7
  • 14