Skip to content

Hosted speech: remote transcription and synthesis

Companion to Hosted generative AI: the same OpenAICompatSpeech transcribes and speaks on an OpenAI-wire server (tempest-ai, OpenAI itself), with no Whisper or speech model in your process.

Remote transcription (speech-to-text)

SpeechToText runs Whisper in your process: it downloads weights, holds RAM (or GPU) and competes for CPU with the rest of the service. When a server that transcribes already exists — tempest-ai, OpenAI itself, a vLLM serving Whisper — OpenAICompatSpeech sends the audio to it over the OpenAI endpoint POST {base_url}/audio/transcriptions and returns the same Transcription.

First, the settings. The key and the root are the ones openai_kwargs() uses (OPENAI_API_KEY, OPENAI_BASE_URL); only the model changes, in OPENAI_STT_MODEL:

# .env
OPENAI_API_KEY=<tempest-ai API key>
OPENAI_BASE_URL=https://ai.buscar.app.br/api/openai/v1
OPENAI_STT_MODEL=<id that GET /models lists>

Then, a service that receives the upload and transcribes it:

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI, UploadFile

from tempest_fastapi_sdk import (
    BaseAppSettings,
    HostedGenAISettings,
    register_exception_handlers,
)
from tempest_fastapi_sdk.genai import OpenAICompatSpeech
from tempest_fastapi_sdk.genai.audio import Transcription


class Settings(HostedGenAISettings, BaseAppSettings):
    """Service settings."""


settings: Settings = Settings()
speech: OpenAICompatSpeech = OpenAICompatSpeech(**settings.openai_speech_kwargs())


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """Close the backend's HTTP client on shutdown."""
    yield
    await speech.aclose()


app: FastAPI = FastAPI(lifespan=lifespan)
register_exception_handlers(app)


@app.post("/transcribe")
async def transcribe(file: UploadFile) -> Transcription:
    """Transcribe the uploaded Portuguese audio."""
    audio: bytes = await file.read()
    return await speech.transcribe(audio, language="pt", with_segments=False)

Piece by piece:

  • openai_speech_kwargs() returns model, api_key, base_url and provider="openai" — the splat builds the backend. With OPENAI_STT_MODEL empty it raises ValueError at boot, as openai_kwargs() does for OPENAI_MODEL.
  • base_url includes the version (.../v1), as with OpenAICompatGenerator; the backend appends /audio/transcriptions. For tempest-ai, pass https://ai.buscar.app.br/api/openai/v1.
  • The request is multipart with file, model, language, prompt and temperature (each only when you pass it) and response_format=verbose_json, the format that carries duration, language and segments. The key goes in Authorization: Bearer.
  • language takes the ISO-639-1 code ("pt") or a LanguageEnum (LanguageEnum.PT_BR becomes "pt"); None lets the server detect it.
  • with_segments=False returns segments=[]; duration and language are still filled.
  • prompt hands the model vocabulary — city names, product names — and temperature pins the decode temperature. How to build the prompt and its token limit are in Give Whisper the vocabulary. Whether the server honours the fields is up to it: the SDK guarantees they go in the form.
  • audio takes bytes or a local path (str or Path). A string is always a path, never a URL: the backend fetches nothing off the machine.

Drop-in for SpeechToText

OpenAICompatSpeech.transcribe takes the same language, with_segments, with_words, prompt and temperature as SpeechToText (hotwords is local-only) and satisfies the SpeechTranscriber protocol. Code that does await transcriber.transcribe(audio, language="pt", with_segments=False) does not change; and make_genai_router(speech_to_text=speech) serves /transcribe with it.

Words with timing and confidence: with_words

Use it when you need to know which word the model misheard — a pronunciation score, word-by-word captions, highlighting a doubtful span. With with_words=True the response carries words, each with its start, end and Whisper's confidence:

from tempest_fastapi_sdk.genai import OpenAICompatSpeech
from tempest_fastapi_sdk.genai.audio import Transcription, TranscriptionWord


async def doubtful_words(
    speech: OpenAICompatSpeech,
    audio: bytes,
    threshold: float = 0.5,
) -> list[TranscriptionWord]:
    """Return the words the model recognized with low confidence.

    Args:
        speech (OpenAICompatSpeech): The transcription backend.
        audio (bytes): The recording.
        threshold (float): Confidence below which a word is doubtful.

    Returns:
        list[TranscriptionWord]: The words under the threshold.
    """
    result: Transcription = await speech.transcribe(
        audio,
        language="pt",
        with_words=True,
    )
    return [
        word
        for word in result.words
        if word.probability is not None and word.probability < threshold
    ]
  • The request gains the repeated timestamp_granularities[] field: word and, while with_segments=True, segment too — OpenAI answers only the granularities asked for, and without segment the segments would come back empty. with_words=False (the default) sends no such field: the request is the same as before and words=[].
  • probability (0 to 1) is a tempest-ai extension, outside the OpenAI wire. A server that does not send it leaves probability=None, never a made-up 0.0 — hence the is not None in the filter above.
  • word arrives with no surrounding space and the punctuation attached ("dia,", "bem?"). faster-whisper 1.2.1 hands each word back with a leading space (" dia,", measured with the small model); tempest-ai strips it before answering and the SDK strips whatever arrives, so the word is the same wherever it came from. The spacing of the whole transcript stays in result.text.
  • A words item that is not an object is skipped, as in segments. A server that cannot time words may refuse the field — it arrives as a ValidationException (422 to your client).
  • The local SpeechToText takes the same with_words (Words with timing and confidence).

