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 the Package Add the package via Composer in your Laravel project:

    composer require symfony/ai-cartesia-platform
    

    If using Symfony, install it directly in your Symfony project.

  2. Configure API Credentials Add Cartesia API credentials to your Laravel .env file:

    CARTE시아_API_KEY=your_api_key_here
    
  3. Set Up a Service Provider Create a Laravel service provider to wrap the Cartesia client. Example:

    // app/Providers/CartesiaServiceProvider.php
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Symfony\AI\Cartesia\Client;
    
    class CartesiaServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton('cartesia', function ($app) {
                return new Client(config('services.cartesia.key'));
            });
        }
    }
    

    Register the provider in config/app.php under providers.

  4. First Use Case: Text-to-Speech (TTS) Generate a TTS response in a controller or service:

    use Illuminate\Support\Facades\Http;
    
    public function generateTTS()
    {
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.cartesia.key'),
        ])->post('https://api.cartesia.ai/tts/bytes', [
            'text' => 'Hello, this is a test.',
            'voice' => 'en-US',
        ]);
    
        return response()->streamDownload(
            fn () => echo $response->body(),
            'output.mp3'
        );
    }
    
  5. First Use Case: Speech-to-Text (STT) Transcribe audio to text:

    public function transcribeAudio()
    {
        $audioFile = storage_path('app/audio.wav');
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.cartesia.key'),
        ])->post('https://api.cartesia.ai/stt/transcribe', [
            'audio' => file_get_contents($audioFile),
        ]);
    
        return $response->json()['text'];
    }
    

Where to Look First

  • README.md: For basic setup and API reference links.
  • Symfony AI Documentation: For understanding the Provider abstraction and model routing.
  • Cartesia API Docs: For payload requirements, rate limits, and authentication details.
  • Laravel HTTP Client Docs: For handling requests, retries, and middleware.

Implementation Patterns

Usage Patterns

  1. Service Layer Abstraction Encapsulate Cartesia interactions in a dedicated service class to decouple business logic from API calls. Example:

    // app/Services/CartesiaService.php
    namespace App\Services;
    
    use Symfony\AI\Cartesia\Client;
    
    class CartesiaService
    {
        public function __construct(private Client $client) {}
    
        public function generateSpeech(string $text, string $voice = 'en-US'): string
        {
            return $this->client->tts()->bytes($text, $voice)->getContent();
        }
    
        public function transcribeSpeech(string $audioPath): string
        {
            $audioContent = file_get_contents($audioPath);
            return $this->client->stt()->transcribe($audioContent)->getText();
        }
    }
    
  2. Middleware for Requests Use Laravel middleware to handle common concerns like authentication, logging, and retries. Example:

    // app/Http/Middleware/CartesiaAuthMiddleware.php
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Http;
    
    class CartesiaAuthMiddleware
    {
        public function handle($request, Closure $next)
        {
            Http::macro('cartesia', function ($method, $url, $data = []) {
                return Http::withHeaders([
                    'Authorization' => 'Bearer ' . config('services.cartesia.key'),
                    'Accept' => 'application/json',
                ])->$method($url, $data);
            });
    
            return $next($request);
        }
    }
    
  3. Event-Driven Workflows Use Laravel events to trigger Cartesia actions asynchronously. Example:

    // Listen for a custom event to generate TTS
    event(new GenerateSpeechEvent('Hello, world!'));
    
    // Event Listener
    public function handle(GenerateSpeechEvent $event)
    {
        $speech = app(CartesiaService::class)->generateSpeech($event->text);
        // Store or process the speech
    }
    
  4. Queue-Based Processing Offload long-running tasks like STT transcription to a queue. Example:

    // Dispatch a job
    TranscribeAudioJob::dispatch($audioPath);
    
    // Job
    public function handle()
    {
        $text = app(CartesiaService::class)->transcribeSpeech($this->audioPath);
        // Process the transcribed text
    }
    

Workflows

  1. Voice-Enabled Chatbot

    • Use STT to transcribe user speech.
    • Process the text with NLP (e.g., Laravel AI or custom logic).
    • Generate a TTS response for the bot's reply.
    $userSpeech = $cartesiaService->transcribeSpeech($audio);
    $responseText = processNLP($userSpeech);
    $botSpeech = $cartesiaService->generateSpeech($responseText);
    
  2. Accessibility Features

    • Convert text content to speech for screen readers.
    • Transcribe audio descriptions for videos.
    $audio = $cartesiaService->generateSpeech($articleText);
    // Serve audio to user
    
  3. Customer Support Automation

    • Transcribe call recordings for analysis.
    • Generate automated responses using TTS.
    $transcript = $cartesiaService->transcribeSpeech($callRecording);
    $response = generateSupportResponse($transcript);
    $audioResponse = $cartesiaService->generateSpeech($response);
    

Integration Tips

  1. Leverage Symfony’s Provider Abstraction If using Symfony, extend the CartesiaProvider to customize behavior:

    use Symfony\AI\Cartesia\Provider\CartesiaProvider;
    
    class CustomCartesiaProvider extends CartesiaProvider
    {
        public function tts(string $text, string $voice): ResponseInterface
        {
            // Custom logic before calling parent
            return parent::tts($text, $voice);
        }
    }
    
  2. Handle Rate Limits Implement exponential backoff for retries:

    use Illuminate\Support\Facades\Http;
    
    $response = Http::withOptions([
        'retry' => 3,
        'timeout' => 30,
        'connect_timeout' => 10,
    ])->post('...');
    
  3. Cache Responses Cache frequent TTS responses to reduce API calls:

    $tts = Cache::remember("tts_{$text}_{$voice}", now()->addHours(1), function () use ($text, $voice) {
        return $cartesiaService->generateSpeech($text, $voice);
    });
    
  4. Monitor API Usage Track API calls and costs using Laravel’s logging or a monitoring tool:

    \Log::info('Cartesia API call', [
        'endpoint' => 'tts/bytes',
        'text' => $text,
        'voice' => $voice,
    ]);
    
  5. Use Environment-Specific Configs Configure different API keys for development, staging, and production:

    CARTEσία_API_KEY=dev_key
    CARTEσία_API_KEY_STAGING=staging_key
    CARTEσία_API_KEY_PRODUCTION=prod_key
    

Gotchas and Tips

Pitfalls

  1. Authentication Issues

    • Pitfall: Forgetting to include the Authorization header or using an incorrect API key.
    • Fix: Double-check the .env file and ensure the header is included in every request.
    • Tip: Use Laravel’s Http facade macros to standardize headers:
      Http::macro('cartesia', function ($method, $url, $data = []) {
          return Http::withHeaders([
              'Authorization' => 'Bearer ' . config('services.cartesia.key'),
          ])->$method($url, $data);
      });
      
  2. Rate Limiting

    • Pitfall: Hitting Cartesia’s rate limits without proper retry logic.
    • Fix: Implement exponential backoff and monitor API usage.
    • Tip: Use Laravel’s retry helper or Symfony’s HttpClient retry middleware.
  3. Payload Validation

    • Pitfall: Sending malformed requests (e.g., incorrect voice codes, unsupported audio formats).
    • Fix: Validate inputs before making API calls.
    • Tip: Use Laravel’s validation rules:
      $validated = $request->validate([
          'text' => 'required|string|max:5000',
          'voice' => 'required|string|in:en
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor