Sarvam AI provides specialized Text-to-Speech (TTS) models trained specifically for Indian languages and accents. Setting up Sarvam AI’s TTS API in Python requires obtaining an API subscription key from the developer portal, sending a structured HTTP POST request containing your text and language code, and converting the base64-encoded audio response into a playable WAV audio file.
- Quick answer
- Prerequisites for Sarvam AI TTS Integration
- Step 1: Obtain Your Sarvam AI API Key
- Step 2: Install Required Python Libraries
- Step 3: Write the Core Python Script
- Load environment variables from .env file
- Supported Indian Languages and Language Codes
- Sarvam AI API Pricing and Usage Limits in India
- Error Codes and Troubleshooting
- What This Guide Does Not Cover
- Sources
Quick answer
To set up Sarvam AI Text-to-Speech in Python, sign up on the Sarvam AI developer dashboard, generate an API key, and install the requests library. Send a POST request to https://api.sarvam.ai/text-to-speech with your target text, language code (such as hi-IN for Hindi), and voice speaker name. Decode the returned base64 string to save the .wav audio file locally.
Information as of March 2026. Sourced from Sarvam AI official developer documentation and the IndiaAI initiative portal.
Prerequisites for Sarvam AI TTS Integration

Before writing Python code to generate speech, ensure you have the following requirements ready:
- Python Environment: Python 3.10 or higher installed on your system.
- Sarvam AI Developer Account: An active account on the official Sarvam AI developer portal.
- API Subscription Key: A valid
api-subscription-keygenerated from your account dashboard. - Basic Dependencies: The standard HTTP library
requestsandbase64module (built into Python).
If you plan to deploy your Python application to cloud servers, using specialized infrastructure like Hostinger India VPS hosting provides reliable network latency for API-heavy voice applications.
Step 1: Obtain Your Sarvam AI API Key
According to Sarvam AI developer guidelines, authentication is handled via a custom header key rather than standard Bearer tokens.
- Navigate to the official Sarvam AI developer dashboard.
- Sign in or register using your email or phone number.
- Select the API Keys tab from the sidebar menu.
- Click Create New Key, assign a label (e.g.,
python-tts-prod), and copy the secret key. - Store this key in an environment variable named
SARVAM_API_KEYto avoid hardcoding secrets in your source code.
Step 2: Install Required Python Libraries

Open your terminal or command prompt and create a clean virtual environment:
“bash
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
pip install requests python-dotenv
`
For applications that require extensive post-processing, cutting, or multitrack editing of the generated audio streams, external tools like Descript or Python libraries such as pydub can be integrated into your pipeline.
Step 3: Write the Core Python Script
Sarvam AI’s TTS service accepts JSON payloads specifying the target string, language code, speaker voice, pitch, and sample rate. The API returns JSON containing a base64-encoded WAV string under the audios key.
Create a file named sarvam_tts.py and paste the following implementation:
`python
import base64
import os
import requests
from dotenv import load_dotenv
Load environment variables from .env file
load_dotenv()
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY")
API_URL = "https://api.sarvam.ai/text-to-speech"
def generate_speech(text: str, target_language_code: str, output_filename: str = "output.wav"):
"""
Sends text to Sarvam AI TTS API and saves the base64 audio output as a WAV file.
"""
if not SARVAM_API_KEY:
raise ValueError("SARVAM_API_KEY is not set in environment variables.")
headers = {
"api-subscription-key": SARVAM_API_KEY,
"Content-Type": "application/json"
}
payload = {
"inputs": [text],
"target_language_code": target_language_code,
"speaker": "meera",
"pitch": 0,
"pace": 1.0,
"loudness": 1.5,
"speech_sample_rate": 8000,
"enable_preprocessing": True,
"model": "bulbul:v1"
}
print(f"Sending request to Sarvam AI for language: {target_language_code}...")
response = requests.post(API_URL, json=payload, headers=headers)
if response.status_code == 200:
data = response.json()
audio_base64 = data["audios"][0]
# Decode base64 audio data
audio_bytes = base64.b64decode(audio_base64)
with open(output_filename, "wb") as f:
f.write(audio_bytes)
print(f"Success! Audio saved to {output_filename}")
else:
print(f"Error {response.status_code}: {response.text}")
if __name__ == "__main__":
sample_text = "नमस्ते! सर्वम एआई टेक्स्ट-टू-स्पीच में आपका स्वागत है।"
generate_speech(text=sample_text, target_language_code="hi-IN", output_filename="hindi_speech.wav")
`
Supported Indian Languages and Language Codes
Sarvam AI’s flagship voice model (bulbul:v1) supports ten major Indian languages. When making API calls, you must specify the correct BCP-47 language tag:
| Language | BCP-47 Code | Example Script |
|---|---|---|
| Hindi | hi-IN | देवनागरी |
| Bengali | bn-IN | বাংলা |
| Kannada | kn-IN | ಕನ್ನಡ |
| Malayalam | ml-IN | മലയാളം |
| Marathi | mr-IN | मराठी |
| Odia | or-IN | ଓଡ଼ିଆ |
| Punjabi | pa-IN | ਪੰਜਾਬੀ |
| Tamil | ta-IN | தமிழ் |
| Telugu | te-IN | తెలుగు |
| Gujarati | gu-IN | ગુજરાતી |
While Sarvam AI specializes in regional Indian linguistic context, developers working on international multi-speaker projects often pair it with global voice platforms like ElevenLabs for broader global accent coverage.
Sarvam AI API Pricing and Usage Limits in India
According to Sarvam AI developer pricing guidelines, API costs are computed based on character count processed during generation.
- Free Trial Quota: New developer accounts typically receive free initial credits upon phone verification to test integration workflows.
- Pay-As-You-Go API Rates: ₹15 to ₹20 per 10,000 characters generated (varies based on output sampling rate and enterprise tier commitments).
- Character Limit Per Request: Standard REST API requests accept up to 500 characters per single call. Longer inputs must be split at sentence boundaries.
- Rate Limits: Default free accounts are capped at 10 requests per minute (RPM). High-concurrency enterprise applications can apply for limit upgrades via the developer console.
If you are calculating infrastructure budget projections or token usage for your startup, you can use our Free Interactive Smart Calculators & Decision Tools Hub to estimate monthly running costs.
Error Codes and Troubleshooting
When calling the Sarvam AI endpoints, HTTP response codes indicate whether request formatting or authentication succeeded.
| Status Code | Meaning | Common Cause | Fix Action |
|---|---|---|---|
| 401 Unauthorized | Missing or invalid key | api-subscription-key missing in request headers | Verify your key on Sarvam dashboard; pass it correctly in headers. |
| 422 Unprocessable Entity | Invalid request body | Malformed JSON or unsupported target_language_code | Check payload structure and confirm language code uses supported format (e.g., hi-IN). |
| 429 Too Many Requests | Rate limit exceeded | Exceeded RPM threshold for your tier | Implement exponential backoff retry logic in Python. |
| 500 Internal Error | Server-side processing failure | API issue or unparseable input characters | Ensure input text is valid UTF-8 and retry after a short delay. |
What This Guide Does Not Cover
This installation guide is designed for developers integrating Sarvam AI via REST API endpoints in Python. It does not cover:
- Setting up real-time WebRTC low-latency streaming sockets for live IVR telefoni networks.
- Enterprise voice cloning procedures (which require formal legal authorization consent filings).
- Self-hosting Sarvam open-weights models on local GPU hardware (such as NVIDIA CUDA setups).
Frequently Asked Questions
What language codes does Sarvam AI TTS support?
Automate workflows, generate Indic audio, and accelerate research with tested production AI platforms.
How do I handle audio base64 decoding in Python?
Use Python's built-in base64 module. Parse the audios list from the JSON response, extract the base64 string, decode it using base64.b64decode(), and write the decoded bytes directly into a file with a .wav` extension.
Is there a character limit per API request?
Yes, standard API calls to Sarvam AI TTS are limited to 500 characters per request. For longer texts, split your paragraph into individual sentences, process them separately, and concatenate the output WAV audio files.
Where do I get a Sarvam AI API key?
You can get an API key by creating a developer account on the official Sarvam AI portal. After logging in, navigate to the API Keys section in your dashboard and click “Create New Key” to generate a subscription token.
Sources
- Sarvam AI Developer Portal & Documentation: https://www.sarvam.ai/
- IndiaAI Portal (MeitY Initiative): https://indiaai.gov.in/








