09.5 Text-to-Speech

Agents & multimodalLesson 5 of 1011,519 wordsOptional16 parts
Module 09 · 0 of 3 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Text-to-speech (TTS) turns the words a model wrote into sound a person can hear. It looks like the simplest modality in this module — send text, get audio — but the engineering is anything but: you choose between half a dozen provider families with different pricing units and voice ecosystems, you prepare text so it is speakable rather than readable, you manage formats, sample rates and streaming latency, and you carry the consent and impersonation responsibilities that come with synthetic voices. This lesson is the complete engineering reference: how modern TTS works, every major provider as of November 2026 (OpenAI, Gemini, OpenRouter, Anthropic, the specialists, and open-source models), full API samples, designing text for the ear, streaming an LLM straight into speech, caching and cost, voice branding and accessibility, consent and cloning risk, and how to evaluate what you ship.

What you'll learn

  • How TTS works at a high level: text normalisation, the acoustic model, the vocoder, and why modern systems are neural codec language models
  • Audio output formats (PCM/WAV, MP3, Opus, AAC, FLAC, μ-law), sample rates, bit depth and channels — and which to choose for files, web players and telephony
  • Latency as an engineering quantity: time-to-first-audio, streaming synthesis, and the chunked-transfer trick that makes speech feel instant
  • Every provider route as of November 2026: OpenAI's Speech API and its announced shutdown, Gemini TTS on the Interactions and generate_content APIs, OpenRouter's /audio/speech, why Anthropic has no speech output, the specialists (ElevenLabs, Cartesia, Deepgram, the cloud speech services), and open-source models (Kokoro, Piper, Dia and friends) with their licences
  • Full, copy-pasteable API samples for each provider, including multi-speaker dialogue and streaming PCM into a WAV container
  • How to design text for speech: verbalising numbers, dates, currencies and IDs; SSML and pronunciation dictionaries; prompting an LLM for voice-friendly output
  • Splitting long text at sentence boundaries, joining audio with crossfades, and keeping a consistent voice across chunks
  • The streaming LLM → TTS pipeline: buffering tokens, detecting sentence boundaries, queueing synthesis, and minimising time-to-first-audio
  • Caching repeated phrases by content hash, and the real cost arithmetic across per-character, per-token and per-minute pricing
  • Voice choice, branding and accessibility: consistency, multilingual voices, captions alongside audio
  • Voice cloning, consent, impersonation and disclosure — the fraud patterns and the mitigations
  • Evaluation: the round-trip intelligibility test (TTS → STT → WER), naturalness listening tests, and latency measurement

What you don't need

  • Any audio background. Sample rate, bit depth, codecs and containers are all defined from zero in Part 2.
  • API keys for most of the lesson. Every pure-local part (WAV handling, text normalisation, sentence streaming, caching, cost arithmetic, WER scoring) runs with the standard library alone and produces real output. Provider samples are labelled illustrative; everything except the API calls themselves — the WAV helpers, verbalise, SentenceBuffer, the cache and the cost/WER code — is runnable for free today.
  • How speech-to-text works. Lesson 09.4 owns transcription, WER in depth and audio inputs to chat models; this lesson links to it wherever the two meet.
  • Realtime voice agents. Transport (WebSocket vs WebRTC vs telephony), VAD, turn-taking and barge-in are lesson 09.6 and lesson 09.7; this lesson ends its streaming pipeline at the point where audio reaches a player.

Setup

The provider samples need Python 3.11+, the module's provider SDKs, and a handful of extra packages. Lessons in this module share one project folder, voice-multimodal. If you haven't created it yet, run uv init voice-multimodal --bare --python 3.13 && cd voice-multimodal first (see lesson 03.1, Part 4 for the full setup and the .env file), then add:

bash
uv add openai anthropic google-genai python-dotenv httpx pydantic elevenlabs
# or: pip install openai anthropic google-genai python-dotenv httpx pydantic elevenlabs

These samples were written and checked against openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0, httpx 0.28.1, pydantic 2.14.3 and elevenlabs 2.76.0 as of November 2026. A plain install gives you the newest release of each, and TTS SDKs move quickly (new model IDs, renamed parameters), so if a call fails with an unexpected-argument error, check the SDK's changelog for the version you installed.

The .env file holds the keys (never commit it):

bash
# .env
OPENAI_API_KEY=...
GEMINI_API_KEY=...   # optional
OPENROUTER_API_KEY=...   # optional gateway
ELEVENLABS_API_KEY=...
DEEPGRAM_API_KEY=...
CARTESIA_API_KEY=...

You will not need ANTHROPIC_API_KEY for this lesson: Anthropic has no speech output (6.2). The Cartesia and Deepgram samples use httpx directly against their REST APIs, so no extra SDK is needed; ElevenLabs uses its official SDK. Open-source samples (Part 8) install their own packages when you reach them.


What you must be able to do after this lesson#

  • Explain how text-to-speech works and its latency
  • Choose an audio format and sample rate for a use case
  • Generate speech through a provider API
  • Write text so it sounds right when spoken
  • Stream LLM output into text-to-speech with low delay
  • Evaluate speech with a round-trip transcription test

Why this matters for an AI engineer#

TTS is where a text pipeline becomes an experience. The decisions you make here — which provider, which voice, how the text is prepared, how audio is streamed — decide whether users hear a natural assistant or a robot reading Markdown aloud.

You'll hear... You'll understand it after...
"The Speech API models are deprecated — migrate to Realtime." 4.1 The current state
"TTS is priced per character, not per token." 12.1 Pricing structures
"Don't send the LLM's Markdown to the voice." 9.1 What changes when output is heard
"Our recap sounds robotic on numbers and dates." 9.2 Text normalisation in code
"Chunk the audio at sentence boundaries, not mid-word." 11.2 Sentence-boundary streaming
"We need a consistent brand voice." 13.1 Choosing and owning a voice
"Can we clone the founder's voice for the podcast?" 14.2 Voice cloning policies
"How do we know the speech is intelligible?" 15.1 The round-trip test
"Why does Gemini return WAV but OpenAI returns raw PCM?" 2.1 What comes back
"ElevenLabs vs Cartesia vs a cloud voice — which and why?" 7.5 When a specialist beats a general model

Part 1: How TTS works#

1.1 From text to sound: the modern pipeline#

Human speech is a pressure wave: air molecules vibrating, sampled by a microphone thousands of times per second. A TTS system's job is to produce that wave from letters. The classical pipeline had three stages, and you will still meet all three names in documentation and papers:

flowchart LR
    T["Input text"] --> N["1. Text normalisation<br/>(expand abbreviations, verbalise numbers)"]
    N --> P["2. Phonemisation / linguistic analysis<br/>(words → sounds, stress, intonation)"]
    P --> A["3. Acoustic model<br/>(sounds → acoustic features or codec tokens)"]
    A --> V["4. Vocoder / neural codec decoder<br/>(features → waveform)"]
    V --> O["Audio out"]
  • Text normalisation rewrites "Dr." to "Doctor", "€1,299.00" to "one thousand two hundred and ninety-nine euros", "ID-4482" to something speakable. It is a deterministic front-end, often rule-based with a few model calls for hard cases. Part 9 is entirely about this stage, because it is where most audible bugs live.
  • Phonemisation and linguistic analysis convert words into the sounds of the target language and decide stress, rhythm and intonation — the ingredients of prosody.
  • The acoustic model predicts how the sounds should be realised: classic systems predicted spectrogram frames; modern neural systems predict the tokens of a neural audio codec.
  • The vocoder turns those predictions into a waveform. Classical vocoders were signal-processing algorithms (PSOLA, WORLD, Griffin-Lim); modern ones are small neural nets that decode codec tokens into PCM.

1.2 Text normalisation: the step everyone forgets#

Text written for eyes is not text written for ears. A screen-reader-friendly sentence like "See section 3.2.1 for details, or visit https://example.com/a/b?ref=nav" is a disaster read aloud: "section three point two point one", a URL spelled letter by letter, or worse, silently mangled. Every TTS system does some normalisation internally — digits become spoken forms, currency symbols become words — but the depth varies, and the results are invisible until you listen.

The engineering consequence: you own a normalisation layer. Before text reaches the TTS API, your code (or an LLM prompted for it) should rewrite it into what a person would actually say. 9.2 implements one, and 9.4 shows the LLM-assisted version for messy input.

1.3 Prosody: the difference between correct and natural#

Prosody is the music of speech: pitch, rhythm, stress, tempo, pauses, emphasis. Two systems can pronounce every word perfectly and still sound utterly different — one flat and robotic, one alive — purely through prosody. This is why "intelligibility" (can you understand the words?) and "naturalness" (does it sound human?) are separate quality axes, and why they need separate evaluation (Part 15).

Modern neural TTS controls prosody through:

  • Voice selection — each voice has a learned style (energetic, calm, narrative).
  • Style instructions — natural-language directions: OpenAI's instructions parameter, Gemini's speech_metadata.style, ElevenLabs' audio tags ([whispers], [laughs]), SSML <prosody> on the cloud services.
  • The text itself — punctuation, sentence length and phrasing shape prosody more than any parameter. A comma is a breath; a period is a full stop with a pitch drop. This is the cheapest, most reliable prosody control you have, and Part 9 is built on it.

1.4 The model families you will meet#

Family How it makes sound Examples Character
Concatenative / parametric Splice recorded speech units or drive a signal model Legacy cloud "standard" voices, espeak-ng Fast, cheap, robotic
Neural vocoder pipelines Acoustic model predicts spectrograms, neural vocoder renders Amazon Polly neural voices, many older cloud tiers Natural-ish, controllable via SSML
Neural codec language models Autoregressive transformer predicts codec tokens; codec decoder renders OpenAI gpt-4o-mini-tts, Gemini 3.8 TTS, ElevenLabs v3/v4, Cartesia Sonic, most open-weight models Most natural; style via prompts/tags; can clone voices
Flow / diffusion TTS Iteratively denoise audio conditioned on text Some open-weight models (F5-TTS class) High quality, slower, research-heavy

Part 2: Audio formats, sample rates and latency#

2.1 What comes back: containers and codecs#

TTS APIs return bytes, and those bytes are either a container (WAV, MP3, OGG, FLAC — a file format with headers) or a raw stream (headerless PCM or μ-law samples you must wrap yourself). The mapping is not uniform across providers, which is the first trap:

