Laravel
Laravel stats
- Downloads
- 428.6K
- Stars
- 1,522
- Open Issues
- 6
- Forks
- 102
OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with the Open AI API
OpenAI PHP for Laravel
OpenAI PHP for Laravel is a powerful, community-maintained PHP API client tailored for Laravel users, enabling seamless integration with the OpenAI API. This tool is ideal for developers looking to utilize advanced AI features in their Laravel applications.
Key Features
- Easy Installation: Quickly install via Composer and publish the configuration with Laravel's artisan commands.
- Framework Integration: Directly integrates with Laravel, leveraging facades for simplified API usage.
- Environment Configuration: Configure your OpenAI credentials and settings in the Laravel environment or config files.
- Testing Support: Includes facilities to fake API responses and assert against expected API calls, which is great for development and testing environments.
Installation
-
Install with Composer:
composer require openai-php/laravel -
Publish Configuration File:
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"This step creates a
config/openai.phpfile which you can customize. -
Set API Key in
.env:OPENAI_API_KEY=sk-...
Usage Example
Utilize the OpenAI facade to interact with the OpenAI API:
use OpenAI\Laravel\Facades\OpenAI; $result = OpenAI::completions()->create([ 'model' => 'text-davinci-003', 'prompt' => 'PHP is',]); echo $result['choices'][0]['text']; // Outputs AI-generated text
Configuration Details
- API Key & Organization: Essential for API requests, settable in
.envor directly in the configuration file. - Request Timeout: Customizable timeout for API requests, default is 30 seconds.
Testing Facilities
The package provides a fake() method to mock API responses for testing:
use OpenAI\Laravel\Facades\OpenAI;use OpenAI\Responses\Completions\CreateResponse; OpenAI::fake([ CreateResponse::fake(['choices' => [['text' => 'awesome!']]]),]); $completion = OpenAI::completions()->create(['model' => 'text-davinci-003', 'prompt' => 'PHP is ']);expect($completion['choices'][0]['text'])->toBe('awesome!');
This package is a must-have for developers looking to leverage AI in their Laravel applications, providing robust tools for both development and production environments.