Server errors become exceptions that register_exception_handlers already answers:

Server status Exception What your client gets
401, 403 HostedAuthenticationError 500 — a wrong key is a configuration defect
413 FileTooLargeException (server's message) 413
400, 422 ValidationException (server's message) 422
429 HostedRateLimitError 500
5xx HostedServerError 500

On 413/400/422, details carries backend, model, status and the server_code the server sent (AUDIO_TOO_LARGE, INVALID_AUDIO).

Remote synthesis (text-to-speech)

The same OpenAICompatSpeech speaks text on a remote server through POST {base_url}/audio/speech and returns the audio bytes. It is the way for a service that does not want XTTS (or Bark) in its own process and already has a tempest-ai with TTS turned on.

The speech model is a different one, so it goes in its own argument, speech_model. With the "default" default, tempest-ai uses whatever TTS it serves; on OpenAI, pass a real id ("tts-1").

from pathlib import Path

from tempest_fastapi_sdk.genai import OpenAICompatSpeech
from tempest_fastapi_sdk.genai.audio import LanguageEnum

speech: OpenAICompatSpeech = OpenAICompatSpeech(
    "default",
    api_key="tai_...",
    base_url="https://ai.buscar.app.br/api/openai/v1",
    speech_model="default",
)


async def read_aloud(text: str, sample: Path | None) -> bytes:
    """Speak the text with a catalog voice or one cloned from the sample."""
    if sample is not None:
        return await speech.synthesize(
            text,
            language=LanguageEnum.EN_US,
            speaker_wav=sample,
        )
    return await speech.synthesize(
        text,
        language="en",
        voice="Ana Florence",
        out_path="reply.wav",
    )

Piece by piece:

  • The body is JSON: model (the speech_model), input, response_format ("wav" by default) and, when you pass it, voice.
  • speaker is the same field as voice, under the name TextToSpeech uses — that is what makes OpenAICompatSpeech satisfy the SpeechSynthesizer protocol. Both together with different values raise ValueError before any request.
  • language goes out as the language field: a LanguageEnum becomes its ISO-639-1 code (LanguageEnum.EN_US → "en", the code XTTS v2 takes too) and a string is sent as given ("zh-cn").
  • speaker_wav takes bytes or a local path and goes out base64-encoded in the reference_audio field: the sample of the voice to clone. A string is always a path, never a URL; a missing file raises FileNotFoundError naming the file, not the path.
  • out_path also writes the returned bytes.

language and reference_audio are not OpenAI wire fields

OpenAI's CreateSpeechRequest has neither: they are extensions tempest-ai reads. A server that does not know them may ignore them or refuse the request with 400.

Errors follow the transcription table: 400/422 (blank text, a voice or language the server does not serve, a sample it cannot decode) become ValidationException, 413 becomes FileTooLargeException, and the rest a typed HostedAPIError (tempest-ai's 404 CAPABILITY_DISABLED comes out as a HostedAPIError with status_code == 404). And make_genai_router(text_to_speech=speech) serves /tts with it.

Streamed synthesis

synthesize_stream sends the same body with response_format: "pcm" and stream_format: "audio" (the STREAM_RESPONSE_FORMAT and STREAM_FORMAT constants) and hands out 16-bit mono PCM at 24 kHz as the server sends it — the player starts on the first piece:

from tempest_fastapi_sdk.genai import OpenAICompatSpeech
from tempest_fastapi_sdk.genai.audio import pcm_to_wav

speech = OpenAICompatSpeech(
    "default",
    api_key="tai_...",
    base_url="https://ai.buscar.app.br/api/openai/v1",
)


async def speak_streamed(text: str) -> bytes:
    """Pass each piece to the player and return the whole WAV at the end."""
    pcm = b""
    async for piece in speech.synthesize_stream(
        text, language="pt", voice="Ana Florence"
    ):
        pcm += piece
    return pcm_to_wav(pcm)

Every piece holds whole samples: a byte the network split off a sample is kept for the next piece. Errors (400/422, 413, the rest) are the same as synthesize's and are raised before the first piece.