In a voice agent, the LLM streams its answer one token at a time, and the text to speech engine has to turn that stream into audio the caller can listen to. Somewhere between those two steps you have to decide when a piece of text is ready to be spoken. That decision sounds small, but it affects two things callers notice right away: how long they wait before the agent starts talking, and whether the agent sounds like a person or like a robot reading words off a list.
This post walks through the problem and a simple chunker in TypeScript that I'd use as a starting point. It isn't tied to one TTS provider, so check your provider's docs for the parts that differ.
Why you can't just send every token
The obvious fast option is to forward each token to TTS as soon as it arrives. The problem is that TTS models decide pitch, stress and pauses from the words around each word. If you give the engine "I can" and then, a moment later, "book that", it has no idea the first part belongs to a longer sentence. You often get odd stress, little breaks between chunks, or a falling tone in the middle of a sentence, as if the agent finished speaking and then changed its mind.
The obvious safe option is to wait for the whole answer and send it at once. That sounds great, but now the caller waits for the full LLM response before hearing anything. For a three sentence answer that can easily add a second or more of silence, and on a phone call silence feels much longer than it does in a chat window.
So the real job is in between. You want to send text in pieces that are big enough to sound natural and small enough that the first audio starts quickly.
Sentences are the natural unit
A full sentence is usually the best chunk. It carries enough context for the TTS engine to get the tone right, and the end of a sentence is a place where a short pause sounds normal anyway. If the boundary between two chunks falls where a person would pause, the caller won't hear the seam.
The first chunk is special. Everything the caller hears later can be generated while earlier audio is playing, but nothing hides the wait before the first sound. So I treat the first chunk differently: I'm happy to send a short opening like "Sure." or "Okay, let me check." on its own, because getting sound out early matters more than perfect flow for that first bit. After that, I prefer longer chunks, because the audio already playing gives the next chunk time to be ready.
Finding the end of a sentence is harder than it looks
Splitting on a period breaks quickly on real text. A few examples from the kind of answers a booking or support agent gives:
- "Your appointment is with Dr. Khan at 3.30 tomorrow." has two periods before the real end.
- "Check example.com for the form." has a period inside a word.
- "The total is 3.5 hours." has a decimal point.
There is also a timing problem. When the stream ends with "Dr." you can't know yet whether the sentence is over, because the next token might be " Khan". The chunker has to wait for at least one more character before it decides. Here's a small version that handles these cases:
const ABBREVIATIONS = new Set(["dr", "mr", "mrs", "ms", "st", "vs", "etc", "e.g", "i.e"]);
// Returns the index just after a safe cut point, or -1 if we should keep waiting.
function findCut(buf: string, minChars: number): number {
for (let i = 0; i < buf.length; i++) {
const ch = buf[i];
const isEnd = ch === "." || ch === "!" || ch === "?" || ch === "\n";
if (!isEnd || i + 1 < minChars) continue;
const next = buf[i + 1];
if (next === undefined) return -1; // can't tell yet, wait for more text
if (ch !== "\n" && !/\s/.test(next)) continue; // "3.5", "example.com"
const lastWord = buf.slice(0, i).split(/\s+/).pop()?.toLowerCase() ?? "";
if (ch === "." && ABBREVIATIONS.has(lastWord)) continue; // "Dr. Khan"
return i + 1;
}
return -1;
}
The minChars value is what makes the first chunk special. For the first chunk I pass a small number so "Sure." goes out right away. For later chunks I pass something like 40, which merges very short sentences with the next one so the agent doesn't speak in tiny bursts. The abbreviation list will never be complete, and that's fine. A wrong cut costs a slightly odd pause, not a broken call, so start with the words your agent actually says and grow the list from your transcripts.
The streaming loop
With findCut in place, the loop that sits between the LLM and TTS is short:
interface TtsStream {
send(text: string): void;
flush(): void; // tell the engine no more text is coming for this turn
}
async function speak(tokens: AsyncIterable<string>, tts: TtsStream) {
let buf = "";
let first = true;
for await (const token of tokens) {
buf += token;
let cut: number;
while ((cut = findCut(buf, first ? 1 : 40)) !== -1) {
tts.send(buf.slice(0, cut));
buf = buf.slice(cut).trimStart();
first = false;
}
}
if (buf.trim()) tts.send(buf);
tts.flush();
}
Two things are easy to forget here. The first is the leftover text at the end. Plenty of LLM answers end without a final period, or with a question mark that is the very last character in the stream, so whatever is left in the buffer has to be sent when the stream closes. The second is telling the TTS engine that the turn is over. Many streaming TTS APIs hold back the last bit of text while they wait for more context, so if you never signal the end, the final words may come out late or not at all. How you signal it depends on the provider, so look for a flush or end-of-input message in its docs.
A sentence that never ends
Sometimes the model writes one long sentence full of commas, and your chunker sits there waiting for a period while the caller hears nothing. A simple fix is a fallback: if the buffer grows past a limit, say around 150 characters, cut at the last comma or semicolon instead. You can also add a timer, so if no cut has happened for a few hundred milliseconds and there is a usable comma in the buffer, you send up to it. Commas are weaker pauses than full stops, but a slightly early pause is much better than a long silence.
Prompting helps too. Asking the model to answer in short, plain sentences, the way people talk on the phone, makes the chunker's job easier and usually makes the agent sound better anyway.
Clean the text before it is spoken
LLMs like to format their answers for a screen. A TTS engine will happily read out asterisks, hash signs or a bulleted list in a strange flat voice. Tell the model in the prompt that its output is spoken, not shown, and then strip leftover markdown in code before you send the chunk, because the prompt won't win every time.
Numbers, times, prices and dates are the other trap. Engines handle "$1,200", "10:30" or "2026-11-24" in different ways, and some read phone numbers as one huge number. Don't guess how yours behaves. Write a short list of the formats your agent really says, run them through your TTS once, and listen. Then normalize only the ones that come out wrong.
When the caller interrupts
Chunking also matters for barge-in. When the caller starts talking over the agent, you need to stop the audio and also throw away whatever text is still in the buffer and whatever the TTS engine has queued. If you only stop playback, the next chunk can start a second later and the agent seems to ignore the caller. Smaller chunks after the first one make this cheaper too, because less audio is already generated and wasted when you cancel.
What to measure
When you tune minChars and the fallback limit, measure the time from the end of the caller's speech to the first agent audio, and also listen to real calls. The numbers tell you whether the first chunk is fast enough. Only listening tells you whether the joins between chunks sound natural. If they don't, try longer chunks after the first one before you try anything clever, since that change alone fixes most of the choppy sound.
Top comments (0)