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 Deepgram Platform Laravel Package

symfony/ai-deepgram-platform

View on GitHub
Deep Wiki
Context7
## 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).

  1. 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');
    
  2. 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
    
  3. 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
    
  4. Key Files to Reference

    • src/DeepgramClient.php: Core client logic.
    • Tests/Fixtures/: Example audio files for testing.
    • Deepgram API Docs: Reference for endpoints.

Implementation Patterns

Common Workflows

1. Audio Processing Pipeline

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'));
    });
}

2. Real-Time Transcription (WebSocket)

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']));
}

3. Model Management

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']]);

4. Error Handling and Retries

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;
}

5. Integration with Laravel Queues

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
    }
}

Integration Tips

Laravel-Specific

  • 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',
    ]);
    

Performance

  • 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);
    });
    

Gotchas and Tips

Pitfalls

1. API Key Exposure

  • Risk: Hardcoding API keys in code or committing them to version control.
  • Fix: Always use .env and add DEEPGRAM_API_KEY to your .gitignore. Use Laravel’s env() helper or config system.

2. File Size Limits

  • Deepgram’s /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).
  • Workaround: Split files or use a different endpoint.

3. Rate Limits

  • Deepgram enforces rate limits. Unhandled 429 errors will crash your app.
  • Fix: Implement exponential backoff or use a queue system to distribute requests.

4. Binary Data Handling

  • The package expects raw file paths or UploadedFile objects. Passing base64 strings or remote URLs directly will fail.
  • Fix: Download remote files first or use a library like spatie/flysystem to handle binary data.

5. Model-Specific Quirks

  • Some models (e.g., nova-2) require specific input formats or parameters. Always check the Deepgram model docs.
  • Example: The enhanced model requires punctuate: true:
    $result = $this->client->listen($audioPath, [
        'model' => 'enhanced',
        'punctuate' => true,
    ]);
    

6. Timeouts

  • Long-running requests (e.g., large audio files) may time out. Deepgram’s default timeout is 30 seconds.
  • Fix: Increase the timeout in the client:
    $client = new DeepgramClient($apiKey, [
        'timeout' => 60, // 60 seconds
    ]);
    

Debugging Tips

1. Enable Verbose Logging

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.

2. Validate API Responses

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');
}

3. Test with Fixtures

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

Extension Points

1. Custom HTTP Client

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.
andydefer/laravel-actions
aimeos/prisma
besmartand-pro/php-quality-config
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