Voice Agent Echo: How to Test and Debug Self-Interruptions
Voice agent echo makes an agent transcribe its own TTS as the caller and cut itself off. Reproduce it with a playback sweep, read the trace, fix the source.
Table of Contents
A caller on speakerphone in her car books a dental appointment. The agent says “Your appointment is booked for Tuesday at three.” The line plays through the car speakers, back into the phone microphone, and the transcript shows the caller saying it (illustrative, the lab’s fixture turn 1).
This is voice agent echo: the agent’s own TTS is transcribed as the caller, so it hears itself and cuts itself off. No VAD or prompt change can see the “caller” is the agent. This post covers leak paths, canceller needs, LiveKit, Pipecat, Vapi and Retell guards, a playback lab tested end to end, trace debugging and fixes.
TL;DR
- Voice agent echo is the agent’s own TTS reaching its input path, where speech-to-text transcribes it as the caller and the agent interrupts or answers itself in a loop.
- The leak comes from speakerphones, car Bluetooth kits and laptops without headphones. On a phone call, echo cancellation usually runs in the caller’s handset or the network, and practitioner reports show it does not always stop speakerphone echo.
- An acoustic echo canceller needs the playback reference, delay alignment, an adaptive filter and residual suppression; in our synthetic lab, NLMS without a delay estimate failed once the echo delay passed its 32 ms filter.
- LiveKit Agents by default ignores interruptions for 3.0 seconds from the agent’s first speech and needs 0.5 seconds of speech per interrupt, while Pipecat offers mute and turn-start strategies plus an optional Soniox echo setting.
- Test with controlled playback across delays and gains, check STT text against the agent’s last line per turn, and fix in audio-path order.
How voice agent echo turns one sentence into a self-interruption loop
Voice agent echo is the agent’s own TTS audio reaching its input path. Speech-to-text transcribes that audio as the caller, the agent treats it as a barge-in, stops talking, and then answers its own words. Each new reply can leak back the same way, so one leak turns into a repeating loop of self-interruptions.
Once that audio is in the input, prompts and turn logic cannot tell the voices apart, and barge-in and turn-taking for voice AI covers other false barge-in causes; this post covers echo.
What the bug reports have in common
In a Pipecat issue on Safari self-transcription (2025-11-15), the bot’s “What’s on your mind?” came back as the user transcript “What’s on your mind?” without headphones.
An AEC regression in the LiveKit Swift SDK made the agent hear its own speaker output in an endless loop on v2.12.0; pinning 2.11.0 fixed it (2026-02-13 to 2026-02-17).
A LiveKit Agents issue on iPhone browsers (2025-10-30) shows the same with echoCancellation true.
In a Retell community thread, the original post (2026-05-26) says “for 10% of the cases, the agent is getting interrupted by its own voice”; another user replied the next day that they saw it “especially right at the start of calls”. These reports point to uncontrolled devices, call start and exact self-transcription.
Where the agent’s voice leaks back into the input path
The agent’s voice leaks back wherever a speaker and a microphone share a room or a cable: a speakerphone, a car’s Bluetooth kit or a laptop without headphones. On phone calls, cancellation usually runs in the caller’s handset or the network, or in a speech service in your pipeline; LiveKit’s room input and Pipecat’s audio filters include none.
Your server holds only the mixed inbound audio and its playback. For a bridge or media path you run, cross-correlate inbound audio with the agent’s playback, as estimate_delay in echo_lab.py does: a strong peak means the agent’s audio is in the inbound stream, and its lag is the delay to cancel.

