Weave 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

Openai Php Client Laravel Package

agence-gw/openai-php-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require agence-gw/openai-php-client
    

    Add the service provider in config/app.php:

    'providers' => [
        // ...
        AgenceGw\Openai\OpenaiServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="AgenceGw\Openai\OpenaiServiceProvider"
    

    Update .env with your OpenAI API key:

    OPENAI_API_KEY=your_api_key_here
    
  3. First Use Case: Chat Completion

    use AgenceGw\Openai\Facades\Openai;
    
    $response = Openai::chat()->create([
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'user', 'content' => 'Hello, how are you?'],
        ],
    ]);
    
    echo $response['choices'][0]['message']['content'];
    

Key Entry Points

  • Facade: Openai::chat(), Openai::completions(), Openai::embeddings(), etc.
  • Config: config/openai.php (API key, base URL, timeout, etc.).
  • Logging: Enable via OPENAI_LOG_RESPONSES=true in .env.

Implementation Patterns

Common Workflows

1. Chat Completions with Streaming

$response = Openai::chat()->create([
    'model' => 'gpt-3.5-turbo',
    'messages' => [...],
    'stream' => true,
]);

foreach ($response as $chunk) {
    echo $chunk['choices'][0]['delta']['content'];
}

2. Embeddings for Semantic Search

$embeddings = Openai::embeddings()->create([
    'model' => 'text-embedding-ada-002',
    'input' => ['Your text here', 'Another text'],
]);

// Store embeddings in a database (e.g., PostgreSQL with vector support)

3. Error Handling

try {
    $response = Openai::completions()->create([...]);
} catch (\AgenceGw\Openai\Exceptions\OpenaiException $e) {
    // Handle rate limits, invalid requests, etc.
    logger()->error($e->getMessage());
}

4. Integration with Laravel Jobs

use AgenceGw\Openai\Facades\Openai;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;

class GenerateSummaryJob implements ShouldQueue
{
    use Queueable;

    public function handle()
    {
        $response = Openai::chat()->create([
            'model' => 'gpt-4',
            'messages' => [
                ['role' => 'system', 'content' => 'Summarize the following text.'],
                ['role' => 'user', 'content' => $this->text],
            ],
        ]);
        // Save summary to DB
    }
}

5. Customizing Requests

Override default headers or URLs via config:

// config/openai.php
'headers' => [
    'Authorization' => 'Bearer ' . env('OPENAI_API_KEY'),
    'Custom-Header' => 'Value',
],
'base_url' => env('OPENAI_CUSTOM_BASE_URL', 'https://api.openai.com/v1'),

Integration Tips

Laravel Ecosystem

  • Caching Responses: Cache frequent queries (e.g., embeddings) using Laravel's cache:

    $cacheKey = 'embeddings_' . md5($input);
    $embeddings = cache()->remember($cacheKey, now()->addHours(1), function () use ($input) {
        return Openai::embeddings()->create(['input' => $input]);
    });
    
  • Queue Long-Running Tasks: Offload expensive API calls (e.g., fine-tuning) to queues:

    dispatch(new FineTuneJob($dataset));
    
  • Testing: Use mocks with Laravel's HTTP testing:

    $response = $this->post('/api/generate', ['text' => 'Test']);
    $response->assertJson(['summary' => '...']);
    

Performance

  • Batch Processing: For bulk embeddings, use chunked requests to avoid rate limits.
  • Async Processing: Use Laravel Horizon to monitor queued OpenAI jobs.

Gotchas and Tips

Pitfalls

  1. Rate Limits

    • OpenAI enforces strict rate limits (e.g., 60 requests/minute for gpt-3.5-turbo).
    • Solution: Implement exponential backoff or use queues to space out requests.
    • Debugging: Check X-RateLimit-* headers in responses.
  2. Model Availability

    • Not all models are available in all regions or at all times.
    • Solution: Validate the model exists before calling:
      $models = Openai::models()->list();
      if (!in_array('gpt-4', $models['data'])) {
          throw new \RuntimeException('Model gpt-4 not available');
      }
      
  3. Token Limits

    • Exceeding token limits (e.g., 4096 for gpt-3.5-turbo) returns truncated responses.
    • Solution: Use max_tokens and validate input length:
      $tokenCount = str_word_count($text) / 4; // Approximate
      if ($tokenCount > 3000) {
          throw new \InvalidArgumentException('Input too long');
      }
      
  4. Streaming Quirks

    • Streaming responses may end abruptly or include partial data.
    • Solution: Always handle null or incomplete chunks:
      foreach ($response as $chunk) {
          if (isset($chunk['choices'][0]['delta']['content'])) {
              echo $chunk['choices'][0]['delta']['content'];
          }
      }
      
  5. API Key Exposure

    • Hardcoding keys in config is risky.
    • Solution: Use Laravel's .env and restrict file permissions:
      chmod 600 .env
      

Debugging Tips

  1. Enable Logging Set OPENAI_LOG_RESPONSES=true in .env to log all requests/responses to storage/logs/openai.log.

  2. Inspect Headers Add custom headers for debugging:

    'headers' => [
        'X-Debug' => 'true',
    ],
    
  3. Validate Payloads Use Laravel's validator to sanitize inputs before sending to OpenAI:

    $validated = $request->validate([
        'messages.*.content' => 'required|string|max:4096',
    ]);
    

Extension Points

  1. Custom Endpoints Extend the client to support OpenAI's beta endpoints (e.g., assistants):

    // app/Providers/OpenaiServiceProvider.php
    Openai::extend('assistants', function ($app) {
        return new \AgenceGw\Openai\Clients\AssistantsClient($app['openai.config']);
    });
    
  2. Middleware Add request/response middleware for logging, retries, or auth:

    Openai::middleware(function ($request) {
        $request->headers->set('X-Custom-Id', auth()->id());
    });
    
  3. Mocking for Tests Override the HTTP client in tests:

    $this->app->singleton(\AgenceGw\Openai\Clients\HttpClient::class, function () {
        return new \Mockery\MockInterface();
    });
    
  4. Webhook Integration Use the client to validate OpenAI webhook signatures (e.g., for fine-tuning events):

    $signature = $request->header('Openai-Signature');
    $payload = $request->getContent();
    if (!Openai::validateWebhook($signature, $payload)) {
        abort(401);
    }
    
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator