KnowSys

Designing a Voice AI Agent

Ananya rings her dentist after hours to move an appointment, and a machine answers, listens, checks the calendar and books her in, while she interrupts it halfway through a sentence. We'll design the agent that does it, from the phone network and μ-law bytes down to turn detection, streaming, barge-in and the cost of a minute of conversation.

⏱ 50 min read◆ IntermediateAssumes: the Zoom case study (chapter 53) and the ChatGPT case study (chapter 54) help a lot; networking basics (chapter 10) help
Start reading

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:

  1. Answer real phone calls, from any phone, on the clinic's ordinary number.
  2. Understand what the caller says, over a phone line, in her accent, with background noise.
  3. Work out what to do and carry it out: look up appointments, move them, send a confirmation.
  4. Reply in speech that sounds natural.
  5. Take turns like a person: wait while the caller is still talking, answer promptly when she's done, and stop when she interrupts.
  6. 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.

Your turn: design it before reading on

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.

A loop diagram: voice capture, speech to text, programmatic logic and LLM interactions, text to speech, audio playout
The basic conversational loop: capture the voice, transcribe it, let the LLM decide what to say and do, synthesise speech, play it. The dashed box is the part that runs in the cloud. Everything in this case study is about making this loop fast and interruptible.Image: Voice AI & Voice Agents: An Illustrated Primer (Kwindla Hultman Kramer and contributors), CC0

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.

Version 1: one request per step, each waiting for the last
recordingplay fileAnanya's phonemobile networkTelephonyrecords the callAgent serverglue codeSTT APIwhole fileLLM APIwhole replyTTS APIwhole clip
Step 1. Ananya talks. The telephony side records until it hears 800 ms of silence, then hands the recording to the agent server.
1 / 5

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 providerassumed≈ 100 ms
Silence that ends the recordingfixed timeout800 ms
Upload + batch transcription of a 4.2 s sentence300 ms + 0.15 × 4,200 ms≈ 930 ms
Whole LLM reply, 26 words ≈ 34 tokens450 ms + 34 ÷ 100 tokens/s≈ 790 ms
Whole TTS clip, rendered before sending26 words × 25 ms + 200 ms≈ 850 ms
Phone network, provider to callerassumed≈ 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.

A diagram of SIP proxies and a redirect server passing INVITE, 200 OK and ACK messages between two users, with a separate thick line for the media path directly between the two endpoints
SIP signalling (thin arrows) hops through proxies to set the call up: INVITE, 200 OK, ACK. The media, RTP packets of audio (the long line at the bottom right), flows on its own path between the endpoints. A cloud telephony provider sits at one end of both: it terminates the SIP signalling and receives the RTP.Image: Tivadar Szemethy, CC BY-SA 3.0, via Wikimedia Commons

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".

Ananya's call is set up and streamed to the agent
CarrierProvider (SIP edge)Clinic's appAgent serverINVITE + SDP offer100 TryingPOST answer webhookXML: Stream, bidirectionalWebSocket open + start200 OK + SDP answerACK, then RTP every 20 msmedia, media, media…
Step 1. A call for the clinic's number. The SDP lists the audio formats the carrier can send, such as G.711 A-law.
1 / 8

?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.

Decision

How should the call's audio reach the agent?

chosen
WebSocket media stream from a provider
The provider terminates SIP and RTP, and forwards each 20 ms of audio as a JSON message over a WebSocket.
  • 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
SIP straight into the agent platform
The agent platform runs its own SIP endpoint and receives RTP directly.
  • 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.

A smooth green wave, dots marking regular samples on it, a yellow stepped version that snaps each sample to a grid level, and a small red wiggle showing the difference between them
Sampling and quantisation. The dots are samples taken at regular intervals; the yellow line is what you get when each sample is rounded to the nearest allowed level; the red line is the rounding error, heard as a faint hiss called quantisation noise. Fewer levels means a bigger red line.Image: Gregory Maxwell, CC BY 3.0, via Wikimedia Commons

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.

An S-shaped curve that rises very steeply through zero and flattens out towards plus and minus one
The μ-law curve. Small inputs near zero are stretched across a large share of the output range, and large inputs are squeezed. Quantising the output evenly therefore gives fine steps for quiet sounds and coarse steps for loud ones.Image: Morn, CC0, via Wikimedia Commons
Top: a sine wave growing from tiny to large amplitude. Bottom: the same wave after mu-law compression, where even the first small cycles reach a large fraction of full scale
A wave that grows from quiet to loud (top), and the same wave after μ-law compression (bottom). The quiet early cycles now use most of the range, so they survive being rounded to 8 bits; the receiver applies the inverse curve to get the original shape back.Image: Morn, CC0, via Wikimedia Commons
zoomVoice agentMedia streamOne 20 ms frameOne μ-law byte

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:

BitsFieldWhat it holds
1sign1 for positive, 0 for negative (after inversion)
3segmentwhich of the 8 segments, 0 to 7: roughly the position of the sample's highest set bit, a crude logarithm
4stepwhich 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.

Encode one phone frame in μ-law, and compare it with plain 8-bit audio
python
Python
import base64, json, math
 
def mulaw_encode(x):                  # x: 16-bit signed sample
    BIAS, CLIP = 0x84, 32635
    sign = 0x80 if x < 0 else 0
    x = min(abs(x), CLIP) + BIAS      # bias so every segment starts at a power of 2
    exp = x.bit_length() - 8          # segment 0..7: position of the top bit
    mant = (x >> (exp + 3)) & 0x0F    # the next 4 bits below the top bit
    return ~(sign | exp << 4 | mant) & 0xFF   # bits are inverted on the wire
 
def mulaw_decode(b):
    b = ~b & 0xFF
    sign, exp, mant = b & 0x80, (b >> 4) & 7, b & 0x0F
    x = ((mant << 3) + 0x84 << exp) - 0x84
    return -x if sign else x
 
def linear8(x):                       # plain 8-bit: 256 evenly spaced steps
    return max(-128, min(127, round(x / 256))) * 256
 
def snr_db(orig, back):
    sig = sum(s * s for s in orig)
    err = sum((s - b) ** 2 for s, b in zip(orig, back))
    return 10 * math.log10(sig / err)
 
RATE = 8000
frame = [int(8000 * math.sin(2 * math.pi * 440 * n / RATE)) for n in range(160)]
payload = bytes(mulaw_encode(s) for s in frame)
msg = json.dumps({"event": "media", "media": {"payload": base64.b64encode(payload).decode()}})
print(f"20 ms at {RATE} Hz = {len(frame)} samples -> {len(payload)} bytes of mu-law")
print(f"first 8 bytes: {payload[:8].hex(' ')}")
print(f"base64 payload {len(base64.b64encode(payload))} chars, minimal JSON message {len(msg)} bytes")
print(f"bit rate: {len(payload) * 8 * 50 // 1000} kbit/s of audio, ~{len(msg) * 8 * 50 // 1000} kbit/s as JSON")
print()
print("amplitude   mu-law SNR   linear 8-bit SNR")
for amp in (16000, 2000, 250):
    s = [int(amp * math.sin(2 * math.pi * 440 * n / RATE)) for n in range(RATE)]
    mu = [mulaw_decode(mulaw_encode(v)) for v in s]
    lin = [linear8(v) for v in s]
    print(f"{amp:>9}   {snr_db(s, mu):7.1f} dB   {snr_db(s, lin):9.1f} dB")
output
C++
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 dB

Look 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) or checkpoint (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) or clearAudio (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):