Format What it is When to use it
WAV / PCM Uncompressed 16-bit samples in a RIFF container (WAV) or headerless (PCM/audio/l16) Lowest latency, zero decode cost, easy to concatenate and analyse. Gemini TTS returns WAV on unary requests and headerless PCM when streaming; OpenAI's pcm format is 24 kHz 16-bit little-endian with no header
MP3 Lossy compressed audio Default everywhere (OpenAI's default, most download-and-play flows). Smaller files, universal players, slight quality loss and encoder delay
Opus Modern lossy codec, often in OGG or WebM Best quality-per-byte for web and realtime; OpenAI offers opus
AAC Lossy codec favoured by YouTube/iOS/Android If your distribution is mobile video or podcast platforms
FLAC Lossless compression Archival or audiophile use; rarely worth it for speech
μ-law / A-law 8-bit companded PCM at 8 kHz Telephony (PSTN, Twilio-style calls). Narrowband but tiny and standard on phone lines; see lesson 09.6

2.2 Sample rate, bit depth, channels#

Three numbers describe raw audio, and TTS providers fix them for you:

  • Sample rate (Hz): how many amplitude snapshots per second. Speech needs ~8 kHz (telephone) to ~48 kHz (music). 16 kHz is the classic ASR input; 24 kHz is what Gemini TTS and OpenAI PCM emit; 44.1/48 kHz appears in "HD" outputs (ElevenLabs Pro tier).
  • Bit depth: resolution per sample. 16-bit signed is the standard; it gives ~96 dB of dynamic range, far beyond speech needs.
  • Channels: mono (1) for speech; stereo only for music or spatial effects.

2.3 Latency: time-to-first-audio vs total generation#

Two different latencies matter, and vendors quote whichever flatters them:

  • Time-to-first-audio (TTFA): request sent → first playable byte arrives. This is what a user perceives as "responsiveness". Streaming synthesis (the provider sends audio chunks as it generates them) is what makes TTFA small; batch endpoints return everything at once.
  • Total generation time: request sent → last byte. For a 2-minute narration this can be tens of seconds even when TTFA is under a second.

Streaming does not make the model generate faster — total work is the same — it changes when bytes arrive, exactly as lesson 03.3 explained for text. The practical consequence for pipelines: start playback on the first chunk and keep a small jitter buffer; never wait for the whole file (Part 11).

2.4 Wrapping raw PCM in a WAV file#

This is the single most useful pure-local skill in the lesson: Gemini streams headerless PCM, OpenAI's pcm format is headerless, and both document "wrap it yourself". Here it is in the standard library, with a synthetic signal so you can see it work end to end:

python
# audio_lab.py — run: python3 audio_lab.py  (standard library only)
import math
import wave
from array import array
from pathlib import Path

RATE = 24000  # Hz, mono, 16-bit — what Gemini TTS streams and OpenAI's pcm returns

def sine_pcm(freq: float, seconds: float, rate: int = RATE) -> bytes:
    n = int(rate * seconds)
    return array("h", (int(0.5 * 32767 * math.sin(2 * math.pi * freq * i / rate))
                       for i in range(n))).tobytes()

def pcm16_to_wav(pcm: bytes, path: str, rate: int = RATE) -> None:
    with wave.open(path, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)      # 16-bit = 2 bytes per sample
        w.setframerate(rate)
        w.writeframes(pcm)

work = Path("out"); work.mkdir(exist_ok=True)
pcm = sine_pcm(440, 0.5) + sine_pcm(660, 0.5)   # pretend this is a provider's stream
pcm16_to_wav(pcm, str(work / "demo.wav"))
print("wrote", work / "demo.wav", len(pcm), "PCM bytes ->", Path(work / "demo.wav").stat().st_size, "bytes")
Output1 line
wrote out/demo.wav 48000 PCM bytes -> 48044 bytes

48,000 samples-bytes plus a 44-byte RIFF header — exactly the "44-byte header" Gemini's docs mention. This snippet is an excerpt of audio_lab.py; the appendix has the complete file, including wav_stats (duration, peak, RMS, clipping), join_wavs (crossfade concatenation, 10.2) and SpeechCache (12.2). Save each snippet above as the file its header comment names (audio_lab.py, text_for_speech.py, sentence_stream.py, cost_and_eval.py, recap_script.py) in one folder and the pure-local parts of this lesson run end to end with no keys.


Part 3: The provider landscape#

Reference

3.1 Four routes to speech#

Route What it is Examples (as of November 2026)
General-model APIs TTS as one feature of a large model API, alongside chat OpenAI Speech API / Realtime, Gemini TTS, OpenRouter /audio/speech
Speech specialists Companies whose whole product is voice: quality, voices, cloning, low latency ElevenLabs, Cartesia, Deepgram and other voice-first vendors
Cloud speech services The hyperscalers' enterprise speech stacks: SSML, telephony, huge voice catalogues, per-character pricing Google Cloud TTS, Azure AI Speech (Neural TTS), AWS Polly
Open weights / self-hosted Models you download and run yourself Kokoro, Piper, Dia, Orpheus, XTTS-class, Chatterbox, CosyVoice

3.2 The decision table#

You need... Start with Why
Speech alongside OpenAI/Gemini chat models, one key The same provider's TTS Fewer vendors, unified billing, voice may match the assistant persona
Maximum naturalness, emotional range, character voices ElevenLabs v3/v4 or Gemini 3.8 Flash TTS Codec-LM quality leaders; audio tags / speech_metadata.style
Real-time voice-agent latency Cartesia Sonic, Deepgram Flux, ElevenLabs Flash/Turbo, or a realtime speech-to-speech model Built for streaming; measure TTFA yourself (15.4)
Multi-speaker dialogue in one request Gemini 3.8 TTS, ElevenLabs dialogue, Dia (open) Structured speaker turns or [speaker] tags
SSML control (pronunciation, say-as, breaks) Google Cloud / Azure / AWS Polly The classic enterprise speech APIs
Cloned or custom voices at scale ElevenLabs, Cartesia, Gemini voice replication Consent and policy requirements apply (Part 14)
Zero marginal cost, privacy, offline Kokoro / Piper self-hosted Apache-2.0 / GPL-3.0 trade-offs; GPU or CPU sizing
Many languages, one API Gemini 3.8 TTS (130+), ElevenLabs (70–90+) Verify per-language quality, not just the count
Cheapest possible per character Cloud "standard" voices, Piper, or budget realtime models Quality drops; test on your script

3.3 What "voice" means across providers#

A voice is a saved acoustic identity — think of it as a named preset the model conditions on. Providers expose them differently: OpenAI uses short lowercase names (coral, marin), Gemini uses capitalised persona names (Kore, Puck), ElevenLabs uses opaque IDs (JBFqnCBsd6RMkjVDRZzb), cloud services use locale-tagged names (en-US-JennyNeural). When you pick a provider, you are really picking a voice catalogue — audition before you commit (13.1).

3.4 Model churn: how to check what's current#

TTS is the most volatile corner of this module: OpenAI's entire Speech API is deprecated as of November 2026 (4.1), Gemini shipped a new TTS generation in September 2026, and OpenRouter's catalogue turns over monthly. Before hard-coding anything:

  • OpenAI: the models and deprecations pages.
  • Gemini: the models list filtered for TTS, and client.models.list() / client.voices.list() in code.
  • OpenRouter: GET /api/v1/models?output_modalities=speech — the live catalogue, no key needed for the list itself.
  • Specialists: each provider's /models or voices endpoint (Cartesia GET /models?capability=tts, Deepgram's model-string convention aura-2-{voice}-{lang} / flux-{voice}-{lang}).

Part 4: OpenAI speech#

4.1 The current state: a deprecation clock#

This is the most important OpenAI fact in the lesson, verified on the official docs as of November 2026: every model on the /v1/audio/speech endpoint is deprecated and shuts down on January 6, 2027 — tts-1, tts-1-hd, gpt-4o-mini-tts and its dated snapshots. OpenAI's guidance is to migrate new integrations to gpt-realtime-2.1-mini through the Realtime API, which is a different workflow (a persistent session, not a request/response file) and is lesson 09.7's subject.

What this means for you: the Speech API samples below are correct and will run until the shutdown, and they remain the simplest way to learn the request shape — but a new production build should plan the Realtime path or a specialist. The rest of this section documents the Speech API because it is still the reference implementation of "send text, get audio".

4.2 Synthesize to a file#

python
# s4_2_openai_speech.py — OpenAI Speech API: text -> mp3 file
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

speech_file = Path("recap.mp3")
with client.audio.speech.with_streaming_response.create(
    model="gpt-4o-mini-tts",
    voice="coral",
    input="Your order has shipped and should arrive by Thursday.",
    instructions="Speak in a warm, concise customer-service tone.",
    response_format="mp3",
) as response:
    response.stream_to_file(speech_file)
print("wrote", speech_file, speech_file.stat().st_size, "bytes")
Example output · illustrative1 line
wrote recap.mp3 58312 bytes

4.3 Streaming to a file and to a player#

The same call streams by default over chunked transfer encoding; with_streaming_response just gives you the raw stream handle. For realtime playback the SDK ships helpers:

python
# s4_3_openai_stream.py — stream PCM to the local speakers (or a file)
import asyncio
from pathlib import Path

from dotenv import load_dotenv
from openai import AsyncOpenAI
from openai.helpers import LocalAudioPlayer

load_dotenv()
client = AsyncOpenAI()


async def main() -> None:
    # Option A: play as it arrives. pcm = headerless 24 kHz 16-bit mono.
    async with client.audio.speech.with_streaming_response.create(
        model="gpt-4o-mini-tts",
        voice="coral",
        input="Streaming text to speech means the first word plays "
              "long before the last one is generated.",
        instructions="Speak clearly and at a moderate pace.",
        response_format="pcm",
    ) as response:
        await LocalAudioPlayer().play(response)

    # Option B: accumulate chunks and wrap them in WAV yourself ([2.4]).
    chunks = bytearray()
    async with client.audio.speech.with_streaming_response.create(
        model="gpt-4o-mini-tts",
        voice="sage",
        input="This sentence is written to a WAV file instead.",
        response_format="pcm",
    ) as response:
        async for chunk in response.iter_bytes():
            chunks.extend(chunk)
    import wave
    with wave.open("streamed.wav", "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(24000)          # OpenAI pcm is fixed at 24 kHz
        w.writeframes(bytes(chunks))
    print("wrote streamed.wav:", len(chunks), "PCM bytes")


asyncio.run(main())

stream_format="sse" is the alternative wire format (server-sent events instead of a raw byte stream); it is not supported on tts-1/tts-1-hd, which are the deprecated tiers anyway.

4.4 Voices, instructions and speed#

  • Voices: 13 built-ins as of November 2026 — alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer, verse, marin, cedar. OpenAI recommends marin or cedar for best quality; tts-1/tts-1-hd only support a 9-voice subset. Voices are "currently optimized for English" per the docs, though the model follows Whisper's ~50-language list. Custom voices come in two flavours: from a recording (a consent recording where the speaker reads a consent phrase, plus a matching audio sample — usable with the Speech API, the Realtime API, GPT-Live and Chat Completions audio output, referenced as {"id": "voice_..."}, and limited to eligible customers) and from a text description (prompt-to-voice — GPT-Live only; the docs state prompt-generated voices are not supported by the Text to Speech, Realtime or Chat Completions APIs).
  • instructions: natural-language style direction — accent, emotional range, intonation, impressions, speed, tone, whispering. Works on gpt-4o-mini-tts only, not tts-1/tts-1-hd.
  • speed: float 0.25–4.0, default 1.0.
  • input limit: 4,096 characters per request — split longer text (10.1).
  • Disclosure: OpenAI's usage policies require telling end users the voice is AI-generated.

4.5 Limits, pricing and the migration path#

Item Value (as of November 2026)
Input limit 4,096 characters
Output formats mp3 (default), opus, aac, flac, wav, pcm
gpt-4o-mini-tts price $0.60 per 1M text-input tokens + $12.00 per 1M audio-output tokens
tts-1 / tts-1-hd price $15 / $30 per 1M characters (different unit!)
Shutdown January 6, 2027 → migrate to gpt-realtime-2.1-mini (Realtime API)

The pricing-unit trap is real: the same provider bills per token on the new model and per character on the old ones. Your cost model must know which unit applies (12.1).


Part 5: Gemini TTS#

Deep-dive

5.1 Models and what they do#

As of November 2026 the current generation is Gemini 3.8 TTS, in two sizes with identical API schemas:

Model Positioning Languages Voice design / replication
gemini-3.8-flash-tts Flagship: fidelity, acting, dialects, long-form stability 130+ Yes
gemini-3.8-flash-lite-tts Fast/cheap workhorse; recommended gemini-3.1-flash-tts-preview replacement 101+ Yes
gemini-3.1-flash-tts-preview Previous preview — No
gemini-2.5-pro-preview-tts, gemini-2.5-flash-preview-tts Older previews, still listed — No

Input is text-only; output is audio-only. Token limits on gemini-3.8-flash-tts: 8,192 input / 16,384 output tokens. Pricing (paid tier): input $0.50/1M text tokens and output $9.00/1M audio tokens for Flash TTS through December 31, 2026, doubling January 1, 2027; Lite is $6.00/1M audio output in the same window (Google's pricing page also expresses it as ≈$0.00225 per 10 s of audio). Batch and Flex inference are supported; a free tier exists. Always re-check the pricing page — these are promotional-window prices.

5.2 Single-speaker synthesis (Interactions API)#

Google's current TTS documentation is written against the Interactions API (client.interactions.create), which accepts typed content blocks with speech_metadata annotations for style:

python
# s5_2_gemini_tts.py — Gemini 3.8 TTS: text -> WAV file (Interactions API)
import base64
from pathlib import Path

from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash-lite-tts",
    input=[{
        "type": "user_input",
        "content": [{
            "type": "text",
            "text": "Your invoice is ready. The total is one thousand two hundred euros.",
            "annotations": [{
                "type": "speech_metadata",
                "style": "calm, professional, unhurried",
            }],
        }],
    }],
    response_format={"type": "audio"},
    generation_config={
        "speech_config": [{"voice": "Kore"}],
    },
)

audio = base64.b64decode(interaction.output_audio.data)
Path("invoice.wav").write_bytes(audio)     # unary returns a complete WAV file
print("wrote invoice.wav:", len(audio), "bytes")
Example output · illustrative1 line
wrote invoice.wav: 214892 bytes

5.3 The generate_content variant#

generate_content also supports TTS — Google's migration guide documents speech_metadata per part and the AUDIO_* output formats. The classic shape still works:

python
# s5_3_gemini_generate_content.py — same synthesis via generate_content
import base64
from pathlib import Path

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.8-flash-lite-tts",
    contents=[types.Part.from_text(text=(
        "Reminder: your appointment is tomorrow at nine am."))],
    config=types.GenerateContentConfig(
        response_modalities=["AUDIO"],
        speech_config=types.SpeechConfig(
            voice_config=types.VoiceConfig(
                prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore"),
            ),
        ),
    ),
)
part = response.candidates[0].content.parts[0]
pcm = base64.b64decode(part.inline_data.data)
Path("reminder.pcm").write_bytes(pcm)       # check docs: WAV vs raw PCM per model
print("wrote reminder.pcm:", len(pcm), "bytes")

