Libraries & SDKs

Official Python and JavaScript clients for the Sarvam AI API — with async, retries, timeouts, streaming, and typed errors.

View as Markdown

The official SDKs wrap every Sarvam AI API — Speech-to-Text, Text-to-Speech, Translation, Chat Completion, and Document Digitization — behind a typed, ergonomic client. They handle auth, serialization, multipart uploads, and error mapping so you don’t have to hand-roll HTTP calls.

LanguagePackageInstall
Pythonsarvamai on PyPIpip install sarvamai
JavaScript / TypeScriptsarvamai on npmnpm install sarvamai

Official SDKs vs. generated request snippets. The Python and JavaScript SDKs above are hand-tested, fully supported clients. The per-endpoint snippets you see in other languages (cURL, Go, Swift, etc.) on API Reference pages are auto-generated request examples — useful as a starting point, but only Python and JavaScript are first-class SDKs.

Initialize the client

Pass your API key directly, or let the SDK read it from the SARVAM_API_KEY environment variable.

1from sarvamai import SarvamAI
2
3client = SarvamAI(api_subscription_key="YOUR_SARVAM_API_KEY")
4
5response = client.text.translate(
6 input="Hello, how are you?",
7 source_language_code="auto",
8 target_language_code="hi-IN",
9)
10print(response)

Async usage

Both SDKs support fully asynchronous calls — use them when you need concurrency (e.g. fanning out many requests, or inside an async web server or voice agent).

1import asyncio
2from sarvamai import AsyncSarvamAI
3
4client = AsyncSarvamAI(api_subscription_key="YOUR_SARVAM_API_KEY")
5
6async def main():
7 # Run several translations concurrently
8 inputs = ["Good morning", "How are you?", "Thank you"]
9 results = await asyncio.gather(*[
10 client.text.translate(
11 input=text,
12 source_language_code="en-IN",
13 target_language_code="hi-IN",
14 )
15 for text in inputs
16 ])
17 for r in results:
18 print(r)
19
20asyncio.run(main())

In JavaScript, every method is already Promise-based — await it directly. In Python, the synchronous SarvamAI and asynchronous AsyncSarvamAI expose the exact same method names and arguments, so you can switch with a one-line change.

Timeouts and retries

Configure timeouts and automatic retries either globally (on the client) or per request. Per-request options override the client defaults.

1from sarvamai import SarvamAI
2
3# Client-level: applies to every request
4client = SarvamAI(
5 api_subscription_key="YOUR_SARVAM_API_KEY",
6 timeout=30.0, # seconds
7)
8
9# Per-request: override timeout and set automatic retries
10response = client.text.translate(
11 input="Hello, how are you?",
12 source_language_code="auto",
13 target_language_code="hi-IN",
14 request_options={
15 "timeout_in_seconds": 60,
16 "max_retries": 3,
17 },
18)

Retries use exponential backoff and apply to transient failures (HTTP 429, 5xx, and connection errors). For a full retry/backoff helper and idempotency guidance, see Errors & Troubleshooting.

Handling errors

The SDKs raise typed exceptions mapped to HTTP status codes, so you can catch exactly the failure you care about. Catch the base class to handle everything.

1from sarvamai import SarvamAI, TooManyRequestsError
2from sarvamai.core.api_error import ApiError
3
4client = SarvamAI(api_subscription_key="YOUR_SARVAM_API_KEY")
5
6try:
7 response = client.text.translate(
8 input="Hello, how are you?",
9 source_language_code="auto",
10 target_language_code="hi-IN",
11 )
12except TooManyRequestsError:
13 print("Rate limited — back off and retry")
14except ApiError as e:
15 # Base class for every API error
16 print(f"API error {e.status_code}: {e.body}")

Exception reference

HTTP statusPython exceptionJavaScript exception
400 Bad requestBadRequestErrorSarvamAI.BadRequestError
403 Forbidden / invalid key¹ForbiddenErrorSarvamAI.ForbiddenError
404 Not foundNotFoundErrorSarvamAI.NotFoundError
413 Payload too largeContentTooLargeErrorSarvamAI.ContentTooLargeError
422 Unprocessable entityUnprocessableEntityErrorSarvamAI.UnprocessableEntityError
429 Rate limited / quotaTooManyRequestsErrorSarvamAI.TooManyRequestsError
500 Server errorInternalServerErrorSarvamAI.InternalServerError
503 Service unavailableServiceUnavailableErrorSarvamAI.ServiceUnavailableError
Any of the above (base)ApiErrorSarvamAIError
Client-side timeouthttpx.TimeoutExceptionSarvamAITimeoutError

¹ Auth failures return HTTP 403 (invalid_api_key_error), not 401 — see the auth status-code note.

Streaming support

Several APIs stream results instead of returning a single response. Here’s what each SDK supports:

CapabilityMethodPythonJavaScript
TTS over HTTP streamtext_to_speech.convert_stream / textToSpeech.convertStream
TTS over WebSockettext_to_speech_streaming / textToSpeechStreaming
STT over WebSocketspeech_to_text_streaming / speechToTextStreaming
STT-translate over WebSocketspeech_to_text_translate_streaming / speechToTextTranslateStreaming
  • HTTP streaming returns an iterable/BinaryResponse of raw audio bytes — see the HTTP Streaming guide.
  • WebSocket streaming uses the async clients (AsyncSarvamAI / SarvamAIClient) with an event-driven connection — see the TTS WebSocket and STT WebSocket guides.

Versioning

The SDKs follow semantic versioning. Pin a version in production and review the API changelog before upgrading across a major version. Always develop against the latest release:

$pip install --upgrade sarvamai

Resources

ResourceLink
Example notebooks & agentsGitHub cookbook
Errors, retries & exceptionsErrors & Troubleshooting
Community supportDiscord
Machine-readable API schemahttps://docs.sarvam.ai/openapi.json · https://docs.sarvam.ai/asyncapi.json