JSON
{"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 bufferassumed≈ 100 ms
Transcription and endpointingPipecat primer300 ms
LLM time to first tokenPipecat primer650 ms
Collect the first sentencePipecat primer20 ms
TTS time to first bytePipecat primer120 ms
Phone path outassumed≈ 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.

A silence timeout on a caller who pauses mid-sentence
python
Python
import random
random.seed(7)
FRAME = 20                                   # ms per frame, as on the phone line
 
def frames(segments):
    """segments: list of (is_speech, ms). Returns one loudness (RMS) value per frame."""
    out = []
    for speech, ms in segments:
        for _ in range(ms // FRAME):
            if speech:  # voiced sound is loud, but stop consonants dip briefly
                out.append(random.uniform(0.05, 0.5) if random.random() > 0.05 else 0.02)
            else:       # line noise
                out.append(abs(random.gauss(0.01, 0.004)))
    return out
 
def endpoint(rms, silence_ms, threshold=0.03):
    """Energy VAD + fixed timeout: the turn ends after silence_ms of quiet frames."""
    quiet = 0
    for i, r in enumerate(rms):
        quiet = quiet + FRAME if r < threshold else 0
        if quiet >= silence_ms:
            return i * FRAME + FRAME          # time (ms) at which we decide "done"
    return len(rms) * FRAME
 
# Ananya: "I'd like to move my appointment to ... uh ... Thursday"
ananya = [(True, 1600), (False, 900), (True, 300), (False, 300), (True, 700), (False, 3000)]
rms = frames(ananya)
print("".join("#" if r >= 0.03 else "." for r in rms[:200:2]))
speech_end = 1600 + 900 + 300 + 300 + 700
for t in (500, 1000):
    at = endpoint(rms, t)
    verdict = "cut her off mid-sentence" if at < speech_end else f"replied {at - speech_end} ms after she finished"
    print(f"timeout {t:>4} ms: {verdict}")
 
# 2,000 synthetic callers: 2-5 pauses inside each turn, most short, some long hesitations
def caller():
    segs = []
    for _ in range(random.randint(2, 5)):
        segs.append((True, random.choice(range(400, 2000, 20))))
        long_pause = random.random() < 0.25
        segs.append((False, int(random.lognormvariate(6.5 if long_pause else 5.3, 0.4)) // FRAME * FRAME))
    segs.append((True, random.choice(range(400, 2000, 20))))
    end = sum(ms // FRAME * FRAME for _, ms in segs)
    return frames(segs + [(False, 3000)]), end
 
callers = [caller() for _ in range(2000)]
print("\ntimeout   cut off early   wait after a real end")
for t in (200, 400, 600, 800, 1000, 1500):
    early, waits = 0, []
    for rms, end in callers:
        at = endpoint(rms, t)
        if at < end: early += 1
        else: waits.append(at - end)
    print(f"{t:>5} ms   {early / len(callers):>11.1%}   {sum(waits) / len(waits):>8.0f} ms")
output
C++
##.#####################################.......................#######........##.##############.....
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 ms

Its 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.

Predict before you read on

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.

Ananya's turn, as VAD and Smart Turn see it
On the linewhat she's sayingTurn audioup to 8 s keptVADSilero, 32 ms chunksSmart Turncomplete?LLMreply startsmove it to…1.6 s audiospeechp = 0.08p = 0.93transcript
Step 1. Ananya starts talking. VAD hears speech, and every 20 ms frame is appended to the audio buffer for this turn.
1 / 6

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.

A pipeline: user audio feeds streaming transcription, VAD and Smart Turn in parallel; then an LLM that first emits a single classifier token (complete, short incomplete, long incomplete) before its reply; the token is stripped before text-to-speech
One state-of-the-art arrangement from the Pipecat primer. VAD and Smart Turn decide when to stop listening; then the LLM itself gets a last say, starting its reply with one token meaning complete, short pause or long pause. If it says the user isn't done, the agent stays silent; otherwise the token is stripped and the reply goes to TTS.Image: Voice AI & Voice Agents: An Illustrated Primer (Kwindla Hultman Kramer and contributors), CC0
Decision

How should the agent decide that the caller has finished?

VAD + fixed silence timeout
End the turn after N ms of silence.
  • Trivial
  • No extra model
  • Short N cuts people off mid-sentence
  • Long N adds N to every reply
Transcript-based model
A small LLM reads the transcript and predicts whether the turn is complete (LiveKit, Dec 2024).
  • Understands grammar and context
  • Can look at the previous turns
  • Can't hear intonation
  • Has to wait for the transcript
chosen
Audio-based model after short VAD silence
After 200 ms of silence, a small audio model classifies the whole turn (Smart Turn v3, Sep 2025).
  • 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
Speech-to-text with turn detection built in
The transcription model itself emits end-of-turn events (Deepgram Flux, Oct 2025).
  • 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.

Time to first audio: batch, streaming, and sentence by sentence
python
Python
import re
 
reply = ("Sure, I can move that for you. Dr. Mehta has Thursday slots at 11:30 "
         "in the morning and 4:15 in the afternoon. Which one works better?")
words = reply.split()
TOKENS_PER_WORD = 1.3
LLM_TTFT, LLM_TOK_S = 450, 100          # ms to first token; tokens per second after that
TTS_TTFB = 120                          # ms from text in to first audio out (streaming TTS)
TTS_BATCH_MS_PER_WORD = 25              # a non-streaming TTS renders the whole clip first
PHONE_IN, PHONE_OUT = 100, 100          # carrier + provider + jitter buffers, each way
SPEAK_MS = 4200                         # Ananya's sentence lasts 4.2 seconds
 
def llm_done(n_words):                  # ms after the request until n_words are generated
    return LLM_TTFT + n_words * TOKENS_PER_WORD / LLM_TOK_S * 1000
 
first_sentence = re.split(r"(?<=[.?!])\s+(?!\d)", reply)[0]
n_first = len(first_sentence.split())
 
designs = {
    "v1: batch everything": [
        ("wait for 800 ms of silence", 800),
        ("upload recording, batch STT", 0.15 * SPEAK_MS + 300),
        ("whole LLM reply", llm_done(len(words))),
        ("whole TTS clip", len(words) * TTS_BATCH_MS_PER_WORD + 200),
    ],
    "stream, wait for full reply": [
        ("endpointing (smart turn)", 300),
        ("whole LLM reply", llm_done(len(words))),
        ("TTS first audio", TTS_TTFB),
    ],
    "stream, sentence by sentence": [
        ("endpointing (smart turn)", 300),
        (f"first sentence ({n_first} words)", llm_done(n_first)),
        ("TTS first audio", TTS_TTFB),
    ],
}
print(f"first sentence sent to TTS: {first_sentence!r}\n")
for name, stages in designs.items():
    total = PHONE_IN + sum(ms for _, ms in stages) + PHONE_OUT
    parts = " + ".join(f"{ms:.0f}" for _, ms in stages)
    print(f"{name:30} {PHONE_IN} + {parts} + {PHONE_OUT} = {total:,.0f} ms")
output
C++
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 ms

Read 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.

One turn, from Ananya's last word to the agent's first
AnanyaPhone pathAgent: VAD + turnLLMTTS"…Thursday, if possible."audio framesspeculative requestturn confirmed: keep it"Sure, let me check…"first audio"Sure, let me check…"
Step 1. t = 0: her last sound. It takes roughly 100 ms to reach the agent through the network and the provider.
1 / 7
Inside the agent: a pipeline of streaming stages
end of turnWebSocket inμ-law, 20 msVAD + turnSilero, Smart TurnStreaming STTinterim + finalContextturns, tool resultsLLMstreams tokensSentencesaggregatorStreaming TTSword timingsWebSocket outplayAudio / media
Step 1. Each 20 ms frame from the provider is decoded from μ-law, resampled, and sent two ways at once: to the VAD and turn detector, and to the streaming speech-to-text service.
1 / 5
zoomVoice agentAgent processPipelineFrames and queues

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
Ananya interrupts the list of slots
LLM + TTSstill producingAudio queueagent + providerAnanya hearsConversation contextwhat the LLM will read next11:30 in the…or 4:15 in the…Which one works…assistant: full reply"the afternoon one"user: the afternoon one
Step 1. The reply is streaming. The first part has played, the next is queued, and the last sentence is still being synthesised. The context already holds the whole reply as written.
1 / 6

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.

Barge-in: from her first word to silence
mediaclearAnanyatalks over agentProviderplayout queueVAD / detectorinbound audioPipelineinterruption frameLLM + TTScancelledContexttruncated
Step 1. Ananya's voice arrives on the inbound track while the agent's audio is playing on the outbound one.
1 / 5

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.

A block diagram: the signal from the far end goes to a hybrid H connected to a telephone; an adaptive filter f_k takes the same far-end signal and produces an estimate y_k, which is subtracted from the hybrid's return signal d_k to give the residual sent toward the far end
A telephone echo canceller. The far-end signal (for us, the agent's voice) goes into the hybrid H, and some of it leaks back into the return path, d. An adaptive filter f watches the same far-end signal, predicts the leak, y, and subtracts it; whatever's left, ε, goes back toward the agent, and also drives the filter's learning.Image: Constant314, CC0, via Wikimedia Commons

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.

Decision

When should overlapping speech stop the agent?

Any speech the VAD hears
Stop as soon as VAD fires on the inbound audio.
  • Fastest possible stop
  • Simple
  • Stops on every cough, mm-hmm and echo
  • Agent sounds nervous and keeps restarting
Thresholds
Require some duration of speech or a number of transcribed words.
  • Cheap
  • Removes most noise and short backchannels
  • Adds that delay to every real interruption
  • Long backchannels still trigger it
chosen
A model of overlapping speech
Classify each overlap as interruption or not, from the audio.
  • 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 diagram of an LLM chip: a first inference of 1,000 ms produces a function call, a lambda runs it, the result goes back into the LLM, and a second inference of 450 ms produces the final result
The primer's example: with a 450 ms time to first token and 100 tokens a second, a 100-token function call takes 1,000 ms to write, and the second inference takes another 450 ms to its first token, 1,450 ms before the caller hears anything, not counting the time the function itself takes.Image: Voice AI & Voice Agents: An Illustrated Primer (Kwindla Hultman Kramer and contributors), CC0

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.

Decision

How should the agent cover the time a tool takes?

Silence
Run the tool, then speak.
  • Nothing to design
  • 1.5 s or more of dead air
  • Callers say 'hello?' and talk over the reply
chosen
Always say a filler first
The prompt asks for a short acknowledgement before every tool call.
  • Predictable
  • The acknowledgement streams while the call is written
  • Sounds repetitive on fast tools
  • A few more tokens per turn
Filler on a timer
Speak only if the tool hasn't returned after, say, a second.
  • 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.

Decision

Cascade or speech-to-speech for the clinic's agent?

chosen
Cascade: STT → LLM → TTS
Three models, each streaming, joined by text.
  • 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
Speech-to-speech
One model hears audio and speaks audio.
  • 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.

Where the pieces run for a call from Pune
ONE REGION, CLOSE TO THE CALLERSIP trunkWebSockettoolsAnanyamobile, PuneCarrierPSTNProvider edgeSIP + RTP, MumbaiDispatcherleast-loaded workerAgent workerone call = one job×200STT, LLM, TTSGPUs, same regionCall storetranscript, stateBooking systemtool calls
Step 1. The call reaches the provider's edge in Mumbai over a SIP trunk from Ananya's carrier.
1 / 6

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 streamingPlivo $0.0055 · Twilio $0.0085 + $0.0044$0.006–0.013
Streaming speech-to-textDeepgram list price$0.008
Text-to-speechRetell's listed starting price$0.015+
LLMdepends on the model and the promptvaries
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
Your turn: design it before reading on

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

The clinic's voice agent, end to end
webhookWebSocketfind_slotsAnanya's phoneTelephony edgeSIP, RTP, G.711Clinic webhookreturns Stream XMLAgent workerpipeline per callVAD + turnSilero, Smart TurnStreaming STTLLMtools, streamingStreaming TTSword timestampsBooking system
Step 1. Ananya's call arrives at the provider over SIP; the provider asks the clinic's webhook what to do and is told to stream the audio.
1 / 6
ComponentWhat it doesAdded because
Telephony edge (Twilio, Plivo)Terminates SIP and RTP, converts G.711, streams audio over a WebSocketPhone calls arrive over the PSTN, not the web (§3)
VAD (Silero)Speech or not, for every 32 ms chunkEverything else needs to know when the caller is talking (§5.1)
Turn detector (Smart Turn, LiveKit's model)Judges whether a pause ends the turnSilence timeouts either cut people off or add dead air (§5.2–5.4)
Streaming STTInterim and final words while the caller talksBatch transcription waits for the whole recording (§2, §6.1)
Sentence aggregatorReleases each complete sentence to TTSTTS needs whole sentences; waiting for the whole reply is slow (§6.2)
Preemptive generationStarts the LLM before the turn is confirmedLLM time to first token dominates once all else streams (§6.3)
Streaming TTS with word timestampsSpeaks quickly and reports what was said whenFast first audio, and truncation on barge-in (§6.4, §7.3)
Interruption handlingCancels work, flushes queues, truncates contextCallers talk over agents (§7)
Worker dispatch + call storeOne call per job, state saved per turnA call is a stateful session that outlives a crash (§10)

12.2From top to bottom

LevelThe choiceData structure or algorithm
NetworkSIP for signalling, RTP for mediaINVITE / 200 OK / ACK; SDP offer and answer; RTP every 20 ms
Audio formatG.711 companding8 kHz × 8 bits; μ-law byte = sign, 3-bit segment, 4-bit step, bias 132, inverted
Transport to the agentWebSocket media streamJSON events, base64 payloads, playback marks, clear
Speech detectionNeural VADSilero on 32 ms chunks, start/stop hysteresis
Turn endingVAD pause, then a modelSmart Turn: Whisper Tiny encoder on up to 8 s of audio, one probability; fallback timer
PipelineFrames through processorsTyped frames, per-processor queues, control frames that jump the queue
GenerationStream and speculateToken streaming, sentence segmentation, preemptive LLM requests
Barge-inTruncate to what was heardTTS word timestamps aligned to playback position
ScaleSession affinityOne 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 happensWhat the caller hearsWhat the design does
The caller pauses mid-sentenceThe agent cuts in on half a sentenceShort VAD pause only triggers a turn model; a fallback timer ends real silences
The caller says "mm-hmm" while the agent talksThe agent stops and restartsMinimum duration or words; an interruption model; resume after a false interruption
The agent's own voice echoes backThe agent interrupts itselfNetwork and handset echo cancellers; noise cancellation; interruption thresholds
Interruption, but audio is queued at the providerThe agent talks over the caller for a secondclear / clearAudio; pacing output so little is queued
Context still holds the unheard part of a replyThe agent assumes she heard an option she didn'tTruncate the assistant message using word timestamps
A slow booking systemLong silence, then "hello?"Acknowledge before the tool call; a watchdog filler
The agent's worker crashesA short gap, then the call carries on or is transferredThe provider runs the fallback instruction; a new worker rebuilds from the saved context

13.2The tradeoffs, in one table

DecisionChosenGiven upWhy it was worth it
Getting the audioProvider's WebSocket media streamA hop, JSON overhead, TCP head-of-line blockingAny web server can run an agent; carriers and SIP stay someone else's job
Ending a turnShort VAD pause + turn modelA model per call, a little CPUFewer cut-offs and less dead air than any silence timeout
GeneratingStream every stage, sentence by sentenceNatural phrasing across sentence boundariesTime to first audio no longer grows with the reply
Starting earlyPreemptive LLM requestsPaid-for tokens on false startsHides most of the LLM's time to first token
InterruptionsThresholds + model + resumeA little latency on real interruptionsThe agent doesn't stop for coughs or backchannels
ArchitectureCascade, for nowTone of voice, some latencyControl, tool reliability, auditability, cost
DeploymentOne call per job, one regionSimple stateless scalingLatency and a call state that survives a crash

14Summary

  1. 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.
  2. 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.
  3. μ-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.
  4. Silence timeouts can't end turns well: any value either cuts off people who pause or adds its full length to every reply.
  5. 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.
  6. 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.
  7. 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.
  8. Tool calls cost a second inference, so the agent speaks a short acknowledgement first and lets the lookup hide behind it.
  9. 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.
  10. 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 / quiet events. 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_slots tool 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

check yourself
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.

Voice AI & Voice Agents: An Illustrated Primer (Kwindla Hultman Kramer and contributors, 2025–2026)

The Pipecat team's open guide: the latency table, turn detection, interruption handling, function calling and costs. CC0, at voiceaiandvoiceagents.com.

Pipecat and Smart Turn (GitHub, pipecat-ai)

The frame-based pipeline, interruption handling, VAD defaults and the open Smart Turn model with its training data.

LiveKit Agents docs and blog (2024–2026)

The transcript-based and audio-based turn detectors, preemptive generation, adaptive interruption handling and SIP.

Twilio Media Streams and Plivo Audio Streams docs

The WebSocket message formats: media, mark and clear; playAudio, checkpoint and clearAudio.

Stivers et al., 'Universals and cultural variation in turn-taking in conversation' (PNAS, 2009)

The ten-language study of gaps between turns that sets the target for every voice agent.

Moshi: a speech-text foundation model for real-time dialogue (Kyutai, 2024)

A full-duplex speech-to-speech model: two audio streams, inner monologue and the Mimi codec, with its latency analysis.

ITU-T G.711 and G.114; RFC 3261, 3264 and 3551

The phone network's audio format, its delay guidance, and the SIP, SDP and RTP profiles that carry calls over IP.

Designing Zoom

RTP, jitter buffers, codecs and the mouth-to-ear budget for people talking to people. Chapter 53.

Designing ChatGPT

Time to first token, streaming and batching on GPUs, the LLM half of every voice agent. Chapter 54.

Designing Claude Code

Tool calls in an agent loop, and managing a context that keeps growing. Chapter 78.

Linux Networking

TCP, sockets and why a stalled packet delays everything behind it on a WebSocket. Chapter 10.

RPC, gRPC and QUIC

Long-lived streams, cancellation and head-of-line blocking. Chapter 63.

Load Balancing

Balancing long-lived connections and draining servers without dropping them. Chapter 34.