openai-php/laravel
Laravel integration for the OpenAI PHP client. Provides config, install command, and an OpenAI facade to call the OpenAI API (Responses, chat, etc.) from Laravel apps. Requires PHP 8.2+.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require openai-php/laravel
php artisan openai:install
This generates config/openai.php and adds .env variables:
OPENAI_API_KEY=sk-...
OPENAI_ORGANIZATION=org-...
First API Call:
Use the OpenAI facade to interact with OpenAI endpoints:
use OpenAI\Laravel\Facades\OpenAI;
$response = OpenAI::chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'user', 'content' => 'Hello!'],
],
]);
echo $response->choices[0]->message->content;
Key Facades: The package provides facades for all major OpenAI endpoints:
chat() → Chat completionscompletions() → Legacy completionsedits() → Editsimages() → Image generationaudio() → Audio processingfiles() → File managementfineTuning() → Fine-tuningmodels() → Model managementembeddings() → Embeddingsrealtime() → Realtime APIsresponses() → Responses API (beta)conversations() → Conversations API (beta)Pattern: Use a dedicated service class to encapsulate OpenAI logic.
namespace App\Services;
use OpenAI\Laravel\Facades\OpenAI;
class ChatService {
public function generateResponse(string $prompt, string $model = 'gpt-3.5-turbo'): string {
$response = OpenAI::chat()->create([
'model' => $model,
'messages' => [['role' => 'user', 'content' => $prompt]],
]);
return $response->choices[0]->message->content;
}
}
Why?
Pattern: Handle streaming responses for real-time use cases (e.g., chatbots).
$response = OpenAI::chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [['role' => 'user', 'content' => 'Explain Laravel']],
'stream' => true,
]);
foreach ($response as $chunk) {
echo $chunk->choices[0]->delta->content;
}
Use Case:
Pattern: Centralize error handling in a middleware or service.
use OpenAI\Exceptions\OpenAIException;
try {
$response = OpenAI::chat()->create([...]);
} catch (OpenAIException $e) {
if ($e->getStatusCode() === 429) {
// Retry or notify user
return response()->json(['error' => 'Rate limit exceeded'], 429);
}
throw $e;
}
Key Exceptions:
OpenAIException: Base exception.RateLimitException: For 429 errors.AuthenticationException: For 401/403 errors.Pattern: Mock API responses in tests.
use OpenAI\Laravel\Facades\OpenAI;
use OpenAI\Responses\Chat\CreateResponse;
public function test_chat_response() {
OpenAI::fake([
CreateResponse::fake([
'choices' => [
['message' => ['content' => 'Test response']],
],
]),
]);
$response = OpenAI::chat()->create([...]);
expect($response->choices[0]->message->content)->toBe('Test response');
}
Assertions:
OpenAI::assertSent(function ($method, $parameters) {
return $method === 'create' && $parameters['model'] === 'gpt-3.5-turbo';
});
Pattern: Override defaults via .env or config file.
OPENAI_API_KEY=your_key
OPENAI_BASE_URL=https://custom-api.openai.com/v1 # For private endpoints
OPENAI_REQUEST_TIMEOUT=60 # Increase timeout for large requests
Dynamic Config:
config(['openai.timeout' => 60]); // Override in runtime
Pattern: Implement exponential backoff for retries.
use OpenAI\Exceptions\RateLimitException;
$attempts = 0;
$maxAttempts = 3;
$delay = 1; // seconds
while ($attempts < $maxAttempts) {
try {
$response = OpenAI::chat()->create([...]);
break;
} catch (RateLimitException $e) {
if ($attempts === $maxAttempts - 1) throw $e;
sleep($delay);
$delay *= 2;
$attempts++;
}
}
Pattern: Use Laravel Queues for non-blocking calls.
use OpenAI\Laravel\Facades\OpenAI;
use Illuminate\Support\Facades\Queue;
Queue::push(function () {
$response = OpenAI::chat()->create([...]);
// Store result in DB or notify user
});
Use Case:
OPENAI_API_KEY in code or version control..env and add it to .gitignore.RateLimitException crashes applications.X-RateLimit-* headers in responses.gpt-4 before release).OpenAI::models()->list() to fetch available models dynamically.$buffer = '';
foreach ($response as $chunk) {
$buffer .= $chunk->choices[0]->delta->content;
}
stream parameter only for real-time use cases.OpenAI::fake([]) to clear fakes or wrap tests in beforeEach.assertSent for verifying API calls over response assertions.php artisan config:clear
config('openai.timeout') in code for dynamic access.openai-php/laravel version in composer.json for stability.try {
$response = OpenAI::chat()->create([...]);
} catch (OpenAIException $e) {
\Log::error('OpenAI Error:', [
'status' => $e->getStatusCode(),
'response' => $e->getResponse()->getBody(),
]);
throw $e;
}
How can I help you explore Laravel packages today?