> This page is for Model APIs.

> Sarvam Voice Agents (Samvaad) is a voice AI agent platform for Indian languages: build, test and deploy AI calling agents on your own phone numbers, from ₹3 a minute. Start here: https://docs.sarvam.ai/voice-agents/why-voice-agents.
> For clean Markdown of any page, append `.md` to the page URL.
> For a complete documentation index, see https://docs.sarvam.ai/llms.txt. For a section index, append `/llms.txt` to any section URL (for example https://docs.sarvam.ai/voice-agents/llms.txt).
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.sarvam.ai/_mcp/server.

# Handle Errors and Retries

> How the Dictate SDKs raise errors, which errors to retry, and a try/except sample in Python and JavaScript.

Every error from the API has the same body:

```json
{
  "error": {
    "code": "invalid_request_error",
    "message": "language_code 'xx-YY' is not supported. Use auto, hi-IN, bn-IN, ...",
    "request_id": "20261109_2de03176-6afa-4fee-bcd9-972b5..."
  }
}
```

The SDKs raise one typed error for each HTTP status, so you can catch the ones you can handle.

|                         | Python                                   | JavaScript                      |
| ----------------------- | ---------------------------------------- | ------------------------------- |
| Any API error           | `ApiError`                               | `SarvamAIError`                 |
| One for each status     | `BadRequestError`, `ForbiddenError`, ... | `SarvamAI.BadRequestError`, ... |
| HTTP status             | `e.status_code`                          | `e.statusCode`                  |
| The body above          | `e.body`                                 | `e.body`                        |
| Headers (`Retry-After`) | `e.headers`                              | `e.rawResponse.headers`         |

The Python errors are in `sarvamai.errors`, and `ApiError` is in `sarvamai.core.api_error`. The full list of classes is in the SDK.

## Catch the error

#### Python

```python
import os
from sarvamai import SarvamAI
from sarvamai.core.api_error import ApiError
from sarvamai.errors import BadRequestError, ForbiddenError

client = SarvamAI(api_subscription_key=os.environ["SARVAM_API_KEY"])

try:
    with open("note.wav", "rb") as f:
        res = client.dictate.transcribe(file=f, language_code="xx-YY")
    print(res.text)
except BadRequestError as e:
    err = e.body["error"]  # has "code", "message" and "request_id"
    print("fix the request:", e.status_code,
          err["code"], err["message"])
except ForbiddenError as e:
    print("check your API key:", e.body["error"]["request_id"])
except ApiError as e:
    # Anything else. The SDK has already retried 408, 429 and 5xx errors.
    print("failed:", e.status_code, e.body)
```

#### JavaScript

```javascript
import fs from "fs";
import { SarvamAI, SarvamAIClient, SarvamAIError } from "sarvamai";

const client = new SarvamAIClient({ apiSubscriptionKey: process.env.SARVAM_API_KEY });

try {
  const res = await client.dictate.transcribe({
    file: fs.createReadStream("note.wav"),
    language_code: "xx-YY",
  });
  console.log(res.text);
} catch (e) {
  if (e instanceof SarvamAI.BadRequestError) {
    const err = e.body.error; // { code, message, request_id }
    console.log("fix the request:", e.statusCode, err.code, err.message);
  } else if (e instanceof SarvamAI.ForbiddenError) {
    console.log("check your API key:", e.body.error.request_id);
  } else if (e instanceof SarvamAIError) {
    // Anything else. The SDK has already retried 408, 429 and 5xx errors.
    console.log("failed:", e.statusCode, e.body);
  } else {
    throw e;
  }
}
```

**`Output`**

```text title="Output" wordWrap
fix the request: 400 invalid_request_error language_code 'xx-YY' is not supported. Use auto, hi-IN, bn-IN, kn-IN, ml-IN, mr-IN, or-IN, pa-IN, ta-IN, te-IN, en-IN, gu-IN, as-IN, ur-IN, ne-IN, ...
```

Keep the `request_id` (it is also in the `x-request-id` response header). Send it to support when you report a problem.

## Which errors to retry

| Status                                           | Retry?    | What to do                                                                                                                                                                            |
| ------------------------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` `invalid_request_error`                    | **No**    | A field, limit, URL or audio problem, a clip over 30 s, a vocabulary entry that is not an object, or a `sounds_like` that two entries with different words share. Correct the request |
| `403` `invalid_api_key_error`                    | **No**    | The key is missing or wrong. Check it                                                                                                                                                 |
| `404` `not_found_error`                          | **No**    | The job does not exist: it was deleted, or the ID is wrong                                                                                                                            |
| `408` `invalid_request_error`                    | **Yes**   | The upload stalled for 30 s, or took longer than 120 s. Try a faster connection, or use a job with `audio_url`                                                                        |
| `409` `conflict_error`                           | **Later** | You deleted a job that is still running. Delete does not stop a job, and nothing else does. Wait until it is `Completed` or `Failed`, then delete it                                  |
| `413` `invalid_request_error`                    | **No**    | The body is over about 12 MB at the gateway. Keep a clip within 10,000,000 bytes, or use a job with `audio_url`                                                                       |
| `429` `rate_limit_exceeded_error`                | **Yes**   | Over your rate limit (job reads count). Wait the `Retry-After` seconds                                                                                                                |
| `500` `internal_server_error`                    | **Once**  | An unexpected problem. If it repeats, report it with the `request_id`                                                                                                                 |
| `502` `asr_invalid_result`                       | **Once**  | Speech recognition sent an unusable answer                                                                                                                                            |
| `503` `service_overloaded` or `model_overloaded` | **Yes**   | Dictate or speech recognition is overloaded. Back off, and follow `Retry-After`                                                                                                       |
| `503` `service_unavailable`                      | **No**    | The route is not available                                                                                                                                                            |

### What the SDK retries for you

The SDK retries `408`, `429` and every `5xx` up to **2 more times**, with a growing wait that follows `Retry-After`. You
only see the error when those tries are used up. To change the number, pass it with the call:

#### Python

```python
res = client.dictate.transcribe(
    file=f, language_code="en-IN",
    request_options={"max_retries": 5},
)
```

#### JavaScript

```javascript
const res = await client.dictate.transcribe(
  { file: fs.createReadStream("note.wav"), language_code: "en-IN" },
  { maxRetries: 5 },
);
```

The SDK also retries `503 service_unavailable`, which is not worth retrying. If you see it, stop and report it.

## A `200` can still be a soft failure

The finishing step never fails a call. If it fails or is too slow, you get a `200` where `text` is the raw
transcript and `degraded` says why. A degraded call is not billed. Check `degraded` in every response, and
`output.degraded` when you send `output_rules`. Send the clip again if you need the finished text.

## An empty `text` is not an error

A clip with no speech, such as background noise, returns `200` with an empty `text`, `degraded` as `null`, and no
finishing tokens. With `language_code=auto`, the `language_code` in the response is `null`. Check for an empty `text`
before you use it.

#### Python

```python
with open("note.wav", "rb") as f:
    response = client.dictate.transcribe(file=f, language_code="en-IN")

if not response.text:
    print("No speech in this clip")
```

#### JavaScript

```javascript
const response = await client.dictate.transcribe({
  file: fs.createReadStream("note.wav"),
  language_code: "en-IN",
});

if (!response.text) {
  console.log("No speech in this clip");
}
```

## On the live socket

The socket reports a problem as an `error` message, and ends with a close code. `1012` means the service is restarting:
connect again. `1013` means overloaded: wait, then connect again. `1011` with `keepalive ping timeout` means your client stopped reading, so it stopped answering the server's pings: read messages in their own task. See the [close codes](/api-reference/dictate/ws).