It's twenty to nine on a Monday evening in Pune, and Ananya Iyer has just remembered that her dental cleaning is tomorrow morning, at the same time as a meeting she can't move. She knows the clinic closed hours ago, but she rings its number anyway, expecting a voicemail. After one ring a calm voice answers: "Sunrise Dental, this is the clinic's assistant. How can I help?" She says she needs to move tomorrow's appointment to, um, Thursday if possible. There's a short pause, the voice says "Let me check Dr. Mehta's calendar," and a second later it offers two slots: "I have 11:30 in the morning, or 4:15 in the afternoon." Halfway through the second slot Ananya cuts in, "the afternoon one," and the voice stops at once and says "4:15 on Thursday it is. You'll get a text confirming it."
A call like this takes under a minute and feels ordinary, and that's what makes it hard. Nobody at the clinic picked up. Ananya's voice crossed a mobile network and reached a program that had to turn eight thousand numbers a second into words, and guess when she'd finished, even though she paused mid-sentence to think. It had to check a calendar, compose a reply, turn it into speech and get that speech back down the line before the gap felt like a machine loading. And when she talked over it, it had to stop within a fraction of a second and remember that she'd only heard half its offer.
Companies such as Vapi, Retell and Bland sell agents like this one, built on cloud telephony providers such as Twilio and Plivo. Two open-source frameworks, Pipecat (started by Daily) and LiveKit Agents, publish their code and their reasoning, and they're our main evidence for how the hard parts are solved. Here's the question this case study answers: when Ananya stops talking, how does a machine at the other end of a phone line hear her, decide she's finished, think, start answering in about a second, and stop the instant she interrupts? We'll start with the obvious design, find where it breaks, and fix it piece by piece, down to the bits of a μ-law sample and the models that decide whose turn it is.
01What we're building, and how big
1.1What it has to do
A voice AI agent is a program that holds a spoken conversation with a person over a live audio connection, here a phone call, and acts on what it hears. For the clinic, the agent has to:
- Answer real phone calls, from any phone, on the clinic's ordinary number.
- Understand what the caller says, over a phone line, in her accent, with background noise.
- Work out what to do and carry it out: look up appointments, move them, send a confirmation.
- Reply in speech that sounds natural.
- Take turns like a person: wait while the caller is still talking, answer promptly when she's done, and stop when she interrupts.
- Hand over to a human, or take a message, when it can't help.
And the qualities it needs while doing that:
- Fast: the gap between the caller finishing and the agent starting to speak should feel like a person's, about a second at most (section 1.3 explains where that figure comes from).
- Interruptible: when the caller talks over it, it stops within a few hundred milliseconds.
- Accurate on phone audio: a misheard "Thursday" books the wrong day.
- Cheap per minute: a clinic won't pay more for the agent than for a receptionist.
- Lawful: in many places, calls made or answered by an AI voice come with rules about consent and disclosure.
In the ChatGPT case study (chapter 54), a user who waits two seconds for the first word on screen barely notices. On a phone call there's no screen and no spinner; silence is the only feedback, and after a second or two of it people say "hello?" Most of this case study is about the time between Ananya's last word and the agent's first.
1.2How big is it?
Voice-agent platforms publish little traffic data; Retell AI says on its site, in late 2026, that it handles over 30 million calls a month for more than 3,000 businesses. So let's estimate the shape of the load from what every call has in common, the phone network's audio format (section 3). For now, all we need is that a call carries audio in chunks of 160 bytes, one every 20 milliseconds, in each direction.
Suppose a platform has 10,000 calls in progress at once. Each call sends one 160-byte audio chunk every 20 ms from the caller to the agent, and the agent sends audio back at the same rate while it speaks. How many chunks per second does the platform handle, and roughly how much bandwidth is that?
1.3How fast is fast enough?
People taking turns in conversation are astonishingly quick. In 2009, Tanya Stivers and colleagues published a study in PNAS of question-and-answer pairs in ten languages, from English, Japanese and Danish to Lao and Tzeltal. In every language, the most common gap between the end of a question and the start of the answer was between 0 and 200 milliseconds, and the overall median was about 100 ms. Languages differed, Danish speakers leaving longer gaps than Japanese ones, but all the averages fell within about a quarter of a second of each other.
That's faster than a person can produce a word from scratch. Stephen Levinson and Francisco Torreira pointed out in 2015 that planning and saying even a single word takes over 600 ms, so listeners must be predicting where the speaker's turn will end and preparing their reply while the speaker is still talking. Keep that in mind, because section 6 copies the same trick.
A machine doesn't have to match a human exactly, and the phone network itself was planned around a looser figure: the ITU's Recommendation G.114 (2003) says one-way delays under 150 ms give speech close to transparent interactivity, and that 400 ms is the most a network planner should allow. Pipecat's open guide to voice agents, Voice AI & Voice Agents: An Illustrated Primer (Kwindla Hultman Kramer and contributors, 2025, updated 2026), says that 500 ms is a typical human response time, that people are happy talking to agents that respond within 1,500 ms, and that its authors have shown Pipecat agents with voice-to-voice latency as low as 500 ms when all the models run in the same GPU cluster.
So our target is the voice-to-voice latency, the time from the caller's last sound to the agent's first sound as the caller hears it, and we'd like it under a second and a half, ideally well under a second. Let's see how far the obvious design gets.
02Version 1: record, transcribe, think, speak
2.1The obvious design
Every voice agent is built from the same three kinds of model. Speech-to-text (STT), also called automatic speech recognition (ASR), turns audio into words. A large language model (LLM) reads the conversation so far and writes a reply, and can ask to call tools, such as a calendar lookup (chapter 54 covers how LLMs generate text; chapter 78 covers tool calls). Text-to-speech (TTS) turns the reply into audio. Chaining the three is called a cascaded design.

An obvious way to run that loop treats each step as a separate request, like a web app calling three APIs. Record what Ananya says until she goes quiet for a while. Send the recording to a speech-to-text API and wait for the transcript. Send the transcript to an LLM and wait for the whole reply. Send the reply to a TTS API and wait for the audio file. Play the file down the phone line. Repeat.
2.2Where it breaks
Let's add up the waits for Ananya's first sentence, using round figures. Phone legs are assumptions; model figures follow the Pipecat primer's latency table (an LLM's time to first token of 450–650 ms, about 100 tokens a second after that) and a TTS that renders a whole clip before returning it.
| Phone network, caller to provider | assumed | ≈ 100 ms |
| Silence that ends the recording | fixed timeout | 800 ms |
| Upload + batch transcription of a 4.2 s sentence | 300 ms + 0.15 × 4,200 ms | ≈ 930 ms |
| Whole LLM reply, 26 words ≈ 34 tokens | 450 ms + 34 ÷ 100 tokens/s | ≈ 790 ms |
| Whole TTS clip, rendered before sending | 26 words × 25 ms + 200 ms | ≈ 850 ms |
| Phone network, provider to caller | assumed | ≈ 100 ms |
| silence Ananya hears before the first word | ≈ 3.6 s | |
That's more than twice the primer's outer limit, and around twenty times the typical gap between human turns. On a real call, Ananya would say "hello?" after two seconds, and her "hello?" would start a second recording that the agent would answer after the first, so the two would talk past each other for the rest of the call.
Latency isn't the only problem. Version 1 breaks in four distinct ways, and each becomes a section of this case study:
- It hears too late. It can't do anything until it has the whole recording. Section 3 gets the audio out of the phone network as a live stream, 20 ms at a time, and section 4 measures what a streaming design can achieve.
- It decides she's finished by the clock. An 800 ms silence is both too long (it's most of a second of dead air on every turn) and too short (Ananya paused for longer than that after "to, um"). Section 5 is about deciding when a turn has ended.
- Every stage waits for the previous one to finish. Sections 6 and 8 overlap the stages, and start some work before the caller has even finished.
- It can't be interrupted. Once the clip starts playing, it plays to the end, and the agent's memory of the conversation says Ananya heard every word. Section 7 handles barge-in.
So the first step is to stop thinking of a call as a recording. Let's look at what a phone call is made of.
03From a phone call to a stream of bytes
3.1How the call reaches the agent
Ananya's phone is on a mobile network, which is one part of the public switched telephone network (PSTN), the worldwide system of carriers and exchanges that routes calls between phone numbers. Inside the PSTN, a call is set up by signalling between exchanges, and once set up, it carries her voice as a continuous stream of digital samples. (Section 3.2 shows what those samples are.)
Sunrise Dental's number doesn't belong to a desk phone. It's rented from a cloud telephony provider such as Twilio or Plivo, which has agreements with carriers, so calls to its numbers are delivered over the internet to the provider's servers, using a protocol called SIP (Session Initiation Protocol, RFC 3261, 2002). A connection between a carrier and a provider that carries SIP calls is called a SIP trunk.
SIP only sets the call up and tears it down. Ananya's carrier sends an INVITE message saying "here is a call for this number", the provider answers 100 Trying and later 200 OK, the carrier confirms with ACK, and at the end one side sends BYE. Inside the INVITE and the 200 OK ride two SDP descriptions (Session Description Protocol), an offer and an answer (RFC 3264), in which the two sides agree on an audio format and tell each other which IP address and port to send audio to.
Her audio travels separately, in RTP packets (Real-time Transport Protocol), which chapter 53 describes in detail: a 12-byte header with a sequence number and a timestamp, then the audio. For phone audio, the default is one packet every 20 ms (RFC 3551, 2003). So signalling and media take different paths, often through different servers.

When the INVITE for the clinic's number arrives, the provider has to decide what to do with the call. It asks the clinic's application: it sends an HTTP request, a webhook, to a URL the clinic configured (Twilio calls the reply TwiML; Plivo calls the URL the Answer URL and the reply Plivo XML). The application answers with a short XML document of instructions. For a voice agent, the instruction is "connect this call's audio to my server over a WebSocket". On Twilio that's a Stream element, with the WebSocket's wss:// URL, nested inside a Connect instruction; on Plivo it's a Stream element with bidirectional="true".
?Why doesn't the agent speak SIP and RTP itself?
It can, and some systems do. But SIP and RTP bring a lot with them: carrier interconnects, format negotiation, jitter buffers (chapter 53, section 6), keypresses carried as special RTP events (RFC 4733), transfers and recording. A provider already runs all of that. Taking the audio over a WebSocket, a long-lived two-way connection over ordinary HTTPS, lets an agent developer write a web server instead of a phone switch.
How should the call's audio reach the agent?
- Any web server can handle it
- The provider handles carriers, jitter, keypresses, transfers
- Same model on Twilio, Plivo and others
- JSON and base64 add overhead per frame
- TCP: a lost packet stalls everything behind it
- One more hop between the caller and the agent
- One hop fewer
- UDP: late packets can be skipped instead of waited for
- You operate SIP, RTP, jitter buffers and carrier interop yourself
Most hosted voice-agent builders started with WebSocket media streams, because Twilio's has been generally available since March 2020 and works with any stack. As the field matured, SIP moved closer to the models: LiveKit offers a SIP service that turns a phone call into a participant in a LiveKit room, and OpenAI's generally available realtime model (August 2025) accepts calls over SIP directly. Either way the provider stays in the path, because the phone number and the carrier connection live there.
3.2What a phone call is made of
Sound is a pressure wave, and a microphone turns it into a voltage that rises and falls with the wave. To carry it digitally, the phone network measures that voltage at regular intervals, which is called sampling, and rounds each measurement to one of a fixed set of levels, which is called quantisation.

Both are set by ITU-T G.711, first published in 1972 and still the format of most of the world's phone calls. It samples 8,000 times a second, with 8 bits per sample, so a call is 64,000 bits a second in each direction. Sampling 8,000 times a second can only represent frequencies below half that, 4 kHz, and phone systems filter the voice to roughly 300 to 3,400 Hz before sampling. Twenty milliseconds of audio is 160 samples, one byte each: the 160-byte chunk from section 1.2.
Eight bits gives only 256 levels, which is too few to space evenly. Speech is mostly quiet with occasional loud peaks, and with 256 evenly spaced levels a quiet sound uses only the few levels near zero, so its rounding error is large compared with the sound itself. G.711's answer is companding (compressing, then expanding): space the levels closely near zero and widely at high amplitudes, roughly logarithmically, so that the rounding error stays about the same fraction of the signal whether it's quiet or loud. G.711 defines two versions of the curve. μ-law is used in North America and Japan, and A-law in Europe, India and most of the rest of the world; links between countries use A-law, and the μ-law side converts.


