Voice agents are quickly replacing the traditional IVR in contact centers. Instead of “press 1 for appointments, press 2 for billing”, the caller simply talks and the agent listens, understands and talks back. Webex Contact Center (WxCC) like many other CCaaS solutions supports this through out-of-the-box Virtual Agents and now with BYOVA (Bring Your Own Virtual Agent) you can plug your own agent into the call flow.
This is the first part of a new series where we start with the basic building blocks of a Voice Virtual Agent from scratch in Python. In the future parts, we’ll build the whole agent ourselves, including the brain – a hand written, rule-based NLU engine and dialogue flow, along with the speech-to-text, text-to-speech powered by Deepgram and audio handling around it. We will take it all the way to a working Webex Contact Center (WxCC) deployment with DTMF, barge-in and handoff to a human agent, within the limits of a rule-based brain. Commercial platforms like Kore.ai, Cognigy & Dialogflow do this at a far more sophisticated level and in a second series we will swap them in for our brain and compare. But not every business needs that or can afford it, so we will see how far a do-it-yourself brain can go first.
But before any of that, we need to get the foundation right. In this part we build the smallest possible version – your laptop microphone, your speaker, and a loop that listens, thinks and speaks. There is no telephony, no LLM and no database yet. Those will come later. For now, everything in this post runs locally on your machine.
A sample interaction looks like this:
Agent: Voice assistant ready. Say something, or say exit to quit.
You said: what time is it
Agent: It’s currently 07:10 PM.
Along with every reply the script prints how long the caller sat in silence, broken down by cause. That number is the single most important metric in a voice agent and we will spend some time on it.
Table of Contents
Why Build a Voice Agent?
In a contact center, the voice channel is still where the most time-consuming and expensive conversations happen. A large share of those calls are routine like checking an appointment, confirming an order status, resetting something simple. These are exactly the calls that a well-built agent can handle end to end, leaving your human agents free for the conversations that actually need a human.
The challenge is that voice is unforgiving. A chatbot that takes four seconds to reply feels fine. A voice agent that stays silent for four seconds feels broken & the caller starts saying “hello?” into the phone. So before adding intelligence, we first need a pipeline that is fast and behaves well in a real conversation.
One of the practical use-cases is a hospital appointment line:
- The caller phones in and the agent greets them
- The agent verifies who they are
- The agent looks up their appointment and reads the details back
- If anything goes wrong, or the caller asks for it, the call is transferred to a human agent
It is an ordinary contact center scenario and it is a good test because it exposes every real-world problem early:
- Latency : How long the caller waits in silence before the agent responds
- Turn-taking : Knowing when the caller has actually finished speaking
- Echo : The agent’s own voice leaking back into the mic and being treated as caller speech
- Accuracy : Names, dates and digits are where speech recognition struggles the most
Architecture Overview
Every voice agent, however sophisticated, is basically the same four pieces in a loop:

