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 Symfony Laravel Package

agence-gw/openai-php-symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require agence-gw/openai-php-symfony
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        AgenceGw\OpenAI\OpenAIBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference AgenceGw\OpenAI
    

    Update config/packages/agence_gw_openai.yaml with your OpenAI API key:

    agence_gw_openai:
        api_key: '%env(OPENAI_API_KEY)%'
        base_uri: 'https://api.openai.com/v1'
    
  3. First Use Case: Chat Completion Inject the client in a Symfony service/controller:

    use AgenceGw\OpenAI\Client\OpenAIClientInterface;
    
    class ChatController
    {
        public function __construct(private OpenAIClientInterface $openAI)
        {
        }
    
        public function askQuestion(Request $request)
        {
            $response = $this->openAI->chat()->create([
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    ['role' => 'user', 'content' => $request->get('question')],
                ],
            ]);
            return new JsonResponse($response->getChoices()[0]->getMessage()->getContent());
        }
    }
    

Implementation Patterns

Common Workflows

  1. Chat Interactions

    $chat = $this->openAI->chat();
    $response = $chat->create([
        'model' => 'gpt-4',
        'messages' => [
            ['role' => 'system', 'content' => 'You are a helpful assistant.'],
            ['role' => 'user', 'content' => 'Explain Laravel middleware.'],
        ],
        'temperature' => 0.3,
    ]);
    
  2. Embeddings for Semantic Search

    $embeddings = $this->openAI->embeddings()->create([
        'model' => 'text-embedding-ada-002',
        'input' => ['"Laravel is a PHP framework"', '"Symfony is a PHP framework"'],
    ]);
    
  3. Image Generation

    $image = $this->openAI->images()->create([
        'prompt' => 'A futuristic cityscape at sunset',
        'n' => 1,
        'size' => '1024x1024',
    ]);
    

Integration Tips

  • Dependency Injection: Prefer injecting OpenAIClientInterface over concrete implementations for testability.
  • Rate Limiting: Use Symfony’s RateLimiter to handle OpenAI’s API limits gracefully.
  • Async Processing: For long-running tasks (e.g., batch embeddings), use Symfony Messenger:
    $this->messageBus->dispatch(new GenerateEmbeddingsMessage($texts));
    
  • Caching Responses: Cache frequent queries (e.g., static FAQs) with Symfony Cache component:
    $cache = $this->cache->get('faq_response_' . $question);
    if (!$cache) {
        $cache = $this->openAI->chat()->create([...]);
        $this->cache->set('faq_response_' . $question, $cache, 3600);
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Never hardcode OPENAI_API_KEY in config. Use Symfony’s %env() or a secrets manager.
    • Validate the key in config/packages/agence_gw_openai.yaml:
      api_key: '%env(OPENAI_API_KEY)%'
      validate_key: true  # Defaults to false; enable for early error detection.
      
  2. Model Versioning

    • OpenAI frequently updates models (e.g., gpt-3.5-turbo → gpt-3.5-turbo-1106). Pin versions in your code:
      $response = $this->openAI->chat()->create(['model' => 'gpt-3.5-turbo-1106', ...]);
      
  3. Token Limits

    • Chat messages are truncated if they exceed OpenAI’s token limit (~4096 for gpt-3.5-turbo). Use tiktoken (PHP port) to validate:
      if ($tokenCount > 4000) {
          throw new \RuntimeException('Message too long. Truncate or split.');
      }
      
  4. Error Handling

    • OpenAI returns HTTP 429 for rate limits. Handle it globally in a Symfony event subscriber:
      public function onKernelException(GetResponseForExceptionEvent $event)
      {
          $exception = $event->getThrowable();
          if ($exception instanceof \GuzzleHttp\Exception\RequestException &&
              $exception->getCode() === 429) {
              $event->setResponse(new Response('Rate limit exceeded. Retry later.', 429));
          }
      }
      

Debugging Tips

  • Enable Guzzle Middleware for request/response logging:
    agence_gw_openai:
        http_client:
            middleware: ['debug']  # Adds Guzzle's debug middleware
    
  • Validate Responses: Use json_last_error() to debug malformed JSON from OpenAI:
    $response = $this->openAI->chat()->create([...]);
    $data = json_decode($response->getBody(), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \RuntimeException('Invalid OpenAI response: ' . json_last_error_msg());
    }
    

Extension Points

  1. Custom Models Extend the base client to support non-OpenAI models (e.g., Anthropic):

    class CustomOpenAIClient extends AbstractOpenAIClient
    {
        public function anthropic(): AnthropicClientInterface
        {
            return new AnthropicClient($this->httpClient, $this->config);
        }
    }
    
  2. Prompts Library Create a service to manage reusable prompts (e.g., for documentation generation):

    class PromptManager
    {
        public function getDocumentationPrompt(string $topic): array
        {
            return [
                ['role' => 'system', 'content' => 'You are a technical writer.'],
                ['role' => 'user', 'content' => "Write a 2-paragraph doc on {$topic}."],
            ];
        }
    }
    
  3. Webhook Integration Use Symfony’s HttpClient to listen for OpenAI webhooks (e.g., file creation events):

    $client = $this->httpClient->stream(
        'https://api.openai.com/v1/events',
        ['headers' => ['Authorization' => 'Bearer ...']]
    );
    
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.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin