我正在使用 Laravel Framework 10.15.0。
我尝试以以下方式加载我的API密钥:
$apiKeyOpenAI = env('OPENAI_API_KEY');
$client = OpenAI::client($apiKeyOpenAI);
在我的 .env 文件中,API密钥已经明确定义:
OPENAI_API_KEY=xx-xxxxxxxxxxxxxxxxxxxxxxx
然而,在服务器上执行我的应用程序时,我得到的 $apiKeyOpenAI 是null。
但是,我的 .env 文件中确实有 OPENAI_API_KEY。我已经检查过了!
我尝试清除缓存 php artisan config:clear ,但仍然出现错误:
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()
有什么建议我做错了吗?
感谢您的回复!
更新
在部署到服务器后,我需要运行此脚本以使其正常工作:
Route::get('/clear', function() {
Artisan::call('cache:clear');
Artisan::call('config:clear');
return "Cache, Config is cleared";
})->middleware(['auth', 'admin']);
在部署时,此脚本也会自动运行:
#!/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!" Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号