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()returnsmodel,api_key,base_urlandprovider="openai"— the splat builds the backend. WithOPENAI_STT_MODELempty it raisesValueErrorat boot, asopenai_kwargs()does forOPENAI_MODEL.base_urlincludes the version (.../v1), as withOpenAICompatGenerator; the backend appends/audio/transcriptions. Fortempest-ai, passhttps://ai.buscar.app.br/api/openai/v1.- The request is multipart with
file,model,language,promptandtemperature(each only when you pass it) andresponse_format=verbose_json, the format that carriesduration,languageandsegments. The key goes inAuthorization: Bearer. languagetakes the ISO-639-1 code ("pt") or aLanguageEnum(LanguageEnum.PT_BRbecomes"pt");Nonelets the server detect it.with_segments=Falsereturnssegments=[];durationandlanguageare still filled.prompthands the model vocabulary — city names, product names — andtemperaturepins 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.audiotakesbytesor a local path (strorPath). 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:wordand, whilewith_segments=True,segmenttoo — OpenAI answers only the granularities asked for, and withoutsegmentthesegmentswould come back empty.with_words=False(the default) sends no such field: the request is the same as before andwords=[]. probability(0 to 1) is atempest-aiextension, outside the OpenAI wire. A server that does not send it leavesprobability=None, never a made-up0.0— hence theis not Nonein the filter above.wordarrives 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 thesmallmodel);tempest-aistrips 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 inresult.text.- A
wordsitem that is not an object is skipped, as insegments. A server that cannot time words may refuse the field — it arrives as aValidationException(422 to your client). - The local
SpeechToTexttakes the samewith_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(thespeech_model),input,response_format("wav"by default) and, when you pass it,voice. speakeris the same field asvoice, under the nameTextToSpeechuses — that is what makesOpenAICompatSpeechsatisfy theSpeechSynthesizerprotocol. Both together with different values raiseValueErrorbefore any request.languagegoes out as thelanguagefield: aLanguageEnumbecomes 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_wavtakesbytesor a local path and goes out base64-encoded in thereference_audiofield: the sample of the voice to clone. A string is always a path, never a URL; a missing file raisesFileNotFoundErrornaming the file, not the path.out_pathalso 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.