Making an LLM Agent Speak: One Process, Sentence Streaming, and Text for the Ear
I wanted to talk to a coding agent and have it talk back. Not a chatbot with a voice skin, but an agent that can run shell commands and read my files, answering out loud. The pieces all exist: a speech-to-text model, an LLM CLI that already has tools wired up, and a text-to-speech engine that ships with the OS. Gluing them together took an afternoon. Making the result feel responsive, and stop saying silly things, took longer.
This post covers the three decisions that mattered most, and one bug that cost me a full minute every time I started the thing.
The pipeline
The shape is simple. A microphone captures an utterance, a local speech-to-text model (whisper.cpp in my case) turns it into text, the text goes to the LLM, and the reply goes to a text-to-speech engine (the built-in say command on macOS). The interesting part is what sits between the LLM and the speaker.
- Micyou stop talking
- Speech-to-text~0.3s per utterance
- LLMstreams tokens
- Sentence splitterreleases each finished sentence
- Text-to-speechrewrite for the ear, then speak
- Speakeryou hear it
If you wait for the whole reply and then speak it, every answer starts with an awkward silence the length of the full generation. If you speak each token as it arrives, the TTS engine gets fragments it cannot pronounce naturally. The sentence is the right unit: big enough to sound like speech, small enough to start early.
Decision 1: one long-lived CLI process, not one per turn
The obvious way to call an LLM CLI from a script is to spawn it per question: pass the prompt as an argument, read stdout, exit. That works, and it is wrong for a conversation, for two reasons.
- Memory. A fresh process has no idea what you said ten seconds ago. "Multiply that by two" means nothing. You end up rebuilding history yourself and replaying it every turn.
- Startup cost. An agent CLI loads its tools, config and integrations on start. Paying that on every turn adds latency you can hear.
The Claude Code CLI can run in a streaming mode where both stdin and stdout carry newline-delimited JSON (-p --input-format stream-json --output-format stream-json, plus --include-partial-messages to get token deltas). Start it once, keep the pipe open, and write one JSON message per user turn. The process keeps one session for its whole life, so conversation memory comes for free and the startup cost is paid once.
The pattern is a background thread that reads stdout into a queue, so the main loop can wait with a timeout instead of blocking forever on a read:
import json, queue, subprocess, threading
class PersistentCLI:
def __init__(self, cmd):
self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, text=True, bufsize=1)
self.events = queue.Queue()
threading.Thread(target=self._pump, daemon=True).start()
def _pump(self):
for line in self.proc.stdout:
if line.strip():
self.events.put(json.loads(line))
self.events.put({"type": "eof"})
def ask(self, text, timeout=60):
msg = {"type": "user", "message": {"role": "user", "content": text}}
self.proc.stdin.write(json.dumps(msg) + "\n")
self.proc.stdin.flush()
while True:
ev = self.events.get(timeout=timeout) # raises queue.Empty
if ev["type"] == "eof":
raise RuntimeError("CLI exited mid-turn")
if ev["type"] == "stream_event":
delta = ev["event"].get("delta", {})
if delta.get("type") == "text_delta":
yield delta["text"]
elif ev["type"] == "result":
returnTwo small things worth doing on top: drain any leftover events before each new turn (an interrupted reply can leave some behind), and keep the last few lines of stderr so that when the process dies you can say why.
The bug: a 60-second wait for a hello that never comes
My first version did what felt responsible. After spawning the process, it waited for a startup event (the CLI's init message carrying the session id) before declaring the brain ready. Every launch then sat there for exactly 60 seconds, hit the timeout, and failed.
The CLI in this mode is silent until it receives its first user message. It does not announce itself at startup. My code was waiting for the other side to speak first, and the other side was waiting for me. A deadlock with a timeout attached.
The fix was to stop waiting for anything at startup. I now give the process about a second to see whether it dies straight away (bad flags, not logged in), and if it is still running, treat it as alive. The session id gets picked up from the first real turn, and that first turn gets a longer timeout because it also pays the startup cost. The lesson I keep relearning: never assume a handshake exists. Check what the other side actually sends before writing code that waits for it.
Decision 2: split the stream into sentences, carefully
Splitting on ., ! and ? is a one-liner, and it is wrong the moment the model says "Dr. Smith" or "about 3.14". The voice pauses mid-thought and the next fragment sounds like a new sentence. The guards I ended up with:
- Need one character of lookahead. A period only ends a sentence if whitespace or a closing quote follows. That alone handles decimals: in
3.14the dot is followed by a digit. It also means the splitter waits for the next token before releasing, which costs almost nothing. - Abbreviations. If the word before the period is in a list (dr, mr, vs, etc, e.g, i.e, month names), it is not a boundary. Single initials like "J." count too.
- Do not over-guard numbers. My first decimal guard said "a digit before the dot means no boundary". That merged "The answer is 42. Next question." into one sentence. The lookahead rule was already enough.
- Glued blocks. When an agent's reply spans several content blocks, they can arrive joined with no space: "...done now.Your files are...". A period followed directly by a capital letter is treated as a boundary.
import re
ABBREV = {"mr", "mrs", "dr", "prof", "vs", "etc", "e.g", "i.e", "approx", "no"}
def is_boundary(buf: str, i: int) -> bool:
if i + 1 >= len(buf):
return False # wait for lookahead
nxt = buf[i + 1]
if not (nxt in " \n\t\"')" or nxt.isupper()):
return False # "3.14", "x.y"
if buf[i] in "!?":
return True
last = re.split(r"[\s(]", buf[:i])[-1].lower().strip("\"'(")
return last not in ABBREV and not (len(last) == 1 and last.isalpha())
class SentenceSplitter:
def __init__(self):
self.buf = ""
def feed(self, chunk: str) -> list[str]:
self.buf += chunk
out, start = [], 0
for i, ch in enumerate(self.buf):
if ch in ".!?" and is_boundary(self.buf, i):
out.append(self.buf[start:i + 1].strip())
start = i + 1
self.buf = self.buf[start:]
return out
def flush(self) -> str:
rest, self.buf = self.buf.strip(), ""
return restEach sentence goes into a queue that a speaker thread drains, so speech and generation run in parallel. Interrupting is then easy: empty the queue and kill the current TTS process.
Decision 3: rewrite text for the ear
LLM output is written to be read. Piped straight into a speech engine, **important** gets its asterisks read out or mangled, a markdown list becomes a stream of "dash", -80°F (-60°C) is gibberish, and a URL is a ten-second recital. So every sentence passes through a normaliser before it is spoken:
- Drop code fences entirely and say "code omitted" instead.
- Strip emphasis, headers, bullets, quotes, tables and link syntax, keeping the words.
- Replace URLs with "a link" and file paths with "a file path".
- Expand units and symbols:
°Cto "degrees Celsius",%to "percent",GBto "gigabytes",5-10to "5 to 10",&to "and". - Turn dashes and ellipses into commas, which the TTS engine reads as short pauses.
- Remove emoji.
The other half of the fix is upstream: a line in the system prompt asking the model to answer conversationally and write numbers as words. The normaliser catches what slips through. I found almost every rule by listening, not by reading docs. Run it for a day and write down every time it says something odd.
What it measured
On an Apple Silicon laptop, with the full tool set loaded:
- Each LLM turn takes about 1.5 seconds, the first one slightly longer.
- Speech-to-text transcribes a 2.5-second utterance in about 0.3 seconds. The first call takes around 16 seconds while GPU shaders compile, so I warm it up at startup rather than make your first question pay for it.
- The TTS engine renders a sentence in about 0.4 seconds.
- End to end, you hear the first words roughly 2 to 3 seconds after you stop talking.
- Marginal cost is about $0.008 per turn at list price, most of it re-reading around 38K tokens of cached context (system prompt and tool definitions). A lean mode with no tools drops that to about $0.0009 per turn, roughly nine times cheaper, but then it is just a chatbot again.
Trade-offs
- Half-duplex. It listens, then thinks and speaks, then listens. Real barge-in needs echo cancellation, or it transcribes its own voice. A keypress interrupts instead.
- One process is one point of failure. If it dies, the conversation's memory goes with it. You need clear errors and a restart path.
- A voice agent with tools acts without a keyboard in the loop. That is the point, and it is also the risk. Point it at a directory you are comfortable with, or run it without tools.
- Sentence-level streaming still waits for the first sentence. If the model opens with a long sentence, you wait for all of it. Asking for short, spoken-style sentences in the prompt helps more than any splitter tweak.
Takeaway
Most of what makes a voice agent feel fast is not the model. It is keeping one process alive, releasing speech one sentence at a time, and rewriting text for the ear. And before you write code that waits for a handshake, check that the other side actually sends one.