That smooth curve is the idea. What a telephone exchange computes is a piecewise version made of eight straight segments, each twice as wide as the one before, which turns into a neat bit layout. A μ-law byte holds:
| Bits | Field | What it holds |
|---|---|---|
| 1 | sign | 1 for positive, 0 for negative (after inversion) |
| 3 | segment | which of the 8 segments, 0 to 7: roughly the position of the sample's highest set bit, a crude logarithm |
| 4 | step | which of 16 evenly spaced steps within that segment |
To encode a 16-bit sample, the standard reference code takes its absolute value, clips it at 32,635, adds a bias of 132 (so that every segment starts at a power of two), finds the highest set bit to get the segment, takes the four bits just below it as the step, and finally inverts all eight bits. That inversion is inherited from early digital phone lines, which needed a steady supply of 1 bits to stay synchronised: quiet audio produces bytes near zero, and inverting them turns those into bytes full of 1s. Every segment has 16 steps, but each segment is twice as wide as the one before, so the step size doubles from one segment to the next. That's the logarithm.
This program implements that encoder and its decoder, then does two things. It builds one 20 ms frame of a 440 Hz tone and wraps it the way a media stream does: base64-encoded inside a JSON message (section 3.3 explains why). Then it compares μ-law with plain 8-bit audio, with 256 evenly spaced levels, for a loud, a medium and a quiet tone, using the signal-to-noise ratio (SNR): how much stronger the signal is than the rounding error, in decibels, where every 10 dB is a factor of ten in power and higher is better.
20 ms at 8000 Hz = 160 samples -> 160 bytes of mu-law
first 8 bytes: ff b9 ab a4 a0 a0 a4 aa
base64 payload 216 chars, minimal JSON message 260 bytes
bit rate: 64 kbit/s of audio, ~104 kbit/s as JSON
amplitude mu-law SNR linear 8-bit SNR
16000 39.1 dB 43.5 dB
2000 37.6 dB 25.5 dB
250 33.0 dB 8.5 dBLook at the first line of the table first. For a loud tone, plain 8-bit audio wins slightly, 43.5 dB against 39.1, because its even steps are finer than μ-law's coarse steps at the top of the range. Then watch the quiet tones. At an amplitude of 2,000, plain 8-bit drops to 25.5 dB while μ-law holds 37.6. At 250, about the level of a soft consonant or a caller far from the microphone, plain 8-bit has an SNR of 8.5 dB, meaning the rounding noise is only about seven times weaker than the speech, while μ-law still manages 33 dB. That steadiness across loudness is what companding buys, and it's why 8 bits a sample were enough for the phone network.
Notice that the frame's first byte is ff: a sample of zero, encoded as the lowest positive level, then inverted, so silence on a μ-law line is a run of ff bytes. And the first four lines of output are the costs a voice agent sees on every frame: 160 bytes of audio become a 216-character base64 string and a JSON message of at least 260 bytes.
3.3The media stream protocol
Once the WebSocket is open, the provider and the agent exchange small JSON messages. Twilio's and Plivo's protocols differ in names but agree on the shape.
Twilio's Media Streams send a connected and a start message, then a media message for each chunk of the caller's audio, dtmf when she presses a key, mark (explained below) and stop. Each media message carries a track, a chunk number counting from 1, a timestamp in milliseconds since the stream started, and a payload, which is the audio in base64. Twilio's docs state that the format is always audio/x-mulaw at 8,000 samples a second, mono. Base64 is needed because JSON can only hold text, and it turns every 3 bytes into 4 characters, so 160 bytes become 216 characters, which with the JSON around them is the roughly 60% overhead the TryIt showed.
Plivo's Audio Streams use start, media, dtmf, playedStream and clearedAudio events, with chunks of about 20 ms. Plivo offers a choice of encodings: 16-bit linear samples (audio/x-l16) at 8,000 or 16,000 samples a second, and audio/x-mulaw at 8,000. On a call that came in from the phone network, the 16 kHz option is the narrowband audio resampled; it doesn't recover anything above 4 kHz that the network threw away.
In the other direction, the agent sends audio to be played to the caller: a media message on Twilio, a playAudio message on Plivo, each with a base64 payload in the agreed format. An agent may send audio faster than real time, a whole sentence in one go, and the provider queues it and plays it out at the right pace. Two more message types exist because of that queue, and both will matter in section 7:
- A marker in the queue. The agent sends a named
mark(Twilio) orcheckpoint(Plivo) after a piece of audio. When playback reaches that point, the provider sends the name back. That's how the agent learns how much of what it sent has been heard. - Flush the queue. The agent sends
clear(Twilio) orclearAudio(Plivo), and the provider throws away all queued audio that hasn't been played yet. Twilio's docs describe it as emptying "all buffered audio".
Twilio announced bidirectional streams, with marks and clear for barge-in, in June 2020. Here's what a few frames from Ananya's call look like on a Twilio-style stream (payloads shortened):
{"event": "start", "start": {"callSid": "CA9f…", "mediaFormat": {"encoding": "audio/x-mulaw", "sampleRate": 8000, "channels": 1}}}
{"event": "media", "media": {"track": "inbound", "chunk": "212", "timestamp": "4240", "payload": "/////7mrpKCgpKq5…"}}
{"event": "media", "media": {"track": "inbound", "chunk": "213", "timestamp": "4260", "payload": "/v7+/fv7+vv8/f7+…"}}
{"event": "mark", "mark": {"name": "reply-3-sentence-1"}}3.4Why phone audio is hard to transcribe
Phone audio is harder to transcribe than a laptop microphone's, for three reasons. Missing frequencies: everything above about 3.4 kHz is gone, and the hissing consonants, s, f, th, put much of their energy up there, so "fifty" and "sixty" are harder to tell apart. Many speech-to-text models expect 16 kHz input, so the agent resamples the stream, computing in-between samples to double the rate; that gives the model the rate it expects but leaves the band above 4 kHz empty. Lossy hops: a mobile call may pass through the mobile network's own codec, a gateway's conversion to G.711, an A-law to μ-law conversion and the agent's resampler, and each adds a little distortion. Real rooms: callers ring from buses and speakerphones, and on a phone call there's no device the agent controls to clean the audio, so LiveKit's docs recommend model-based noise cancellation for SIP callers.
So the speech-to-text model should be one that does well on telephone audio, it should be given the words it should expect, such as the doctors' names, and the agent should read back anything costly to get wrong. That's why the clinic's agent confirms "4:15 on Thursday" before booking.
With a live stream of audio arriving, we can stop waiting for whole recordings. How fast can the loop go now?
04Where the second goes
4.1A voice-to-voice budget
With audio arriving as a stream, every stage can start as soon as it has something to work on. Speech-to-text can transcribe while Ananya is still talking, the LLM can start the moment she finishes, and TTS can start speaking the first words of the reply while the LLM is still writing the rest. Section 6 shows how. First, let's see what such a design costs at best, stage by stage.
Pipecat's primer publishes a breakdown of a voice-to-voice round trip for an agent talking to a user in a browser, from the microphone to the speaker. Here it is adapted to a phone call: the primer's numbers for the agent's own stages, and an assumed figure for each direction of the phone path, which covers the mobile network, the carrier, the provider's jitter buffer (chapter 53, section 6) and the WebSocket.
| Phone path in: network, carrier, provider buffer | assumed | ≈ 100 ms |
| Transcription and endpointing | Pipecat primer | 300 ms |
| LLM time to first token | Pipecat primer | 650 ms |
| Collect the first sentence | Pipecat primer | 20 ms |
| TTS time to first byte | Pipecat primer | 120 ms |
| Phone path out | assumed | ≈ 100 ms |
| voice-to-voice, streaming cascade | ≈ 1.3 s | |
That's under the primer's 1,500 ms target, and a third of version 1's 3.6 seconds. It also shows where to look next. Two rows are three quarters of the total: deciding that Ananya has finished (part of the 300 ms "transcription and endpointing" row, and in version 1 a flat 800 ms), and the LLM's time to first token (TTFT), the wait between sending a request and receiving the first piece of the reply. Chapter 54 explains why TTFT exists: the model must read the whole prompt before it can write anything. A small, fast model on a nearby server can probably bring it to a couple of hundred milliseconds; a large model far away can take more than a second.
?Why not just pick the fastest model?
Because the LLM also has to get the conversation right: understand "move it to Thursday if possible", call the calendar tool with the right arguments, and cope when the tool returns nothing. The primer notes that the models most used for voice agents in 2026 are chosen for low latency together with reliable instruction following and function calling. Every millisecond saved elsewhere can be spent on a smarter model, which is a big reason the other stages are squeezed so hard.
4.2Physics sets a floor
Part of the phone rows comes down to distance. Ananya is in Pune. If her call lands at a provider's servers in Mumbai, but the agent runs in a data centre in the eastern United States, every chunk of audio crosses about 13,000 km of fibre each way. Light in fibre covers about 200,000 km a second, so that's at least 65 ms one way and 130 ms round trip, before any router, and the real path is longer. A cascaded agent pays the distance more than once: audio goes to the agent, the agent calls the speech-to-text service, then the LLM, then TTS, and if each of those lives in a different region, each call adds a round trip.
So the biggest controllable cost in the budget is deciding when Ananya has finished, and that turns out to be a hard problem in its own right.
05Knowing when she's finished
5.1Detecting speech
Before the agent can decide a turn has ended, it has to know, for every 20 ms of audio, whether Ananya is speaking at all. A component that answers that question is called a voice activity detector (VAD).
A simple VAD measures loudness: compute the energy of each frame, and call it speech when the energy is above a threshold. That works in a quiet room and fails on a bus, where traffic noise is louder than a soft voice. So production agents use small neural networks trained to tell speech from noise. Probably the most widely used is Silero VAD, released under the MIT licence. According to its README, it handles 8 kHz and 16 kHz audio, the model is about two megabytes, and processing one chunk of 30 ms or more takes under a millisecond on one CPU thread. Pipecat feeds it chunks of 256 samples at 8 kHz or 512 at 16 kHz, both 32 ms. The primer estimates that running Silero on one call's audio uses less than an eighth of a typical virtual machine's CPU core.
A VAD gives a stream of speech probabilities. Turning that into "she started talking" and "she stopped talking" takes a few settings. In Pipecat, a VAD reports speech only after start_secs of continuous speech (0.2 s by default), counts a frame as speech above a confidence of 0.7 and a minimum volume of 0.6, and reports that speech has stopped after stop_secs of quiet.
5.2Why a silence timeout fails
An obvious rule for the end of a turn is a silence timeout: when the VAD has heard nothing for some fixed time, the turn is over. For years that was Pipecat's default: stop_secs was 0.8 seconds until February 2026.
Trouble is, people pause in the middle of what they're saying. Ananya said "I'd like to move my appointment to, um, Thursday", and between "to" and "Thursday" she stopped for most of a second to remember which day she was free. A short timeout cuts her off at "to", and the agent starts answering a sentence that hasn't been finished. A long timeout waits through her pause correctly, but then also adds that full wait after every finished sentence, on every turn of every call.
This program simulates it. It builds a loudness value for each 20 ms frame of Ananya's sentence, with her 900 ms pause, and runs an energy VAD with a fixed silence timeout over it. Then it does the same for 2,000 synthetic callers who pause two to five times per turn, mostly briefly, sometimes for longer to think. Its pause lengths are made up for the illustration, but the shape of the trade-off doesn't depend on them.
##.#####################################.......................#######........##.##############.....
timeout 500 ms: cut her off mid-sentence
timeout 1000 ms: replied 1000 ms after she finished
timeout cut off early wait after a real end
200 ms 95.2% 199 ms
400 ms 62.5% 399 ms
600 ms 42.9% 599 ms
800 ms 25.0% 799 ms
1000 ms 12.2% 999 ms
1500 ms 1.6% 1499 msIts first line draws Ananya's sentence, one character per 40 ms: # where the VAD hears speech and . where it doesn't. That long run of dots in the middle is her "um" pause; the isolated dots inside the speech are brief dips on consonants, so a VAD needs some smoothing. A 500 ms timeout cuts her off in that pause. A 1,000 ms timeout lets her finish and then makes her wait a full second.
Below it, the table makes the trade explicit. There is no good setting. Every timeout short enough to feel responsive cuts off a large share of turns (roughly a quarter of them at 800 ms, in this synthetic population), and every timeout long enough to rarely cut anyone off adds a second or more of dead air to every reply. Its wait column is just the timeout itself, because a silence detector can't know a turn has ended until the silence has lasted the full timeout. To do better, the agent needs to know something silence can't tell it: whether what she's said so far sounds finished.
A caller is reading out a 10-digit phone number in groups: '98220… 41… 7365'. What does a 600 ms silence timeout do?
5.3Turn detection from words: LiveKit's model
A transcript carries a lot of evidence about whether a turn is finished. "I'd like to move my appointment to" ends on a preposition and is clearly incomplete; "Thursday afternoon, please" is clearly complete. In December 2024 LiveKit published a turn detector: a small language model that reads the last few turns of the transcript and outputs the probability that the user has finished. Version one was a 135-million-parameter transformer based on Hugging Face's SmolLM v2, English only, looking at a sliding window of the last four turns, taking about 50 ms per prediction. LiveKit reported 85% fewer unintentional interruptions than using VAD alone.
This model works with the VAD: it adjusts how long the agent waits. When VAD reports silence, the agent asks the model, and a high probability of "finished" means the agent waits only a short minimum before replying, while a low probability makes it wait longer for more speech. In LiveKit Agents' 2026 docs those bounds are a min_delay of 0.5 s and a max_delay of 3.0 s. In December 2025 LiveKit replaced the model with a multilingual one, a Qwen2.5 model with 0.5 billion parameters distilled from a 7-billion-parameter teacher, covering 14 languages, and reported 39% fewer false interruptions than its previous version at the same detection rate.
A text model has a blind spot, though. It sees words, not voices. "I'd like Thursday" is a complete sentence on paper, but said with a rising, trailing intonation it means "...or maybe Friday, let me think". And the transcript of the last fraction of a second may not exist yet when the decision has to be made.
5.4Turn detection from sound: Smart Turn
Daily's team took the other route with Smart Turn, an open model that listens to the audio itself. They published the first version in March 2025, an English-only proof of concept built on a 580-million-parameter speech model that took about 150 ms on a GPU and about 1.5 seconds on a CPU. Version 2, in July 2025, was about 95 million parameters and covered 14 languages. Version 3, announced in September 2025, rebuilt it on the encoder of OpenAI's Whisper Tiny speech model: about 8 million parameters, an 8 MB file, 23 languages, and inference in 12.6 ms on a c7a.2xlarge cloud CPU instance by Daily's own benchmark, nearly a hundred times faster than version 2 on a small instance. Model, training code and training data are all open, under the BSD 2-clause licence.
Smart Turn takes up to the last 8 seconds of the user's turn as 16 kHz audio and outputs one number: the probability that the turn is complete. It hears what a transcript can't, like intonation, a drawn-out "uhhh", the rhythm of a list that hasn't ended. It's used together with VAD in a particular way, which the Smart Turn README describes as: once VAD detects silence, run Smart Turn on the entire recording of the user's turn.
Those probabilities are illustrative; the mechanics are from Pipecat's docs. Since Pipecat 0.0.102 (February 2026), Smart Turn v3 is Pipecat's default way to end a turn, and the same release cut the VAD's default stop_secs from 0.8 to 0.2 seconds, which is safe now because a short silence only triggers the question. If Smart Turn keeps saying "incomplete" while the silence continues, a fallback timer, 3 seconds by default, ends the turn anyway.
LiveKit went the same way in 2026. In June it published an audio-based turn detector of its own, and reported a false cut-off rate of 9.9% when it must decide within 300 ms, against 12.9% for Deepgram's Flux; both figures are LiveKit's.

