PHPackages                             mepsd/sarvam-laravel-sdk - 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. mepsd/sarvam-laravel-sdk

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

mepsd/sarvam-laravel-sdk
========================

Laravel SDK for Sarvam AI - India's Indigenous Language AI Platform

v1.0.0(5mo ago)01MITPHPPHP ^8.0

Since Dec 5Pushed 5mo agoCompare

[ Source](https://github.com/mepsd/sarvam-laravel-sdk)[ Packagist](https://packagist.org/packages/mepsd/sarvam-laravel-sdk)[ Docs](https://github.com/mepsd/sarvam-laravel-sdk)[ RSS](/packages/mepsd-sarvam-laravel-sdk/feed)WikiDiscussions main Synced 1mo ago

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

Laravel Sarvam AI SDK
=====================

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

[![Latest Version](https://camo.githubusercontent.com/4d2ca343cdcfe4d42c62bc2217ba2949e4db55ff0f97c2a98cf1f3f3813de5f6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f6d657073642f73617276616d2d6c61726176656c2d73646b)](https://github.com/mepsd/sarvam-laravel-sdk/releases)[![License](https://camo.githubusercontent.com/53889fb5f4e7a9a7376c81cdf51a98c3d24b19121e52e2533cb33b7aa8ef33e9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d657073642f73617276616d2d6c61726176656c2d73646b)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/911a83e2aa6fe73660ab613629a95c76622bf03049a7344e80c5ea72d4ef9c7d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e302d626c7565)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/b1b25c8f1b033da466084c9efd1b0f0216fc505f390802dfa5a90ddb0ffa0075/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d253545392e3025374325354531302e3025374325354531312e302d726564)](https://laravel.com)

A comprehensive Laravel SDK for [Sarvam AI](https://sarvam.ai) - India's Indigenous Language AI Platform. This package provides seamless integration with Sarvam AI's APIs for speech-to-text, text-to-speech, translation, chat completion, and more across 22+ Indian languages.

🌟 Features
----------

[](#-features)

- **🎤 Speech-to-Text**: Convert audio to text in multiple Indian languages
- **🔊 Text-to-Speech**: Generate natural-sounding speech from text
- **🌐 Translation**: Translate between 22+ Indian languages and English
- **💬 Chat Completion**: Multi-lingual conversational AI
- **📝 Transliteration**: Convert text between different scripts
- **🔍 Language Detection**: Automatically identify languages
- **📄 PDF Parsing**: Extract structured data from PDFs
- **📑 Document Translation**: Translate entire documents
- **⚡ Streaming Support**: Real-time streaming for chat and TTS
- **🔄 Batch Processing**: Process multiple requests efficiently
- **💾 Caching Support**: Built-in response caching
- **📊 Comprehensive Logging**: Debug and monitor API calls

📋 Requirements
--------------

[](#-requirements)

- PHP 8.0 or higher
- Laravel 9.0, 10.0, or 11.0
- Sarvam AI API Key ([Get it here](https://dashboard.sarvam.ai))

🚀 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require sarvam/laravel-sdk
```

⚙️ Configuration
----------------

[](#️-configuration)

### Publish the configuration file:

[](#publish-the-configuration-file)

```
php artisan vendor:publish --provider="Sarvam\Laravel\SarvamServiceProvider" --tag="sarvam-config"
```

### Add your API key to `.env`:

[](#add-your-api-key-to-env)

```
SARVAM_API_KEY=your_api_key_here

# Optional configurations
SARVAM_BASE_URL=https://api.sarvam.ai
SARVAM_TIMEOUT=60
SARVAM_RETRY_TIMES=3
SARVAM_CACHE_ENABLED=false
SARVAM_LOGGING_ENABLED=false
```

📖 Quick Start
-------------

[](#-quick-start)

### Basic Usage

[](#basic-usage)

```
use Sarvam\Laravel\Facades\Sarvam;

// Translate text
$translation = Sarvam::text()->translate('Hello World', 'hi-IN');
echo $translation->getTranslatedText(); // "नमस्ते दुनिया"

// Text-to-Speech
$audio = Sarvam::speech()->fromText('नमस्ते', 'hi-IN');
$audio->saveToFile('output.wav');

// Speech-to-Text
$transcript = Sarvam::speech()->toText('audio.wav');
echo $transcript->getTranscript();

// Chat completion
$response = Sarvam::chat()->completion('Tell me about India in Hindi');
echo $response->getContent();
```

🎯 Detailed Usage Examples
-------------------------

[](#-detailed-usage-examples)

### 📝 Text Services

[](#-text-services)

#### Translation

[](#translation)

```
use Sarvam\Laravel\Facades\Sarvam;

// Simple translation
$result = Sarvam::text()->translate('Good morning', 'hi-IN');
echo $result->getTranslatedText(); // "सुप्रभात"

// Translation with options
$result = Sarvam::text()->translate('Your EMI of Rs. 3000 is pending', 'hi-IN', [
    'source_language' => 'en-IN',
    'mode' => 'formal', // formal, colloquial
    'enable_preprocessing' => true,
    'speaker_gender' => 'Female',
]);

// Batch translation
$texts = ['Hello', 'How are you?', 'Good bye'];
$results = Sarvam::text()->batchTranslate($texts, 'ta-IN');
```

#### Transliteration

[](#transliteration)

```
// Convert between scripts
$result = Sarvam::text()->transliterate(
    'मुझे कल 9:30am को appointment है',
    'hi-IN',
    'hi-IN',
    ['format' => 'latin']
);
echo $result->getTransliteratedText(); // "mujhe kal 9:30am ko appointment hai"

// Spoken form transliteration
$result = Sarvam::text()->transliterate('मुझे कल appointment है', 'hi-IN', 'hi-IN', [
    'spoken_form' => true,
    'spoken_form_numerals_language' => 'english',
]);
```

#### Language Detection

[](#language-detection)

```
$result = Sarvam::text()->detectLanguage('आप कैसे हैं?');
echo $result->getLanguageCode(); // "hi-IN"
echo $result->getLanguageName(); // "Hindi"
echo $result->getConfidence(); // 0.98
echo $result->getScript(); // "Devanagari"
```

### 🎤 Speech Services

[](#-speech-services)

#### Speech-to-Text (Transcription)

[](#speech-to-text-transcription)

```
// Basic transcription
$result = Sarvam::speech()->toText('audio.wav');
echo $result->getTranscript();
echo $result->getLanguageCode();

// With options
$result = Sarvam::speech()->toText('meeting.wav', [
    'model' => 'saarika:v2.5',
    'language_code' => 'hi-IN',
    'with_timestamps' => true,
    'with_diarization' => true,
    'num_speakers' => 2,
]);

// Access diarized transcript
if ($result->hasDiarization()) {
    foreach ($result->getDiarizedTranscript() as $entry) {
        echo "Speaker {$entry['speaker_id']}: {$entry['transcript']}\n";
        echo "Time: {$entry['start_time_seconds']}s - {$entry['end_time_seconds']}s\n";
    }
}

// Get transcript by speaker
$speaker1Transcript = $result->getTranscriptBySpeaker('SPEAKER_01');
```

#### Speech-to-Text with Translation

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

```
// Transcribe and translate to English in one step
$result = Sarvam::speech()->toTextTranslate('hindi_audio.wav');
echo $result->getTranscript(); // English translation
echo $result->getSourceLanguage(); // "hi-IN"
```

#### Text-to-Speech

[](#text-to-speech)

```
// Basic TTS
$result = Sarvam::speech()->fromText('Hello World', 'en-IN');
$result->saveToFile('output.wav');

// With voice customization
$result = Sarvam::speech()->fromText('नमस्ते दुनिया', 'hi-IN', [
    'speaker' => 'Anushka', // Female voice
    'pitch' => 0.2,        // -0.75 to 0.75
    'pace' => 1.2,         // 0.5 to 2.0
    'loudness' => 1.0,     // 0.3 to 3.0
    'sample_rate' => 22050,
    'audio_format' => 'mp3',
]);

// Save to Laravel storage
$result->saveToFile('audio/greeting.mp3', 's3');

// Stream directly to browser
return $result->stream('download.mp3');

// Get available speakers
$speakers = Sarvam::speech()->getAvailableSpeakers();
// Female: ['Anushka', 'Manisha', 'Vidya', 'Arya']
// Male: ['Abhilash', 'Karun', 'Hitesh']
```

### 💬 Chat Services

[](#-chat-services)

#### Chat Completion

[](#chat-completion)

```
// Simple chat
$response = Sarvam::chat()->completion('What is the capital of India?');
echo $response->getContent();

// With conversation history
$messages = [
    ['role' => 'system', 'content' => 'You are a helpful assistant that speaks Hindi.'],
    ['role' => 'user', 'content' => 'Tell me about Indian festivals'],
    ['role' => 'assistant', 'content' => 'भारत में कई त्योहार मनाए जाते हैं...'],
    ['role' => 'user', 'content' => 'Tell me more about Diwali']
];

$response = Sarvam::chat()->completion($messages, [
    'temperature' => 0.7,
    'max_tokens' => 500,
    'wiki_grounding' => true, // Use Wikipedia for factual accuracy
]);

echo $response->getContent();
echo "Tokens used: " . $response->getTotalTokens();
```

#### Streaming Chat

[](#streaming-chat)

```
// Stream responses for real-time display
Sarvam::chat()->streamCompletion(
    'Write a story about ancient India',
    function ($chunk) {
        // Process each chunk as it arrives
        if (isset($chunk['choices'][0]['delta']['content'])) {
            echo $chunk['choices'][0]['delta']['content'];
            flush(); // Send to browser immediately
        }
    },
    ['max_tokens' => 1000]
);
```

#### Multi-turn Conversation

[](#multi-turn-conversation)

```
$conversation = [
    'Tell me about the Taj Mahal',
    'When was it built?',
    'Who built it and why?'
];

$responses = Sarvam::chat()->conversation($conversation);

foreach ($responses as $index => $response) {
    echo "Q: {$conversation[$index]}\n";
    echo "A: {$response->getContent()}\n\n";
}
```

### 📄 Parse Services

[](#-parse-services)

#### PDF Parsing

[](#pdf-parsing)

```
// Parse a single page
$result = Sarvam::parse()->parsePdf('document.pdf', 1);
$html = $result->getDecodedHtml();
$text = $result->getText();

// Extract structured data
$tables = $result->getTables();
foreach ($tables as $table) {
    $headers = $table['headers'];
    $rows = $table['rows'];
    // Process table data
}

$headings = $result->getHeadings();
foreach ($headings as $heading) {
    echo "H{$heading['level']}: {$heading['text']}\n";
}

// Parse entire PDF
$allPages = Sarvam::parse()->parseFullPdf('document.pdf', [
    'max_pages' => 50
]);
```

#### Document Translation

[](#document-translation)

```
$result = Sarvam::parse()->translateDocument('document.pdf', 'hi-IN', [
    'source_language' => 'en-IN'
]);

// Save translated document
$result->saveToFile('translated_document.pdf');

// Stream to browser
return $result->stream('translated.pdf');
```

🧪 Testing
---------

[](#-testing)

Test your SDK configuration:

```
# Test all services
php artisan sarvam:test

# Test specific service
php artisan sarvam:test --service=text
php artisan sarvam:test --service=speech
php artisan sarvam:test --service=chat
php artisan sarvam:test --service=parse

# Test with custom text
php artisan sarvam:test --text="Your custom text here" --language=hi-IN
```

🎨 Advanced Features
-------------------

[](#-advanced-features)

### Caching Responses

[](#caching-responses)

Enable caching in your config to reduce API calls:

```
// config/sarvam.php
'cache' => [
    'enabled' => true,
    'ttl' => 3600, // 1 hour
],
```

### Logging

[](#logging)

Enable logging to debug API interactions:

```
// config/sarvam.php
'logging' => [
    'enabled' => true,
    'channel' => 'sarvam', // Define in config/logging.php
],
```

### Error Handling

[](#error-handling)

```
use Sarvam\Laravel\Exceptions\SarvamException;

try {
    $result = Sarvam::text()->translate('Hello', 'hi-IN');
} catch (SarvamException $e) {
    if ($e->isInvalidApiKey()) {
        // Handle invalid API key
    } elseif ($e->isInsufficientQuota()) {
        // Handle quota exceeded
    } elseif ($e->isRateLimitError()) {
        // Handle rate limiting
    } else {
        // Handle other errors
        echo $e->getUserMessage();
    }
}
```

### WebSocket Support (Coming Soon)

[](#websocket-support-coming-soon)

```
// Real-time TTS streaming
Sarvam::speech()->streamFromText($text, $language, function($audioChunk) {
    // Process audio chunks in real-time
});

// Real-time STT
Sarvam::speech()->streamToText($audioStream, function($transcript) {
    // Process transcript in real-time
});
```

🌍 Supported Languages
---------------------

[](#-supported-languages)

The SDK supports the following Indian languages:

- English (en-IN)
- Hindi (hi-IN)
- Bengali (bn-IN)
- Gujarati (gu-IN)
- Kannada (kn-IN)
- Malayalam (ml-IN)
- Marathi (mr-IN)
- Odia (od-IN)
- Punjabi (pa-IN)
- Tamil (ta-IN)
- Telugu (te-IN)
- Assamese (as-IN)
- Bodo (brx-IN)
- Dogri (doi-IN)
- Konkani (gom-IN)
- Kashmiri (ks-IN)
- Maithili (mai-IN)
- Manipuri (mni-IN)
- Nepali (ne-IN)
- Sanskrit (sa-IN)
- Sindhi (sd-IN)
- Urdu (ur-IN)

🔧 Troubleshooting
-----------------

[](#-troubleshooting)

### Common Issues

[](#common-issues)

1. **Invalid API Key Error**

    - Verify your API key in the `.env` file
    - Check if the key is active in your [Sarvam Dashboard](https://dashboard.sarvam.ai)
2. **Quota Exceeded**

    - Check your usage in the dashboard
    - Upgrade your plan if needed
3. **Audio File Issues**

    - Ensure audio files are in supported formats (WAV, MP3, etc.)
    - For best results, use 16kHz sample rate
4. **Language Not Detected**

    - Provide more text for better detection
    - Specify the language explicitly when known

📚 Documentation
---------------

[](#-documentation)

- [Sarvam AI Documentation](https://docs.sarvam.ai)
- [API Reference](https://docs.sarvam.ai/api-reference-docs/introduction)
- [Cookbook Examples](https://github.com/sarvamai/sarvam-ai-cookbook)

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

📄 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

🔗 Links
-------

[](#-links)

- [Sarvam AI Website](https://sarvam.ai)
- [Sarvam AI Dashboard](https://dashboard.sarvam.ai)
- [Discord Community](https://discord.gg/5rAsykttcs)
- [Package on Packagist](https://packagist.org/packages/sarvam/laravel-sdk)

💡 Support
---------

[](#-support)

For support, email  or join our [Discord community](https://discord.gg/5rAsykttcs).

---

Made with ❤️ for the Indian AI community

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance72

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

159d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2d208c2df0bb5813d6d4d2286ef5e000d3666020e5e3548879616781b1113588?d=identicon)[mepsd](/maintainers/mepsd)

---

Top Contributors

[![mepsd](https://avatars.githubusercontent.com/u/45997529?v=4)](https://github.com/mepsd "mepsd (1 commits)")

---

Tags

laravelsdktranslationaispeech-to-texttext-to-speechsarvamindian-languages

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mepsd-sarvam-laravel-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/mepsd-sarvam-laravel-sdk/health.svg)](https://phpackages.com/packages/mepsd-sarvam-laravel-sdk)
```

###  Alternatives

[kkomelin/laravel-translatable-string-exporter

Translatable String Exporter for Laravel

3291.4M10](/packages/kkomelin-laravel-translatable-string-exporter)[tio/laravel

Add this package to localize your Laravel application (PHP, JSON or GetText).

170318.5k](/packages/tio-laravel)[opgginc/codezero-laravel-localized-routes

A convenient way to set up, manage and use localized routes in a Laravel app.

2770.1k1](/packages/opgginc-codezero-laravel-localized-routes)[smousss/laravel-globalize

Make Laravel projects translatable in a matter of seconds!

2266.3k](/packages/smousss-laravel-globalize)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
