## Getting Started
### Minimal Setup
1. **Install the Package**
```bash
composer require symfony/ai-deepgram-platform
Ensure symfony/ai is also installed (this package extends it).
Configure Deepgram API Key
Add your Deepgram API key to .env:
DEEPGRAM_API_KEY=your_api_key_here
Or configure it programmatically:
use Symfony\Component\AI\Deepgram\DeepgramClient;
$client = new DeepgramClient('your_api_key_here');
First Use Case: Speech-to-Text (STT) Transcribe a pre-recorded audio file:
use Symfony\Component\AI\Deepgram\DeepgramClient;
$client = new DeepgramClient(config('services.deepgram.key'));
$result = $client->listen('path/to/audio.mp3');
// $result contains transcribed text and metadata
First Use Case: Text-to-Speech (TTS) Generate speech from text:
$result = $client->speak('Hello, world!', 'en-US');
// $result contains a URL to the generated audio file
Key Files to Reference
src/DeepgramClient.php: Core client logic.Tests/Fixtures/: Example audio files for testing.Use the client in a Laravel service for batch processing:
class AudioProcessor
{
public function __construct(private DeepgramClient $client) {}
public function processAudio(string $filePath): string
{
$transcript = $this->client->listen($filePath);
// Post-process transcript (e.g., save to DB, analyze sentiment)
return $transcript['text'];
}
}
Register the client in AppServiceProvider:
public function register()
{
$this->app->singleton(DeepgramClient::class, function ($app) {
return new DeepgramClient(config('services.deepgram.key'));
});
}
For live transcription, use Deepgram’s WebSocket API (not directly supported by this package). Instead, integrate the HTTP client with a Laravel Echo/Pusher setup:
// Example: Trigger transcription on audio upload
public function handleUploadedAudio(Request $request)
{
$audio = $request->file('audio');
$path = $audio->store('temp');
$transcript = $this->client->listen(storage_path("app/{$path}"));
// Broadcast transcript via Laravel Echo
broadcast(new AudioTranscribed($transcript['text']));
}
List available models to dynamically select the best one for a task:
$models = $this->client->listModels();
$bestModel = collect($models)->first(fn ($model) => $model['name'] === 'nova-2');
$result = $this->client->listen($audioPath, ['model' => $bestModel['name']]);
Wrap API calls in a retry mechanism for transient failures:
use Symfony\Component\AI\Exception\AIException;
try {
$result = $this->client->speak($text, $locale);
} catch (AIException $e) {
if ($e->getCode() === 429) { // Rate limited
sleep(2);
retry();
}
throw $e;
}
Offload transcription to a queue job:
class TranscribeJob implements ShouldQueue
{
public function handle()
{
$transcript = $this->client->listen($this->audioPath);
// Save to DB or process further
}
}
Configuration: Use Laravel’s config system to manage the API key:
// config/services.php
'deepgram' => [
'key' => env('DEEPGRAM_API_KEY'),
'timeout' => 30, // seconds
];
Then inject the config value into the client:
$client = new DeepgramClient(config('services.deepgram.key'));
File Handling: For uploaded files, use Laravel’s Storage facade:
use Illuminate\Support\Facades\Storage;
$path = $request->file('audio')->store('uploads');
$transcript = $this->client->listen(storage_path("app/{$path}"));
Validation: Validate audio files before processing:
$request->validate([
'audio' => 'required|file|mimes:mp3,wav,ogg|max:10000',
]);
Chunking Large Files: For files > 5MB, split them into chunks and process sequentially:
$chunkSize = 5 * 1024 * 1024; // 5MB
$chunks = chunk_file($audioPath, $chunkSize);
foreach ($chunks as $chunk) {
$transcript = $this->client->listen($chunk);
// Merge results
}
Caching: Cache frequent TTS requests (e.g., common phrases):
$cacheKey = "tts_{$text}_{$locale}";
$result = Cache::remember($cacheKey, now()->addHours(1), function () use ($text, $locale) {
return $this->client->speak($text, $locale);
});
.env and add DEEPGRAM_API_KEY to your .gitignore. Use Laravel’s env() helper or config system./v1/listen endpoint has a 15-minute audio limit for pre-recorded files. For longer files, use the Deepgram Streaming API (not supported by this package).429 errors will crash your app.UploadedFile objects. Passing base64 strings or remote URLs directly will fail.spatie/flysystem to handle binary data.nova-2) require specific input formats or parameters. Always check the Deepgram model docs.enhanced model requires punctuate: true:
$result = $this->client->listen($audioPath, [
'model' => 'enhanced',
'punctuate' => true,
]);
$client = new DeepgramClient($apiKey, [
'timeout' => 60, // 60 seconds
]);
Configure the client to log raw API responses:
$client = new DeepgramClient($apiKey, [
'debug' => true,
]);
Check logs in storage/logs/laravel.log for detailed request/response payloads.
Deepgram’s API may return partial or malformed responses. Always validate:
$result = $this->client->listen($audioPath);
if (!isset($result['text'])) {
throw new \RuntimeException('Invalid response from Deepgram');
}
Use the provided test fixtures (Tests/Fixtures/audio.mp3) to verify local setup:
$result = $this->client->listen(__DIR__.'/../../Tests/Fixtures/audio.mp3');
dd($result); // Should return a transcript
How can I help you explore Laravel packages today?