How should the agent decide that the caller has finished?
- Trivial
- No extra model
- Short N cuts people off mid-sentence
- Long N adds N to every reply
- Understands grammar and context
- Can look at the previous turns
- Can't hear intonation
- Has to wait for the transcript
- Hears intonation and hesitation
- Runs on CPU in about 10 ms
- Doesn't wait for the transcript
- Another model to run per call
- Needs a fallback timer
- One model, one stream
- Can emit an early, tentative end of turn
- Ties turn-taking to one vendor's STT
Pipecat and LiveKit both moved from the first option to the others between late 2024 and 2026. Both now use a model by default, and they've converged on one architecture: cheap VAD finds candidate pauses, and a model judges each one. Pipecat chose audio, LiveKit started with text and added audio. Deepgram's Flux, launched in October 2025, folds the decision into speech-to-text: its announcement says the same model that produces transcripts also models conversational flow and turn detection, and it can emit a tentative "eager" end of turn 150–250 ms before the confirmed one. OpenAI's Realtime API offers a similar choice, with a silence-based server_vad mode and a semantic_vad mode whose eagerness setting trades responsiveness for patience.
Knowing when Ananya has finished as early as possible is half the budget. Most of the other half is everything that happens after: the LLM and TTS, and how much of their work can start before the turn is over.
06Streaming every stage
6.1Transcribing while she talks
In version 1, transcription started when the recording ended. A streaming speech-to-text service takes audio as it arrives, over its own WebSocket, and sends back words as it recognises them. It sends two kinds of results. Interim (or partial) results are its current best guess at the words so far, which it may revise as more audio arrives: "I'd like to move my appointment to Thurs" may become "...to Thursday". A final result is a stretch of transcript the service won't change any more.
So by the time Ananya stops talking, almost the whole transcript already exists. What remains is the last few hundred milliseconds of audio and the step from interim to final, so the primer's budget gives transcription and endpointing together only 300 ms.
6.2Speaking the first sentence while the LLM writes the rest
An LLM streams its reply as tokens (chapter 54, section 4). A streaming TTS can also start producing audio before it has the whole text. But TTS can't work token by token: how to pronounce a word, and with what intonation, depends on the words after it. "Read" is said differently in "I'll read it" and "I've read it", and a question's rising tone depends on the question mark at the end. So agents collect the LLM's tokens into a sentence and send each sentence to TTS as soon as it's complete. Pipecat's default text aggregation mode works this way, and its source notes that the mode sounds more natural but adds latency, about 200–300 ms per sentence.
Finding sentence ends sounds trivial and isn't. "Dr. Mehta has Thursday slots" contains a full stop that isn't a sentence end, and so does "4.15" in some styles of writing times. Pipecat uses a sentence-splitting library combined with its own punctuation checks for this.
This program puts numbers on three designs for the clinic's first reply: version 1; a streaming design that waits for the LLM's whole reply before calling TTS; and one that sends the first sentence to TTS as soon as it's written. It uses the primer's figures (450 ms to the first token, 100 tokens a second, 120 ms for TTS to start), counts about 1.3 tokens per word, and splits sentences with a regular expression that refuses to break before a digit.
first sentence sent to TTS: 'Sure, I can move that for you.'
v1: batch everything 100 + 800 + 930 + 788 + 850 + 100 = 3,568 ms
stream, wait for full reply 100 + 300 + 788 + 120 + 100 = 1,408 ms
stream, sentence by sentence 100 + 300 + 541 + 120 + 100 = 1,161 msRead the three totals from the top. Streaming and a turn model together take the reply from about 3.6 seconds to 1.4, mostly by deleting the batch transcription and the fixed silence. Sending the first sentence early saves roughly another quarter of a second, and it would save more on a longer reply, because the wait no longer grows with the length of the answer. Notice what's left in the last line, though: of the 541 ms for the first sentence, 450 is the LLM's time to first token. Once everything streams, TTFT is the largest single cost, which is why the next trick goes after it.
Notice also that the first sentence the LLM wrote was a short acknowledgement. Voice agents' prompts often ask the model to start with one, because a short first sentence reaches TTS sooner, and it's what a person on the phone would say anyway.
6.3Starting before she's finished
Levinson and Torreira's observation from section 1.3 was that people start preparing an answer while the other person is still talking. Agents can do the same. As soon as a pause looks like it might be the end of a turn, start the LLM on the transcript so far, before the turn detector has confirmed it. If the turn did end, the reply is already partly written. If she keeps talking, throw the speculative reply away and start again later.
LiveKit Agents added this as preemptive generation in version 1.2 (July 2025), off by default, and turned it on by default in version 1.5 (March 2026). By default only the LLM runs early; TTS waits until the turn is confirmed, so the agent never says anything based on a guess, and the speculative response is discarded and regenerated if the conversation's context changes in the meantime. Pipecat's equivalent strategy starts on an early, tentative end of turn from the speech-to-text service, such as Flux's eager end-of-turn event, and discards the response if the user resumes or the final transcript differs from the tentative one.
What it costs is wasted LLM work: every false start is a request whose tokens were paid for and never used. That's the same trade CPUs make with speculative execution (chapter 44): spend some work that may be thrown away, in exchange for having the answer ready when the guess is right.
Here is the clinic's first turn with all of this in place, as a timeline from Ananya's last word.
Pipecat's code makes this pipeline literal. Everything that moves through an agent is a frame, a small typed object: audio, a transcription, LLM text, TTS audio. A pipeline is a chain of processors, each with an input queue, each taking frames from the one before and pushing frames to the next: speech-to-text turns audio frames into transcription frames, an aggregator turns those into a context, the LLM turns the context into text frames. Because every processor works frame by frame, every stage streams by construction. And because frames can also flow upstream, a processor can send control signals back up the chain, which the next section depends on.
6.4TTS that starts in a tenth of a second
Last in the budget is TTS's time to first byte. TTS vendors compete on it, and their published figures are claims about the model alone, before network time: ElevenLabs said in December 2024 that its Flash model generates speech in 75 ms plus application and network latency, and Cartesia describes its Sonic models (2025) as having around 90 ms of model latency, or as low as 40 ms for a turbo variant. Pipecat's budget allows 120 ms for this stage, including the network.
What matters as much as the first byte is that the TTS streams the rest faster than real time, and that it returns word timestamps, the time offset at which each word starts in the audio it produced. Pipecat's docs list Cartesia, ElevenLabs and Rime as providers that return them. A voice agent can work without them, and that's exactly where the next problem starts.
07When she interrupts
7.1Four things that must happen at once
The agent is reading out the slots: "I have 11:30 in the morning, or 4:15 in the afternoon. Which one works better?" At "4:15 in the after-", Ananya says "the afternoon one". Talking over someone to cut them short is called barge-in, and people do it all the time on the phone. When it happens, four things have to go right, quickly.
- Stop the sound. By the time Ananya speaks, audio for the rest of the sentence, and maybe the next one, has already been generated, because TTS runs faster than real time. Some of it is queued in the agent's output, and some may already be queued at the provider. All of it must be thrown away, or Ananya hears the agent carry on talking over her for a second or two.
- Stop the work. The LLM may still be writing and TTS still synthesising. Both must be cancelled, or their output will arrive a moment later and start playing again.
- Remember what was said. The conversation context holds the reply the LLM wrote. But Ananya never heard "Which one works better?", and if the context says she did, the LLM will reason from a conversation that didn't happen. So the context must be cut to what she heard.
- Don't overreact. A cough, a "mm-hmm", a door slamming or the agent's own voice coming back down the line must not stop the agent mid-word.
7.2Stopping the sound and the work
Pipecat's design shows how to make "cancel everything" reliable. When the user aggregator decides that the user has started a new turn while the bot is speaking, it broadcasts an interruption frame both upstream and downstream through the pipeline from section 6.3. Every processor that receives it cancels its current task and discards the data frames in its queue. Any in-flight LLM request is cancelled mid-stream, and the output transport drains its audio queue, discarding everything that hasn't played. Control frames like this one are handled ahead of the queued data, so the interruption doesn't wait behind the audio it's meant to cancel.
A provider's queue needs the same treatment, and clear and clearAudio exist for it (section 3.3). How much is queued there depends on how the agent sends audio. If it sends each sentence as soon as TTS produces it, the provider may hold several seconds, and everything depends on the clear message. If the agent paces its output at real-time speed, sending each 20 ms as it's due, the provider holds very little and most of the queue stays in the agent, where cancelling it is a local operation.
7.3Remembering only what was heard
To truncate the context correctly, the agent needs to know which words had been played when the interruption happened. It knows what it sent. What it needs is a map from playback time to words, and that's what TTS word timestamps provide: "or" at 1.84 s, "4:15" at 2.02 s, "in" at 2.61 s, and so on, relative to the start of the clip. Combined with knowing when the clip started playing, from playback markers like Twilio's mark or Plivo's checkpoint, or from the agent's own pacing, it can find the last word that played.
Pipecat does this by pushing the text of each word downstream in sync with the audio playback, so text that never played never reaches the part of the pipeline that records the assistant's message. On interruption, that recorder commits the partial, spoken-so-far text. LiveKit's docs describe the same outcome: on interruption the agent truncates its conversation history to the part of the speech the user heard. OpenAI's Realtime API exposes it as an explicit operation, conversation.item.truncate, with an audio_end_ms field; its reference notes that the server produces audio faster than real time, and that truncating also deletes the text transcript the user never heard.
7.4Coughs, mm-hmms and echoes
Requirement four is the subtle one. While the agent talks, the inbound audio isn't silent. Callers say "mm-hmm" and "okay" to show they're following, which linguists call backchannels; they cough, a child shouts in the background, and sometimes the agent's own voice comes back.
That last one has a specific cause on phone lines. A line to many landline phones is a single pair of wires carrying both directions, and at the exchange a circuit called a hybrid splits it into separate send and receive paths. That split is never perfect, so a little of the agent's outgoing voice leaks back into the incoming direction, delayed by the round trip: line echo. Speakerphones add acoustic echo, the agent's voice from the loudspeaker reaching the microphone. Phone networks deal with line echo using echo cancellers, specified in ITU-T G.168: an adaptive filter learns how the outgoing signal leaks back and subtracts its prediction from the incoming one.

Echo that gets through is a classic voice-agent bug: the VAD hears the agent's own words coming back and the agent cuts itself off mid-sentence. In a browser, WebRTC's echo cancellation runs on the user's device; on a phone call, the agent relies on the handset's and the network's cancellers, plus noise cancellation on its side.
All of this argues for not stopping at the first sound. Simple defences are thresholds: LiveKit Agents by default requires half a second of speech before treating it as an interruption (min_duration), and can require a minimum number of transcribed words; Vapi's defaults wait for 0.2 s of voice. LiveKit also handles false interruptions: if the agent stopped but the transcript of the "interruption" comes back empty, then after 2 seconds it resumes speaking from where it left off.
A stronger defence is another model. In March 2026 LiveKit Agents 1.5 added adaptive interruption handling, an audio model that classifies overlapping speech as a real interruption or as a backchannel, cough or sigh. LiveKit reported 86% precision and 100% recall at 500 ms of overlapping speech, rejecting 51% of the false alarms a plain VAD raises, in 30 ms or less.
When should overlapping speech stop the agent?
- Fastest possible stop
- Simple
- Stops on every cough, mm-hmm and echo
- Agent sounds nervous and keeps restarting
- Cheap
- Removes most noise and short backchannels
- Adds that delay to every real interruption
- Long backchannels still trigger it
- Ignores backchannels and coughs
- Fast decision
- Another model per call
- A missed interruption feels like being ignored
In practice the options stack: thresholds as a floor, a model to judge what passes, and resume-after-false-interruption as the safety net. Failure costs are lopsided, and that's probably why LiveKit tuned for 100% recall: an agent that stops for a cough and resumes sounds a little odd, but an agent that keeps talking while the caller says "no, wait, that's wrong" makes the caller feel unheard.
08Looking things up mid-sentence
8.1A tool call costs a second inference
To offer Thursday's slots, the agent has to look at the clinic's calendar. Give the LLM a tool, say find_slots(doctor, date), and when it decides to use it, it'll write a structured request for the tool and stops (chapter 78 describes this loop for a coding agent). Then the agent server runs the tool, here an HTTP call to the clinic's booking system, adds the result to the context, and calls the LLM again to write the reply.
That costs time twice over. A tool request is generated token by token like any other output, and can't be streamed to TTS, because it's meant for the agent and not for the caller. Then the second call to the LLM pays its time to first token again.

A second and a half of silence, plus however long the clinic's booking system takes, puts us back near version 1. A fix is to say something first, and the primer suggests two ways: always speak a short message before running the function ("Let me check Dr. Mehta's calendar"), or start a watchdog timer and speak only if the tool hasn't returned before it fires ("Still checking, one moment"). Sunrise Dental's agent does the first: its prompt asks it to acknowledge the request in one short sentence before calling a tool, so that sentence streams to TTS while the tool request is still being written. So the caller hears speech within the normal budget, and the lookup hides behind it.
How should the agent cover the time a tool takes?
- Nothing to design
- 1.5 s or more of dead air
- Callers say 'hello?' and talk over the reply
- Predictable
- The acknowledgement streams while the call is written
- Sounds repetitive on fast tools
- A few more tokens per turn
- Fast tools stay seamless
- A late filler can collide with the real reply
Saying something first wins for a booking agent because its tools are slow and unpredictable: they're other companies' systems. It also matches what people do; a receptionist says "let me have a look" before turning to the screen. For slow tools, agents combine both: an acknowledgement up front and a timer for "still looking". Making the tool itself fast matters too, and the same rules as section 4.2 apply: put the agent near the systems it calls, and keep the tool's answer short, because every token of a tool result is read again on the next LLM call.
09One model instead of three?
9.1Speech-to-speech models
Everything so far has been a cascade, and each conversion to text loses something: the transcript of a doubtful "Thursday?" is the same as a confident "Thursday." Each stage also adds its own latency. A speech-to-speech model removes the text in the middle: it takes audio in and produces audio out, representing sound as audio tokens, short codes produced by a neural audio codec, so that one model can read and write speech the way a text LLM reads and writes words.
OpenAI launched its Realtime API in public beta on 1 October 2024, serving a GPT-4o model that took audio in and produced audio out over a persistent connection. Launch pricing for audio was $100 per million input tokens and $200 per million output tokens, which OpenAI put at about $0.06 a minute of audio in and $0.24 a minute out. In August 2025 it released gpt-realtime as generally available, with function calling and with connections over WebRTC, WebSocket or SIP, so a phone call can reach the model directly; its audio prices were $32 per million input tokens and $64 per million output tokens. Two days after the launch, LiveKit announced that ChatGPT's own Advanced Voice Mode used LiveKit's client SDK for its audio transport.
Kyutai, a non-profit lab in Paris, went further with Moshi (paper, September 2024). Moshi is full duplex: it models two audio streams at once, its own and the user's, so it's always listening, even while speaking, and doesn't need a separate turn detector to decide when to talk. It also predicts the text of its own speech alongside the audio, which the paper calls an "inner monologue", to keep its words coherent. Its audio codec, Mimi, compresses 24 kHz audio into 12.5 frames a second at 1.1 kilobits a second. Kyutai reported a theoretical latency of 160 ms (80 ms for one Mimi frame plus 80 ms of acoustic delay) and about 200 ms in practice on an NVIDIA L4 GPU. The code is under MIT and Apache licences and the weights under CC BY 4.0.
Cascade or speech-to-speech for the clinic's agent?
- Pick the best model for each job, and swap any one
- Text in the middle can be logged, checked and filtered
- Strong, well-tested tool calling in text LLMs
- Usually cheaper per minute
- Tone of voice is lost in the transcript
- Three latencies add up; needs separate turn detection
- Lowest latency
- Hears hesitation and tone; speaks with natural prosody
- Full-duplex models handle overlap natively
- Fewer models to choose from, harder to steer
- Text exists only as a transcript on the side
- Higher price per minute (2024–2025)
Phone agents built on the open frameworks still mostly run cascades, and the reasons are about control. A clinic needs its agent to follow a booking script, call tools reliably, never invent a slot, and leave an auditable record; text in the middle makes each of those straightforward, and lets a platform pair a cheap, fast LLM with another company's voice. Speech-to-speech wins where the feel of the conversation matters most, and the boundary is moving: OpenAI's realtime models gained tools and SIP, while cascades borrowed conversation-aware TTS such as Sesame's CSM (a 1-billion-parameter version open-sourced under Apache 2.0 in March 2025), which uses the conversation's audio to choose how a reply should sound.
Whichever model architecture the clinic picks, it now has to run thousands of these calls at once, each with its own state, near its callers, at a price per minute that makes sense.
10Many calls at once
10.1A call is a session, pinned to one process
A web server can send each request to any machine, because requests are independent. A voice agent can't. Ananya's call is one WebSocket from the provider, a running pipeline with queues in flight, a VAD's state, a turn's worth of buffered audio, a growing conversation context, and open streams to speech-to-text and TTS. All of that lives in one process for the length of the call, so the call must stay with that process from the first start message to the last stop. A load balancer in front of agent servers balances connections, not messages, and a deploy can't just restart servers; it has to stop sending new calls to a server and wait for its current calls to end.
LiveKit Agents builds this in: agent code runs as workers that register with the LiveKit server and are dispatched sessions as jobs, reporting their load so new sessions go to workers with room. Per call, the worker's own share is small: Silero needs less than an eighth of a CPU core by the primer's estimate, and a Smart Turn check takes around 10 ms each time the caller pauses. The expensive parts, speech-to-text, the LLM and TTS, run on GPUs as shared services that batch many calls' requests together (chapter 54 explains why), at a vendor or in the platform's own cluster.
10.2When a worker dies mid-call
Suppose the worker holding Ananya's call crashes after she's chosen 4:15. Her phone call doesn't drop, because the call lives at the provider; what ends is the WebSocket. What happens next is set in the instructions the clinic's application gave the provider. Twilio's docs say a Connect-Stream instruction blocks the instructions after it until the WebSocket disconnects, so the application can put a fallback after it: connect a new stream (which the dispatcher sends to a healthy worker), or transfer the call to a human, or play an apology.
A new worker starts with an empty pipeline. If the call's transcript and state were saved after each turn, it can rebuild the context and continue, "Sorry about that, we were booking 4:15 on Thursday", and lose only the turn in progress. If they weren't, the caller starts over. That's the same move as Uber keeping trip state on the driver's phone (chapter 50, section 9): something outside the failed process must hold enough to rebuild the session.
10.3What a minute costs
A clinic will compare the agent's cost with a receptionist's, so platforms price by the minute. Here's a rough per-minute cost for the cascade from US list prices on the providers' and vendors' own pages in late 2026. Plivo listed $0.0055 a minute for an inbound call to a local US number with audio streaming included; Twilio listed $0.0085 a minute plus $0.0044 for Media Streams. Deepgram listed $0.0077 a minute for streaming Nova-3 or Flux. Retell's pricing page lists TTS from $0.015 a minute. Vapi listed $0.05 a minute for hosting, passing model costs through at cost.
| Telephony, inbound with streaming | Plivo $0.0055 · Twilio $0.0085 + $0.0044 | $0.006–0.013 |
| Streaming speech-to-text | Deepgram list price | $0.008 |
| Text-to-speech | Retell's listed starting price | $0.015+ |
| LLM | depends on the model and the prompt | varies |
| Platform (orchestration, hosting) | Vapi's listed hosting fee | $0.05 |
| all-in, matching the platforms' own calculators (Vapi $0.08–0.13, Retell's example $0.11) | ≈ $0.10 a minute | |
Ananya's call lasted under a minute. If Sunrise Dental gets 2,000 calls a month averaging two minutes, what does the agent cost? And how would the same calls compare on OpenAI's 2024 Realtime launch pricing, if the agent speaks for about half of each call?
11Rules for calls made by machines
11.1Consent and disclosure
Phone calls are regulated in ways web chats aren't, and AI voices are now explicitly covered. In the US, the Telephone Consumer Protection Act restricts calls that use an "artificial or prerecorded voice". On 8 February 2024 the FCC released a declaratory ruling, adopted on 2 February (FCC 24-17), confirming that those restrictions encompass current AI technologies that generate human voices, so such calls need the called party's prior express consent unless they're for an emergency or otherwise exempt. Ananya called the clinic, so her call is inbound and this ruling is about the opposite direction, but the moment the clinic's agent starts phoning patients with reminders, it applies.
Recording is the other rule. A cascaded agent produces transcripts as a matter of course, and many jurisdictions require callers to be told that a call is recorded, some requiring every party's consent. So the clinic's greeting says it's an assistant and that the call may be recorded. What's required varies by country and changes over time, so treat these as design inputs to check, not legal advice.
12The whole system
12.1Every box, and why it's there
| Component | What it does | Added because |
|---|---|---|
| Telephony edge (Twilio, Plivo) | Terminates SIP and RTP, converts G.711, streams audio over a WebSocket | Phone calls arrive over the PSTN, not the web (§3) |
| VAD (Silero) | Speech or not, for every 32 ms chunk | Everything else needs to know when the caller is talking (§5.1) |
| Turn detector (Smart Turn, LiveKit's model) | Judges whether a pause ends the turn | Silence timeouts either cut people off or add dead air (§5.2–5.4) |
| Streaming STT | Interim and final words while the caller talks | Batch transcription waits for the whole recording (§2, §6.1) |
| Sentence aggregator | Releases each complete sentence to TTS | TTS needs whole sentences; waiting for the whole reply is slow (§6.2) |
| Preemptive generation | Starts the LLM before the turn is confirmed | LLM time to first token dominates once all else streams (§6.3) |
| Streaming TTS with word timestamps | Speaks quickly and reports what was said when | Fast first audio, and truncation on barge-in (§6.4, §7.3) |
| Interruption handling | Cancels work, flushes queues, truncates context | Callers talk over agents (§7) |
| Worker dispatch + call store | One call per job, state saved per turn | A call is a stateful session that outlives a crash (§10) |
12.2From top to bottom
| Level | The choice | Data structure or algorithm |
|---|---|---|
| Network | SIP for signalling, RTP for media | INVITE / 200 OK / ACK; SDP offer and answer; RTP every 20 ms |
| Audio format | G.711 companding | 8 kHz × 8 bits; μ-law byte = sign, 3-bit segment, 4-bit step, bias 132, inverted |
| Transport to the agent | WebSocket media stream | JSON events, base64 payloads, playback marks, clear |
| Speech detection | Neural VAD | Silero on 32 ms chunks, start/stop hysteresis |
| Turn ending | VAD pause, then a model | Smart Turn: Whisper Tiny encoder on up to 8 s of audio, one probability; fallback timer |
| Pipeline | Frames through processors | Typed frames, per-processor queues, control frames that jump the queue |
| Generation | Stream and speculate | Token streaming, sentence segmentation, preemptive LLM requests |
| Barge-in | Truncate to what was heard | TTS word timestamps aligned to playback position |
| Scale | Session affinity | One call per job on a worker; per-turn checkpoints of the context |
13What goes wrong, and what it costs
13.1Failures this design has to survive
| What happens | What the caller hears | What the design does |
|---|---|---|
| The caller pauses mid-sentence | The agent cuts in on half a sentence | Short VAD pause only triggers a turn model; a fallback timer ends real silences |
| The caller says "mm-hmm" while the agent talks | The agent stops and restarts | Minimum duration or words; an interruption model; resume after a false interruption |
| The agent's own voice echoes back | The agent interrupts itself | Network and handset echo cancellers; noise cancellation; interruption thresholds |
| Interruption, but audio is queued at the provider | The agent talks over the caller for a second | clear / clearAudio; pacing output so little is queued |
| Context still holds the unheard part of a reply | The agent assumes she heard an option she didn't | Truncate the assistant message using word timestamps |
| A slow booking system | Long silence, then "hello?" | Acknowledge before the tool call; a watchdog filler |
| The agent's worker crashes | A short gap, then the call carries on or is transferred | The provider runs the fallback instruction; a new worker rebuilds from the saved context |
13.2The tradeoffs, in one table
| Decision | Chosen | Given up | Why it was worth it |
|---|---|---|---|
| Getting the audio | Provider's WebSocket media stream | A hop, JSON overhead, TCP head-of-line blocking | Any web server can run an agent; carriers and SIP stay someone else's job |
| Ending a turn | Short VAD pause + turn model | A model per call, a little CPU | Fewer cut-offs and less dead air than any silence timeout |
| Generating | Stream every stage, sentence by sentence | Natural phrasing across sentence boundaries | Time to first audio no longer grows with the reply |
| Starting early | Preemptive LLM requests | Paid-for tokens on false starts | Hides most of the LLM's time to first token |
| Interruptions | Thresholds + model + resume | A little latency on real interruptions | The agent doesn't stop for coughs or backchannels |
| Architecture | Cascade, for now | Tone of voice, some latency | Control, tool reliability, auditability, cost |
| Deployment | One call per job, one region | Simple stateless scaling | Latency and a call state that survives a crash |
14Summary
- The budget is about a second. People answer each other within about 200 ms, and agents that reply within 1.5 seconds feel acceptable; the naive record-transcribe-think-speak design takes about 3.6.
- A phone call is G.711 over SIP and RTP: 8,000 samples a second, 8 bits each, 160 bytes per 20 ms, which providers forward as base64 JSON frames over a WebSocket, with marks to track playback and clear messages to flush it.
- μ-law and A-law companding space quantisation levels logarithmically, a sign bit, a 3-bit segment and a 4-bit step, so quiet speech keeps a good signal-to-noise ratio in 8 bits.
- Silence timeouts can't end turns well: any value either cuts off people who pause or adds its full length to every reply.
- Turn models judge pauses: a 200 ms VAD pause triggers a model, audio-based like Smart Turn or text-based like LiveKit's, with a fallback timer behind it.
- Stream every stage and start early: interim transcripts, sentence-by-sentence TTS, and preemptive LLM requests, until the LLM's time to first token is the main cost left.
- Barge-in means four things at once: cancel the work, flush every audio queue, cut the context to the words she heard, and ignore coughs, backchannels and echoes.
- Tool calls cost a second inference, so the agent speaks a short acknowledgement first and lets the lookup hide behind it.
- Cascades still win on control for phone agents, while speech-to-speech models like OpenAI's realtime models and Kyutai's full-duplex Moshi win on latency and tone.
- A call is a stateful session: pin it to one worker in one region near the telephony edge, save its context every turn, and drain instead of restarting.
15Build this
A phone agent you can hear yourself.
- Rent a phone number from a cloud telephony provider and point its answer webhook at a small web server that replies with a bidirectional stream to your WebSocket endpoint.
- Start with an echo bot that sends each frame straight back, then add a 500 ms buffer and hear the difference.
- Add Silero VAD and print
speech/quietevents. Read a phone number aloud in groups and see where a fixed 600 ms timeout would end your turn. - Build the cascade with Pipecat or LiveKit Agents: streaming STT, an LLM with one fake
find_slotstool that sleeps for 2 seconds, and streaming TTS. Log the time from your last word to the first audio frame sent. - Turn on Smart Turn (Pipecat) or the turn detector (LiveKit) and compare cut-offs and response times against the silence timeout.
- Interrupt the agent mid-list and print the assistant message before and after truncation; then disable truncation and watch the next reply go wrong.
16Interview questions
beginnerWhy can't a voice agent just wait for a second of silence to know the caller has finished?›
Because people pause mid-sentence, between digits of a phone number, and while thinking, often for most of a second. A timeout short enough to feel responsive cuts those callers off, and a timeout long enough to avoid that adds its whole length to every reply, since a silence detector can't know a turn has ended until the silence has lasted the full timeout. Modern agents use a short VAD pause, around 200 ms, as a trigger for a turn model that judges from the audio or transcript whether the turn sounds complete, with a longer fallback timer behind it.
intermediateWalk through the latency budget of a cascaded voice agent. Where would you cut first?›
Phone path in (about 100 ms), transcription and endpointing (about 300 ms with streaming STT and a turn model), LLM time to first token (several hundred ms), collecting the first sentence, TTS time to first byte (about 100 ms), phone path out. Cut endpointing first, by replacing silence timeouts with a turn model, then hide LLM time to first token with a smaller model nearby, prompts that start with a short sentence, and preemptive generation on likely ends of turn. Keep every model in the same region as the telephony edge, because each cross-ocean hop costs over a hundred milliseconds.
intermediateThe caller interrupts the agent. What has to happen, and what goes wrong if you skip the last step?›
Detect a real interruption (not a cough or "mm-hmm"), cancel the in-flight LLM and TTS work, discard queued audio in the agent, and send the provider's clear message so its playout queue is flushed. Then truncate the assistant's message in the context to the words that were played, using TTS word timestamps and the playback position. Skip that and the LLM believes the caller heard options or instructions they never heard, and its next reply refers to them.
deepWould you build a phone agent on a speech-to-speech model or a cascade?›
It depends on what matters more for the use case. A cascade gives control: text in the middle can be logged, checked and filtered, each model can be chosen and swapped independently, text LLMs have strong tool calling, and it's usually cheaper. A speech-to-speech model has lower latency and hears and produces tone, and full-duplex models like Moshi handle overlapping speech natively, but they're harder to steer and cost more per minute on 2024–2025 pricing. For a booking agent with tools and compliance needs, a cascade with good turn detection is the safer default; for a companion or tutoring app where feel dominates, speech-to-speech is attractive.
17Go deeper
How many bytes are in 20 ms of G.711 audio, and how big is it as a base64 payload?›
8,000 samples a second × 0.02 s = 160 samples, one byte each, so 160 bytes. Base64 turns every 3 bytes into 4 characters, so 216 characters, plus the JSON wrapper around it.
Why did Pipecat's default VAD stop time drop from 0.8 s to 0.2 s in 2026?›
Because turn ending was handed to Smart Turn. A 0.2 s silence no longer ends the turn; it only triggers the turn model, which decides whether the caller has finished. A fallback timer still ends long silences.
An agent interrupts itself halfway through a sentence on speakerphone calls only. What's the likely cause?›
Echo: its own voice from the loudspeaker reaches the caller's microphone, comes back on the inbound audio, and the VAD treats it as the caller speaking. Echo cancellation, noise cancellation and interruption thresholds or an interruption model are the fixes.
The Pipecat team's open guide: the latency table, turn detection, interruption handling, function calling and costs. CC0, at voiceaiandvoiceagents.com.
The frame-based pipeline, interruption handling, VAD defaults and the open Smart Turn model with its training data.
The transcript-based and audio-based turn detectors, preemptive generation, adaptive interruption handling and SIP.
The WebSocket message formats: media, mark and clear; playAudio, checkpoint and clearAudio.
The ten-language study of gaps between turns that sets the target for every voice agent.
A full-duplex speech-to-speech model: two audio streams, inner monologue and the Mimi codec, with its latency analysis.
The phone network's audio format, its delay guidance, and the SIP, SDP and RTP profiles that carry calls over IP.
18Related chapters
RTP, jitter buffers, codecs and the mouth-to-ear budget for people talking to people. Chapter 53.
Time to first token, streaming and batching on GPUs, the LLM half of every voice agent. Chapter 54.
Tool calls in an agent loop, and managing a context that keeps growing. Chapter 78.
TCP, sockets and why a stalled packet delays everything behind it on a WebSocket. Chapter 10.
Long-lived streams, cancellation and head-of-line blocking. Chapter 63.
Balancing long-lived connections and draining servers without dropping them. Chapter 34.