5.4 Multi-speaker dialogue#

Two speakers per request, each turn a separate text item tagged with speech_metadata.speaker:

python
# s5_4_gemini_dialogue.py — two-speaker dialogue in one request
import base64
from pathlib import Path

from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash-tts",
    input=[{
        "type": "user_input",
        "content": [
            {"type": "text", "text": "Did the deploy finish, Sam?",
             "annotations": [{"type": "speech_metadata", "speaker": "Priya",
                               "style": "cheerful and friendly"}]},
            {"type": "text", "text": "Yes — all green, we are live.",
             "annotations": [{"type": "speech_metadata", "speaker": "Sam",
                               "style": "calm and relaxed"}]},
        ],
    }],
    response_format={"type": "audio"},
    generation_config={
        "speech_config": {
            "speakers": [
                {"speaker": "Priya", "voice": "Puck"},
                {"speaker": "Sam", "voice": "Kore"},
            ],
        }
    },
)
Path("dialogue.wav").write_bytes(base64.b64decode(interaction.output_audio.data))
print("wrote dialogue.wav")

Limits: multi-speaker in one request supports up to 2 speakers with prebuilt voices. For custom designed/replicated voices, synthesize each turn individually and concatenate (mind the WAV headers — request audio/l16 or strip headers before joining, per the docs' own note).

5.5 Streaming and audio output formats#

python
# s5_5_gemini_stream.py — stream headerless PCM chunks
import base64
import wave
from pathlib import Path

from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

stream = client.interactions.create(
    model="gemini-3.8-flash-lite-tts",
    input=[{"type": "user_input", "content": [{
        "type": "text", "text": "Streaming speech arrives chunk by chunk.",
        "annotations": [{"type": "speech_metadata", "style": "neutral"}],
    }]}],
    response_format={"type": "audio", "mime_type": "audio/l16",
                     "sample_rate": 24000},
    generation_config={"speech_config": [{"voice": "Kore"}]},
    stream=True,
)
pcm = bytearray()
for event in stream:
    # Audio arrives as step.delta events whose delta.type == "audio"
    # (per the docs' streaming example — other event types carry no audio).
    if event.event_type == "step.delta" and event.delta.type == "audio":
        pcm.extend(base64.b64decode(event.delta.data))
with wave.open("streamed_gemini.wav", "wb") as w:
    w.setnchannels(1); w.setsampwidth(2); w.setframerate(24000)
    w.writeframes(bytes(pcm))
print("wrote streamed_gemini.wav:", len(pcm), "PCM bytes")

mime_type and sample_rate live inside response_format, not generation_config — putting sample_rate in the wrong dict is silently ignored. response_format.mime_type also accepts audio/mulaw and audio/alaw — the telephony formats lesson 09.6 needs. sample_rate accepts 8000/16000/24000 (default 24000). And the trap this shape avoids: iterating the stream and base64-decoding every event yields b"" for non-audio events — you must filter on event.event_type/event.delta.type or you write a header-only WAV and never notice.

5.6 The voice ecosystem#

Gemini 3.8 TTS has the richest voice tooling of any provider here:

  • 30 prebuilt studio voices (Kore, Puck, Charon, Zephyr, Fenrir, …) listed on the docs page.
  • Extended Voice Library: hundreds more, queryable in code — client.voices.list(language_code=["en-US"], gender=["female"], contexts=["Audiobook"], type_=["prebuilt"], search="warm") (GET /v1beta/voices, needs google-genai ≥ 2.25; you have 2.34).
  • Voice design: describe a persona in natural language → persistent voice_... ID with a sample-audio preview.
  • Voice replication: reference + consent audio → voice_... (stored, 200/project, 1-year TTL) or stateless voicekey_... (7-day TTL).
  • Voice remixing: modify a base voice with instructions → new voice_....
  • Inline vocal tags: <laugh>, <sigh>, <cough>, <breath>, <short pause> inside the transcript; sustained style goes in speech_metadata.style, not in the text (the model may read stage directions aloud — a documented migration gotcha).

5.7 Limits#

Text-only input, audio-only output; no function calling, search grounding, caching or thinking on TTS models. Multi-speaker capped at 2 prebuilt voices per request. Custom voices: 200 stored per project, TTL as above. Language coverage is broad but uneven — the docs list per-language support; verify your language on the supported-languages table.


Part 6: OpenRouter and the "not supported" providers#

Reference

6.1 OpenRouter /audio/speech#

OpenRouter exposes an OpenAI-compatible speech endpoint at POST /api/v1/audio/speech that returns a raw audio bytestream. Discovery is via the Models API:

python
# s6_1_openrouter_tts.py — OpenRouter speech via the openai SDK
import os
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(base_url="https://openrouter.ai/api/v1",
                api_key=os.environ["OPENROUTER_API_KEY"])

speech = client.audio.speech.create(
    model="mistralai/voxtral-mini-tts-2603",   # check output_modalities=speech for current list
    voice="en_paul_neutral",
    input="Your delivery is scheduled for tomorrow morning.",
    response_format="mp3",
)
Path("openrouter.mp3").write_bytes(speech.read())
print("wrote openrouter.mp3")
Example output · illustrative1 line
wrote openrouter.mp3

Verified facts as of November 2026 (checked against the docs and the live catalogue): input may be a string or a list of turns for multi-speaker (supported by Gemini TTS models and Fish Audio models); instructions is honoured by OpenAI gpt-4o-mini-tts, Gemini TTS and Fish Audio; response_format accepts mp3/pcm and defaults to pcm, returned with Content-Type: audio/mpeg or audio/pcm — the docs don't fix bit depth or sample rate for the generic format, so treat pcm like any headerless stream and confirm rate/depth per model; speed is a playback-speed multiplier honoured only by models that support it (others ignore it or 400 on a non-default value; Seed Audio 1.0 enforces 0.5–2.0); and the provider object carries data-policy routing preferences (zdr, data_collection — with zdr: true the request only routes to zero-data-retention endpoints) plus provider-specific passthrough under provider.options. Other routing preferences (order, only, ignore) are not applied to speech requests.

Two features matter beyond the basic call:

  • Stateless voice cloning via input_references. Instead of creating a saved voice, you attach 1–3 input_audio parts (base64 data or a public url OpenRouter downloads for you), each optionally paired with a text transcript, and optionally one image_url part for voice design or scene conditioning. No voice-creation step — the sample rides along with the request. Multi-clip models like Seed Audio 1.0 address clips as @Audio1, @Audio2, @Audio3 inside input. Which endpoints actually accept references is exposed on the endpoints API via supports_voice_cloning, supports_multiple_audio_references and supports_image_reference — check those flags rather than assuming a model slug implies cloning.
  • Per-second pricing exists. Most TTS models bill per input character, but audio-generation models such as Seed Audio 1.0 bill per second of generated audio (reported under pricing.completion in the Models API) — another pricing unit for your cost model (12.1).

Model examples seen in the live catalogue when checked (38 models): mistralai/voxtral-mini-tts-2603, x-ai/grok-voice-tts-1.0, microsoft/mai-voice-2, google/gemini-3.8-flash-tts, elevenlabs/eleven-v4, fish-audio/s2.1-pro, bytedance-seed/seed-audio-1-0, deepgram/flux-tts. The docs also use openai/gpt-4o-mini-tts-2025-12-15 as an example slug, but no openai/ speech model was in the live catalogue at check time — treat every ID here as volatile. Always query GET /api/v1/models?output_modalities=speech for the live list; OpenRouter's own blog noted the catalogue turns over and not every speech model is present at all times.

6.2 Anthropic: no speech output#

Anthropic's models overview states every current model supports "text and image input, text output" — there is no audio input, audio output, STT or TTS in the Messages API as of November 2026. A Claude voice agent is therefore always a cascade: STT → Claude (text brain) → TTS, which is exactly the architecture lessons 09.6–09.7 build. Don't plan a "Claude voice"; plan a pipeline with Claude in the middle.

6.3 Discovering audio models programmatically#

python
# s6_3_discover.py — which models can speak, on OpenRouter right now
import os
import httpx

r = httpx.get("https://openrouter.ai/api/v1/models",
              params={"output_modalities": "speech"}, timeout=30)
for m in r.json()["data"]:
    print(f"{m['id']:45} {m.get('name', '')[:40]}")

The same output_modalities filter accepts transcription (STT), audio and all — one endpoint discovers every modality.


Part 7: Specialist TTS providers#

Reference

The specialists compete on voice quality, latency, cloning and price-per-character. All facts below verified on official docs/PyPI as of November 2026; SDK versions: elevenlabs 2.76.0, cartesia 4.2.0, deepgram-sdk 7.17.0.

7.1 ElevenLabs#

The category leader for voice quality and cloning. API surface:

  • POST /v1/text-to-speech/{voice_id} — batch; /stream suffix — HTTP chunked streaming; wss://…/stream-input WebSocket — send text incrementally (built for piping an LLM's tokens straight into speech).
  • Models (per pricing page): eleven_v4 ($0.08/1K chars), eleven_v4_turbo (~$0.04, ~100 ms latency claim), eleven_v3 ($0.08, 70+ languages, audio tags [laughs]/[whispers], multi-speaker dialogue), eleven_multilingual_v2, eleven_flash_v2_5/eleven_turbo_v2_5 (ultra-low latency tier). Per-request character limits vary by model (40,000 on Flash/Turbo v2.5; smaller on v3/v4 — check the model page).
  • output_format is codec_sample_rate_bitrate (e.g. mp3_44100_128); 44.1 kHz PCM needs the Pro tier.
  • Voice library: 10,000+ community voices; instant and professional voice cloning (professional from Creator tier); enable_logging=false gives zero-retention mode for enterprise.
  • Continuity parameters (the API reference's own answer to chunk-seam prosody — see 10.3): previous_text/next_text give the neighbouring text context, and previous_request_ids/next_request_ids (up to 3 each, best with the same model) stitch the audio of adjacent generations so concatenated clips keep prosodic flow — if both text and request IDs are sent, the text is ignored. voice_settings overrides the stored voice per request (stability, similarity_boost, style, speed, use_speaker_boost); pronunciation_dictionary_locators applies up to 3 project lexicons per request (9.3); seed (0–4294967295) is a best-effort determinism hint, not a guarantee; apply_text_normalization (auto/on/off) controls whether the engine expands numbers and dates itself.
  • Pricing is per character (~1 credit/char in-app; API priced per 1K chars by model). A 2,400-char recap ≈ $0.19 on v4 — see 12.1.
python
# s7_1_elevenlabs.py — synthesize and stream with the official SDK
from pathlib import Path

from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs

load_dotenv()
client = ElevenLabs()

# Batch: iterator of audio chunks -> file
audio = client.text_to_speech.convert(
    voice_id="JBFqnCBsd6RMkjVDRZzb",       # from client.voices.get_all() or the library
    text="Your order has shipped and should arrive by Thursday.",
    model_id="eleven_v4",
    output_format="mp3_44100_128",
)
Path("eleven.mp3").write_bytes(b"".join(audio))
print("wrote eleven.mp3")

# Streaming: same call shape, chunks as they are generated
stream = client.text_to_speech.stream(
    voice_id="JBFqnCBsd6RMkjVDRZzb",
    text="Streaming begins on the first chunk, not the last.",
    model_id="eleven_v4_turbo",
    output_format="mp3_44100_128",
)
for chunk in stream:
    ...  # feed `chunk` to your audio player as it arrives
Example output · illustrative1 line
wrote eleven.mp3

7.2 Cartesia#

sonic-3.6 is the current GA model (44 languages; sonic-3.5, sonic-3, sonic-latest aliases also listed), with a dated Cartesia-Version API header (e.g. 2026-08-14). REST endpoints: POST /tts/bytes (full transcript → audio stream), POST /tts/sse (SSE events), and a WebSocket endpoint for streaming input with continuations. GET /models?capability=tts lists callable model IDs — the same discovery pattern as OpenRouter. Python SDK cartesia. On sonic-3+ models the request also accepts generation_config with volume (0.5–2.0×), speed (0.6–1.5×) and emotion (a fixed enum — neutral, happy, calm, angry, sad, etc.), plus pronunciation_dict_id and a normalization mode (auto/off/locale-pinned) — Cartesia's answer to the speed/emotion controls the general-model APIs express through prompts instead.

python
# s7_2_cartesia.py — Cartesia Sonic via httpx (no SDK needed)
import os
from pathlib import Path

import httpx
from dotenv import load_dotenv

load_dotenv()
resp = httpx.post(
    "https://api.cartesia.ai/tts/bytes",
    headers={"Cartesia-Version": "2026-08-14",
             "Authorization": f"Bearer {os.environ['CARTESIA_API_KEY']}"},
    json={
        "model_id": "sonic-3.6",
        "transcript": "Your table is ready. Please see the host stand.",
        "voice": {"id": "db6b0ed5-d5d3-463d-ae85-518a07d3c2b4"},   # or just the ID string
        "output_format": {"container": "mp3", "sample_rate": 44100,
                          "bit_rate": 128000},
        "language": "en",
    },
    timeout=60,
)
resp.raise_for_status()
Path("cartesia.mp3").write_bytes(resp.content)
print("wrote cartesia.mp3:", len(resp.content), "bytes")
Example output · illustrative1 line
wrote cartesia.mp3: 40218 bytes

7.3 Deepgram#

Two generations coexist: Flux TTS (latest, /v2/speak, streaming-first, turn-based, conversation-native) and Aura-2 (/v1/speak, voices in 7 languages, model strings like aura-2-thalia-en); original Aura is English-only. GET-style discovery is by convention: the model query param is the voice. Useful params: encoding, container, bit_rate, callback (async webhook). Default model aura-asteria-en.

python
# s7_3_deepgram.py — Deepgram Aura-2 speak request
import os
from pathlib import Path

import httpx
from dotenv import load_dotenv

load_dotenv()
resp = httpx.post(
    "https://api.deepgram.com/v1/speak",
    headers={"Authorization": f"Token {os.environ['DEEPGRAM_API_KEY']}",
             "Content-Type": "application/json"},
    params={"model": "aura-2-thalia-en", "encoding": "mp3", "container": "none"},
    json={"text": "Your prescription is ready for pickup."},
    timeout=60,
)
resp.raise_for_status()
Path("deepgram.mp3").write_bytes(resp.content)
print("wrote deepgram.mp3:", len(resp.content), "bytes")
Example output · illustrative1 line
wrote deepgram.mp3: 31904 bytes

7.4 The cloud speech services#

Google Cloud Text-to-Speech, Azure AI Speech (Neural TTS) and AWS Polly are the enterprise tier: per-character pricing, SSML support, telephony formats (μ-law), custom voice programmes and massive voice catalogues. Their defining trait for this lesson is SSML — the W3C markup language for pronunciation (<say-as>), breaks (<break time="500ms"/>), emphasis, rates and phonemes — which the general-model APIs mostly don't accept (they take natural-language style instead). Voice tiers run Standard → WaveNet/Neural2 → Chirp 3 HD → Studio on Google Cloud; Polly has standard/neural/long-form/generative engines (its neural engine is literally a sequence-to-sequence model plus a neural vocoder — the architecture from 1.1). Verify current per-character prices on each pricing page; they change and differ by tier and region.

7.5 When a specialist beats a general model#

Choose a specialist when you need: voice cloning at product scale, a specific voice catalogue (elevenlabs-style IDs), SSML, telephony-native output, sub-100 ms streaming claims you can verify, or per-character pricing at high volume. Choose a general-model API when TTS is one feature among many (chat + vision + speech under one key), when you want style control via natural language rather than SSML, or when the voice should match the assistant persona the chat model already has. There is no universal winner — run your own script through 2–3 candidates and score them (Part 15).


Part 8: Open-source and self-hosted TTS#

Reference

8.1 The landscape and licences#

Open-weight TTS trades API cost for your own GPU/CPU, latency control and privacy — but the licence is the decision, and it differs between code and weights:

Project Licence (code / weights) Best for Notes
Kokoro-82M Apache-2.0 Cheap realtime English/multilingual TTS 82M params, pip install kokoro, 24 kHz output, needs espeak-ng + misaki G2P; ~8 language packs
Piper (OHF-Voice/piper1-gpl) GPL-3.0 (embeds espeak-ng) Fully offline, CPU, embedded/RPi Successor to archived rhasspy/piper; fast; per-voice licences vary — check each
Dia (nari-labs) Apache-2.0 One-pass multi-speaker dialogue, laughs/sighs 1.6B, English; runs via Hugging Face Transformers; Dia2 also released
Orpheus Apache-2.0 Emotive dialogue, token-streaming for agents Llama-based
XTTS v2 (idiap/coqui-ai-TTS fork) Code MPL-2.0 / weights Coqui Public ML — non-commercial Zero-shot cloning research Weights forbid commercial use including outputs; Coqui is defunct
Chatterbox MIT Production voice agents, watermarking built in 23+ languages (Multilingual V3)
CosyVoice, GPT-SoVITS, Fish Speech, F5-TTS Apache-2.0 / MIT code, mixed weights Cloning, Chinese-English, research Verify each weight licence before shipping

8.2 Kokoro: the default starting point#

python
# s8_2_kokoro.py — local TTS, no API key (needs: uv add kokoro soundfile)
from kokoro import KPipeline
import soundfile as sf

pipeline = KPipeline(lang_code="a")          # 'a' = American English
generator = pipeline(
    "Your order has shipped and should arrive by Thursday.",
    voice="af_heart",
    speed=1.0,
)
for i, (gs, ps, audio) in enumerate(generator):
    sf.write(f"kokoro_{i}.wav", audio, 24000)  # 24 kHz mono float32
    print(f"chunk {i}: {gs} {ps} -> kokoro_{i}.wav")
Example output · illustrative1 line
chunk 0: Your order has shipped... -> kokoro_0.wav

Kokoro streams chunks as it generates (the generator yields per sentence-ish segment), runs on CPU for short texts, and its weights are Apache-2.0 — the safest licence on the list. It is not a cloning model; voices are fixed presets.

8.3 Piper: the offline workhorse#

pip install piper-tts (package piper-tts, repo OHF-Voice/piper1-gpl, GPL-3.0). Voices are per-language .onnx files with their own licences; inference is CPU-fast enough for Raspberry Pi-class devices. Choose it for privacy-sensitive offline products (kiosks, embedded devices, air-gapped environments) where a slightly more synthetic voice is acceptable. The original rhasspy/piper repo is archived; development moved to the OHF fork.

8.4 Dialogue and cloning models#

Dia generates multi-speaker dialogue in one pass (speaker turns marked [S1]/[S2]-style, non-verbal sounds like [laughs]), English-only, Apache-2.0 — the open equivalent of Gemini's multi-speaker or ElevenLabs' dialogue mode. Orpheus and Chatterbox target low-latency agent speech. Cloning-capable open models (XTTS v2, GPT-SoVITS, F5-TTS, IndexTTS) mostly carry non-commercial or research weight licences — fine for learning, a legal review before product use.

8.5 When self-hosting pays#

Self-host when: audio can't leave your infrastructure (health, legal, defence), volume is high enough that per-character API pricing hurts, you need deterministic latency, or you must run offline. It costs you: GPU/CPU capacity planning, voice consistency across model updates, the normalisation layer still being yours, and licence diligence. A pragmatic hybrid — cache hot phrases locally, call an API for the long tail — is covered in Part 12.


Part 9: Designing text for speech#

9.1 What changes when output is heard, not read#

Text that reads well fails when spoken. The differences that matter:

Written for eyes Written for ears
"See §3.2 / https://x.io/a?b=c" "See section three point two, or use the link I just sent"
"€1,299.00 (incl. VAT)" "one thousand two hundred and ninety-nine euros, tax included"
Markdown: bold, - bullets, tables, links Plain sentences; lists become "first… second… finally…"
"ID-4482 / TIX-1042 / rev 3.2.1" Spelled or described: "I D dash four four eight two"
Long subordinate clauses Short sentences, one idea each, natural pauses
"Dr. Smith, 14:30, 2026-11-05" "Doctor Smith, at two thirty pm on the fifth of November"

Punctuation is your prosody control: commas make breaths, periods make pitch drops, question marks make rises. An LLM asked for "voice-friendly" output will flatten lists into prose; you can also keep structure and expand it yourself (9.4).

9.2 Text normalisation in code#

text_for_speech.py is a deterministic verbaliser covering the cases that break most often — dates, times, money, percentages, versions, section numbers, emails, URLs, IDs:

python
# text_for_speech.py — run: python3 text_for_speech.py  (standard library only)
import re

ONES = ["zero","one","two","three","four","five","six","seven","eight","nine",
        "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen",
        "seventeen","eighteen","nineteen"]
TENS = ["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]

def int_words(n: int) -> str:
    if n < 20: return ONES[n]
    if n < 100: return TENS[n//10] + ("-" + ONES[n%10] if n%10 else "")
    return ONES[n//100] + " hundred" + (" and " + int_words(n%100) if n%100 else "")

def number_words(text: str) -> str:
    d = text.replace(",", "")
    if d.isdigit() and int(d) < 1_000_000:
        n = int(d)
        return int_words(n) if n < 1000 else int_words(n//1000) + " thousand" + \
               (" " + int_words(n%1000) if n%1000 else "")
    return text

def verbalise(text: str) -> str:
    out = text
    out = re.sub(r"https?://\S+", "the link in the chat", out)
    out = re.sub(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b", "the email address", out)
    MONTHS = ["January","February","March","April","May","June","July",
              "August","September","October","November","December"]
    out = re.sub(r"\b(\d{4})-(\d{2})-(\d{2})\b",
                 lambda m: f"{int(m.group(3))} {MONTHS[int(m.group(2))-1]} {m.group(1)}", out)
    def clock(m):
        h, mi = int(m.group(1)), int(m.group(2)); mer = "am" if h < 12 else "pm"
        h12 = h % 12 or 12
        if mi == 0: return f"{int_words(h12)} {mer}"
        if mi < 10: return f"{int_words(h12)} oh {ONES[mi]} {mer}"
        return f"{int_words(h12)} {int_words(mi)} {mer}"
    out = re.sub(r"\b([01]?\d|2[0-3]):([0-5]\d)\b", clock, out)
    # Money: €1,299.00 / $42.50 / £9 / $0.99 -> spoken form, cents included
    def money(m):
        sym = m.group(1)
        unit = "euros" if sym == "€" else "pounds" if sym == "£" else "dollars"
        whole, _, frac = m.group(2).partition(".")
        parts = []
        if int(whole.replace(",", "")):
            parts.append(f"{number_words(whole)} {unit}")
        cents = int(frac[:2].ljust(2, "0")) if frac else 0
        if cents:
            parts.append(f"{number_words(str(cents))} cents")
        return " and ".join(parts) if parts else f"zero {unit}"
    out = re.sub(r"([€$£])\s?([\d,]+(?:\.\d+)?)", money, out)
    def percent(m):
        whole, _, frac = m.group(1).partition(".")
        spoken = number_words(whole)
        if frac:                                    # 12.5% -> "twelve point five": digits after the point
            spoken += " point " + " ".join(ONES[int(c)] for c in frac)
        return spoken + " percent"
    out = re.sub(r"(\d+(?:\.\d+)?)\s?%", percent, out)
    out = re.sub(r"\b(\d+)\.(\d+)\.(\d+)\b",
                 lambda m: " point ".join(int_words(int(g)) for g in m.groups()), out)
    out = re.sub(r"\b(\d+)\.(\d{2})\b",
                 lambda m: f"{number_words(m.group(1))} point {int_words(int(m.group(2)))}", out)
    # IDs before bare numbers: '#4482' and 'TIX-1042' must not become
    # "four thousand…" / "one thousand forty-two" — spell them instead.
    out = re.sub(r"#(\d+)\b",
                 lambda m: "number " + " ".join(ONES[int(d)] for d in m.group(1)), out)
    out = re.sub(r"\b([A-Z]{2,})-(\d+)\b",
                 lambda m: " ".join(m.group(1)) + " dash " + " ".join(m.group(2)), out)
    out = re.sub(r"\b\d[\d,]*\b", lambda m: number_words(m.group(0)), out)
    return out

if __name__ == "__main__":     # the guard lets recap_script.py import verbalise() without running the demo
    for s in ["Your order #4482 shipped on 2026-11-05 and arrives by 14:30.",
              "The invoice total is €1,299.00, up 12.5% on last month.",
              "The total came to $42.50, down from $49.99.",
              "See section 3.2.1 or email priya@acme.example for details.",
              "We hit 98.6% uptime; ticket TIX-1042 is closed.",
              "Join at https://meet.example.com/abc or call +1-555-0199."]:
        print("IN :", s); print("OUT:", verbalise(s), "\n")
Output17 lines
IN : Your order #4482 shipped on 2026-11-05 and arrives by 14:30.
OUT: Your order number four four eight two shipped on five November two thousand twenty-six and arrives by two thirty pm.

IN : The invoice total is €1,299.00, up 12.5% on last month.
OUT: The invoice total is one thousand two hundred and ninety-nine euros, up twelve point five percent on last month.

IN : The total came to $42.50, down from $49.99.
OUT: The total came to forty-two dollars and fifty cents, down from forty-nine dollars and ninety-nine cents.

IN : See section 3.2.1 or email priya@acme.example for details.
OUT: See section three point two point one or email the email address for details.

IN : We hit 98.6% uptime; ticket TIX-1042 is closed.
OUT: We hit ninety-eight point six percent uptime; ticket T I X dash one zero four two is closed.

IN : Join at https://meet.example.com/abc or call +1-555-0199.
OUT: Join at the link in the chat or call +one-five hundred and fifty-five-one hundred and ninety-nine.

Read the imperfections honestly: #4482 becomes "number four four eight two" (order-number style, right for IDs, though a plain "#1" also reads "number one"); percentages keep their decimals as digits ("twelve point five percent"), but a bare decimal outside a percentage, money or version is only handled when it has exactly two decimals, and then reads the fraction as one number (3.14 becomes "three point fourteen"), while 1.5 million comes out as "one.five million"; and phone numbers need digit-by-digit reading, which the generic number rule gets wrong (the last output line). Money keeps its cents ($42.50 → "forty-two dollars and fifty cents", $0.99 → "ninety-nine cents") — but only for the symbol-first form: "42.50 dollars" or "USD 42.50" still slips through, fractions longer than two digits are truncated to cents, and "cents" is always plural. This is why the function is a starting layer, not a solution: domain-specific passes (order IDs, SKUs, phone numbers, currency conventions) belong in your own rules, and ambiguous cases go to an LLM (9.4).

9.3 SSML and pronunciation control#

SSML (Speech Synthesis Markup Language) is the W3C XML dialect the cloud services speak: <speak>, <voice>, <prosody rate/pitch/volume>, <break time="500ms"/>, <say-as interpret-as="digits|ordinal|telephone|date">, <phoneme>, <lang>, <emphasis>, <audio> for embedded sounds, plus vendor extensions (Polly's <amazon:effect name="whispered">, <break> strength). Example for Azure/Google/Polly-class APIs:

xml
<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US">
  Your order <say-as interpret-as="digits">4482</say-as> shipped
  <break time="300ms"/>
  <prosody rate="slow">and arrives <say-as interpret-as="date">2026-11-05</say-as>.</prosody>
</speak>

The general-model APIs don't take SSML — they take style prompts and, on some, inline tags (Gemini's <laugh>/<short pause>, ElevenLabs' [whispers]). Pronunciation dictionaries/lexicons exist on the cloud services and ElevenLabs: map "Nguyen" → "win", "SQL" → "sequel", "ACME-9" → a custom reading, once per project rather than per request.

9.4 Asking an LLM for voice-friendly output#

When the source text is messy (a support ticket, a contract clause, markdown notes), an LLM pass is the pragmatic normaliser. The prompt contract that works (see 04.8 for the pattern-card approach):

text
Rewrite the following text so it can be read aloud naturally by a TTS voice.
Rules: plain spoken sentences, no markdown, no URLs or markdown links, no
tables; expand abbreviations on first use; write numbers, dates, times and
money the way a person would say them; keep every fact and name unchanged;
keep it under 120 words; do not add commentary.

TEXT: {{text}}
SPOKEN VERSION:

Then run verbalise() over the result anyway — belt and braces, because LLMs occasionally leave a stray "e.g." or convert "€1,299" to "1299 euros" inconsistently. Validate by round-tripping through STT (15.1).


Part 10: Long text: splitting and joining#

Deep-dive

10.1 Where to split long text#

Every provider caps input per request (OpenAI 4,096 chars; Gemini ~8k input tokens; ElevenLabs per-model character limits). Split at sentence boundaries, not character counts — a sentence is the natural unit of prosody, and mid-sentence cuts produce audible seams. Lesson 05.6 owns sentence segmentation in depth; SentenceBuffer (11.2) gives you the streaming version here. For batch jobs, split into ~2–4 sentence paragraphs so each TTS call has prosodic context without hitting limits, and keep a consistent voice + style config across chunks.

10.2 Joining audio with crossfades#

Hard-cut concatenation clicks at every join. A 50–150 ms linear crossfade hides it. join_wavs from audio_lab.py does this on same-format WAVs with the standard library:

python
# audio_lab.py (excerpt — full file in the appendix) — join_wavs(paths, "out.wav", fade_ms=100)
def join_wavs(paths, out, fade_ms=100, rate=24000):
    chunks = []
    for p in paths:
        with wave.open(p, "rb") as w:
            assert w.getframerate() == rate and w.getsampwidth() == 2 and w.getnchannels() == 1
            buf = array("h"); buf.frombytes(w.readframes(w.getnframes()))
            chunks.append(buf)
    fade = int(rate * fade_ms / 1000)
    out_samples = array("h", chunks[0])
    for nxt in chunks[1:]:
        overlap = min(fade, len(out_samples), len(nxt))
        head = out_samples[:-overlap] if overlap else out_samples
        blend = array("h", (int(out_samples[len(out_samples)-overlap+i] * (1 - i/overlap)
                             + nxt[i] * (i/overlap)) for i in range(overlap)))
        out_samples = array("h", head) + blend + array("h", nxt[overlap:])
    with wave.open(out, "wb") as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(rate)
        w.writeframes(out_samples.tobytes())

Real output from the full script (three 0.4 s tones, 100 ms fades): joined : {'seconds': 1.0, 'rate': 24000, 'channels': 1, 'peak': 16383, 'rms': 11191, 'clipped_samples': 0} — 1.2 s of audio minus 2×0.1 s overlap = 1.0 s, no clipping. For compressed formats (MP3), join before encoding or re-encode after; for different sample rates, resample first (09.4 covers resampling tools).

10.3 Consistency across chunks#

Splitting introduces drift: chunk 3 may sound subtly different from chunk 1 (different prosody reset, different take). Mitigations: identical voice/style config on every call; overlap context — prepend the previous chunk's last sentence as a "lead-in" the provider reads but you trim from the audio (providers don't offer partial-return trimming, so the cleaner trick is synthesising paragraph-sized chunks, not sentence-sized); and for critical brand consistency, generate the whole passage in one call when it fits. Some vendors ship a first-class mechanism for exactly this problem: ElevenLabs' previous_text/next_text and previous_request_ids/next_request_ids stitch adjacent generations' prosody (7.1), and Cartesia's WebSocket endpoint supports continuations (7.2) — prefer those over hand-rolled lead-in tricks when your provider offers them.


Part 11: Streaming LLM output into TTS#

11.1 The pipeline#

The latency-optimal architecture for "AI speaks its answer": stream the LLM's tokens, cut them into sentences as they complete, and fire TTS per sentence — the first sentence's audio starts playing while the LLM is still writing sentence three.

flowchart LR
    L["LLM stream<br/>(tokens/deltas)"] --> B["SentenceBuffer<br/>feed(delta) → sentences"]
    B --> Q["TTS queue<br/>(bounded, ordered)"]
    Q --> S["TTS API stream<br/>per sentence"]
    S --> A["Audio queue<br/>(chunks)"]
    A --> P["Player /<br/>WebSocket client"]
    P -.->|barge-in: cancel| Q

11.2 Sentence-boundary streaming (code)#

sentence_stream.py — the buffer that turns token deltas into speakable units:

python
# sentence_stream.py — run: python3 sentence_stream.py  (standard library only)
import re

_BOUNDARY = re.compile(r"(?<=[.!?…])(?:[\"'”’)\]]+)?(?=\s|$)")

# Abbreviations that must NOT end a sentence.
# ("no" is handled separately in feed(): "No." is an abbreviation only before
# a digit — "Order No. 5" — and the word "no" everywhere else.)
_KEEP = {"mr", "mrs", "ms", "dr", "prof", "sr", "jr", "st", "vs", "etc", "e.g",
         "i.e", "fig", "approx", "dept", "est", "inc", "ltd", "co",
         "u.s", "u.k", "a.m", "p.m"}
_MAX_LEN = 320          # chars: force a break so one long sentence can't stall TTS

class SentenceBuffer:
    def __init__(self):
        self.buf = ""
    def feed(self, delta: str) -> list[str]:
        self.buf += delta
        out = []
        while True:
            # Walk every boundary and emit at the first that is not an
            # abbreviation. finditer matters: _BOUNDARY is zero-width, so
            # re-searching from the previous cut would re-match the same
            # boundary forever and stall the buffer.
            cut = None
            for m in _BOUNDARY.finditer(self.buf):
                cand = m.end()
                head = self.buf[:cand].rstrip()
                words = head.split()
                last = words[-1].lower().rstrip(".!?…\"'”’)") if words else ""
                following = self.buf[cand:].lstrip()[:1]
                if last == "no":
                    # "No." = numero only before a digit ("Order No. 5");
                    # "He said no." is a real sentence end.
                    abbrev = following.isdigit()
                else:
                    abbrev = last in _KEEP
                if not abbrev:
                    cut = cand
                    break
            if cut is None:
                break
            sentence, self.buf = self.buf[:cut].strip(), self.buf[cut:].lstrip()
            if sentence: out.append(sentence)
        if len(self.buf) > _MAX_LEN:                      # force-split very long sentences
            window = self.buf[:_MAX_LEN]
            cut = max(window.rfind(", "), window.rfind("; "), window.rfind(" — "))
            if cut > _MAX_LEN // 2:
                out.append(self.buf[: cut + 1].strip())
                self.buf = self.buf[cut + 1 :].lstrip()
        return out
    def flush(self) -> str:
        rest, self.buf = self.buf.strip(), ""
        return rest


if __name__ == "__main__":
    # A scripted LLM stream: one word per delta, like real token deltas.
    TEXT = ("Your order #4482 shipped this morning. The courier expects delivery by 14:30. "
            "Total due: €1,299.00. Questions? Reply to this email, or see section 3.2.1 for details.")
    sb = SentenceBuffer()
    for i, delta in enumerate(w + " " for w in TEXT.split()):
        for sentence in sb.feed(delta):
            print(f"[{i:02d}] SENTENCE: {sentence}")
    if rest := sb.flush():
        print(f"[end] FLUSH: {rest}")

Running it on a scripted token stream (deltas arrive word-by-word like real LLM tokens):

Output5 lines
[05] SENTENCE: Your order #4482 shipped this morning.
[11] SENTENCE: The courier expects delivery by 14:30.
[14] SENTENCE: Total due: €1,299.00.
[15] SENTENCE: Questions?
[25] SENTENCE: Reply to this email, or see section 3.2.1 for details.

Note what it got right for free: 14:30. ends a sentence (colon isn't a boundary), €1,299.00. ends one (the decimal's internal dot is followed by a digit, not whitespace), 3.2.1 doesn't break mid-version. Its honest limits: sentences ending in an abbreviation (e.g., etc., Inc.) merge with the following sentence — that's the price of not splitting "Dr. Smith"; "No." splits early if the next delta hasn't arrived yet to reveal the digit; markdown (**bold**, - ) passes through untouched — run verbalise() and a markdown-stripper upstream. And the subtle bug this code is shaped to avoid: _BOUNDARY is a zero-width match, so "find the next boundary after this one" can't be done by searching from the same position — it re-matches itself and the buffer stalls forever, dumping everything into flush(). finditer walks all candidates in one pass instead.

11.3 Backpressure, cancellation and barge-in#

  • Bounded queue: TTS is usually slower than LLM token generation per sentence but faster per byte; cap the sentence queue (e.g. 8 sentences) and apply backpressure to the LLM stream if it fills — a runaway generation shouldn't buffer an hour of audio in memory.
  • Cancellation: when the user interrupts (barge-in), cancel the in-flight TTS request and flush the audio queue and — critically — tell the LLM which part of its reply the user actually heard, or the transcript/context diverges from reality. The mechanics of VAD, end-of-turn and truncation are lesson 09.6 and 09.7; your pipeline just needs the hooks.
  • Ordering: sentences must play in order; per-sentence TTS calls can complete out of order — sequence them before the audio queue.
  • Concurrency: the simplest correct design is serial — one sentence in flight at a time, which preserves order for free and keeps burst rate-limit pressure at one request. Parallelising (a small worker pool, say 3–4 concurrent TTS calls) cuts wall-clock latency on long replies, but you must reassemble by sequence number since completions arrive out of order, and every in-flight request multiplies your burst against provider rate limits and cost spikes. For live agents the added complexity rarely pays; for batch long-form (a chapter narration) a bounded pool is reasonable — cap it and queue the overflow.

11.4 Time-to-first-audio budget#

A useful mental budget for a voice agent (verify against your own measurements — 15.4): network + STT finalisation ~200–500 ms, LLM first sentence ~300–1500 ms (model-dependent), TTS first chunk ~100–500 ms (specialists) to ~1 s (batch APIs). The sentence-streaming design hides most of the LLM+TTS latency behind the first sentence; everything after plays while later sentences synthesise. If your LLM is slow, pre-generate the greeting ("One moment…") — cached audio, zero latency (12.2).


Part 12: Caching and cost#

Deep-dive

12.1 Pricing structures compared#

TTS bills in three different units — know which yours uses before building a cost model:

Structure Who Unit Rough shape (as of Nov 2026, verify)
Per character OpenAI tts-1/tts-1-hd, ElevenLabs, cloud services characters in $15–30/1M chars (OpenAI tiers); ~$0.04–0.08/1K chars (ElevenLabs v4/v4-turbo); cloud standard ~$4/1M chars
Per token OpenAI gpt-4o-mini-tts, Gemini TTS, realtime models text in + audio out gpt-4o-mini-tts: $0.60/1M text + $12/1M audio tokens; gemini-3.8-flash-tts: $0.50/1M text + $9/1M audio (promo window)
Per minute Some flat-rate/bundled plans generated audio minutes e.g. Deepgram/enterprise bundles; check each

cost_and_eval.py (full file in the appendix) normalises all three to USD per script using ~900 chars/minute of speech.

Output4 lines
script                   chars | openai-tts-1-per-1M-chars | elevenlabs-v4-per-1K-chars |     flat-5c-per-minute
chat reply                 240 |                 0.0036 |                 0.0192 |                 0.0133
meeting recap             2400 |                 0.0360 |                 0.1920 |                 0.1333
chapter narration        14000 |                 0.2100 |                 1.1200 |                 0.7778

Read it: the same 2,400-char recap costs ~$0.04 on per-character OpenAI tts-1, ~$0.19 on ElevenLabs v4 API, ~$0.13 on a hypothetical 5¢/min flat plan. At 10k recaps/month that's $360 vs $1,920 — the unit and vendor choice is a 5× cost decision. For token-priced models you need the audio-token count, which only usage metadata or the provider's estimator gives you — measure once on real traffic, don't guess.

12.2 The content-hash cache#

Repeated phrases — greetings, disclaimers, confirmations, error messages, the meeting recap's boilerplate — are identical inputs producing identical audio. Cache them:

python
# audio_lab.py (excerpt — full file in the appendix) — SpeechCache usage
cache = SpeechCache("audio_cache")
k = cache.key("gemini-3.8-flash-lite-tts", "Kore",
              "Your order has shipped.", style="warm")
if (wav := cache.get(k)) is None:                    # miss: call the API, then put()
    wav = synthesize_via_api(...)                    # returns WAV bytes
    cache.put(k, wav)
# hit: replay wav with zero API cost and zero latency

Real output from the script's demo: cache : key=e51cf0d87247d8c00e90c7c6 first=miss->stored second=HIT hits=1 misses=1. The key must include everything that affects output: model, voice, text, style/instructions, format, sample rate — a stale cache serving the wrong voice is a classic production bug. Store WAVs on disk or object storage with a TTL; lesson 03.7 covers the general caching playbook.

12.3 Cost caps#

Per-user daily quotas on characters/minutes, alerts at spend thresholds, and a "cheap voice for drafts, premium for final" tiering are the standard controls — same pattern as 03.7's cost tracker, extended with an audio-bytes field.


Part 13: Voice, branding and accessibility#

Deep-dive

13.1 Choosing and owning a voice#

Voice is brand. Practical rules: pick from the provider's audition surface (OpenAI.fm for OpenAI voices; AI Studio for Gemini; each specialist's playground), test on your script in your language (a voice that's warm in English may be flat in yours), and pin the voice ID — providers add and retire voices, and a "latest" alias changes under you. For a consistent brand voice across providers, the only real options are a cloned/custom voice (consent required, Part 14) or accepting per-provider voices and compensating with consistent script style and pacing.

13.2 Multilingual voices and accents#

Language coverage is broad but uneven: Gemini 3.8 TTS lists 130+ languages, ElevenLabs 70–90+, OpenAI follows Whisper's ~50. A voice that speaks your second language may carry an accent or reduced expressiveness — test per language, and where quality matters, use a voice native to that locale (Gemini's voice library filters by language_code/region_code/accent). Code-switching mid-sentence (English product names inside Hindi) is where TTS struggles most; normalise mixed-language text deliberately or accept the accent.

13.3 Accessibility#

Audio must never be the only channel: always ship captions/transcripts alongside (you have the text — it's free), offer a transcript download, respect prefers-reduced-motion-style user settings analogues (a "reduce motion"-like audio setting: lower pace, no music bed), and remember screen readers already exist — your TTS competes with them, so don't auto-play audio over a screen reader's output without user control. WCAG awareness: audio content needs a text alternative; this is awareness, not legal advice — Module 12 covers compliance depth.


Deep-dive

14.1 The disclosure requirement#

OpenAI's usage policy explicitly requires disclosing that a TTS voice is AI-generated. The same expectation applies industry-wide: listeners deserve to know they're hearing synthetic speech, especially in service, news, political or emergency contexts. Build disclosure into the product (a subtle "AI voice" badge, a line in the intro, terms-of-service language) rather than relying on users to guess.

14.2 Voice cloning policies#

Every provider gates cloning: OpenAI custom voices require a consent recording (the speaker reads a consent phrase) plus a matching audio sample; Gemini voice replication takes reference and consent audio; ElevenLabs separates instant vs professional cloning tiers with verification; cloud "custom voice" programmes have their own approval flows. The engineering rule is simple: never clone without documented, verifiable consent — store the consent artifact with the voice ID, restrict who can invoke it, and log every synthesis.

14.3 Fraud patterns and mitigations#

Synthetic voices enable voice-clone fraud (fake executives authorising payments, fake family members in distress), impersonation in support/social engineering, and non-consensual intimate audio. Defences, in rough order of leverage: require step-up verification for any voice-authenticated action (a spoken passphrase is not authentication — it can be cloned); watermark or disclose synthetic speech where the platform supports it (Google's SynthID-style approaches, provider provenance features — verify current offerings); rate-limit and authenticate callers before they reach your TTS/agent; and keep human escalation for high-stakes actions. This is awareness-level coverage — Module 12 owns the security depth, and 09.10 the operational side.


Part 15: Evaluation#

Deep-dive

15.1 Intelligibility: the round-trip test#

The cheapest meaningful TTS eval: synthesize your script, transcribe it back with your STT provider (lesson 09.4), and compute WER between script and transcript. High WER means listeners likely misheard — catch it before users do:

python
# cost_and_eval.py (excerpt — full file in the appendix) — wer() + roundtrip()
def _norm(s):
    s = re.sub(r"[^\w\s]", " ", s.lower(), flags=re.UNICODE)
    return s.split()

def wer(reference, hypothesis):
    ref, hyp = _norm(reference), _norm(hypothesis)
    n = len(ref)
    if n == 0: return 0.0 if not hyp else float("inf")
    dp = [[0]*(len(hyp)+1) for _ in range(n+1)]
    for i in range(n+1): dp[i][0] = i
    for j in range(len(hyp)+1): dp[0][j] = j
    for i in range(1, n+1):
        for j in range(1, len(hyp)+1):
            c = 0 if ref[i-1] == hyp[j-1] else 1
            dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+c)
    return dp[n][len(hyp)] / n

def roundtrip(reference, transcript):
    return {"wer": round(wer(reference, transcript), 4),
            "ref_words": len(_norm(reference)), "hyp_words": len(_norm(transcript))}
Output2 lines
roundtrip good: {'wer': 0.0, 'ref_words': 11, 'hyp_words': 11}
roundtrip bad : {'wer': 0.1818, 'ref_words': 11, 'hyp_words': 11}

A WER of ~0.18 on an 11-word sentence ("morning"→"mourning", "two"→"to") is exactly the class of error a listener hears. Caveats: round-trip WER measures intelligibility through one STT, not naturalness; STT errors and TTS errors are confounded (a good TTS + bad STT looks bad); normalise both sides the same way. Note this lesson's _norm is deliberately minimal — it replaces punctuation with a space, so "hello-world" counts as two words; 09.4's wer.py deletes punctuation instead and is the canonical implementation if you need consistent scoring across lessons. 09.4 covers WER properly; Module 10A owns eval depth.

15.2 Pronunciation and normalisation errors#

The failure gallery for TTS (below): mispronounced names and acronyms (your verbalise/lexicon pass is the fix), read-aloud URLs and markdown, clipped sentences at chunk boundaries, numbers spoken wrong ("one thousand two" vs "twelve hundred" — both correct, consistency matters), wrong language detection on mixed text, and SSML/tag text read literally (Gemini reads stage directions aloud if you put them in text instead of speech_metadata.style).

15.3 Naturalness: MOS and listening tests#

MOS (Mean Opinion Score): humans rate 1–5 naturalness; the industry standard is ITU-T P.800-style listening tests — small panels, your real scripts, blind A/B between providers. It's slow and subjective but it's the only measure that captures "sounds human". Cheaper proxies: round-trip WER (intelligibility), speaking-rate and pause statistics vs a reference corpus, and preference votes in-product ("was this helpful?"). Don't trust vendor benchmark claims — run your own.

15.4 Latency measurement#

Measure TTFA properly: timestamp request start, first audio byte arrival, last byte; report p50/p95 across ≥50 runs per provider/voice/config — cold vs warm, short vs long input, streaming vs batch. Include your own pipeline stages (LLM TTFT, sentence-buffer delay, queue depth) for end-to-end voice latency. These numbers feed the budget in 11.4 and the realtime work in 09.6/09.7.


Part 16: The running example — meeting recap generator#

The module's running example ties it together: meeting notes → speakable recap → TTS audio with chapters. recap_script.py (standard library + the two helpers above):

python
# recap_script.py — meeting dict -> voice-friendly script + per-chapter cost
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from text_for_speech import verbalise
from sentence_stream import SentenceBuffer
from cost_and_eval import CHARS_PER_MINUTE

MEETING = {
    "title": "Sprint 14 sync", "date": "2026-11-05",
    "decisions": ["Ship the invoice extractor behind a flag on 2026-11-12.",
                  "Priya owns the TTS cost dashboard; first cut by Friday 17:00.",
                  "No voice cloning without written consent on file."],
    "action_items": [{"who": "Tom", "what": "Benchmark three TTS providers"},
                     {"who": "Ana", "what": "Write the cloning consent checklist"}],
}

def recap_script(m):
    lines = [f"Recap of {verbalise(m['title'])}, {verbalise(m['date'])}."]
    lines.append("Decisions: " + " ".join(verbalise(d) for d in m["decisions"]))
    lines.append("Action items: " + "; ".join(
        f"{verbalise(a['who'])} to {verbalise(a['what'])}" for a in m["action_items"]))
    return "\n\n".join(lines)

script = recap_script(MEETING)
print(script)
print(f"\n~{len(script)/CHARS_PER_MINUTE:.1f} minutes of speech, {len(script)} chars")
# Then: SentenceBuffer over an LLM stream, or split `script` into chapters and
# call your chosen TTS per chapter with the same voice config.
Output7 lines
Recap of Sprint fourteen sync, five November two thousand twenty-six.

Decisions: Ship the invoice extractor behind a flag on twelve November two thousand twenty-six. Priya owns the TTS cost dashboard; first cut by Friday five pm. No voice cloning without written consent on file.

Action items: Tom to Benchmark three TTS providers; Ana to Write the cloning consent checklist

~0.4 minutes of speech, 376 chars

The imperfections are instructive: "17:00" became "five pm", which is right to the ear but drops the 24-hour precision (add a rule if your audience schedules in 24-hour time); "Tom to Benchmark" keeps the title case of the source line (lowercase action verbs before speaking); and "TTS" is read as written, so the engine may say it as a word (add it to a pronunciation lexicon or respell it "T T S"). This is the honest state of text normalisation: good enough to ship behind a review step, never good enough to trust blind on names, IDs and times.


The TTS-specific ways production goes wrong, with the fix for each:

Failure Symptom Cause Fix
Mispronounced name/term "Nguyen" → "nuh-GWAY-en" Model never saw the word Pronunciation dictionary/lexicon, or respell in text ("win")
Reading URLs/markdown "h-t-t-p-s colon slash…" Raw markup sent to TTS verbalise() + markdown strip before the API
Wrong number spoken "one thousand two" vs "twelve hundred" Number verbalisation Your own rules; consistent style beats "correct" ambiguity
Clipped/choppy joins Click or level jump every chunk Hard concatenation join_wavs crossfade; consistent voice/format; paragraph-sized chunks
Wrong voice mid-stream Chunk 3 sounds different Voice/style param drift between calls Pin every parameter; cache by full key
Sample-rate mismatch Chipmunk or slow-motion audio Playing 24 kHz PCM as 44.1 kHz Track rate+depth+channels with the bytes; wav_stats sanity check
Garbled tail Last sentence cut off max-token/char limit hit mid-text Split at sentence boundaries before limits; check finish/length fields
SSML read aloud "less than break time equals…" SSML sent to a non-SSML API Route SSML only to cloud services; use style prompts elsewhere
Stage directions spoken "Say cheerfully:" read literally Directions embedded in text Gemini 3.8: move to speech_metadata.style; ElevenLabs: audio tags
Hallucinated words Extra sentence appears Rare but real on neural TTS Round-trip WER spot checks; shorter inputs; pinned model versions
Silent wrong-language English voice on Hindi text Auto-detect picked wrong language Pin language/locale where the API allows; verify per language
Cost spike Bill 10× expected Per-token audio output is expensive; retries multiply Cost caps, cache, batch APIs for offline work, measure usage

Common misconceptions#

Misconception Reality
"TTS is just POST text → audio; the hard part is the model." The model is the easy half. Text preparation, format/sample-rate handling, streaming, cost units and consent are where the engineering lives (Parts 2, 9–14).
"OpenAI's Speech API is the way to do TTS on OpenAI." Every Speech API model is deprecated and shuts down January 6, 2027; new builds use gpt-realtime-2.1-mini via the Realtime API (4.1).
"Streaming makes TTS faster." It doesn't change total generation time — it changes when bytes arrive. TTFA drops; total time is the same (2.3).
"WAV and PCM are the same thing." WAV is PCM plus a RIFF header. Headerless streams need you to supply rate/depth/channels yourself (2.1).
"All TTS is priced per character." Three units exist: per character, per token (text in + audio out), per minute. Your cost model must know which (12.1).
"Gemini returns the same audio format on every endpoint." Unary Interactions returns WAV on 3.8 models; older previews and streaming return headerless audio/l16; generate_content differs again. Check response_format.mime_type (5.3).
"SSML works everywhere." It's the cloud services' dialect (Google/Azure/Polly). General-model APIs take natural-language style or vendor tags instead (9.3).
"If the words are right, the speech is good." Prosody is separate from intelligibility; a flat-but-correct reading fails users the same way gibberish does (1.3).
"Open-source TTS is free, so it's free." Weights licences differ from code licences; XTTS v2 forbids commercial outputs, Piper is GPL-3.0, and you still pay in GPU/ops (8.1).
"Anthropic can do TTS like the others." It can't — all current Claude models are text/image in, text out (6.2).
"A cloned voice is fine if the person agreed verbally." Providers require documented consent artifacts; store them, restrict access, log syntheses (14.2).
"Round-trip WER proves the voice sounds good." It proves intelligibility through one STT — not naturalness, accent quality or prosody. Add listening tests (15.3).

Key takeaways#

  • TTS = normalise → synthesize → format → stream. The model is one stage; text prep and audio plumbing are yours.
  • Check the deprecation clock. OpenAI's Speech API dies January 6, 2027 → Realtime API; always verify current model IDs on official pages.
  • Know your pricing unit: per character vs per token vs per minute — a 5× cost swing on identical text.
  • Formats bite: WAV = PCM + header; headerless streams need your own rate/depth metadata; μ-law is telephony.
  • Streaming helps TTFA, not total time; sentence-boundary chunking is the standard LLM→TTS pattern.
  • Design text for the ear: verbalise numbers/dates/IDs, strip markdown, prefer short sentences — verbalise() is a starting layer, not a finish line.
  • Cache repeated phrases by full-parameter content hash; pre-generate greetings.
  • Voice is brand and liability: audition before committing, pin IDs, disclose AI voices, clone only with documented consent.
  • Evaluate intelligibility with TTS→STT round-trip WER, naturalness with listening tests, latency with p50/p95 TTFA measurement.
  • Open weights are licence-bound: Apache-2.0/MIT weights ship (Kokoro, Dia, Chatterbox); non-commercial weights (XTTS v2) don't.

Terms introduced in this lesson#

Term One-line definition
Text-to-speech (TTS) Converting written text into spoken audio
Text normalisation Rewriting text (numbers, dates, abbreviations) into speakable form before synthesis
Prosody The rhythm, stress, pitch and intonation that make speech sound natural
Vocoder The component that turns acoustic predictions into a waveform
Neural codec language model A TTS architecture that predicts audio-codec tokens autoregressively, like an LLM predicts text tokens
Codec token A discrete unit representing a short slice (~20–80 ms) of audio
PCM Raw uncompressed audio samples (here: 16-bit signed little-endian)
audio/l16 Headerless linear PCM — Gemini's streaming TTS format
WAV / RIFF A container wrapping PCM with a ~44-byte header
μ-law / A-law 8-bit companded PCM used on telephony lines
Sample rate Audio snapshots per second (Hz); 24 kHz is common for speech TTS
Time-to-first-audio (TTFA) Latency from request to first playable audio byte
Voice A named acoustic identity a TTS model conditions on
SSML Speech Synthesis Markup Language — XML dialect for pronunciation/prosody on cloud TTS
Pronunciation dictionary / lexicon A project-level map of custom word readings for TTS
Voice cloning Creating a voice model from a person's audio, usually requiring consent
Zero-retention mode Provider option that doesn't store request audio/text (e.g. ElevenLabs enterprise)
Content-hash cache Caching synthesized audio keyed by a hash of all inputs that affect output
MOS Mean Opinion Score — human 1–5 naturalness rating
WER Word error rate — (S+D+I)/N between reference and hypothesis transcripts
Barge-in User interrupting the agent mid-speech; requires cancelling TTS and audio playback
SpeechMetadata / speech_config Provider structures carrying per-turn style/speaker annotations (Gemini)

All terms are also collected in the glossary.


Exercises#

  1. Formats (2.4): extend pcm16_to_wav usage: take the sine_pcm output, split it into two halves, and write each as its own WAV. Then modify wav_stats to report per-file duration and confirm they sum correctly.
  2. Normalisation (9.2): add rules to verbalise for phone numbers (+1-555-0199 → digit-by-digit "plus one, five five five…"), order IDs (#4482 → "number four four eight two"), and SKU codes. Test each on five realistic strings.
  3. Sentence streaming (11.2): feed SentenceBuffer a stream containing "Dr. Smith said e.g. wait... what? Really." Trace which sentences emit and which merge; adjust _KEEP or add a max-words-per-sentence rule and re-run.
  4. Long text (10.2): synthesise three "chunks" locally with sine_pcm at different frequencies, join them with join_wavs at fade_ms=50 vs 200, and compare wav_stats RMS — which sounds smoother by the numbers?
  5. Cache (12.2): write a cached_synthesize(text, provider_fn) wrapper around a fake provider_fn that counts calls; show that 100 requests over 10 unique phrases make only 10 provider calls.
  6. Cost (12.1): extend cost_table with a per-token Gemini-style pricing (audio_out_per_1m_tokens + an audio-token estimate of ~25 tokens/second of audio — verify the real rate on Google's docs) and compare a 10-minute podcast chapter across all four structures.
  7. Round-trip (15.1): write roundtrip_file(script_path, transcript_path) that reads two text files and prints WER plus the differing words (extend _norm/wer to return the alignment).
  8. Providers (5/6/7): pick one provider from Parts 4–7, find its current model/voice list endpoint, and write a list_voices() function that prints name + locale for each — run it against the live API if you have a key.
  9. Design (9.4): take a real support ticket or README section, run the voice-friendly prompt through your LLM of choice, then verbalise() the output; listen for what still sounds wrong.
  10. Consent (14): draft the consent-record schema (who, when, scope, revocation, artifact link) your app would store alongside a cloned voice ID, as a Pydantic model — no API needed.
Hints for the exercises
  1. Slice the PCM bytes at an even offset (two bytes per sample) so a sample is never split; the two durations should add up to the original 1.0 s.
  2. Add the phone rule before the generic number rule, as the ID rules are, and spell each digit with ONES; test with at least one number that has a leading zero.
  3. With the current _KEEP, Dr. Smith said e.g. wait... what? Really. emits three sentences: Dr. Smith said e.g. wait..., what? and Really.. The Dr. and e.g. stay merged by design; the ellipsis ends a sentence. A max-words rule would split the first piece again.
  4. A longer fade removes more of each tone from the output (RMS changes a little) and shortens the file by fade_ms per join; numbers alone cannot tell you which sounds smoother, so open the files and listen.
  5. The wrapper hashes (text,), checks a dict, calls provider_fn only on a miss, and increments a counter; 100 requests over 10 unique phrases give a counter of 10.
  6. Audio tokens = seconds × 25; a 10-minute chapter is 15,000 audio tokens plus about 9,000 characters (roughly 2,250 text tokens) of text input at the lesson's ~900 characters per minute, so at the promotional $9 per million audio tokens that is about $0.135 for the audio plus a fraction of a cent for the text (check the live page before quoting).
  7. Return the list of word pairs from the dynamic-programming table by walking back from dp[n][m]; print only the pairs where the words differ.
  8. OpenRouter: GET /api/v1/models?output_modalities=speech; Gemini: client.voices.list(); Cartesia: GET /models?capability=tts; Deepgram: the model string is the voice (see its model list page).
  9. Expect leftovers such as abbreviations, list markers and code identifiers; they feed your next lexicon rule.
  10. Minimum fields: voice ID, speaker name, consent date, scope of use, expiry or revocation date, location of the consent recording, and who approved it.

Check yourself#

  1. What are the four stages of the classical TTS pipeline, and which two have merged in modern neural systems?
  2. Why is pcm headerless, and what three numbers must you know to play it?
  3. What is the difference between TTFA and total generation time, and does streaming change the second one?
  4. Which OpenAI Speech API models exist, and what happens to them on January 6, 2027?
  5. Name two ways Gemini 3.8 TTS lets you control style, and where each goes in the request.
  6. Why does Anthropic appear in this lesson only as "not supported"?
  7. What does output_modalities=speech do on OpenRouter's Models API?
  8. Give two concrete licence traps in open-source TTS and which models avoid them.
  9. Why is verbalise() a starting layer rather than a complete solution? Name three cases it gets wrong.
  10. When splitting long text for TTS, why split at sentence boundaries and what consistency settings must stay fixed across chunks?
  11. In the LLM→TTS stream, what three things must happen on barge-in?
  12. Name the three TTS pricing units and which providers use each.
  13. What does a content-hash TTS cache key need to include, and what's the classic bug if it doesn't?
  14. What does round-trip WER actually measure, and what does it not measure?
  15. List three mitigations for voice-clone fraud in a voice-agent product.

Further resources#


Appendix: the pure-local helper files#

The lesson's keyless backbone is five small files. text_for_speech.py (9.2), sentence_stream.py (11.2) and recap_script.py (Part 16) are shown complete in their sections; the two below are referenced by excerpts in 2.4, 10.2, 12.1, 12.2 and 15.1). Save each under the filename in its first comment, in one folder, and python3 <file> runs its demo — standard library only, no keys.

python
# audio_lab.py — run: python3 audio_lab.py  (standard library only)
import hashlib
import io
import math
import wave
from array import array
from pathlib import Path

RATE = 24000          # Hz: what Gemini TTS emits, and OpenAI's pcm format


def sine_pcm(freq: float, seconds: float, rate: int = RATE, amp: float = 0.5) -> bytes:
    """A 16-bit mono sine wave as raw PCM bytes (what a TTS stream would emit)."""
    n = int(rate * seconds)
    samples = array("h", (int(amp * 32767 * math.sin(2 * math.pi * freq * i / rate))
                           for i in range(n)))
    return samples.tobytes()


def pcm16_to_wav(pcm: bytes, path: str, rate: int = RATE) -> None:
    """Wrap headerless 16-bit mono PCM in a WAV file (RIFF header added)."""
    with wave.open(path, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)          # 16-bit = 2 bytes per sample
        w.setframerate(rate)
        w.writeframes(pcm)


def wav_bytes(pcm: bytes, rate: int = RATE) -> bytes:
    buf = io.BytesIO()
    with wave.open(buf, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(rate)
        w.writeframes(pcm)
    return buf.getvalue()


def wav_stats(path: str) -> dict:
    """Duration, peak and RMS level of a WAV file — sanity-check TTS output."""
    with wave.open(path, "rb") as w:
        n, sw, ch, rate = w.getnframes(), w.getsampwidth(), w.getnchannels(), w.getframerate()
        raw = w.readframes(n)
    samples = array("h")
    samples.frombytes(raw[: len(raw) // 2 * 2])
    peak = max((abs(s) for s in samples), default=0)
    rms = math.sqrt(sum(s * s for s in samples) / max(len(samples), 1))
    clipped = sum(1 for s in samples if abs(s) >= 32767)
    return {"seconds": round(n / rate, 3), "rate": rate, "channels": ch,
            "peak": peak, "rms": round(rms), "clipped_samples": clipped}


def join_wavs(paths: list[str], out: str, fade_ms: int = 100, rate: int = RATE) -> None:
    """Concatenate same-format WAVs with a linear crossfade at each join.

    A hard cut clicks; a short crossfade makes chunked TTS audio sound continuous.
    """
    chunks = []
    for p in paths:
        with wave.open(p, "rb") as w:
            assert w.getframerate() == rate and w.getsampwidth() == 2 and w.getnchannels() == 1, \
                f"{p}: expected {rate} Hz 16-bit mono"
            buf = array("h")
            buf.frombytes(w.readframes(w.getnframes()))
            chunks.append(buf)
    fade = int(rate * fade_ms / 1000)
    out_samples = array("h", chunks[0])
    for nxt in chunks[1:]:
        overlap = min(fade, len(out_samples), len(nxt))
        head = out_samples[:-overlap] if overlap else out_samples
        tail = nxt[overlap:]
        blend = array("h", (
            int(out_samples[len(out_samples) - overlap + i] * (1 - i / overlap)
                + nxt[i] * (i / overlap))
            for i in range(overlap)))
        out_samples = array("h", head) + blend + array("h", tail)
    with wave.open(out, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(rate)
        w.writeframes(out_samples.tobytes())


class SpeechCache:
    """Content-hash cache: identical (provider, voice, text) requests reuse audio."""

    def __init__(self, directory: str):
        self.dir = Path(directory)
        self.dir.mkdir(parents=True, exist_ok=True)
        self.hits = self.misses = 0

    @staticmethod
    def key(model: str, voice: str, text: str, **params) -> str:
        blob = repr((model, voice, text, sorted(params.items()))).encode()
        return hashlib.sha256(blob).hexdigest()[:24]

    def get(self, key: str):
        p = self.dir / f"{key}.wav"
        if p.exists():
            self.hits += 1
            return p.read_bytes()
        self.misses += 1
        return None

    def put(self, key: str, wav_bytes_: bytes) -> Path:
        p = self.dir / f"{key}.wav"
        p.write_bytes(wav_bytes_)
        return p


if __name__ == "__main__":
    work = Path("out")
    work.mkdir(exist_ok=True)

    # 1. Synthesize a "provider response": raw PCM, as Gemini stream / OpenAI pcm returns.
    pcm = sine_pcm(440, 0.5) + sine_pcm(660, 0.5)          # two "sentences" of tone
    pcm16_to_wav(pcm, str(work / "raw_stream.wav"))
    print("wav_stats:", wav_stats(str(work / "raw_stream.wav")))

    # 2. Join three chunks with a 100 ms crossfade, like long-form TTS assembly.
    for i, f in enumerate([220, 330, 440]):
        pcm16_to_wav(sine_pcm(f, 0.4), str(work / f"chunk{i}.wav"))
    join_wavs([str(work / f"chunk{i}.wav") for i in range(3)], str(work / "joined.wav"))
    print("joined :", wav_stats(str(work / "joined.wav")))

    # 3. Cache: same request twice -> one synthesis, one hit.
    cache = SpeechCache(str(work / "cache"))
    k = cache.key("gemini-3.8-flash-lite-tts", "Kore", "Your order has shipped.")
    first = cache.get(k)
    if first is None:
        first = wav_bytes(sine_pcm(520, 0.3))               # pretend this came from the API
        cache.put(k, first)
    second = cache.get(k)
    print(f"cache  : key={k} first={'miss->stored' if first else '?'} "
          f"second={'HIT' if second == first else 'MISS'} hits={cache.hits} misses={cache.misses}")
Output3 lines
wav_stats: {'seconds': 1.0, 'rate': 24000, 'channels': 1, 'peak': 16383, 'rms': 11584, 'clipped_samples': 0}
joined : {'seconds': 1.0, 'rate': 24000, 'channels': 1, 'peak': 16383, 'rms': 11191, 'clipped_samples': 0}
cache  : key=e51cf0d87247d8c00e90c7c6 first=miss->stored second=HIT hits=1 misses=1
python
# cost_and_eval.py — run: python3 cost_and_eval.py  (standard library only)
import re

# Rough speech rate used only for unit conversion; real rate varies by voice.
CHARS_PER_MINUTE = 900        # typical English narration (~15 chars/sec)


def estimate_cost(chars: int, pricing: dict, label: str) -> float:
    """Cost in USD for `chars` characters under a pricing structure.

    pricing keys (any subset):
      per_1m_chars   USD per million input characters (OpenAI tts-1 style)
      per_1k_chars   USD per thousand characters (ElevenLabs style)
      (Gemini-style per-token pricing, audio_out_per_1m_tokens, is not handled here:
       adding it with a chars->audio-token estimate is exercise 6)
      per_minute     USD per minute of generated audio (flat-rate services)
    """
    minutes = chars / CHARS_PER_MINUTE
    if "per_minute" in pricing:
        return minutes * pricing["per_minute"]
    if "per_1k_chars" in pricing:
        return chars / 1000 * pricing["per_1k_chars"]
    if "per_1m_chars" in pricing:
        return chars / 1_000_000 * pricing["per_1m_chars"]
    raise ValueError(f"{label}: no usable pricing key in {pricing}")


def cost_table(scripts: dict[str, int], pricings: dict[str, dict]) -> None:
    """scripts: name -> characters. pricings: provider -> pricing dict."""
    print(f"{'script':22} {'chars':>7} | " + " | ".join(f"{p:>22}" for p in pricings))
    for name, chars in scripts.items():
        row = " | ".join(f"{estimate_cost(chars, pricings[p], p):>22.4f}"
                         for p in pricings)
        print(f"{name:22} {chars:>7} | {row}")


# ---------- WER ----------

def _norm(s: str) -> list[str]:
    s = s.lower()
    s = re.sub(r"[^\w\s]", " ", s, flags=re.UNICODE)
    return s.split()


def wer(reference: str, hypothesis: str) -> float:
    """Word error rate: (S+D+I)/N via Levenshtein on normalised word lists."""
    ref, hyp = _norm(reference), _norm(hypothesis)
    n = len(ref)
    if n == 0:
        return 0.0 if not hyp else float("inf")
    # dp[i][j] = edit distance between ref[:i] and hyp[:j]
    dp = [[0] * (len(hyp) + 1) for _ in range(n + 1)]
    for i in range(n + 1):
        dp[i][0] = i
    for j in range(len(hyp) + 1):
        dp[0][j] = j
    for i in range(1, n + 1):
        for j in range(1, len(hyp) + 1):
            cost = 0 if ref[i - 1] == hyp[j - 1] else 1
            dp[i][j] = min(dp[i - 1][j] + 1,      # deletion
                           dp[i][j - 1] + 1,      # insertion
                           dp[i - 1][j - 1] + cost)  # substitution
    return dp[n][len(hyp)] / n


def roundtrip(reference: str, transcript: str) -> dict:
    """Score a TTS->STT round trip: how much did the words survive?"""
    return {"wer": round(wer(reference, transcript), 4),
            "ref_words": len(_norm(reference)),
            "hyp_words": len(_norm(transcript))}


if __name__ == "__main__":
    # 1. Cost arithmetic with illustrative November-2026 prices.
    scripts = {"chat reply": 240, "meeting recap": 2_400, "chapter narration": 14_000}
    pricings = {
        "openai-tts-1-per-1M-chars": {"per_1m_chars": 15.0},
        "elevenlabs-v4-per-1K-chars": {"per_1k_chars": 0.08},
        "flat-5c-per-minute": {"per_minute": 0.05},
    }
    cost_table(scripts, pricings)

    # 2. Round-trip WER on a recap script vs its (imperfect) transcript.
    ref = "Your order shipped this morning and arrives by two thirty pm."
    good = "Your order shipped this morning and arrives by two thirty pm."
    bad = "Your order shipped this mourning and arrives by to thirty pm."
    print("\nroundtrip good:", roundtrip(ref, good))
    print("roundtrip bad :", roundtrip(ref, bad))

The cost table shown in 12.1 and the WER scores in 15.1 come from this file's __main__:

Output7 lines
script                   chars | openai-tts-1-per-1M-chars | elevenlabs-v4-per-1K-chars |     flat-5c-per-minute
chat reply                 240 |                 0.0036 |                 0.0192 |                 0.0133
meeting recap             2400 |                 0.0360 |                 0.1920 |                 0.1333
chapter narration        14000 |                 0.2100 |                 1.1200 |                 0.7778

roundtrip good: {'wer': 0.0, 'ref_words': 11, 'hyp_words': 11}
roundtrip bad : {'wer': 0.1818, 'ref_words': 11, 'hyp_words': 11}

← 09.4 — Speech-to-Text | Module 09 overview | 09.6 — Audio-Native Models and Realtime Foundations →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close