Speakerphones, cars and the phone network
A speakerphone or car kit plays the agent loud near the microphone. LiveKit Agents’ room input and Pipecat’s audio filters include no reference-based echo canceller, so on a phone call cancellation usually runs in the caller’s handset or the network, unless a speech service in your pipeline does it.
LiveKit’s noise and echo cancellation page says: “WebRTC cancellation runs in the client only, so it applies to conferencing. For agents and telephony (where there is no browser frontend), use the LiveKit Cloud models above.” It calls those models voice isolation and background noise suppression.
On a Pipecat issue on where echo cancellation belongs (2024-12-03), a contributor wrote: “Echo cancellation should be part of the client implementation.”
This is contested. Deepgram’s voice agent echo cancellation docs say under “Telephony systems” that “Modern phones have hardware-level and software-level echo cancellation built in, ensuring users don’t hear their own voice echoed back during calls.” Deepgram adds that on PSTN or VoIP “the built-in echo cancellation handles audio issues automatically without requiring additional configuration”.
Yet a speakerphone echo report on the OpenAI forum (2025-12-23) says the agent heard itself, and the Retell reporter suspects caller-side cancellation.
Browser and mobile WebRTC clients
W3C Media Capture and Streams, a Candidate Recommendation Draft of 19 November 2026, makes echoCancellation a getUserMedia constraint, defines EchoCancellationModeEnum with “all” and “remote-only”, and leaves both what true removes and the default to the user agent. A non-normative note says implementations tend to default it to true; mobile clients add hardware paths.
What acoustic echo cancellation needs inside a voice agent
An acoustic echo canceller needs four things: a copy of the far-end reference (the audio the agent is playing), an estimate of the delay between playback and capture, an adaptive filter that models the echo path, and residual suppression for what the filter misses. WebRTC’s AEC3 module is the open reference implementation of all four.
At commit a777a4f3, AEC3’s source maps them to code: AnalyzeRender “Analyzes and stores an internal copy of the split-band domain render signal”; render_delay_controller, echo_path_delay_estimator and SetAudioBufferDelay for delay; adaptive_fir_filter and subtractor; residual_echo_estimator and suppression_gain.
Delay alignment and double talk in the lab
echo_lab.py runs an illustrative, not production-quality, NLMS canceller on synthetic signals. At 120 ms and -6 dB the echo path ends at 126 ms while the 256-tap filter covers 32 ms, so misalignment without a delay estimate stays at +0.1 dB. After a cross-correlation bulk-delay estimate, NLMS adapts.
Double talk without a freeze reads -3.2 dB at 6.5 s (after caller turn 1) and +22.7 dB at 8.4 s, with 1 false trigger after the caller stops. A naive Geigel freeze holds -16.5 and -16.8 dB with 0 such triggers. The sweep’s 3/0 for nlms+delay there counts the whole call.
Echo guards in LiveKit, Pipecat, Vapi and Retell
In LiveKit and Pipecat, voice AI echo cancellation sits mostly in the client, outside the agent. LiveKit Agents by default ignores interruptions for 3.0 seconds after the agent first speaks and needs 0.5 seconds of speech to count one, Pipecat offers mute and turn-start strategies, and the Vapi and Retell settings pages document denoising without documenting echo cancellation.
LiveKit Agents warmup and interruption options
In LiveKit’s agent_session.py at commit b9b50f2c, _DEFAULT_AEC_WARMUP_DURATION = 3.0.
The docstring reads: “The duration in seconds that the agent will ignore user’s audio interruptions after the agent starts speaking. This is useful to prevent the agent from being interrupted by echo before AEC is ready. Defaults to 3.0, or None for outbound SIP calls.”
The source starts “a one-shot wall-clock timer on the first speaking turn”, so it guards call start only; simulation turns it off. LiveKit’s InterruptionOptions adds min_duration and min_words (STT only); old keyword arguments are deprecated for turn_handling=TurnHandlingOptions(...).
Pipecat mute and turn-start strategies
Per Pipecat’s changelog, 1.0.0 (2026-04-14) removed allow_interruptions for user_turn_strategies and user_mute_strategies; 1.16.0 (2026-11-11) added Soniox enable_echo_cancellation, default False.
AzureVoiceLiveLLMService (1.13.0, 2026-10-18) exposes Azure’s server-side echo cancellation as input_audio_echo_cancellation, None by default; its InputAudioEchoCancellation class “Keeps the agent from hearing its own playback”.
AlwaysUserMuteStrategy “always mutes the user while the bot is speaking”, and MinWordsUserTurnStartStrategy starts a user turn after a minimum word count from transcription.
No Pipecat audio filter is a reference-based canceller (aic is real-time enhancement; koala, krisp_viva and rnnoise suppress noise), and the Krisp VIVA filter “Optionally supports TTS detection” to “delay voice isolation until bot speech playback has stopped”.
Vapi and Retell denoising settings
Vapi background speech denoising documents Smart Denoising (Krisp) and Fourier Denoising (Experimental); the Retell create-agent reference documents denoising_mode and interruption_sensitivity from 0 to 1; neither page documents echo cancellation.
Vapi’s Deepgram transcriber feedback filter, on by default, drops text repeating the assistant. Echo guards by framework:
| Framework (version or commit) | Where any canceller runs | Guard against acting on echo | Default | Caveat |
|---|---|---|---|---|
| LiveKit Agents (commit b9b50f2c, same defaults at release 1.9.0) | Client WebRTC | aec_warmup_duration | 3.0 s from the agent’s first speech, None for outbound SIP and in simulation | One-shot at call start |
| LiveKit Agents | Client WebRTC | InterruptionOptions min_duration and min_words | 0.5 s and 0 words (false_interruption_timeout 2.0 s, resume_false_interruption True) | min_words needs STT |
| Pipecat (commit 08ebe185, latest release 1.17.0) | Client, no canceller among the audio filters | AlwaysUserMuteStrategy via user_mute_strategies | Empty list by default | Blocks real barge-in while the bot speaks |
| Pipecat | Client | MinWordsUserTurnStartStrategy via user_turn_strategies | You pass it (the field defaults to None) | Needs transcription frames |
| Pipecat with Soniox STT | STT side | enable_echo_cancellation | False | Needs a TTS that reports word timestamps |
| Pipecat with Azure Voice Live | Speech service (server_echo_cancellation) | input_audio_echo_cancellation | None | reference_source “client” needs 2 input channels |
| Vapi | Not documented on its page | Smart Denoising, Fourier Denoising | Smart on, Fourier off | Denoising targets background noise |
| Retell | Not documented on its page | denoising_mode, interruption_sensitivity | noise-cancellation, 1 | 0 disables interruption |
Testing voice agent echo with controlled playback into the input path
To test voice agent echo, mix the agent’s own audio back into the input path at controlled delays and gains, then count false barge-ins while the caller is silent and missed barge-ins while the caller really speaks. Our standard-library lab sweeps four delays and four gains across seven guard configurations, all on synthetic signals.
The mic path mixes a synthetic caller (barge-ins at 1.6 to 2.4 s and 6.6 to 7.8 s), seeded noise and a speech-like agent signal through a 6 ms echo response, delayed 20 to 250 ms at -30 to -6 dB.
An energy VAD (frame RMS above 0.01) is the simplest instrument, not any vendor’s; see how voice activity detection gates barge-in. All signals are synthetic or illustrative fixture, not recorded calls. Save the two blocks below as echo_lab.py and stt_fixture.csv:
"""echo_lab.py: play a voice agent's own audio back into its input path and count self-interruptions.
Python standard library only, 8 kHz mono.
Everything here is a synthetic or illustrative fixture, not recorded calls: the agent and caller
waveforms, the echo impulse response, the noise, the STT transcripts and every threshold.
The NLMS canceller illustrates what an acoustic echo canceller does (far-end reference, delay
alignment, adaptive filter); it is not production quality and has no residual echo suppressor.
The energy VAD is the simplest possible instrument, not a model of any vendor's VAD.
Two defaults are taken from LiveKit Agents at livekit/agents@b9b50f2c8cc0b2f5d9d6930649df603a269a73c6:
voice/turn.py InterruptionOptions min_duration = 0.5 s
voice/agent_session.py _DEFAULT_AEC_WARMUP_DURATION = 3.0 s (one-shot, from the agent's first speech)
Usage: python3 echo_lab.py [--stt stt_fixture.csv] [--wav-dir DIR]
Exit 1 (fail closed) if the chosen config still false-triggers at -12 dB or louder,
or if the STT fixture is empty, repeats a turn_id or has a malformed row.
"""
import argparse
import array
import csv
import difflib
import math
import os
import random
import sys
import wave
from collections import deque
from operator import mul
FS = 8000
CALL_S = 10.0
N = int(FS * CALL_S)
FRAME_MS = 20
FRAME = FS * FRAME_MS // 1000
# Synthetic call script (seconds). Illustrative fixture, not a recorded call.
AGENT_TURNS = [(0.0, 4.5), (5.5, 9.5)]
CALLER_TURNS = [(1.6, 2.4), (6.6, 7.8)] # real barge-ins: one inside the warmup window, one later
# Illustrative thresholds.
VAD_RMS = 0.01 # frame RMS above this is "speech" (about -40 dBFS)
BASE_MIN_S = 0.1 # raw energy VAD needs 100 ms of speech to fire
LK_MIN_DURATION_S = 0.5 # LiveKit InterruptionOptions.min_duration default
LK_AEC_WARMUP_S = 3.0 # LiveKit aec_warmup_duration default
DETECT_TOL_S = 0.06 # a trigger up to 60 ms after a caller turn ends still counts as detecting it
NLMS_TAPS = 256 # 32 ms adaptive filter
NLMS_MU = 0.5
GEIGEL_T = 0.5 # naive double-talk freeze threshold
TEXT_MATCH = 0.8 # difflib ratio at or above this = "STT text matches the agent's last utterance"
DELAYS_MS = [20, 60, 120, 250]
GAINS_DB = [-30, -20, -12, -6]
GATE_GAIN_DB = -12
CHOSEN = "aec+min-dur" # NLMS after the bulk delay estimate, then the 0.5 s gate
def voice(rng, turns, f0a, f0b, syl_hz, word_s, gap_s):
"""Speech-like synthetic voice: harmonics on a gliding f0, syllable-rate envelope, word gaps."""
out = [0.0] * N
phase = 0.0
for a, b in turns:
i0, i1 = int(a * FS), int(b * FS)
dur = b - a
for i in range(i0, i1):
t = (i - i0) / FS
f0 = f0a + (f0b - f0a) * (t / dur) + 6 * math.sin(2 * math.pi * 0.7 * t)
phase += 2 * math.pi * f0 / FS
s = 0.0
k = 1
while k * f0 < 3400:
s += math.sin(k * phase) / k
k += 1
env = 0.0 if (t % (word_s + gap_s)) > word_s else 0.45 + 0.55 * abs(math.sin(math.pi * syl_hz * t))
out[i] = env * s + 0.02 * rng.gauss(0, 1) # breath noise excites the whole band
rms = math.sqrt(sum(v * v for v in out) / sum(1 for v in out if v != 0.0))
return [v * 0.1 / rms for v in out]
def make_ir(rng, taps=48):
"""Synthetic decaying echo path (6 ms), unit energy."""
h = [rng.gauss(0, 1) * math.exp(-k / 10) for k in range(taps)]
h[0] = abs(h[0]) + 1.0
e = math.sqrt(sum(v * v for v in h))
return [v / e for v in h]
def convolve(x, h):
y = [0.0] * len(x)
for k, hk in enumerate(h):
for i in range(k, len(x)):
y[i] += hk * x[i - k]
return y
def shift(x, d):
return [0.0] * d + x[: len(x) - d] if d > 0 else x[:]
def frame_rms(x):
return [math.sqrt(sum(v * v for v in x[i:i + FRAME]) / FRAME) for i in range(0, len(x) - FRAME + 1, FRAME)]
def vad_triggers(x, min_s, warmup_s=None):
"""Energy VAD with a minimum-duration gate. Returns decision times (s).
warmup_s: ignore triggers decided within warmup_s of the agent's FIRST speech (one-shot, as LiveKit does).
Open loop: the agent keeps talking after a trigger, so counts are triggers per call."""
need = math.ceil(min_s * 1000 / FRAME_MS)
run, fired, out = 0, False, []
first_speech = AGENT_TURNS[0][0]
for idx, r in enumerate(frame_rms(x)):
if r > VAD_RMS:
run += 1
if run >= need and not fired:
fired = True
t = (idx + 1) * FRAME_MS / 1000
if warmup_s is None or not (first_speech <= t < first_speech + warmup_s):
out.append(t)
else:
run, fired = 0, False
return out
def score(triggers):
detected = [any(a <= t <= b + DETECT_TOL_S for t in triggers) for a, b in CALLER_TURNS]
false = sum(1 for t in triggers if not any(a <= t <= b + DETECT_TOL_S for a, b in CALLER_TURNS))
return false, detected.count(False)
def estimate_delay(ref, mic, max_ms=300):
"""Bulk delay from cross-correlation: 1 ms envelopes first, then sample-level refinement."""
seg = int(1.5 * FS) # agent single talk, before the first caller turn
env = lambda s: [sum(abs(v) for v in s[i:i + 8]) for i in range(0, seg, 8)]
er, em = env(ref), env(mic)
mr, mm = sum(er) / len(er), sum(em) / len(em)
er, em = [v - mr for v in er], [v - mm for v in em]
coarse = max(range(max_ms), key=lambda L: sum(map(mul, er[: len(er) - L], em[L:])))
best, best_c = 0, -1e18
for d in range(max(0, coarse * 8 - 16), coarse * 8 + 17):
c = sum(map(mul, ref[800:seg - d], mic[800 + d:seg]))
if c > best_c:
best, best_c = d, c
return best
def nlms(ref, mic, taps=NLMS_TAPS, freeze=True, snap_at=()):
"""Illustrative NLMS echo canceller with an optional naive Geigel double-talk freeze."""
x = deque([0.0] * taps, maxlen=taps)
xmax = deque([0.0] * taps, maxlen=taps)
w = [0.0] * taps
pw = 0.0
out = [0.0] * len(mic)
hold = 0
snaps = {}
snap_at = set(snap_at)
for n in range(len(mic)):
xn = ref[n]
pw += xn * xn - x[-1] * x[-1]
x.appendleft(xn)
xmax.appendleft(abs(xn))
e = mic[n] - sum(map(mul, w, x))
out[n] = e
if freeze:
if abs(mic[n]) > GEIGEL_T * max(xmax):
hold = 240 # keep adaptation frozen 30 ms after double talk is seen
elif hold:
hold -= 1
if pw > 1e-4 and not (freeze and hold):
g = NLMS_MU * e / (pw + 1e-6)
w = [wi + g * xi for wi, xi in zip(w, x)]
if n in snap_at:
snaps[n] = w[:]
return out, snaps
def misalignment_db(w, true_h):
num = sum((a - b) ** 2 for a, b in zip(w, true_h)) + sum(b * b for b in true_h[len(w):])
return 10 * math.log10(num / sum(b * b for b in true_h))
def write_wav(path, x):
with wave.open(path, "wb") as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(FS)
f.writeframes(array.array("h", (max(-32767, min(32767, int(v * 32767))) for v in x)).tobytes())
def load_stt(path):
"""Synthetic STT fixture. Raises ValueError on any malformed row, a repeated turn_id or no rows (fail closed)."""
with open(path, newline="") as f:
rows = [r for r in csv.reader(line for line in f if not line.startswith("#"))]
header = ["turn_id", "agent_last_utterance", "stt_text", "stt_started_during_agent_playback", "fixture_truth"]
if not rows or rows[0] != header:
raise ValueError(f"bad header: {rows[0] if rows else 'empty file'}")
out = []
for i, r in enumerate(rows[1:], start=2):
if len(r) != 5 or not r[0].isdigit() or not r[1].strip() or not r[2].strip() \
or r[3] not in ("yes", "no") or r[4] not in ("echo", "caller"):
raise ValueError(f"malformed fixture row {i}: {r}")
if any(r[0] == o[0] for o in out):
raise ValueError(f"duplicate turn_id {r[0]} at fixture row {i}")
out.append(r)
if not out:
raise ValueError("no fixture rows after the header")
return out
def norm_words(s):
return "".join(c for c in s.lower() if c.isalnum() or c == " ").split()
def self_transcription(path):
print("\n== Self-transcription: STT text per turn vs the agent's last utterance ==")
print("(synthetic or illustrative fixture, not recorded calls; threshold %.2f is illustrative)" % TEXT_MATCH)
rows = load_stt(path)
unresolved = 0
for tid, agent, stt, during, truth in rows:
ratio = difflib.SequenceMatcher(None, norm_words(agent), norm_words(stt)).ratio()
text_says = "echo" if ratio >= TEXT_MATCH else "caller"
note = ""
if text_says != truth:
unresolved += 1
note = " <- text alone cannot resolve: started_during_playback=%s points to %s" % (
during, "echo" if during == "yes" else "caller")
print(f"turn {tid}: ratio {ratio:.2f} text-says {text_says:6s} fixture-truth {truth:6s}{note}")
print(f"turns the text match got wrong: {unresolved} of {len(rows)}")
def main():
ap = argparse.ArgumentParser()
here = os.path.dirname(os.path.abspath(__file__))
ap.add_argument("--stt", default=os.path.join(here, "stt_fixture.csv"))
ap.add_argument("--wav-dir", default=here)
args = ap.parse_args()
# Parse the fixture first so a malformed row fails closed before the long sweep.
try:
load_stt(args.stt)
except (ValueError, OSError) as exc:
print(f"FAIL (exit 1): STT fixture: {exc}")
return 1
rng = random.Random(7)
agent = voice(rng, AGENT_TURNS, 120, 150, 4.0, 0.85, 0.12)
caller = voice(rng, CALLER_TURNS, 210, 180, 5.0, 0.7, 0.10)
ir = make_ir(rng)
noise = [0.003 * rng.gauss(0, 1) for _ in range(N)]
echo_base = convolve(agent, ir)
print("All signals: synthetic or illustrative fixture, not recorded calls. 8 kHz mono, seed 7.")
print(f"agent turns {AGENT_TURNS}, caller barge-ins {CALLER_TURNS} (s); noise RMS 0.003; VAD frame RMS > {VAD_RMS}")
print(f"configs: none = energy VAD {BASE_MIN_S}s; nlms = NLMS {NLMS_TAPS} taps, no delay estimate; "
f"nlms+delay = NLMS after cross-correlation bulk delay; warmup = {LK_AEC_WARMUP_S}s one-shot; "
f"min-dur = {LK_MIN_DURATION_S}s gate; aec+X = nlms+delay output with that guard added")
configs = ["none", "nlms", "nlms+delay", "warmup", "min-dur", "aec+warmup", "aec+min-dur"]
print("\n== False / missed barge-ins per condition (F/M; 2 real caller barge-ins per call) ==")
print("delay gain est_delay | " + " ".join(f"{c:>11s}" for c in configs))
gate_fail = []
for d_ms in DELAYS_MS:
d = d_ms * FS // 1000
for g_db in GAINS_DB:
g = 10 ** (g_db / 20)
echo = [g * v for v in shift(echo_base, d)]
mic = [c + n + e for c, n, e in zip(caller, noise, echo)]
est = estimate_delay(agent, mic)
margin = 8
ref_aligned = shift(agent, max(0, est - margin))
aec_out = nlms(ref_aligned, mic)[0]
res = {
"none": score(vad_triggers(mic, BASE_MIN_S)),
"nlms": score(vad_triggers(nlms(agent, mic)[0], BASE_MIN_S)),
"nlms+delay": score(vad_triggers(aec_out, BASE_MIN_S)),
"warmup": score(vad_triggers(mic, BASE_MIN_S, warmup_s=LK_AEC_WARMUP_S)),
"min-dur": score(vad_triggers(mic, LK_MIN_DURATION_S)),
"aec+warmup": score(vad_triggers(aec_out, BASE_MIN_S, warmup_s=LK_AEC_WARMUP_S)),
"aec+min-dur": score(vad_triggers(aec_out, LK_MIN_DURATION_S)),
}
cells = " ".join(f"{'%d/%d' % res[c]:>11s}" for c in configs)
print(f"{d_ms:4d}ms {g_db:4d}dB {est * 1000 / FS:6.1f}ms | {cells}")
if g_db >= GATE_GAIN_DB and res[CHOSEN][0] > 0:
gate_fail.append((d_ms, g_db, res[CHOSEN][0]))
if d_ms == 120 and g_db == -12:
write_wav(os.path.join(args.wav_dir, "synthetic_mic_d120ms_g-12dB.wav"), mic)
print("\n== NLMS filter length vs echo delay (d = 120 ms, gain -6 dB) ==")
d = 120 * FS // 1000
g = 10 ** (-6 / 20)
echo = [g * v for v in shift(echo_base, d)]
mic = [c + n + e for c, n, e in zip(caller, noise, echo)]
est = estimate_delay(agent, mic)
s = max(0, est - 8)
t_before, t_after = int(6.5 * FS), int(8.4 * FS)
true_raw = [0.0] * d + [g * v for v in ir]
true_aligned = [0.0] * (d - s) + [g * v for v in ir]
_, sn_raw = nlms(agent, mic, snap_at=[t_before])
print(f"echo path ends at {(d + len(ir)) * 1000 / FS:.0f} ms, filter covers {NLMS_TAPS * 1000 / FS:.0f} ms: "
f"misalignment without delay estimate {misalignment_db(sn_raw[t_before], true_raw):+.1f} dB")
print("\n== Double talk: naive freeze vs none (same condition, reference shifted by the delay estimate) ==")
for freeze in (False, True):
e_out, sn = nlms(shift(agent, s), mic, freeze=freeze, snap_at=[t_before, t_after])
after = [t for t in vad_triggers(e_out, BASE_MIN_S) if t > CALLER_TURNS[1][1] + DETECT_TOL_S]
print(f"freeze={str(freeze):5s} misalignment at 6.5 s {misalignment_db(sn[t_before], true_aligned):+.1f} dB, "
f"at 8.4 s (after caller turn 2) {misalignment_db(sn[t_after], true_aligned):+.1f} dB, "
f"false triggers after the caller stops {len(after)}")
write_wav(os.path.join(args.wav_dir, "synthetic_agent_reference.wav"), agent)
self_transcription(args.stt)
if gate_fail:
print(f"\nFAIL (exit 1): {CHOSEN} still false-triggers at gain >= {GATE_GAIN_DB} dB: {gate_fail}")
return 1
print(f"\nPASS: {CHOSEN} has 0 false barge-ins at every delay for gain >= {GATE_GAIN_DB} dB")
return 0
if __name__ == "__main__":
sys.exit(main())
# synthetic or illustrative fixture, not recorded calls: invented per-turn STT text for echo_lab.py
turn_id,agent_last_utterance,stt_text,stt_started_during_agent_playback,fixture_truth
1,"Your appointment is booked for Tuesday at three.","your appointment is booked for tuesday at three",yes,echo
2,"Can I help with anything else today?","can i help with anything else",yes,echo
3,"Can I help with anything else today?","no that's all thanks",no,caller
4,"Tuesday at three, right?","tuesday at three right",no,caller
5,"Let me check the calendar for you.","wait I need Wednesday instead",yes,caller
Tested end to end with Python 3.12.5, it prints the output below and exits 0. It exits 1 on an aec+min-dur false barge-in at -12 dB or louder, and on each broken fixture: a maybe row, the header alone, turn 1 twice.
python3 -I echo_lab.py
All signals: synthetic or illustrative fixture, not recorded calls. 8 kHz mono, seed 7.
agent turns [(0.0, 4.5), (5.5, 9.5)], caller barge-ins [(1.6, 2.4), (6.6, 7.8)] (s); noise RMS 0.003; VAD frame RMS > 0.01
configs: none = energy VAD 0.1s; nlms = NLMS 256 taps, no delay estimate; nlms+delay = NLMS after cross-correlation bulk delay; warmup = 3.0s one-shot; min-dur = 0.5s gate; aec+X = nlms+delay output with that guard added
== False / missed barge-ins per condition (F/M; 2 real caller barge-ins per call) ==
delay gain est_delay | none nlms nlms+delay warmup min-dur aec+warmup aec+min-dur
20ms -30dB 42.0ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
20ms -20dB 19.0ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
20ms -12dB 19.0ms | 16/0 0/0 0/0 13/1 0/0 0/1 0/0
20ms -6dB 19.0ms | 8/1 2/0 3/0 6/1 7/1 0/1 0/0
60ms -30dB 66.0ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
60ms -20dB 59.0ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
60ms -12dB 59.0ms | 15/0 12/0 0/0 12/1 0/0 0/1 0/0
60ms -6dB 59.0ms | 7/1 9/1 3/0 5/1 7/1 0/1 0/0
120ms -30dB 118.2ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
120ms -20dB 119.0ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
120ms -12dB 119.0ms | 14/0 17/0 0/0 10/1 0/0 0/1 0/0
120ms -6dB 119.0ms | 7/1 9/1 3/0 5/1 5/0 0/1 0/0
250ms -30dB 248.0ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
250ms -20dB 249.0ms | 0/0 0/0 0/0 0/1 0/0 0/1 0/0
250ms -12dB 249.0ms | 15/0 17/0 0/0 12/1 0/0 0/1 0/0
250ms -6dB 249.0ms | 7/2 7/2 3/0 5/2 5/1 0/1 0/0
== NLMS filter length vs echo delay (d = 120 ms, gain -6 dB) ==
echo path ends at 126 ms, filter covers 32 ms: misalignment without delay estimate +0.1 dB
== Double talk: naive freeze vs none (same condition, reference shifted by the delay estimate) ==
freeze=False misalignment at 6.5 s -3.2 dB, at 8.4 s (after caller turn 2) +22.7 dB, false triggers after the caller stops 1
freeze=True misalignment at 6.5 s -16.5 dB, at 8.4 s (after caller turn 2) -16.8 dB, false triggers after the caller stops 0
== Self-transcription: STT text per turn vs the agent's last utterance ==
(synthetic or illustrative fixture, not recorded calls; threshold 0.80 is illustrative)
turn 1: ratio 1.00 text-says echo fixture-truth echo
turn 2: ratio 0.92 text-says echo fixture-truth echo
turn 3: ratio 0.00 text-says caller fixture-truth caller
turn 4: ratio 1.00 text-says echo fixture-truth caller <- text alone cannot resolve: started_during_playback=no points to caller
turn 5: ratio 0.00 text-says caller fixture-truth caller
turns the text match got wrong: 1 of 5
PASS: aec+min-dur has 0 false barge-ins at every delay for gain >= -12 dB
python3 -I echo_lab.py --stt stt_malformed.csv
python3 -I echo_lab.py --stt stt_empty.csv
python3 -I echo_lab.py --stt stt_duplicate.csv
FAIL (exit 1): STT fixture: malformed fixture row 3: ['2', 'Can I help?', 'can i help', 'maybe', 'echo']
FAIL (exit 1): STT fixture: no fixture rows after the header
FAIL (exit 1): STT fixture: duplicate turn_id 1 at fixture row 3
What the delay and gain sweep shows
At -30 and -20 dB no config false-triggers. At -12 dB the unguarded VAD fires 14 to 16 times at every delay and NLMS without a delay estimate fails from 60 ms on, while NLMS after the estimate holds 0 (3 at -6 dB).

