Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- FonadaLabs honors Retry-After cooldowns up to one hour and logs generated request IDs, status and elapsed time without exposing request content.

- FonadaLabs waits at least 60 seconds (or the Retry-After cooldown, up to one hour) and retries once on HTTP 429; timeouts and other failures are not automatically retried.

- Native FonadaLabs Kapture V3 speech-to-text with customer API keys, explicit language mapping, a 25 MB upload guard and no automatic retries other than one HTTP 429 retry.

## [2.28.0] - 2026-10-03

### Added
Expand Down
2 changes: 2 additions & 0 deletions docs/providers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Welcome to the Esperanto provider guide. This page helps you choose the right AI
| [Voyage](./voyage.md) | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| [Cohere](./cohere.md) | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ |
| [ElevenLabs](./elevenlabs.md) | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ |
| [FonadaLabs](./fonadalabs.md) | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ |

*⚠️ OpenAI-Compatible: JSON mode support depends on the specific endpoint implementation

Expand Down Expand Up @@ -342,6 +343,7 @@ Require API keys, pay-per-use:
- [Voyage](./voyage.md)
- [Cohere](./cohere.md)
- [ElevenLabs](./elevenlabs.md)
- [FonadaLabs](./fonadalabs.md)

### Cloud Enterprise Providers

Expand Down
24 changes: 24 additions & 0 deletions docs/providers/fonadalabs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# FonadaLabs

Native Kapture V3 speech-to-text over `POST https://api.fonada.ai/v3/asr/transcribe`. Audio is processed in Fonada's cloud using customer-owned credits.

```python
import os
from esperanto import AIFactory

model = AIFactory.create_speech_to_text(
"fonadalabs", "kapture-v3", {"api_key": os.environ["FONADALABS_API_KEY"]}
)
result = await model.atranscribe("lecture.mp3", language="hi")
print(result.text)
```

`FONADALABS_API_KEY` is also the environment fallback. `language` maps to multipart `language_id`; config `language` and then `FONADALABS_LANGUAGE` are fallbacks, defaulting to English (`en`). The endpoint does not promise automatic language detection. Both synchronous and asynchronous methods accept paths or binary streams. Prompt guidance is unsupported and raises ValueError.

Kapture V3 supports `en`, `bn`, `gu`, `hi`, `kn`, `ml`, `mr`, `or`, `pa`, `ta` and `te`. Send the code for the recording language. An unsupported code is rejected by Fonada before transcription.

Uploads must be nonempty and at most 25,000,000 bytes. Extract video audio and split larger recordings in the calling application's media layer. HTTP 429 waits at least 60 seconds and honors a longer `Retry-After` cooldown up to one hour, then retries the same chunk once. A cooldown longer than one hour fails immediately without retrying. Other HTTP failures, including 502/503/504, and transport errors are not automatically retried: a timeout or gateway response may follow a successful billed request. Errors identify invalid keys, denied access, exhausted credits, upload limits, invalid audio/language and rate limits without echoing response bodies or secrets.

The response maps actual `text`, `transcript` or `transcription` fields, including the `result` envelope, to `TranscriptionResponse.text`. Timings, usage, duration and speaker labels remain absent. Model discovery returns `kapture-v3` statically and does not validate a key or consume credits.

An optional `base_url` accepts either `https://api.fonada.ai/v3/asr` or the complete `/v3/asr/transcribe` endpoint, with or without a trailing slash. The provider appends the transcription path only once.
8 changes: 7 additions & 1 deletion src/esperanto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@
except ImportError:
MistralSpeechToTextModel = None # type: ignore[assignment,misc]

try:
from esperanto.providers.stt.fonadalabs import FonadaLabsSpeechToTextModel
except ImportError:
FonadaLabsSpeechToTextModel = None # type: ignore[assignment,misc]

try:
from esperanto.providers.tts.deepgram import DeepgramTextToSpeechModel
except ImportError:
Expand Down Expand Up @@ -211,6 +216,7 @@
"VertexTextToSpeechModel",
"MistralTextToSpeechModel",
"MistralSpeechToTextModel",
"FonadaLabsSpeechToTextModel",
"DeepgramTextToSpeechModel",
"DeepgramSpeechToTextModel",
"OpenRouterTextToSpeechModel",
Expand All @@ -219,4 +225,4 @@
"CohereLanguageModel",
"CohereEmbeddingModel",
"CohereRerankerModel",
]
]
1 change: 1 addition & 0 deletions src/esperanto/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class AIFactory:
"cohere": "esperanto.providers.embedding.cohere:CohereEmbeddingModel",
},
"speech_to_text": {
"fonadalabs": "esperanto.providers.stt.fonadalabs:FonadaLabsSpeechToTextModel",
"openai": "esperanto.providers.stt.openai:OpenAISpeechToTextModel",
"groq": "esperanto.providers.stt.groq:GroqSpeechToTextModel",
"elevenlabs": "esperanto.providers.stt.elevenlabs:ElevenLabsSpeechToTextModel",
Expand Down
7 changes: 7 additions & 0 deletions src/esperanto/model_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import httpx

from esperanto.common_types import Model
from esperanto.providers.stt.fonadalabs import FONADALABS_MODELS
from esperanto.utils import ModelCache

# Global cache instance for model discovery
Expand Down Expand Up @@ -1225,8 +1226,14 @@ def get_cohere_models(
raise RuntimeError(f"Failed to fetch Cohere models: {e}")


def get_fonadalabs_models(api_key: Optional[str] = None, **kwargs) -> List[Model]:
"""Static catalog; discovery does not validate credentials or bill audio."""
return list(FONADALABS_MODELS)


# Provider registry mapping provider names to discovery functions
PROVIDER_MODELS_REGISTRY: Dict[str, Callable[..., List[Model]]] = {
"fonadalabs": get_fonadalabs_models,
"openai": get_openai_models,
"openai-compatible": get_openai_compatible_models,
"anthropic": get_anthropic_models,
Expand Down
1 change: 1 addition & 0 deletions src/esperanto/providers/stt/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Speech-to-text (STT) provider implementations for audio transcription.
- **`elevenlabs.py`**: ElevenLabs speech recognition
- **`openai_compatible.py`**: Generic OpenAI-compatible STT API
- **`mistral.py`**: Mistral transcription API
- **`fonadalabs.py`**: Native Kapture V3 REST API; 25 MB uploads, language_id, plain text, one HTTP 429 retry only
- **`deepgram.py`**: Deepgram transcription API
- **`openrouter.py`**: OpenRouter transcription API

Expand Down
255 changes: 255 additions & 0 deletions src/esperanto/providers/stt/fonadalabs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
"""FonadaLabs Kapture V3 transcription over the native REST API."""

import asyncio
import logging
import os
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from typing import BinaryIO, List, Optional, Union
from uuid import uuid4

import httpx

from esperanto.common_types import TranscriptionResponse
from esperanto.providers.stt.base import (
Model,
SpeechToTextModel,
_guess_audio_content_type,
)

logger = logging.getLogger(__name__)

MAX_UPLOAD_BYTES = 25_000_000
FONADALABS_MODELS = [
Model(id="kapture-v3", owned_by="FonadaLabs", type="speech_to_text")
]


class FonadaLabsAPIError(RuntimeError):
"""Sanitized provider failure carrying a machine-readable HTTP status."""

def __init__(self, status_code: int, message: str):
self.status_code = status_code
super().__init__(message)


@dataclass
class FonadaLabsSpeechToTextModel(SpeechToTextModel):
"""Plain-text ASR with one delayed retry for explicit HTTP 429 responses."""

def __post_init__(self) -> None:
super().__post_init__()
self.api_key = self.api_key or os.getenv("FONADALABS_API_KEY")
if not self.api_key:
raise ValueError("Set FONADALABS_API_KEY or provide api_key in config.")
if self.get_model_name() != "kapture-v3":
raise ValueError("FonadaLabs supports the kapture-v3 model.")
self.base_url = (self.base_url or "https://api.fonada.ai/v3/asr").rstrip("/")
# Configuration forms may contain the documented full endpoint.
# Keep a single /transcribe suffix when constructing requests.
if self.base_url.endswith("/transcribe"):
self.base_url = self.base_url.removesuffix("/transcribe")
self._create_http_clients()

@property
def provider(self) -> str:
return "fonadalabs"

def _get_default_model(self) -> str:
return "kapture-v3"

def _get_models(self) -> List[Model]:
return list(FONADALABS_MODELS)

def _prepare(
self,
audio_file: Union[str, BinaryIO],
language: Optional[str],
prompt: Optional[str],
):
if prompt:
raise ValueError("FonadaLabs does not support transcription prompts.")
language_id = (
language
or self._config.get("language")
or os.getenv("FONADALABS_LANGUAGE")
or "en"
)
if not isinstance(language_id, str) or not language_id.strip():
raise ValueError("A non-empty FonadaLabs language code is required.")
if isinstance(audio_file, str):
filename = Path(audio_file).name
with open(audio_file, "rb") as stream:
data = stream.read(MAX_UPLOAD_BYTES + 1)
else:
stream_name = getattr(audio_file, "name", None)
filename = Path(stream_name).name if isinstance(stream_name, str) and stream_name else "audio.wav"
data = audio_file.read(MAX_UPLOAD_BYTES + 1)
if not data or len(data) > MAX_UPLOAD_BYTES:
raise ValueError(
"FonadaLabs requires non-empty audio up to 25 MB; split larger recordings."
)
return {"file": (filename, data, _guess_audio_content_type(filename))}, {
"language_id": language_id.strip()
}

@staticmethod
def _rate_limit_delay(response: httpx.Response) -> float:
"""Wait at least one minute and honor a longer server cooldown."""
value = response.headers.get("retry-after", "").strip()
try:
seconds = float(int(value))
except ValueError:
try:
deadline = parsedate_to_datetime(value)
if deadline.tzinfo is None:
deadline = deadline.replace(tzinfo=timezone.utc)
seconds = (deadline - datetime.now(timezone.utc)).total_seconds()
except (ValueError, TypeError, OverflowError):
seconds = 60
# Do not occupy a worker indefinitely for a long quota suspension.
if seconds > 3600:
raise FonadaLabsAPIError(
429,
"FonadaLabs requests a cooldown longer than one hour. Retry later after checking account limits.",
)
return max(60, seconds)

def _response(self, response: httpx.Response) -> TranscriptionResponse:
if not response.is_success:
messages = {
401: "Invalid API key",
403: "Access denied",
402: "Credits exhausted",
413: "Audio exceeds 25 MB",
422: "Unsupported audio or language",
429: "Rate or credit limit reached",
}
message = messages.get(response.status_code, "Transcription request failed")
logger.warning(
"FonadaLabs transcription failed: HTTP %s (%s)",
response.status_code,
message,
)
raise FonadaLabsAPIError(
response.status_code,
f"FonadaLabs HTTP {response.status_code}: {message}. Check request status before retrying.",
)
try:
payload = response.json()
if isinstance(payload, dict) and isinstance(payload.get("result"), dict):
payload = payload["result"]
if not isinstance(payload, dict):
raise ValueError("Expected object")
text = next(
(
payload[key]
for key in ("text", "transcript", "transcription")
if isinstance(payload.get(key), str)
),
None,
)
if text is None:
raise ValueError("Missing text")
except (ValueError, TypeError):
raise RuntimeError(
"FonadaLabs returned an unrecognized transcription response."
) from None
return TranscriptionResponse(
text=text, model=self.get_model_name(), provider=self.provider
)

def _post(self, files, data):
request_id = uuid4().hex
started = time.monotonic()
response = self.client.post(
f"{self.base_url}/transcribe",
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Request-ID": request_id,
},
files=files,
data=data,
)
logger.info(
"FonadaLabs ASR request_id=%s status=%s elapsed_seconds=%.2f",
request_id,
response.status_code,
time.monotonic() - started,
)
return response

async def _apost(self, files, data):
request_id = uuid4().hex
started = time.monotonic()
response = await self.async_client.post(
f"{self.base_url}/transcribe",
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Request-ID": request_id,
},
files=files,
data=data,
)
logger.info(
"FonadaLabs ASR request_id=%s status=%s elapsed_seconds=%.2f",
request_id,
response.status_code,
time.monotonic() - started,
)
return response

def transcribe(
self,
audio_file: Union[str, BinaryIO],
language: Optional[str] = None,
prompt: Optional[str] = None,
) -> TranscriptionResponse:
files, data = self._prepare(audio_file, language, prompt)
try:
response = self._post(files, data)
if response.status_code == 429:
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
delay = self._rate_limit_delay(response)
logger.warning(
"FonadaLabs rate limit: waiting %s seconds before one retry", delay
)
time.sleep(delay)
response = self._post(files, data)
except httpx.HTTPError as error:
logger.warning(
"FonadaLabs transcription transport failure: %s", type(error).__name__
)
raise RuntimeError(
"FonadaLabs connection or timeout error; request may already be billed. Check before retrying."
) from None
return self._response(response)

async def atranscribe(
self,
audio_file: Union[str, BinaryIO],
language: Optional[str] = None,
prompt: Optional[str] = None,
) -> TranscriptionResponse:
files, data = await asyncio.to_thread(
self._prepare, audio_file, language, prompt
)
try:
response = await self._apost(files, data)
if response.status_code == 429:
delay = self._rate_limit_delay(response)
logger.warning(
"FonadaLabs rate limit: waiting %s seconds before one retry", delay
)
await asyncio.sleep(delay)
response = await self._apost(files, data)
except httpx.HTTPError as error:
logger.warning(
"FonadaLabs transcription transport failure: %s", type(error).__name__
)
raise RuntimeError(
"FonadaLabs connection or timeout error; request may already be billed. Check before retrying."
) from None
return self._response(response)
Loading