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

Ai Cartesia Platform Laravel Package

symfony/ai-cartesia-platform

Symfony AI bridge for the Cartesia Platform. Integrates Cartesia APIs for text-to-speech (bytes) and speech-to-text transcription, enabling easy API requests and usage within Symfony applications via the Symfony AI ecosystem.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies Require the package and Symfony AI:

    composer require symfony/ai symfony/ai-cartesia-platform
    
  2. Configure API Credentials Add to config/services.php (Laravel) or .env:

    CARTESIA_API_KEY=your_key_here
    CARTESIA_API_URL=https://api.cartesia.ai
    
  3. Basic TTS Usage

    use Symfony\AI\Cartesia\Client;
    use Symfony\Component\AI\Provider\CartesiaProvider;
    
    $client = new Client();
    $provider = new CartesiaProvider($client);
    
    // Generate speech bytes
    $speechBytes = $provider->tts()->bytes('Hello, world!')->getContent();
    file_put_contents('speech.mp3', $speechBytes);
    
  4. Basic STT Usage

    $transcription = $provider->stt()->transcribe(file_get_contents('audio.wav'));
    $text = $transcription->getText();
    
  5. Laravel Facade (Optional) Create a facade for convenience:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        $this->app->bind('cartesia', function () {
            $client = new Client();
            return new CartesiaProvider($client);
        });
    }
    

    Usage:

    $tts = app('cartesia')->tts()->bytes('Text')->getContent();
    

Implementation Patterns

Core Workflows

  1. Provider-Based Routing Leverage Symfony’s Provider abstraction to route requests:

    // Route by model (if Cartesia supports multiple)
    $provider->setModel('cartesia-pro');
    $result = $provider->tts()->bytes('Text');
    
  2. Async Processing with Queues Offload STT/TTS to background jobs:

    // app/Jobs/ProcessSpeech.php
    public function handle()
    {
        $provider = app('cartesia');
        $transcription = $provider->stt()->transcribe($this->audioPath);
        // Save to DB or process further
    }
    
  3. Middleware for Requests Add logging/retries via Symfony middleware:

    use Symfony\Component\AI\Middleware\RetryMiddleware;
    
    $client = new Client();
    $client->addMiddleware(new RetryMiddleware());
    

Laravel-Specific Patterns

  1. Service Container Binding Bind the provider as a singleton:

    $this->app->singleton('cartesia', function () {
        $client = new Client();
        $provider = new CartesiaProvider($client);
        $provider->setApiKey(config('services.cartesia.key'));
        return $provider;
    });
    
  2. Event Listeners Trigger events for STT/TTS completion:

    // app/Listeners/SpeechProcessed.php
    public function handle($event)
    {
        Log::info('Speech processed', ['text' => $event->text]);
    }
    
  3. Form Request Validation Validate audio inputs before STT:

    use Illuminate\Validation\Rule;
    
    $request->validate([
        'audio' => ['required', 'file', 'mimes:wav,mp3'],
    ]);
    

Integration Tips

  • Hybrid Providers: Combine with other Symfony AI providers:
    $provider = new MultiProvider([
        new CartesiaProvider($client),
        new OpenAIProvider($openAiClient),
    ]);
    
  • Caching Responses: Cache frequent TTS requests:
    $bytes = Cache::remember("tts_{$text}", now()->addHours(1), function () use ($provider, $text) {
        return $provider->tts()->bytes($text)->getContent();
    });
    
  • Error Handling: Centralize Cartesia errors:
    try {
        $provider->stt()->transcribe($audio);
    } catch (CartesiaException $e) {
        report($e);
        return back()->withError('Speech processing failed');
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication Quirks

    • Cartesia may require API key in headers, not just auth middleware.
    • Fix: Explicitly set headers:
      $client->setHeaders(['Authorization' => 'Bearer ' . config('services.cartesia.key')]);
      
  2. Audio Format Restrictions

    • STT may fail on unsupported formats (e.g., .ogg).
    • Fix: Convert audio to .wav or .mp3 before processing:
      use FFMpeg\FFMpeg;
      $ffmpeg = FFMpeg::create();
      $ffmpeg->open($request->file('audio'))
              ->save('converted.wav');
      
  3. Rate Limiting

    • Cartesia may throttle requests without clear headers.
    • Fix: Implement exponential backoff:
      use Symfony\Component\AI\Middleware\RetryMiddleware;
      $client->addMiddleware(new RetryMiddleware(3, 100));
      
  4. Provider Abstraction Gaps

    • The Provider abstraction may not cover all Cartesia endpoints.
    • Fix: Extend the provider:
      class ExtendedCartesiaProvider extends CartesiaProvider {
          public function customEndpoint(array $data) {
              return $this->client->request('POST', '/custom', ['json' => $data]);
          }
      }
      
  5. Laravel-Symfony HTTP Client Mismatch

    • Symfony’s HttpClient differs from Laravel’s Http.
    • Fix: Use a bridge:
      use Symfony\Component\HttpClient\HttpClient;
      use Illuminate\Support\Facades\Http;
      
      $symfonyClient = HttpClient::create();
      $laravelResponse = Http::withOptions(['handler' => $symfonyClient->getHandler())->post(...);
      

Debugging Tips

  1. Enable Verbose Logging

    $client = new Client();
    $client->setDebug(true); // Logs full request/response
    
  2. Inspect Raw Responses

    $response = $provider->stt()->transcribe($audio);
    \Log::debug('Cartesia STT Response', [
        'status' => $response->getStatusCode(),
        'content' => $response->getContent(),
    ]);
    
  3. Mock Cartesia for Testing

    // tests/TestCase.php
    protected function mockCartesia()
    {
        $client = $this->createMock(ClientInterface::class);
        $client->method('request')
               ->willReturn(new Response(200, [], json_encode(['text' => 'Mocked'])));
        $this->app->instance(ClientInterface::class, $client);
    }
    

Configuration Quirks

  1. Environment Variables

    • Ensure .env variables are loaded in config/services.php:
      'cartesia' => [
          'key' => env('CARTESIA_API_KEY'),
          'url' => env('CARTESIA_API_URL', 'https://api.cartesia.ai'),
      ],
      
  2. Provider Initialization

    • The CartesiaProvider requires a fully configured Client:
      $client = new Client();
      $client->setHeaders(['Authorization' => 'Bearer ' . $apiKey]);
      $provider = new CartesiaProvider($client);
      
  3. Model Routing

    • If Cartesia supports multiple models, set the model before each request:
      $provider->setModel('cartesia-pro');
      $result = $provider->tts()->bytes('Text');
      

Extension Points

  1. Custom Middleware Add middleware to the Client:

    $client->addMiddleware(function (Request $request, callable $next) {
        $request = $request->withHeader('X-Custom-Header', 'value');
        return $next($request);
    });
    
  2. Event Subscribers Subscribe to Symfony AI events:

    use Symfony\Component\AI\Event\SpeechProcessedEvent;
    
    $dispatcher->addListener(SpeechProcessedEvent::class, function ($event) {
        // Handle event (e.g., update DB)
    });
    
  3. Response Transformers Override response handling:

    class CustomCartesiaProvider extends CartesiaProvider {
        protected function transformResponse(ResponseInterface $response): array {
            $data = parent::transformResponse($response);
            return array_merge($data, ['custom_field' => 'value']);
        }
    }
    
  4. Fallback Providers Implement a fallback chain:

    $provider = new CartesiaProvider($client);
    $fallback = new OpenAIProvider($openAiClient);
    
    $result = $provider->tts()->bytes('Text');
    if ($result->failed()) {
        $result =
    
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.
monarobase/country-list
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity