Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Laravel Package

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+.

View on GitHub
Deep Wiki
Context7
## 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-...
  1. 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;
    
  2. Key Facades: The package provides facades for all major OpenAI endpoints:

    • chat() → Chat completions
    • completions() → Legacy completions
    • edits() → Edits
    • images() → Image generation
    • audio() → Audio processing
    • files() → File management
    • fineTuning() → Fine-tuning
    • models() → Model management
    • embeddings() → Embeddings
    • realtime() → Realtime APIs
    • responses() → Responses API (beta)
    • conversations() → Conversations API (beta)

Implementation Patterns

1. Service Layer Integration

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?

  • Keeps API calls out of controllers.
  • Easier to mock in tests.
  • Centralizes error handling (e.g., rate limits, API failures).

2. Streaming Responses

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:

  • Live chat interfaces.
  • Progress indicators for long-running tasks.

3. Error Handling

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.

4. Testing with Fakes

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';
});

5. Configuration Management

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

6. Rate Limit Handling

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++;
    }
}

7. Async Processing

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:

  • Long-running tasks (e.g., fine-tuning).
  • Background processing for user requests.

Gotchas and Tips

1. API Key Security

  • Gotcha: Hardcoding OPENAI_API_KEY in code or version control.
  • Fix: Always use .env and add it to .gitignore.
  • Tip: Restrict API keys to specific IP addresses in OpenAI dashboard.

2. Rate Limits

  • Gotcha: Unhandled RateLimitException crashes applications.
  • Tip: Implement retry logic with exponential backoff (see Pattern 6).
  • Debugging: Check X-RateLimit-* headers in responses.

3. Model Availability

  • Gotcha: Using deprecated or non-existent models (e.g., gpt-4 before release).
  • Fix: Validate models against OpenAI’s official list.
  • Tip: Use OpenAI::models()->list() to fetch available models dynamically.

4. Streaming Quirks

  • Gotcha: Streaming responses may truncate or duplicate chunks.
  • Fix: Buffer chunks and validate structure:
    $buffer = '';
    foreach ($response as $chunk) {
        $buffer .= $chunk->choices[0]->delta->content;
    }
    
  • Tip: Use stream parameter only for real-time use cases.

5. Testing Pitfalls

  • Gotcha: Forgetting to reset fakes between tests.
  • Fix: Use OpenAI::fake([]) to clear fakes or wrap tests in beforeEach.
  • Tip: Prefer assertSent for verifying API calls over response assertions.

6. Configuration Overrides

  • Gotcha: Config changes not reflecting in runtime.
  • Fix: Clear Laravel cache after config changes:
    php artisan config:clear
    
  • Tip: Use config('openai.timeout') in code for dynamic access.

7. Laravel Version Compatibility

  • Gotcha: Using unsupported Laravel versions (e.g., Laravel 10 with v0.19+).
  • Fix: Check changelog for supported versions.
  • Tip: Pin openai-php/laravel version in composer.json for stability.

8. Error Debugging

  • Gotcha: Cryptic error messages from OpenAI API.
  • Tip: Log raw responses for debugging:
    try {
        $response = OpenAI::chat()->create([...]);
    } catch (OpenAIException $e) {
        \Log::error('OpenAI Error:', [
            'status' => $e->getStatusCode(),
            'response' => $e->getResponse()->getBody(),
        ]);
        throw $e;
    }
    

**9. Performance

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle