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.
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.
Configure API Credentials
Add Cartesia API credentials to your Laravel .env file:
CARTE시아_API_KEY=your_api_key_here
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.
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'
);
}
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'];
}
Provider abstraction and model routing.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();
}
}
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);
}
}
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
}
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
}
Voice-Enabled Chatbot
$userSpeech = $cartesiaService->transcribeSpeech($audio);
$responseText = processNLP($userSpeech);
$botSpeech = $cartesiaService->generateSpeech($responseText);
Accessibility Features
$audio = $cartesiaService->generateSpeech($articleText);
// Serve audio to user
Customer Support Automation
$transcript = $cartesiaService->transcribeSpeech($callRecording);
$response = generateSupportResponse($transcript);
$audioResponse = $cartesiaService->generateSpeech($response);
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);
}
}
Handle Rate Limits Implement exponential backoff for retries:
use Illuminate\Support\Facades\Http;
$response = Http::withOptions([
'retry' => 3,
'timeout' => 30,
'connect_timeout' => 10,
])->post('...');
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);
});
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,
]);
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
Authentication Issues
Authorization header or using an incorrect API key..env file and ensure the header is included in every request.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);
});
Rate Limiting
retry helper or Symfony’s HttpClient retry middleware.Payload Validation
$validated = $request->validate([
'text' => 'required|string|max:5000',
'voice' => 'required|string|in:en
How can I help you explore Laravel packages today?