Here is what happens when you speak to it:
- PyAudio captures audio from the mic in small chunks of about 64 ms
- A background thread streams every chunk to Deepgram over a WebSocket (shown in step 1)
- Deepgram sends back interim results as you speak then a final result and finally a speech_final marker when it decides you have stopped talking
- The finished sentence goes onto a queue and the main thread passes it to think(). This is the brain. (shown in step 2)
- The reply text is posted to Deepgram TTS (shown in step 3)
- The audio is streamed straight to the speaker while it is still being generated (shown in step 4)
Notice that both directions are streaming. The mic audio goes up continuously and the reply audio comes down continuously. That is what keeps the conversation feeling natural.
Understanding STT and TTS
Speech-to-Text (STT) simply converts audio into text. There are two modes worth knowing about:
- Batch : You send a complete recording and get the transcript back afterwards. This is perfect for post-call analytics but pretty much useless for a live conversation.
- Streaming : Audio flows to the service continuously and the transcript comes back while the person is still talking. This is what a live agent needs.
Text-to-Speech (TTS) does the opposite and converts your reply text into spoken audio. The same split applies. A non-streaming call waits until the whole audio file has been generated and only then lets you play it. A streaming call hands you audio bytes almost immediately, so playback starts while the rest is still being produced. For short replies the difference is small. For longer ones it is the difference between a natural pause and an awkward one.
In between the two sits the brain, which takes the caller’s text and decides what to say. In this post, I’ve deliberately kept it simple by hardcoding a handful of rules. In later parts. we will increase the complexity by adding a DB, LLMs, MCP tools etc
Why Deepgram?
I evaluated a few options for this project including Deepgram, AssemblyAI, Whisper, ElevenLabs etc. For this first stage I went with Deepgram for these reasons:
- One provider for both directions : A single API key covers STT (the Nova-3 model) and TTS (the Aura-2 voices)
- Streaming is first class : On both the STT and TTS side
- Endpointing built in : Deepgram tells you when the speaker has finished, so you do not need to write your own voice activity detection
- Telephony friendly formats : It handles the audio encodings that phone networks use, which will matter when we reach WxCC
I am not claiming that this is the best provider at everything. ElevenLabs voices are also very natural and for accuracy you should always test a couple of providers against your own audio.
My suggestion is to start with a cloud provider that gives free credit (like Deepgram), so you are debugging your own code and not your GPU configuration. Once the pipeline works, swapping a provider is a small change because the brain does not care where its text came from. That is the same idea we saw in the SIPp series, where swapping the LLM was straightforward as long as the integration layer stayed consistent.
Project Setup
- Install Python. I used Python 3.12.
- Create a free account on Deepgram and generate an API key.
- Install the packages:
pip install deepgram-sdk pyaudio requests
- Create a config.json file next to the script and add your key:
{
"deepgram_api_key" : ""
}
I have used a flat JSON file here for the same reason as in my earlier projects. While you are actively developing and restarting often, a single file you can open and edit in seconds is more practical than environment variables. If you deploy this in production, move to environment variables. Either way, never commit your key to Git.
- Wear headphones. The reason is explained in the echo section below.
The Code
Here is the full code. Copy it to your machine and save the file as stt_stream_tts_stream.py
"""Mic -> Deepgram streaming STT -> think() -> Deepgram streaming TTS -> SpeakerBoth directions stream: the mic is sent to Deepgram continuously, and the spoken reply starts playing while Deepgram is still generating it."""import datetimeimport osimport queue, jsonimport reimport threadingimport timeimport pyaudioimport requestsfrom deepgram import DeepgramClientfrom deepgram.core.events import EventTypewith open("config.json", "r") as f: config_json = json.load(f)DEEPGRAM_API_KEY = config_json["deepgram_api_key"]# =============================================================================# Settings that can be modified# =============================================================================ENDPOINTING_MS = 800 # silence before Deepgram ends the turnPREBUFFER_MS = 150 # audio collected before playback startsSTT_MODEL = "nova-3"TTS_VOICE = "aura-2-thalia-en"# -----------------------------------------------------------------------------MIC_RATE = 16000 # Hz, mono, 16-bitMIC_CHUNK_FRAMES = 1024 # about 64 ms of mic audio per chunkTTS_RATE = 24000 # Hz, mono, 16-bitBYTES_PER_SAMPLE = 2TTS_URL = ( f"https://api.deepgram.com/v1/speak?model={TTS_VOICE}" f"&encoding=linear16&container=none&sample_rate={TTS_RATE}")# Shared statespeaking = threading.Event() # set while the assistant is talkingstop_event = threading.Event()turns = queue.Queue() # finished caller turns waiting for think()turn_text = [] # FINAL pieces of the turn in progress# One HTTPS session. This keeps the connection to Deepgram open between replies.tts_session = requests.Session()tts_session.headers.update({ "Authorization": f"Token {DEEPGRAM_API_KEY}", "Content-Type": "application/json",})# =============================================================================# THE BRAIN# =============================================================================def think(text): """ The 'brain'. It takes the caller's text & returns the reply text. Rules are hardcoded for now. DB Communication/LLM/agents/MCP logic goes here later. """ words = re.findall(r"\w+", text.lower()) if "hello" in words or "hi" in words: return "Hello! How can I help you today?" elif "time" in words: now = datetime.datetime.now().strftime("%I:%M %p") return f"It's currently {now}." elif "bye" in words or "exit" in words: return "Goodbye!" else: return f"You said: {text}. I don't have a smart response wired up yet."# =============================================================================# STT SIDE: mic -> Deepgram -> finished turns# =============================================================================def on_message(result): """Runs on the SDK's thread each time Deepgram sends a result.""" if result.type != "Results": return # Ignore anything heard while the assistant is talking (its own voice, echo). if speaking.is_set(): turn_text.clear() return transcript = result.channel.alternatives[0].transcript if transcript and result.is_final: turn_text.append(transcript) elif transcript: print(f" ...{transcript}", end="\r") if result.speech_final and turn_text: full_turn = " ".join(turn_text).strip() turn_text.clear() turns.put((full_turn, time.time())) # time = when end of turn arriveddef stream_mic(connection, mic): """Push mic audio to Deepgram. While speaking, push silence instead.""" silence = b"\x00" * (MIC_CHUNK_FRAMES * BYTES_PER_SAMPLE) while not stop_event.is_set(): chunk = mic.read(MIC_CHUNK_FRAMES, exception_on_overflow=False) connection.send_media(silence if speaking.is_set() else chunk)# =============================================================================# TTS SIDE: text -> Deepgram -> speaker, played while it downloads# =============================================================================def speak(text, speaker): """ Streams Deepgram TTS audio straight to the speaker. Returns (seconds until first audio was sent to the speaker, timestamp of that moment), or (0.0, None) if the request failed. """ print(f"Agent: {text}") prebuffer_bytes = int(TTS_RATE * BYTES_PER_SAMPLE * PREBUFFER_MS / 1000) t_start = time.time() response = tts_session.post(TTS_URL, json={"text": text}, stream=True, timeout=30) if response.status_code != 200: print(f"TTS error {response.status_code}: {response.text}") return 0.0, None pending = bytearray() # audio waiting to be written leftover = b"" first_audio_at = None for chunk in response.iter_content(chunk_size=4096): if not chunk: continue data = leftover + chunk usable = len(data) - (len(data) % BYTES_PER_SAMPLE) pending.extend(data[:usable]) leftover = data[usable:] # Hold back until the prebuffer is full, then play everything as it arrives. if first_audio_at is None and len(pending) < prebuffer_bytes: continue if first_audio_at is None: first_audio_at = time.time() speaker.write(bytes(pending)) pending.clear() if pending: # short replies that never filled the prebuffer if first_audio_at is None: first_audio_at = time.time() speaker.write(bytes(pending)) time.sleep(0.3) # let the last audio leave the sound card before the mic path reopens return ((first_audio_at - t_start) if first_audio_at else 0.0), first_audio_at# =============================================================================# MAIN LOOP# =============================================================================def main(): if not DEEPGRAM_API_KEY: print("DEEPGRAM_API_KEY is not set. See the SETUP notes at the top of this file.") return audio = pyaudio.PyAudio() mic = audio.open( format=pyaudio.paInt16, channels=1, rate=MIC_RATE, input=True, frames_per_buffer=MIC_CHUNK_FRAMES, ) speaker = audio.open( format=pyaudio.paInt16, channels=1, rate=TTS_RATE, output=True, ) speaking.set() speak("Voice assistant ready. Say something, or say exit to quit.", speaker) speaking.clear() client = DeepgramClient(api_key=DEEPGRAM_API_KEY) with client.listen.v1.connect( model=STT_MODEL, language="en", smart_format=True, interim_results=True, endpointing=ENDPOINTING_MS, encoding="linear16", sample_rate=MIC_RATE, channels=1, ) as connection: ready = threading.Event() connection.on(EventType.OPEN, lambda _: ready.set()) connection.on(EventType.MESSAGE, on_message) connection.on(EventType.ERROR, lambda err: print(f"[ERROR] {err}")) threading.Thread(target=connection.start_listening, daemon=True).start() if not ready.wait(timeout=10): print("Could not connect to Deepgram within 10 seconds.") return sender = threading.Thread(target=stream_mic, args=(connection, mic), daemon=True) sender.start() print(f"\nListening (endpointing = {ENDPOINTING_MS} ms). Speak now.\n") try: while not stop_event.is_set(): try: user_text, turn_ended_at = turns.get(timeout=0.2) except queue.Empty: continue print(f"You said: {user_text}") speaking.set() # mic path sends silence from here try: t_think = time.time() reply = think(user_text) think_seconds = time.time() - t_think tts_seconds, first_audio_at = speak(reply, speaker) if first_audio_at: total = ENDPOINTING_MS / 1000 + first_audio_at - turn_ended_at print( f" **** silence the caller heard: about {total:.1f}s " f"(endpointing {ENDPOINTING_MS / 1000:.1f}s + think {think_seconds:.2f}s " f"+ TTS first audio {tts_seconds:.2f}s) ****" ) finally: turn_text.clear() speaking.clear() words = re.findall(r"\w+", user_text.lower()) if "bye" in words or "exit" in words: stop_event.set() except KeyboardInterrupt: print("\nStopping...") stop_event.set() sender.join(timeout=2) connection.send_close_stream() mic.stop_stream() mic.close() speaker.stop_stream() speaker.close() audio.terminate()if __name__ == "__main__": main()
Run it with:
python stt_stream_tts_stream.py
Say “bye” or “exit” to quit, or press Ctrl+C.
Understanding the Code
The settings block
ENDPOINTING_MS = 800
PREBUFFER_MS = 150
STT_MODEL = "nova-3"
TTS_VOICE = "aura-2-thalia-en"
These are the knobs you will actually tune.
- ENDPOINTING_MS : How much silence Deepgram waits for before deciding the caller has finished their turn. This is the dead air knob. You can experiment with it. If you lower it too much, the agent might feel snappier but may cut in on someone who paused to think. If you raise it too much, it becomes more patient but slower.
- PREBUFFER_MS : How much audio is collected before playback starts. If it’s too small, the audio can stutter if the network hiccups. If it’s too large then you add delay for no benefit.
The audio constants matter too. The mic is 16 kHz, mono, 16-bit while the TTS output is 24 kHz, mono, 16-bit. Because the two rates differ, the mic and the speaker are opened as two separate streams. On a real phone call (e.g with WxCC) both directions will be 8 kHz, which we will deal with in future blogs.
The shared state
speaking = threading.Event()
stop_event = threading.Event()
turns = queue.Queue()
turn_text = []
The script uses threads, so these are how they communicate:
- speaking : Set while the assistant is talking. This is the key to handling echo.
- stop_event : Tells every thread to shut down
- turns : A queue of finished caller turns waiting for the brain
- turn_text : Collects the pieces of the sentence currently being spoken
There is also a single requests.Session for TTS. Reusing it keeps the HTTPS connection to Deepgram open between replies, so you do not pay the connection setup cost on every turn.
think(text)
def think(text):
words = re.findall(r"\w+", text.lower())
if "hello" in words or "hi" in words:
return "Hello! How can I help you today?"
...
Text goes in, text comes out. It lowercases the input, splits it into words and matches a few keywords. Matching against the list of words is important. Checking “hi” in text would also match “this” and “thinking”, whereas “hi” in words only matches the actual word.
It is deliberately simple. The whole point of this stage is that think() is the only function that changes when we bring in an LLM, an agent or MCP tools later. Everything else is plumbing.
on_message(result)
This runs on the Deepgram SDK’s own thread every time a result arrives & it is where turn-taking is decided. Deepgram sends three kinds of signals and it is worth keeping them straight:
- Interim result : A rolling guess at what is being said right now. It can change as more audio arrives. The script just prints it on a single line so you can watch it.
- Final result (is_final) : Deepgram is confident about that chunk of words. These are appended to turn_text.
- Speech final (speech_final) : The endpoint. The caller has been silent for ENDPOINTING_MS. This is the moment the script joins the pieces into one sentence and puts it on the turns queue.
The very first thing the function does is check the speaking flag. If the assistant is talking, anything transcribed is thrown away, because it is almost certainly the assistant’s own voice coming back through the mic.
stream_mic(connection, mic)
A simple loop that reads a chunk from the mic (1024 frames, about 64 ms), sends it to Deepgram and repeats.
The detail worth noticing is that while the assistant is speaking, it sends silence instead of real audio. There are two reasons for this. First, it stops the agent from hearing itself. Second, it keeps data flowing on the WebSocket so Deepgram does not decide the connection is idle and close it.
This mute-while-speaking approach is also why headphones help. It prevents the agent from hearing itself, but it also means you cannot talk over the agent. We will explore true barge-in, where the caller can interrupt, in the later parts of this series.
speak(text, speaker)
This is the most interesting function. It posts the text to Deepgram’s TTS endpoint with stream=True, then reads the audio back in 4096 byte chunks and writes each one straight to the speaker as it arrives.
A few small details that matter a lot:
- Prebuffer : Playback is held back until PREBUFFER_MS of audio has been collected, after which everything is played as it arrives
- The leftover byte : Each audio sample is 2 bytes, but a network chunk can end in the middle of a sample. The code keeps any stray odd byte and adds it to the front of the next chunk. If you skip this you get crackling noise that is not pretty to debug.
- Short replies : If a reply is so short that it never fills the prebuffer. Whatever has been collected is flushed at the end so nothing is lost
- The 0.3 second sleep : after the last byte is written the sound card still has audio queued. The sleep lets it finish before the mic path reopens otherwise the tail end of the agent’s voice is heard as the caller
The function also returns how long it took to get the first audio to the speaker, which feeds the latency report.
main()
main() opens the mic and the speaker, speaks a greeting with the speaking flag set so the greeting is not transcribed, and then opens a streaming connection to Deepgram with the model, language, interim results, endpointing value and audio format (linear16, 16 kHz, mono).
It then starts two background threads, one listening for results and one sending mic audio, and waits up to 10 seconds for the connection to open. After that the main thread settles into a loop:
- Pull a finished turn off the queue
- Set speaking so the mic path goes quiet
- Call think() and then speak()
- Print how much silence the caller experienced
- Clear speaking inside a finally block, so a crash can never leave the agent deaf
- If the caller said “bye” or “exit”, stop the loop
Measuring the Silence the Caller Hears
I personally use this sort of technique when I am working with agents because latency is what makes or breaks a voice agent, and most demos never measure it. After every reply the script prints a line like this:
**** silence the caller heard: about 1.4s (endpointing 0.8s + think 0.00s + TTS first audio 0.58s) ****
The total is the sum of three things:
- Endpointing : The silence Deepgram waits for before declaring the turn over. You pay this on every single turn.
- Think time : How long the brain took. It is effectively zero with in this example hardcoded rules but it will grow dramatically as we start working with LLMs, MCP tools, APIs.
- TTS time to first audio : How long until the caller hears the first sound
Once you can see the three numbers separately you know exactly which one to attack because optimising blindly is how you will lay your weekend to waste.
Scope and Limitations
It is worth being clear about what this version does and does not do. This is the foundation to learn the pipeline on and not something to put in front of callers.
What it does: listens through your mic using streaming STT, passes the text to a simple rule-based brain and speaks the reply back using streaming TTS, while measuring the silence the caller experiences.
What it does not do: It has no telephony, so there is no phone call involved and the audio is 16 kHz and 24 kHz rather than the 8 kHz of a real phone network. It has no real understanding because keyword matching is not intelligence. It does not support barge-in, DTMF or call transfer. TTS is also done over HTTP here, which works well for this prototype, but a persistent WebSocket is the better pattern for live audio and we will switch to it once we start working with WxCC.
What is Next
Here is the roadmap for the series:
- Give the agent a real purpose and real data with the hospital appointment scenario
- Bring in DB, LLM and MCP based reasoning
- Move the whole thing behind Webex Contact Center BYOVA so a real phone call can reach it
- Handle DTMF and hand the call over to a human agent
Youtube Video
An explanatory video is in the works and should be available in the next few days. In the meantime, please feel free to check out other videos on the channel and don’t forget to subscribe while you are there. That helps a lot!
https://www.youtube.com/@learnuccollab
I hope this post gives you a clear picture of the building blocks behind every voice agent and helps you understand how a streaming voice pipeline works under the hood. In the next parts, we will build on it towards a real contact center voice agent.
Feel free to drop your questions or feedback in the comments below. Until then, Keep Learning!!