Counts are open-loop triggers per call, so louder echo can trigger fewer. Delay estimates land within 1 ms at -20 dB and up, drifting at -30 dB (42.0, 66.0, 118.2, 248.0 ms). The lab has no room, codec or phone-path canceller, so confirm on the real call path.
Warmup alone fires 10 to 13 at -12 dB and, like aec+warmup, misses the caller inside the first 3.0 s in every row. min-dur alone clears -12 dB but not -6 dB. Only aec+min-dur is 0/0 in all 16 rows. F/M per synthetic call, 2 real caller barge-ins (synthetic or illustrative fixture, not recorded calls):
| Guard | 20 ms, -12 dB | 120 ms, -12 dB | 250 ms, -12 dB | 120 ms, -6 dB |
|---|---|---|---|---|
| none | 16/0 | 14/0 | 15/0 | 7/1 |
| nlms (no delay estimate) | 0/0 | 17/0 | 17/0 | 9/1 |
| nlms+delay | 0/0 | 0/0 | 0/0 | 3/0 |
| warmup 3.0 s | 13/1 | 10/1 | 12/1 | 5/1 |
| min-dur 0.5 s | 0/0 | 0/0 | 0/0 | 5/0 |
| aec+warmup | 0/1 | 0/1 | 0/1 | 0/1 |
| aec+min-dur | 0/0 | 0/0 | 0/0 | 0/0 |
Why a synthetic simulator never hears itself
A synthetic simulator sends clean audio, so the agent’s speech never returns unless injected. LiveKit disables the warmup in simulation because “a simulator publishes synthesized audio, so the agent’s speech never echoes back”. An echo test adds playback on purpose.
How to simulate a voice AI agent covers scenario simulation.
Debugging self-transcription from the per-turn trace
Self-transcription leaves a clear mark in a per-turn trace: the user turn’s STT text matches the agent’s previous utterance, and the agent reply that was playing is marked interrupted. Compare the text first, then check whether the user speech started while the agent was still playing before you call it echo and change the audio path.
Read the interruption count per call too, since echo can recur on every reply. The lab’s difflib word ratio (illustrative 0.80 threshold) printed 1.00 (echo) for turn 1, 0.92 (echo) for turn 2 and 0.00 (caller) for turns 3 and 5.
When the caller repeats the agent
In turn 4 the caller repeats “Tuesday at three, right?” to confirm: ratio 1.00, text says echo, truth is caller. Timing resolves it (“started_during_playback=no points to caller”); the lab prints “turns the text match got wrong: 1 of 5”. A rule needs timing plus text, and 0.80 is illustrative, never a production value.
Echo fixes ranked by where they sit in the audio path
Rank echo fixes by where they sit in the audio path. Cancel echo first on the client with a reference-based canceller, then mute the user while the agent speaks if barge-in can wait, then require minimum words or speech duration before an interrupt, and add STT-side agent-echo filtering where the vendor documents it.
- Client AEC. Keep WebRTC echoCancellation on; LiveKit’s page says “Leaving these WebRTC settings on is strongly recommended when you are not using enhanced noise cancellation (ai-coustics or Krisp).” Cost: only clients you ship.
- Half-duplex mute. Pipecat’s AlwaysUserMuteStrategy. Cost: no real barge-in.
- Minimum speech or words. LiveKit min_duration 0.5 s or Pipecat MinWordsUserTurnStartStrategy. Cost: slower real interrupts; in the lab it cleared -12 dB, not -6 dB. Turn-end timing belongs to endpointing and turn detection.
- STT-side filtering. Soniox STT v6 (November 3, 2026): “Soniox STT v6 introduces agent voice echo cancellation.” Pipecat’s Soniox STT service has enable_echo_cancellation (default False, agent_text_lead_ms 700). Cost: a TTS that reports word timestamps, such as SonioxTTSService.
Reading per-turn Pipecat spans in Future AGI with traceAI-pipecat
Future AGI receives the per-turn spans that Pipecat’s own tracing creates. With traceAI-pipecat mapping them, each stt span carries the transcript as output.value, each tts span carries the spoken text as input.value, and turn.was_interrupted sits in metadata, so you can put a user transcript next to the agent line it repeats.
Pipecat creates conversation, turn, stt, llm and tts spans. Per traceAI-pipecat setup, call register(..., transport=Transport.HTTP, set_global_tracer_provider=True), then enable_http_attribute_mapping(), with PipelineWorker(..., enable_tracing=True, enable_turn_tracking=True). The docs pin traceAI-pipecat==0.1.1 with pipecat-ai[tracing]==1.15.0.
Compare each stt output.value with the latest tts input.value and check turn.was_interrupted on that tts span’s turn; Pipecat also sets it True on a turn left open at conversation end, so skip the last turn. FI_HIDE_INPUTS and FI_HIDE_OUTPUTS do not remove native Pipecat content; the mapping lives in traceAI on GitHub.
Simulate call metrics report ai_interruption_count, user_interruption_count, avg_stop_time_after_interruption_ms and talk_ratio, and simulation personas carry voice traits such as background sound and interrupt sensitivity. Voice simulation runs on Future AGI Cloud (plans that include it) or an Enterprise deployment.
Booking the speakerphone caller without the echo loop
The speakerphone caller from the opening gets booked once the agent’s own sentence stops reaching speech-to-text as a caller turn. Reproduce the leak with the playback lab, read the trace for repeated text on interrupted turns, and fix it in the order the audio path runs: canceller, mute, minimum speech, then STT filtering.
Back in the car, the agent finishes, the caller says “thanks”, and the booking closes. Copy echo_lab.py, set DELAYS_MS and GAINS_DB to your calls’ delays and levels, and add the sweep to your voice AI evaluation infrastructure.
Frequently Asked Questions
What is voice agent echo?
What is AEC in audio?
How do I stop a voice agent from interrupting its own responses?
How does voice AI echo cancellation stop assistants from interrupting themselves?
Can a phone or SIP bridge send the agent's voice back into its input?
How to run IVR testing when your agent is the caller: send DTMF the far-end menu accepts, handle changed menus, timeouts and retries, and reach the right desk.
Speech emotion recognition gives a voice agent a model's guess about tone. Score the detector and the escalation rule apart, and pick audio you can license.
Five checks for a voice agent warm transfer: bridge, context, hold, unanswered lines and hangups, with pass rules, SIP mechanics, platform notes and code.