PHPackages                             nextbuild/sarvam-ai-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Localization &amp; i18n](/categories/localization)
4. /
5. nextbuild/sarvam-ai-laravel

ActiveLibrary[Localization &amp; i18n](/categories/localization)

nextbuild/sarvam-ai-laravel
===========================

Laravel package for Sarvam AI integration with speech-to-text, text-to-speech, translation, and chat completion capabilities

1.0.0(11mo ago)03MITPHPPHP ^8.1

Since Jul 20Pushed 11mo agoCompare

[ Source](https://github.com/next-build/sarvam-ai-laravel)[ Packagist](https://packagist.org/packages/nextbuild/sarvam-ai-laravel)[ RSS](/packages/nextbuild-sarvam-ai-laravel/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (6)Versions (2)Used By (0)

Sarvam AI Laravel Package
=========================

[](#sarvam-ai-laravel-package)

A comprehensive Laravel package for integrating [Sarvam](https://www.sarvam.ai/) AI's powerful speech-to-text, text-to-speech, translation, and chat completion capabilities into your Laravel applications.

Features
--------

[](#features)

- **Speech to Text**: Convert audio files to text
- **Speech to Text with Translation**: Convert audio to text with automatic translation
- **Text to Speech**: Generate audio from text
- **Text Translation**: Translate text between languages
- **Language Identification**: Detect the language of text
- **Text Transliteration**: Convert text between scripts
- **Chat Completions**: AI-powered chat responses
- **Laravel Integration**: Built specifically for Laravel with facades and service providers
- **Error Handling**: Comprehensive error handling with custom exceptions
- **Configuration**: Flexible configuration options

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require nextbuild/sarvam-ai-laravel
```

### Laravel Auto-Discovery

[](#laravel-auto-discovery)

The package will automatically register itself with Laravel's package auto-discovery feature.

### Manual Registration (if needed)

[](#manual-registration-if-needed)

If auto-discovery is disabled, manually add the service provider to your `config/app.php`:

```
'providers' => [
    // Other providers...
    NextBuild\SarvamAI\SarvamAIServiceProvider::class,
],

'aliases' => [
    // Other aliases...
    'SarvamAI' => NextBuild\SarvamAI\Facades\SarvamAI::class,
],
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=sarvam-ai-config
```

Add your Sarvam AI API key to your `.env` file:

```
SARVAM_AI_API_KEY=your-api-key-here
```

Usage
-----

[](#usage)

### Using the Facade

[](#using-the-facade)

```
use NextBuild\SarvamAI\Facades\SarvamAI;

// Speech to Text
$response = SarvamAI::speechToText('/path/to/audio/file.wav', 'saarika:v1', 'hi-IN');
$transcript = $response->getTranscript();

// Text to Speech
$response = SarvamAI::textToSpeech('Hello world', 'en-IN');
$audioUrl = $response->getAudioUrl();

// Translation
$response = SarvamAI::translateText('Hello world', 'en-IN', 'hi-IN');
$translatedText = $response->getTranslatedText();

// Chat Completions
$messages = [
    ['role' => 'user', 'content' => 'Hello, how are you?']
];
$response = SarvamAI::chatCompletions($messages);
$reply = $response->getChatCompletionContent();
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use NextBuild\SarvamAI\SarvamAI;

class YourController extends Controller
{
    protected $sarvamAI;

    public function __construct(SarvamAI $sarvamAI)
    {
        $this->sarvamAI = $sarvamAI;
    }

    public function translateText(Request $request)
    {
        $response = $this->sarvamAI->translateText(
            $request->input('text'),
            $request->input('source_language', 'auto'),
            $request->input('target_language', 'en-IN')
        );

        return response()->json([
            'translated_text' => $response->getTranslatedText(),
            'original_data' => $response->getData()
        ]);
    }
}
```

API Methods
-----------

[](#api-methods)

### Speech to Text

[](#speech-to-text)

Convert audio files to text:

```
$response = SarvamAI::speechToText('/path/to/audio/file.wav');
$transcript = $response->getTranscript();
```

### Speech to Text with Translation

[](#speech-to-text-with-translation)

Convert audio to text with automatic translation:

```
$response = SarvamAI::speechToTextTranslate('/path/to/audio/file.wav', null, 'saarika:v1');
$transcript = $response->getTranscript();
```

### Text to Speech

[](#text-to-speech)

Generate audio from text:

```
$response = SarvamAI::textToSpeech('Hello world', 'en-IN');
$audioUrl = $response->getAudioUrl();
```

### Text Translation

[](#text-translation)

Translate text between languages:

```
$response = SarvamAI::translateText('Hello world', 'en-IN', 'hi-IN');
$translatedText = $response->getTranslatedText();
```

### Language Identification

[](#language-identification)

Detect the language of text:

```
$response = SarvamAI::identifyLanguage('Hello world');
$detectedLanguage = $response->getDetectedLanguage();
```

### Text Transliteration

[](#text-transliteration)

Convert text between scripts:

```
$response = SarvamAI::transliterateText('Hello world', 'en-IN', 'hi-IN');
$transliteratedText = $response->getTransliteratedText();
```

### Chat Completions

[](#chat-completions)

AI-powered chat responses:

```
$messages = [
    ['role' => 'user', 'content' => 'What is the capital of India?']
];
$response = SarvamAI::chatCompletions($messages, 'sarvam-m');
$reply = $response->getChatCompletionContent();
```

Response Handling
-----------------

[](#response-handling)

All methods return a `SarvamAIResponse` object with the following methods:

```
$response = SarvamAI::translateText('Hello', 'en-IN', 'hi-IN');

// Get specific data
$translatedText = $response->getTranslatedText();
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();

// Get raw data
$data = $response->getData();
$body = $response->getBody();

// Convert to array or JSON
$array = $response->toArray();
$json = $response->toJson();

// Check if successful
$isSuccessful = $response->isSuccessful();
```

Error Handling
--------------

[](#error-handling)

The package throws `SarvamAIException` for API errors:

```
use NextBuild\SarvamAI\Exceptions\SarvamAIException;

try {
    $response = SarvamAI::translateText('Hello world', 'en-IN', 'hi-IN');
    $translatedText = $response->getTranslatedText();
} catch (SarvamAIException $e) {
    // Handle the error
    Log::error('Sarvam AI Error: ' . $e->getMessage());
    return response()->json(['error' => 'Translation failed'], 500);
}
```

Configuration Options
---------------------

[](#configuration-options)

The configuration file includes the following options:

```
return [
    'api_key' => env('SARVAM_AI_API_KEY'),
    'default_source_language' => env('SARVAM_AI_DEFAULT_SOURCE_LANGUAGE', 'auto'),
    'default_target_language' => env('SARVAM_AI_DEFAULT_TARGET_LANGUAGE', 'en-IN'),
    'timeout' => env('SARVAM_AI_TIMEOUT', 30),
    'retry' => env('SARVAM_AI_RETRY', 3),
    'chat' => [
        'default_model' => env('SARVAM_AI_DEFAULT_MODEL', 'sarvam-m'),
        'max_tokens' => env('SARVAM_AI_MAX_TOKENS=1000
SARVAM_AI_TEMPERATURE=0.7
```

Advanced Usage
--------------

[](#advanced-usage)

### Custom API Key

[](#custom-api-key)

You can set a custom API key at runtime:

```
SarvamAI::setApiKey('your-custom-api-key')->translateText('Hello', 'en-IN', 'hi-IN');
```

### Custom Timeout

[](#custom-timeout)

Set a custom timeout for requests:

```
SarvamAI::setTimeout(60)->speechToText('/path/to/long/audio/file.wav');
```

### Chaining Methods

[](#chaining-methods)

You can chain configuration methods:

```
$response = SarvamAI::setApiKey('custom-key')
    ->setTimeout(60)
    ->translateText('Hello world', 'en-IN', 'hi-IN');
```

### Working with Files

[](#working-with-files)

For speech-to-text operations, ensure your audio files are in supported formats:

```
// Supported formats: WAV, MP3, FLAC, etc.
$audioFile = storage_path('app/audio/sample.wav');
$response = SarvamAI::speechToText($audioFile);

if ($response->isSuccessful()) {
    $transcript = $response->getTranscript();
    // Process the transcript
}
```

Testing
-------

[](#testing)

The package includes comprehensive tests. Run them with:

```
composer test
```

For test coverage:

```
composer test-coverage
```

Examples
--------

[](#examples)

### Complete Translation Service

[](#complete-translation-service)

```
