Articles

IVR Testing for Outbound Voice Agents: DTMF, Menus, and Retries

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.

· 14 min read
voice-ai-agents ivr-testing dtmf outbound-calls voice-agent-testing sip agent-simulation
An IVR testing maze where the prompt-reading route reaches the rescheduling desk and the cached replay ends at goodbye after the menu fingerprint changed.
Table of Contents

IVR testing for an outbound voice agent confirms that it, as the caller, can get past a phone menu someone else owns. It starts with a call like this one. Your agent dials Acme Clinic (illustrative fixture, simulation, not recorded calls) to move a patient’s appointment.

Last month it pressed 1 for appointments and 2 for rescheduling. This week the clinic put prescription refills on 1 and moved appointments to 2. Replaying its cached DTMF 12, the agent ends at the goodbye node instead of the rescheduling desk.

Someone else’s menu changed without notice, and the failure is a quiet wrong node with no error. Below are DTMF digit transport, the tone timing receivers expect, five platforms’ send paths, nine cases with pass criteria (timeouts and retries included) from a lab tested end to end, and a rerun on menu change.

TL;DR

  • IVR testing for an outbound voice agent checks whether your agent, as the caller, gets through another company’s phone menu to the right destination.
  • Digits travel as in-band tones, RFC 4733 telephone events (which obsoleted RFC 2833 in 2006) or vendor-specific SIP INFO; low-rate codecs can garble in-band tones.
  • RFC 4733 summarises ITU-T Q.24 receivers as expecting tones and pauses of at least 40 ms; our synthetic Goertzel sweep decoded every 40 ms cell, which says nothing about a real IVR.
  • Twilio, Vapi, Retell, LiveKit and the OpenAI Live API each send digits differently; a “sent” confirmation never proves the menu accepted the key.
  • Nine fixture cases each print PASS or FAIL against the node reached, and a menu fingerprint change reruns them.

Outbound IVR testing puts your agent on the caller side

Outbound IVR navigation means your agent is the caller and the menu belongs to someone else. You cannot change its prompts, its timeouts or the day it gets reordered, so the test has to prove the agent listens, presses the right keys at the right moment and lands on the destination it was sent to reach.

IVR testing in general checks a phone menu with keypad and speech inputs; here your agent sends them. This is not an outbound IVR campaign, where a dialer plays your menu to a recipient, nor inbound IVR replacement, which modernizing an IVR with AI voice agents covers.

Simulation versus IVR testing and tool picks sit in voice AI simulation tools for CX teams.

What OpenAI’s outbound SIP release changed

OpenAI’s API changelog entry dated Nov 2, 2026 reads: “Outbound SIP calling is now available to all organizations through the Live API. Connect GPT-Live to a phone number through your SIP provider.” More agents now press keys on calls they place, and no event says the menu accepted the key.

OpenAI’s SIP guide has three sideband events: transport.dtmf.received for a caller’s key, transport.dtmf.send to send a tone, and transport.dtmf.sent after the tone is sent to the trunk.

How DTMF digits travel from your agent to their menu

A DTMF digit leaves your agent’s stack in one of three forms: audible tones inside the voice stream, RFC 4733 telephone events carried in RTP beside the audio, or a SIP INFO message. Telephone events must be negotiated with your SIP peer at call setup, and a gateway can turn tones into events or events back into tones.

So log which form each call used: telephone events are offered in SDP (RFC 4733’s example: a=rtpmap:100 telephone-event/8000), in-band tones need no negotiation, and SIP INFO is a vendor setting.

On one stack, a LiveKit SIP issue on outbound DTMF modes, open since 2026-11-01, reports that in-band keypad input is unavailable there when the peer does not negotiate telephone-event.

In-band tones and low-rate codecs

RFC 4733 says separate payloads “are desirable since low-rate voice codecs cannot be guaranteed to reproduce these tone signals accurately enough for automatic recognition”, and that gateway detection “avoids having low bit-rate codecs like G.723.1 [20] render DTMF tones unintelligible”.

Telnyx’s DTMF settings page warns “Codecs such as G.729 or Opus can degrade or destroy the tones” and recommends RFC 2833 on G.711. RFC 4733 section 1.4: “The gateway or end system can change to a higher-bandwidth codec such as G.711 [19] when tone signals are to be conveyed.”

RFC 4733 telephone events and the RFC 2833 label

RFC 2833’s status page shows the May 2000 RFC obsoleted by RFC 4733 and RFC 4734 in December 2006. RFC 4733 (Proposed Standard, updated by RFC 4734 and RFC 5244) codes digits 0 to 9 as themselves, star 10, pound 11 and A to D 12 to 15.

RFC 4733 says the consuming device “is most commonly an IVR”. Telnyx still labels its setting RFC 2833 (read 2026-11-26), and Twilio’s SIP interface page says “Twilio supports RFC-2833 for sending and receiving DTMF.” Read the label as the same out-of-band mode, not the current standard.

SIP INFO and vendor-specific bodies

RFC 6086 (January 2011): “Companies have been using INFO messages in order to transport Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are proprietary and have not been standardized.” A harness records the INFO body each vendor documents and names none without that vendor’s page.

Vapi’s DTMF tool configuration documents one switch (read 2026-11-26): “On Vapi numbers and BYO SIP trunks, set sipInfoDtmfEnabled to true to send each key as a SIP INFO message instead of the default method”. Vapi says to use it only when the far end expects SIP INFO, with no fallback to audio tones.

DTMF testing against Q.23 tones and Q.24 timing

DTMF testing checks two things before any call goes out: the tone pairs your stack generates and the timing a receiver will accept. ITU-T Q.23 fixes eight frequencies in two groups, and RFC 4733 summarises ITU-T Q.24 receivers as expecting tones of at least 40 ms with pauses of at least 40 ms.

The right key in the wrong shape still fails, so the lab pairs a tone generator with a Goertzel decoder, neither a production receiver, to find where timing and noise break decoding. The standard-library ivr_lab.py was tested end to end with Python 3.12.5 (python3 -I ivr_lab.py, exit code 0).

The Q.23 keypad grid and Q.24 receive timing

ITU-T Q.23 (11/88) sets the low group at 697, 770, 852 and 941 Hz and the high group at 1209, 1336, 1477 and 1633 Hz, each within plus or minus 1.8% of nominal.

ITU-T Q.24 Annex A Table A-1 covers five administrations: a 40 ms minimum operate duration everywhere, a 30, 40 or 70 ms minimum pause and a 10 to 20 ms maximum signal interruption.

The ITU-T Q.23 Figure 1 DTMF keypad grid with rows at 697, 770, 852 and 941 Hz, columns at 1209, 1336, 1477 and 1633 Hz, and keys 1 2 3 A, 4 5 6 B, 7 8 9 C and star 0 pound D

RFC 4733 adds a rate of 8 to 10 digits per second. Other Table A-1 ranges: 20 to 25 ms non-operate maximum, 93 to 125 ms per digit signalling velocity, twist maximum 5 to 10 dB (AT&T +4 to -8 dB).

ivr_lab.py, signal layer:

#!/usr/bin/env python3
"""ivr_lab.py: DTMF signal layer plus an outbound IVR navigation harness (Python standard library only).

Every menu, prompt, timing, policy stub and printed metric here is an
illustrative fixture, simulation, not recorded calls. No call was placed.

Parts
  (a) DTMF generator at 8 kHz, frequency grid per ITU-T Q.23 Figure 1
  (b) Goertzel detector (illustrates detection; it is not a Q.24 receiver)
  (c) detector sweep over tone and gap {30, 40, 50, 70, 100} ms x {clean, 20 dB, 10 dB SNR}
  (d) IVR state-machine harness over invented "Acme Clinic" menu trees
  (e) in-band (Goertzel) vs out-of-band (RFC 4733 event tuples) round trip
  (f) fail-closed summary: exit 1 on any FAIL, a crashed case, an empty or duplicated case list,
      a required case not executed, no fixtures or a malformed fixture
  Platform snippets (Twilio, Vapi, Retell, LiveKit, OpenAI SIP) are printed, not executed.
"""
import copy
import hashlib
import json
import math
import random
import re
import struct
import sys
import wave
from collections import deque
from pathlib import Path

LABEL = "illustrative fixture, simulation, not recorded calls"
FS = 8000

# ---------------------------------------------------------------- (a) generator
# ITU-T Q.23 Figure 1: rows 697/770/852/941 Hz, columns 1209/1336/1477/1633 Hz.
ROWS = [697, 770, 852, 941]
COLS = [1209, 1336, 1477, 1633]
KEYPAD = ["123A", "456B", "789C", "*0#D"]
FREQS = {KEYPAD[r][c]: (ROWS[r], COLS[c]) for r in range(4) for c in range(4)}


def generate(digits, tone_ms=100, gap_ms=100, amp=0.25, twist_db=0.0, snr_db=None,
             lead_samples=400, seed=0):
    """Return float samples for a digit string.

    twist_db: high-group level relative to low-group level.
    snr_db: SNR = (power of the two-tone burst) / (white Gaussian noise power), noise added everywhere.
    """
    rng = random.Random(seed)
    a_lo, a_hi = amp, amp * 10 ** (twist_db / 20)
    n_tone, n_gap = int(FS * tone_ms / 1000), int(FS * gap_ms / 1000)
    out = [0.0] * lead_samples
    for d in digits:
        f1, f2 = FREQS[d]
        w1, w2 = 2 * math.pi * f1 / FS, 2 * math.pi * f2 / FS
        out += [a_lo * math.sin(w1 * n) + a_hi * math.sin(w2 * n) for n in range(n_tone)]
        out += [0.0] * n_gap
    out += [0.0] * 400
    if snr_db is not None:
        p_sig = a_lo ** 2 / 2 + a_hi ** 2 / 2
        sigma = math.sqrt(p_sig / 10 ** (snr_db / 10))
        out = [x + rng.gauss(0, sigma) for x in out]
    return out


def write_wav(path, samples):
    with wave.open(str(path), "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(FS)
        w.writeframes(b"".join(struct.pack("<h", max(-32767, min(32767, int(x * 32767)))) for x in samples))


def read_wav(path):
    with wave.open(str(path), "rb") as w:
        raw = w.readframes(w.getnframes())
    return [v / 32767 for v in struct.unpack("<%dh" % (len(raw) // 2), raw)]


# ---------------------------------------------------------------- (b) Goertzel detector
# Design choices (not Q.24 values): window 205 samples = 25.6 ms, hop 80 samples = 10 ms.
WINDOW, HOP = 205, 80
ENERGY_FLOOR = 1e-3        # mean frame power floor
TONE_SHARE_MIN = 0.6       # (row power + col power) / frame energy
BIN_RATIO_MIN = 4.0        # strongest bin vs runner-up in its group (6 dB)
TWIST_MAX_DB = 8.0         # |high - low| level difference allowed
DEBOUNCE_HOPS = 2          # consecutive no-tone hops needed before the same key can register again
ALL_F = ROWS + COLS
COEF = [2 * math.cos(2 * math.pi * f / FS) for f in ALL_F]


def goertzel_powers(frame):
    out = []
    for c in COEF:
        s1 = s2 = 0.0
        for x in frame:
            s1, s2 = x + c * s1 - s2, s1
        out.append((s1 * s1 + s2 * s2 - c * s1 * s2) * 2 / len(frame))
    return out


def classify_frame(frame):
    energy = sum(x * x for x in frame)
    if energy / len(frame) < ENERGY_FLOOR:
        return None
    p = goertzel_powers(frame)
    rows, cols = p[:4], p[4:]
    r = max(range(4), key=rows.__getitem__)
    c = max(range(4), key=cols.__getitem__)
    r2 = max(v for i, v in enumerate(rows) if i != r)
    c2 = max(v for i, v in enumerate(cols) if i != c)
    if (rows[r] + cols[c]) / energy < TONE_SHARE_MIN:
        return None
    if rows[r] < BIN_RATIO_MIN * r2 or cols[c] < BIN_RATIO_MIN * c2:
        return None
    if abs(10 * math.log10(cols[c] / rows[r])) > TWIST_MAX_DB:
        return None
    return KEYPAD[r][c]


def detect(samples):
    """Two consecutive hops must agree to register a key; DEBOUNCE_HOPS silent hops re-arm."""
    out, prev, armed, quiet = [], None, True, 0
    for start in range(0, len(samples) - WINDOW + 1, HOP):
        cand = classify_frame(samples[start:start + WINDOW])
        if cand is None:
            quiet += 1
            prev = None
            if quiet >= DEBOUNCE_HOPS:
                armed = True
            continue
        quiet = 0
        if armed and cand == prev:
            out.append(cand)
            armed = False
        prev = cand
    return "".join(out)


# ---------------------------------------------------------------- (c) sweep
SWEEP_MS = [30, 40, 50, 70, 100]
SWEEP_SNR = [None, 20, 10]
SWEEP_DIGITS = "1123*#"     # repeated key on purpose: a merged gap shows up as a missing "1"
OFFSETS = [0, 27, 53]       # lead-in offsets against the 80-sample hop grid
SEEDS = [1, 2]


def sweep():
    print(f"\n== (c) DETECTOR SWEEP [{LABEL}] ==")
    print(f"digits={SWEEP_DIGITS!r}, amp 0.25 per tone, twist 0 dB; trials per cell: clean = "
          f"{len(OFFSETS)} hop offsets (no noise, so no seed applies), noisy = {len(OFFSETS)} hop offsets x "
          f"{len(SEEDS)} noise seeds = {len(OFFSETS) * len(SEEDS)}")
    print("SNR = two-tone burst power / white Gaussian noise power. Cell = exact decodes/trials "
          "(m = merged or missed, s = split or extra, w = wrong key).")
    rows = []
    for snr in SWEEP_SNR:
        name = "clean" if snr is None else f"{snr} dB SNR"
        print(f"\n  {name}: rows tone ms, columns gap ms")
        print("  tone\\gap " + "".join(f"{g:>14}" for g in SWEEP_MS))
        for tone in SWEEP_MS:
            line = f"  {tone:>8} "
            for gap in SWEEP_MS:
                ok = m = s = w = 0
                seeds = SEEDS if snr is not None else SEEDS[:1]  # clean signal ignores the seed
                for off in OFFSETS:
                    for seed in seeds:
                        got = detect(generate(SWEEP_DIGITS, tone, gap, snr_db=snr,
                                              lead_samples=400 + off, seed=seed * 1000 + tone + gap))
                        if got == SWEEP_DIGITS:
                            ok += 1
                        elif len(got) < len(SWEEP_DIGITS):
                            m += 1
                        elif len(got) > len(SWEEP_DIGITS):
                            s += 1
                        else:
                            w += 1
                n = len(OFFSETS) * len(seeds)
                line += f"{f'{ok}/{n} m{m} s{s} w{w}':>14}"
                rows.append((name, tone, gap, ok, n))
            print(line)
    ok40 = [r for r in rows if r[1] == 40 and r[2] == 40]
    print("\n  40 ms tone / 40 ms pause cells (RFC 4733's summary of Q.24 Table A-1 minimums): "
          + ", ".join(f"{r[0]} {r[3]}/{r[4]}" for r in ok40))
    print("  Reported as measured; no cell is asserted to pass.")
    return rows


def dropout_check():
    print(f"\n== (b) DEBOUNCE vs DROPOUT, one press of '5', 100 ms [{LABEL}] ==")
    for drop_ms in [0, 10, 20, 30]:
        for snr in [None, 10]:
            sig = generate("5", 100, 100, snr_db=None)
            mid = 400 + 400 - int(FS * drop_ms / 2000)
            for i in range(mid, mid + int(FS * drop_ms / 1000)):
                sig[i] = 0.0
            if snr is not None:
                rng = random.Random(7)
                sigma = math.sqrt((0.25 ** 2) / 10 ** (snr / 10))
                sig = [x + rng.gauss(0, sigma) for x in sig]
            got = detect(sig)
            print(f"  dropout {drop_ms:>2} ms, {'clean' if snr is None else '10 dB SNR':>9}: decoded {got!r} "
                  f"({'one press' if got == '5' else 'NOT one press'})")
    print(f"  Trade-off: a press only re-arms after DEBOUNCE_HOPS={DEBOUNCE_HOPS} no-tone hops. A longer debounce "
          "bridges longer breaks inside one press but merges repeated keys separated by short gaps (see the sweep); "
          "the rows above are what this setting measured.")


def detector_self_checks():
    checks = []
    checks.append(("clean 100/100 decodes 0-9 * # A-D", detect(generate("0123456789*#ABCD")) == "0123456789*#ABCD"))
    checks.append(("twist +3 dB decodes", detect(generate("147*", twist_db=3)) == "147*"))
    checks.append(("twist -3 dB decodes", detect(generate("369#", twist_db=-3)) == "369#"))
    checks.append(("silence decodes to nothing", detect([0.0] * 4000) == ""))
    checks.append(("single 1000 Hz tone rejected",
                   detect([0.25 * math.sin(2 * math.pi * 1000 * n / FS) for n in range(4000)]) == ""))
    return checks


# ---------------------------------------------------------------- (e) out-of-band, RFC 4733
# RFC 4733 Section 3.2 Table 3: 0-9 -> 0-9, * -> 10, # -> 11, A-D -> 12-15.
EVENT = {**{str(i): i for i in range(10)}, "*": 10, "#": 11, "A": 12, "B": 13, "C": 14, "D": 15}
EVENT_INV = {v: k for k, v in EVENT.items()}


def to_rfc4733(digits, tone_ms=100):
    """(event code, end bit, duration in 8000 Hz timestamp units) per key; 40 ms = 320 units."""
    return [(EVENT[d], 1, tone_ms * FS // 1000) for d in digits]


def from_rfc4733(events):
    return "".join(EVENT_INV[e] for e, end, _dur in events if end == 1)

The run printed:

ivr_lab.py  [illustrative fixture, simulation, not recorded calls]
Detector design choices: window 205 samples (25.6 ms), hop 80 samples (10 ms) at 8000 Hz; tone share >= 0.6, bin ratio >= 4.0, |twist| <= 8.0 dB, debounce 2 hops. These illustrate detection; they are not ITU-T Q.24 values and the detector is not a Q.24 receiver.
== (b) DETECTOR SELF-CHECKS [illustrative fixture, simulation, not recorded calls] ==
  PASS  clean 100/100 decodes 0-9 * # A-D
  PASS  twist +3 dB decodes
  PASS  twist -3 dB decodes
  PASS  silence decodes to nothing
  PASS  single 1000 Hz tone rejected
== (a) WAV ROUND TRIP [illustrative fixture, simulation, not recorded calls] ==
  wrote acme_dtmf_fixture.wav (16-bit, 8000 Hz, mono), decoded back '1123*#'

== (e) IN-BAND vs OUT-OF-BAND [illustrative fixture, simulation, not recorded calls] ==
  digits '1123*#0'
  in-band, Goertzel decode: '1123*#0'
  out-of-band RFC 4733 (event code, end bit, duration in 8000 Hz units): [(1, 1, 800), (1, 1, 800), (2, 1, 800), (3, 1, 800), (10, 1, 800), (11, 1, 800), (0, 1, 800)]
  out-of-band decode: '1123*#0'; 40 ms = 320 units

What the detector sweep measured

The sweep sends '1123*#' (0.25 amplitude per tone, 0 dB twist) over tones and gaps of 30 to 100 ms, with 3 clean and 6 noisy trials per cell. Clean scored 3/3 and 20 dB SNR 6/6 in all 25 cells.

At 10 dB only the 30 ms tone with a 50 or 70 ms gap slipped, to 5/6, one merged or missed trial each, so every 40/40 cell decoded every trial. The detector accepted 30 ms tones, below Table A-1’s 40 ms minimum: a toy decoder’s limits, never proof that 40/40 is safe on a real IVR.

== (c) DETECTOR SWEEP [illustrative fixture, simulation, not recorded calls] ==
digits='1123*#', amp 0.25 per tone, twist 0 dB; trials per cell: clean = 3 hop offsets (no noise, so no seed applies), noisy = 3 hop offsets x 2 noise seeds = 6
SNR = two-tone burst power / white Gaussian noise power. Cell = exact decodes/trials (m = merged or missed, s = split or extra, w = wrong key).

  clean: rows tone ms, columns gap ms
  tone\gap             30            40            50            70           100
        30   3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0
        40   3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0
        50   3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0
        70   3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0
       100   3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0  3/3 m0 s0 w0

  20 dB SNR: rows tone ms, columns gap ms
  tone\gap             30            40            50            70           100
        30   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0
        40   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0
        50   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0
        70   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0
       100   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0

  10 dB SNR: rows tone ms, columns gap ms
  tone\gap             30            40            50            70           100
        30   6/6 m0 s0 w0  6/6 m0 s0 w0  5/6 m1 s0 w0  5/6 m1 s0 w0  6/6 m0 s0 w0
        40   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0
        50   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0
        70   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0
       100   6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0  6/6 m0 s0 w0

  40 ms tone / 40 ms pause cells (RFC 4733's summary of Q.24 Table A-1 minimums): clean 3/3, 20 dB SNR 6/6, 10 dB SNR 6/6
  Reported as measured; no cell is asserted to pass.

One press that decodes as two digits

Q.24 section 2.5 says: “To minimize erroneous double-registration of a signal if reception is interrupted by a short break in transmission or by a noise pulse, interruptions shorter than a specified maximum value must not be recognized.” RFC 4733 says playout breaks in event-to-tone receivers can create “the appearance of extra digits”.

In one 100 ms press of 5, a 0 ms dropout decoded '5' clean and noisy, 10 ms decoded '5' clean but '55' at 10 dB, and 20 or 30 ms gave '55' in both. A longer debounce bridges longer breaks but merges repeated keys.

== (b) DEBOUNCE vs DROPOUT, one press of '5', 100 ms [illustrative fixture, simulation, not recorded calls] ==
  dropout  0 ms,     clean: decoded '5' (one press)
  dropout  0 ms, 10 dB SNR: decoded '5' (one press)
  dropout 10 ms,     clean: decoded '5' (one press)
  dropout 10 ms, 10 dB SNR: decoded '55' (NOT one press)
  dropout 20 ms,     clean: decoded '55' (NOT one press)
  dropout 20 ms, 10 dB SNR: decoded '55' (NOT one press)
  dropout 30 ms,     clean: decoded '55' (NOT one press)
  dropout 30 ms, 10 dB SNR: decoded '55' (NOT one press)
  Trade-off: a press only re-arms after DEBOUNCE_HOPS=2 no-tone hops. A longer debounce bridges longer breaks inside one press but merges repeated keys separated by short gaps (see the sweep); the rows above are what this setting measured.

Sending digits on Twilio, Vapi, Retell, LiveKit and the OpenAI Live API

Each platform sends digits its own way. Twilio plays them from TwiML or a call parameter, Vapi and Retell give the agent a keypad tool, LiveKit publishes RFC 4733 events from the participant, and the OpenAI Live API takes one key per sideband event. Every row below comes from the vendor’s own page, read 2026-11-26.

Platform and surfaceHow the agent sends a keyPause controlTrap to test
Twilio’s Play verbdigits attribute, 0 to 9, A to D, star, poundw = 0.5 s, W = 1 sCannot play digits inside Gather
Twilio’s Call resource SendDigitsString dialed after connect, maximum 32 digitsw and WMachineDetection is ignored when SendDigits is set; URL-encode pound
Vapi’s DTMF toolKeys as one string, such as 1234#w and W on Twilio and Telnyx onlyThe result “doesn’t confirm that the other side received them”
Retell’s Press Digit toolTool in single and multi-prompt agents, node in conversation flowsPause Detection Delay, default 1000 ms, 0 to 5000 msMatch the delay to the menu’s own pauses
LiveKit’s DTMF page: publish_dtmf, send_dtmf_eventsRFC 4733 telephone-event/8000 from the local participantsend_dtmf_events waits 0.3 s between keysIn Python, leave ivr_detection off with answering machine detection
OpenAI Live API SIPtransport.dtmf.send on the sideband WebSocket, one key per eventSend separate eventstransport.dtmf.sent means sent to the SIP trunk; judge acceptance by the next prompt

ivr_lab.py, platform snippets: unranked, dated, copied except the Vapi type config, not executed.

# ---------------------------------------------------------------- platform snippets (not executed)
NOT_EXEC = "not executed: needs a telephony account, phone numbers and a live IVR"
PLATFORM_SNIPPETS = [
    ("Twilio TwiML <Play digits>", "https://www.twilio.com/docs/voice/twiml/play", "2026-11-26",
     '<Response>\n    <Play digits="wwww3"></Play>\n</Response>',
     "w = 0.5 s pause, W = 1 s pause; cannot play digits inside <Gather>."),
    ("Twilio Call resource SendDigits", "https://www.twilio.com/docs/voice/api/call-resource", "2026-11-26",
     "(no code sample on the page; parameter text) \"The string of keys to dial after connecting to the number, "
     "with a maximum length of 32 digits.\"",
     "w = half-second, W = one-second pause; URL-encode '#'. MachineDetection: \"If send_digits is provided, "
     "this parameter is ignored.\""),
    ("Vapi dtmf tool", "https://docs.vapi.ai/tools/dtmf/configure", "2026-11-26",
     '{\n  "type": "dtmf"\n}', "Vapi DTMF tool page: the result \"doesn't confirm that the other side received them.\""),
    ("Vapi IVR navigation", "https://docs.vapi.ai/ivr-navigation", "2026-11-26",
     "1st try  ->  123#           (fast)\n2nd try  ->  1w2w3#         (medium; 0.5s gaps)\n"
     "3rd try  ->  1W2W3#         (slow; 1s gaps)\n\ndtmf(keys=w7w6w4)",
     "Progressive retries apply to Twilio and Telnyx; arrows rewritten as '->'. Pause characters do not work on "
     "Vapi numbers."),
    ("Retell Press Digit", "https://docs.retellai.com/build/single-multi-prompt/press-digit", "2026-11-26",
     "Press digit 1 to reach the support department.",
     "Prompt text from the page; Pause Detection Delay default 1000 ms, range 0 to 5000 ms (dashboard setting)."),
    ("LiveKit publish_dtmf (Python)", "https://docs.livekit.io/telephony/features/dtmf/", "2026-11-26",
     "# publishes 123# in DTMF\nawait local_participant.publish_dtmf(code=1, digit='1')\n"
     "await local_participant.publish_dtmf(code=2, digit='2')\n"
     "await local_participant.publish_dtmf(code=3, digit='3')\n"
     "await local_participant.publish_dtmf(code=11, digit='#')",
     "Node.js uses localParticipant.publishDtmf(code, digit)."),
    ("LiveKit ivr_detection", "https://docs.livekit.io/telephony/features/dtmf/", "2026-11-26",
     "session = AgentSession(\n  ivr_detection=True,\n  # ... stt, llm, vad, turn_detection, etc.\n)", ""),
    ("OpenAI Live API SIP transport.dtmf.send",
     "https://developers.openai.com/api/reference/resources/live/sideband-websocket", "2026-11-26",
     '{\n  "type": "transport.dtmf.send",\n  "event_id": "evt_dtmf_001",\n  "event": "#"\n}',
     "One key per event (\"Send separate events for multiple keypresses\"); success emits transport.dtmf.sent; "
     "a caller key arrives as transport.dtmf.received. Guide: "
     "https://developers.openai.com/api/docs/guides/voice-sip?api=live"),
]

Traps that look like a clean call

On Twilio’s Call resource, machineDetection says “If send_digits is provided, this parameter is ignored.”, so digits on connect mean no answering machine result. LiveKit answering machine detection sends DTMF in its machine-ivr stage: “The built-in DTMF tool send_dtmf_events is available only in the machine-ivr stage”.

Twilio Media Streams says: “DTMF is supported with bidirectional Media Streams only in the inbound direction, from Twilio toward your media server. Sending DTMF outbound from your media server toward Twilio is not supported.” Our voice API comparison for AI agents records the same limit.

Vapi’s IVR navigation guide starts at 0.5 s pauses, lengthened only while keys are missed: “If keys fail, retry with increased spacing; if tones still fail, speak the option out loud as a fallback.” Per where Vapi keypad tones work, web and WebSocket calls carry none.

Nine IVR testing cases with a pass criterion each

IVR testing for an outbound agent needs a case for every way someone else’s menu can go wrong: a changed menu, a timeout, an invalid key, an early press, a loop, a person answering, voicemail and a dead end. Each case below has a pass criterion, judged on the node the agent reached.

The runner is a state machine over fixture menu trees. A policy stub keyword-matches each prompt, your agent replaces its decide() step, and two must-fail controls (a cached replay and an eager presser) prove three cases catch their failure. The suite was tested end to end.

A FAIL, crash, empty or duplicated case list, missing required case, or missing or invalid fixture sets exit code 1. The run printed suite completeness: ok and exit code 0, and a demo on a broken copy printed that copy would exit 1. All cases: illustrative fixture, simulation, not recorded calls.

CaseFixture triggerPass criterionWhat the run printed
Happy pathv1 menuReach resched with the minimum digits”final=resched digits sent=2 min=2”
Menu changedv2: refills on 1, appointments on 2Reader reaches resched; replay misses”prompt-reading final=resched (2 digits, min 2); cached replay ‘12’ final=goodbye (control must miss)“
Timeout and repeatPrompt garbled once, then alwaysRecover once; give up after max retries, claiming nothing”timeouts=1 final=resched t=31.85 s; never understood: timeouts=3 (max_retries 2) final=goodbye claim=None”
Wrong digit and invalid entryFirst key received as 9Re-press after the repeated prompt”invalid entries=1, re-pressed after the repeated prompt, final=resched”
Premature pressOptions heard mid-promptNo key before prompt end”prompt-reading: early presses=0 final=resched; eager control: early presses discarded=2 final=main”
Loop back to root”Anything else” loops to mainStop after N=2 cycles”root heard 3 times, digits sent=2, outcome=agent_stopped_loop”
Human answers mid-treeA person answers by 19.5 sZero digits after the answer”digits after that=0, agent outcome=human”
Voicemail or dead endVoicemail and closed treesName the terminal state, press nothing”claim=voicemail digits=0; closed -> claim=dead_end digits=0”
Destination reachedSecond key lostJudge the node reached, not digits sent”digits sent=3 (min 2), received=‘12’, final node=resched”

ivr_lab.py, fixtures and cases (part d):

# ---------------------------------------------------------------- (d) IVR fixtures
# Invented clinic, no real company, no phone numbers. Every tree is an illustrative fixture.
GOODBYE = {"prompt": "We did not receive a valid response. Goodbye.", "terminal": "dead_end"}
TREE_V1 = {
    "name": "acme_clinic_v1", "root": "main",
    "nodes": {
        "main": {"prompt": "Thank you for calling Acme Clinic. For appointments, press 1. For lab results, press 2. "
                           "For billing, press 3. For anything else, press 0.",
                 "options": {"1": "appts", "2": "lab", "3": "billing", "0": "front"},
                 "timeout_s": 5, "max_retries": 2, "on_invalid": "repeat"},
        "appts": {"prompt": "To book a new appointment, press 1. To reschedule or cancel an appointment, press 2. "
                            "To return to the main menu, press star.",
                  "options": {"1": "book", "2": "resched", "*": "main"},
                  "timeout_s": 5, "max_retries": 2, "on_invalid": "repeat"},
        "billing": {"prompt": "For questions about a statement, press 1. To return to the main menu, press star.",
                    "options": {"1": "front", "*": "main"},
                    "timeout_s": 5, "max_retries": 2, "on_invalid": "repeat"},
        "book": {"prompt": "You have reached the booking desk. Please hold.", "terminal": "destination"},
        "resched": {"prompt": "You have reached the rescheduling desk. Please hold.", "terminal": "destination"},
        "lab": {"prompt": "You have reached the lab results line. Please hold.", "terminal": "destination"},
        "front": {"prompt": "Front desk, this is Priya speaking, how can I help you?", "terminal": "human"},
        "goodbye": GOODBYE,
    },
}
# v2: the same clinic after a menu change (digits reordered, a refill option added).
TREE_V2 = copy.deepcopy(TREE_V1)
TREE_V2["name"] = "acme_clinic_v2"
TREE_V2["nodes"]["main"] = {
    "prompt": "Thank you for calling Acme Clinic. Our menu has changed. For prescription refills, press 1. "
              "For appointments, press 2. For lab results, press 3. For billing, press 4. For anything else, press 0.",
    "options": {"1": "refill", "2": "appts", "3": "lab", "4": "billing", "0": "front"},
    "timeout_s": 5, "max_retries": 2, "on_invalid": "repeat"}
TREE_V2["nodes"]["refill"] = {"prompt": "To request a refill, press 1. To return to the main menu, press star.",
                              "options": {"1": "front", "*": "main"},
                              "timeout_s": 5, "max_retries": 2, "on_invalid": "repeat"}
# Loop: the goal is not offered and "anything else" drops back to the root.
TREE_LOOP = {
    "name": "acme_clinic_loop", "root": "main",
    "nodes": {
        "main": {"prompt": "Acme Clinic billing line. For a statement copy, press 1. For anything else, press 0.",
                 "options": {"1": "stmt", "0": "other"}, "timeout_s": 5, "max_retries": 2, "on_invalid": "repeat"},
        "other": {"prompt": "That request is handled elsewhere. Returning to the main menu.", "next": "main"},
        "stmt": {"prompt": "You have reached the statement desk. Please hold.", "terminal": "destination"},
        "goodbye": GOODBYE,
    },
}
TREE_VOICEMAIL = {"name": "acme_clinic_voicemail", "root": "vm", "nodes": {
    "vm": {"prompt": "You have reached Acme Clinic. Please leave a message after the tone.", "terminal": "voicemail"},
    "goodbye": GOODBYE}}
TREE_CLOSED = {"name": "acme_clinic_closed", "root": "closed", "nodes": {
    "closed": {"prompt": "Acme Clinic is closed for the holiday. Goodbye.", "terminal": "dead_end"},
    "goodbye": GOODBYE}}
FIXTURES = [TREE_V1, TREE_V2, TREE_LOOP, TREE_VOICEMAIL, TREE_CLOSED]
VALID_KEYS = set(FREQS)
TERMINALS = {"destination", "human", "voicemail", "dead_end"}


def validate_tree(tree):
    errs = []
    nodes = tree.get("nodes", {})
    if tree.get("root") not in nodes:
        errs.append("root missing")
    if "goodbye" not in nodes:
        errs.append("no goodbye node for exhausted retries")
    for nid, n in nodes.items():
        if not isinstance(n.get("prompt"), str) or not n["prompt"]:
            errs.append(f"{nid}: empty prompt")
        if "terminal" in n:
            if n["terminal"] not in TERMINALS:
                errs.append(f"{nid}: unknown terminal {n['terminal']!r}")
        elif "next" in n:
            if n["next"] not in nodes:
                errs.append(f"{nid}: next -> missing {n['next']!r}")
        else:
            for k, tgt in n.get("options", {}).items():
                if not isinstance(k, str) or k not in VALID_KEYS:
                    errs.append(f"{nid}: key {k!r} is not a DTMF key string")
                if tgt not in nodes:
                    errs.append(f"{nid}: option {k} -> missing {tgt!r}")
            if not n.get("options"):
                errs.append(f"{nid}: menu node without options")
            if not (isinstance(n.get("timeout_s"), (int, float)) and n["timeout_s"] > 0):
                errs.append(f"{nid}: timeout_s must be > 0")
            if not (isinstance(n.get("max_retries"), int) and n["max_retries"] >= 0):
                errs.append(f"{nid}: max_retries must be an int >= 0")
            if n.get("on_invalid") != "repeat":
                errs.append(f"{nid}: on_invalid must be 'repeat'")
    return errs


def fingerprint(tree):
    return hashlib.sha256(json.dumps(tree["nodes"], sort_keys=True).encode()).hexdigest()[:12]


def min_digits(tree, goal):
    """BFS over menu options: fewest keys from the root to the goal node."""
    nodes, seen, q = tree["nodes"], {tree["root"]}, deque([(tree["root"], 0)])
    while q:
        nid, d = q.popleft()
        if nid == goal:
            return d
        n = nodes[nid]
        nxt = [(n["next"], d)] if "next" in n else [(t, d + 1) for t in n.get("options", {}).values()]
        for t, nd in nxt:
            if t not in seen:
                seen.add(t)
                q.append((t, nd))
    return None


# ---------------------------------------------------------------- (d) simulated clock and IVR
WORD_S = 0.35          # seconds per spoken word (illustrative)
THINK_S = 0.30         # agent decision delay after a prompt ends (illustrative)
KEY_S = 0.20           # 100 ms tone + 100 ms gap per key (illustrative)
IVR_LATENCY_S = 0.50   # IVR reaction time after a key (illustrative)


def speak_s(text):
    return len(text.split()) * WORD_S


OPTION_RE = re.compile(r"(?:for|to) ([^.]+?), press (\d|star|pound)", re.I)
WORD_KEY = {"star": "*", "pound": "#"}


def parse_options(text):
    return [(m.group(1).lower(), WORD_KEY.get(m.group(2).lower(), m.group(2)), m.end()) for m in OPTION_RE.finditer(text)]


class PromptReadingPolicy:
    """Deterministic agent stub: keyword match on the prompt text. A real agent replaces decide().
    Illustrative fixture, simulation, not recorded calls."""
    name = "prompt-reading stub"
    FALLBACK = ["anything else", "representative", "operator"]

    def __init__(self, goal_keywords, destination_phrase, loop_limit=2):
        self.goal, self.dest, self.loop_limit = goal_keywords, destination_phrase, loop_limit
        self.heard = {}

    def classify_end(self, text):
        t = text.lower()
        if self.dest in t:
            return "reached"
        if "speaking" in t or "how can i help" in t:
            return "human"
        if "leave a message" in t:
            return "voicemail"
        if "goodbye" in t and not parse_options(text):
            return "dead_end"
        return None

    def decide(self, text, t_start, t_end):
        if not text:
            return ("wait",)
        end = self.classify_end(text)
        if end:
            return ("stop", end)
        if not parse_options(text):
            return ("listen",)
        key = text.replace("That is not a valid option. ", "")
        self.heard[key] = self.heard.get(key, 0) + 1
        if self.heard[key] >= self.loop_limit + 1:
            return ("stop", "loop")
        opts = parse_options(text)
        scored = [(sum(k in label for k in self.goal), digit) for label, digit, _ in opts]
        best = max(scored)
        if best[0] > 0:
            return ("press", best[1], t_end + THINK_S)
        for label, digit, _ in opts:
            if any(f in label for f in self.FALLBACK):
                return ("press", digit, t_end + THINK_S)
        return ("wait",)


class EagerPolicy(PromptReadingPolicy):
    """Control stub: presses as soon as the matching option is spoken, before the prompt ends."""
    name = "eager control stub"

    def decide(self, text, t_start, t_end):
        act = super().decide(text, t_start, t_end)
        if act[0] != "press":
            return act
        for _label, digit, pos in parse_options(text):
            if digit == act[1]:
                return ("press", digit, t_start + speak_s(text[:pos]))
        return act


class CachedReplayPolicy:
    """Control stub: replays a recorded digit path without reading the prompt."""
    name = "cached-path replay control stub"

    def __init__(self, digits, destination_phrase):
        self.digits, self.dest = list(digits), destination_phrase

    def decide(self, text, t_start, t_end):
        if self.dest in text.lower():
            return ("stop", "reached")
        if text and self.digits:
            return ("press", self.digits.pop(0), t_end + THINK_S)
        return ("wait",)


def run_call(tree, policy, faults=()):
    """Drive one simulated call; return a result dict with a per-call log.

    A menu key at t_end + timeout_s is accepted; a later decision is cancelled,
    not carried into a repeat. The existing timeout/retry loop then runs.
    Logs follow prompt/action append order, not timestamp order for early keys.
    """
    nodes, cur, t, retries, prefix = tree["nodes"], tree["root"], 0.0, 0, ""
    log, sent, received, timeouts, invalids, discarded = [], [], [], 0, 0, 0
    presses_seen, outcome, claim = 0, None, None
    first_prompt = True
    for _step in range(60):
        node = nodes[cur]
        text = prefix + node["prompt"]
        t_start, t_end = t, t + speak_s(text)
        heard = "" if ("garble_first" in faults and first_prompt) or "garble_all" in faults else text
        first_prompt = False
        log.append((round(t_start, 2), "prompt", cur, heard if heard else "<unintelligible>"))
        log.append((round(t_end, 2), "prompt_end", cur, f"retries={retries}"))
        prefix = ""
        act = policy.decide(heard, t_start, t_end)
        if "terminal" in node or "next" in node:
            if act[0] == "press":
                sent.append((round(act[2], 2), act[1], cur))
                log.append((round(act[2], 2), "digit_sent_after_terminal", cur, act[1]))
            if "next" in node:
                cur, t = node["next"], t_end
                continue
            outcome = node["terminal"]
            claim = act[1] if act[0] == "stop" else None
            break
        if act[0] == "stop":
            outcome, claim = f"agent_stopped_{act[1]}", act[1]
            break
        got = None
        if act[0] == "press":
            digit, t_press = act[1], act[2]
            if t_press > t_end + node["timeout_s"]:
                log.append((round(t_end + node["timeout_s"], 2), "keypress_missed_deadline", cur, digit))
                t = t_end  # Cancel this decision; use the existing timeout/retry path below.
            else:
                sent.append((round(t_press, 2), digit, cur))
                log.append((round(t_press, 2), "digit_sent", cur, digit))
                presses_seen += 1
                if t_press < t_end:
                    discarded += 1
                    log.append((round(t_press, 2), "ivr_discarded_early_key", cur, digit))
                elif "drop_second" in faults and presses_seen == 2:
                    log.append((round(t_press, 2), "transport_dropped_key", cur, digit))
                else:
                    got = "9" if ("flip_first" in faults and presses_seen == 1) else digit
                    received.append(got)
                t = max(t_press, t_end) + KEY_S
        if got is None:
            timeouts += 1
            retries += 1
            t = max(t, t_end) + node["timeout_s"]
            log.append((round(t, 2), "timeout", cur, f"retry {retries}/{node['max_retries']}"))
        elif got in node["options"]:
            cur, retries = node["options"][got], 0
            t += IVR_LATENCY_S
            continue
        else:
            invalids += 1
            retries += 1
            prefix = "That is not a valid option. "
            log.append((round(t, 2), "invalid_entry", cur, got))
            t += IVR_LATENCY_S
        if retries > node["max_retries"]:
            cur, retries = "goodbye", 0
    else:
        outcome = "harness_step_limit"
    return {"final": cur, "outcome": outcome, "claim": claim, "sent": sent, "received": received,
            "timeouts": timeouts, "invalids": invalids, "discarded": discarded, "t_end": round(t, 2),
            "log": log, "policy": policy.name}


# ---------------------------------------------------------------- (d) cases
REQUIRED_CASES = ["happy_path", "menu_changed", "timeout_and_repeat", "wrong_digit_invalid_entry",
                  "premature_press", "loop_to_root", "human_answers_mid_tree", "voicemail_or_dead_end",
                  "destination_reached"]
CASE_REGISTRY = list(REQUIRED_CASES)


def suite_errors(registry, executed, fixtures):
    """Fail-closed completeness check: empty or duplicated registry, a required case not executed, no fixtures."""
    errs = []
    if not registry:
        errs.append("case registry is empty")
    dups = sorted({n for n in registry if registry.count(n) > 1})
    if dups:
        errs.append(f"duplicate cases {dups}")
    missing = [n for n in REQUIRED_CASES if n not in executed]
    if missing:
        errs.append(f"required cases not executed {missing}")
    unknown = sorted(set(executed) - set(REQUIRED_CASES))
    if unknown:
        errs.append(f"unregistered cases executed {unknown}")
    if not fixtures:
        errs.append("no fixtures")
    return errs
RESCHED = dict(goal_keywords=["reschedul", "appointment"], destination_phrase="rescheduling desk")


def no_early(r, tree):
    """Bind each digit to its current prompt occurrence in append order, not timestamp order."""
    prompt_end = None
    for at, event, nid, _detail in r["log"]:
        if event == "prompt":
            prompt_end = None
        elif event == "prompt_end":
            prompt_end = (nid, at)
        elif event in {"digit_sent", "digit_sent_after_terminal"}:
            if prompt_end is None or prompt_end[0] != nid or at < prompt_end[1]:
                return False
    return True


def case_happy_path(ctx):
    r = run_call(TREE_V1, PromptReadingPolicy(**RESCHED))
    mn = min_digits(TREE_V1, "resched")
    ctx["happy"] = r
    ok = r["final"] == "resched" and r["claim"] == "reached" and len(r["sent"]) == mn and no_early(r, TREE_V1)
    return ok, f"final={r['final']} digits sent={len(r['sent'])} min={mn} time to goal={r['t_end']} s (simulated)"


def case_menu_changed(ctx):
    cached = "".join(d for _t, d, _n in ctx["happy"]["sent"])
    r_read = run_call(TREE_V2, PromptReadingPolicy(**RESCHED))
    r_rep = run_call(TREE_V2, CachedReplayPolicy(cached, "rescheduling desk"))
    mn = min_digits(TREE_V2, "resched")
    ok = r_read["final"] == "resched" and len(r_read["sent"]) == mn and r_rep["final"] != "resched"
    return ok, (f"v1 fingerprint {fingerprint(TREE_V1)} -> v2 {fingerprint(TREE_V2)}; prompt-reading final="
                f"{r_read['final']} ({len(r_read['sent'])} digits, min {mn}); cached replay {cached!r} final="
                f"{r_rep['final']} (control must miss)")


def case_timeout_and_repeat(ctx):
    r = run_call(TREE_V1, PromptReadingPolicy(**RESCHED), faults=("garble_first",))
    r_x = run_call(TREE_V1, PromptReadingPolicy(**RESCHED), faults=("garble_all",))
    mr = TREE_V1["nodes"]["main"]["max_retries"]
    ok = (r["final"] == "resched" and r["timeouts"] == 1 and len(r["sent"]) == min_digits(TREE_V1, "resched")
          and r_x["final"] == "goodbye" and r_x["timeouts"] == mr + 1 and r_x["claim"] != "reached")
    return ok, (f"first prompt unintelligible: timeouts={r['timeouts']} final={r['final']} t={r['t_end']} s; "
                f"never understood: timeouts={r_x['timeouts']} (max_retries {mr}) final={r_x['final']} "
                f"claim={r_x['claim']}")


def case_wrong_digit(ctx):
    r = run_call(TREE_V1, PromptReadingPolicy(**RESCHED), faults=("flip_first",))
    ok = r["final"] == "resched" and r["invalids"] == 1 and r["received"][0] == "9" and no_early(r, TREE_V1)
    return ok, (f"first key received as '9' (not an option): invalid entries={r['invalids']}, "
                f"re-pressed after the repeated prompt, final={r['final']}, digits sent={len(r['sent'])}")


def case_premature_press(ctx):
    r_ok = run_call(TREE_V1, PromptReadingPolicy(**RESCHED))
    r_bad = run_call(TREE_V1, EagerPolicy(**RESCHED))
    ok = no_early(r_ok, TREE_V1) and r_ok["discarded"] == 0 and r_bad["discarded"] >= 1 and r_bad["final"] != "resched"
    return ok, (f"prompt-reading: early presses={r_ok['discarded']} final={r_ok['final']}; eager control: "
                f"early presses discarded={r_bad['discarded']} final={r_bad['final']}")


def case_loop(ctx):
    n = 2
    r = run_call(TREE_LOOP, PromptReadingPolicy(**RESCHED, loop_limit=n))
    root_heard = sum(1 for e in r["log"] if e[1] == "prompt" and e[2] == "main")
    ok = r["claim"] == "loop" and root_heard == n + 1 and len(r["sent"]) == n
    return ok, f"N={n}: root heard {root_heard} times, digits sent={len(r['sent'])}, outcome={r['outcome']}"


def case_human(ctx):
    # Goal "statement" leads billing -> 1 -> front desk where a person answers.
    pol = PromptReadingPolicy(goal_keywords=["billing", "statement"], destination_phrase="statement desk")
    r = run_call(TREE_V1, pol)
    t_human = next(e[0] for e in r["log"] if e[1] == "prompt_end" and e[2] == "front")
    after = [s for s in r["sent"] if s[0] >= t_human]
    r_rep = run_call(TREE_V1, CachedReplayPolicy("3111", "statement desk"))
    rep_after = [e for e in r_rep["log"] if e[1] == "digit_sent_after_terminal"]
    ok = r["final"] == "front" and r["claim"] == "human" and not after and rep_after
    return ok, (f"person answered by t={t_human} s: digits after that={len(after)}, agent outcome={r['claim']}; "
                f"replay control kept pressing: {len(rep_after)} digit(s) into the person's ear")


def case_voicemail_dead_end(ctx):
    r_vm = run_call(TREE_VOICEMAIL, PromptReadingPolicy(**RESCHED))
    r_cl = run_call(TREE_CLOSED, PromptReadingPolicy(**RESCHED))
    ok = (r_vm["claim"] == "voicemail" and r_cl["claim"] == "dead_end"
          and not r_vm["sent"] and not r_cl["sent"])
    return ok, f"voicemail -> claim={r_vm['claim']} digits={len(r_vm['sent'])}; closed -> claim={r_cl['claim']} digits={len(r_cl['sent'])}"


def case_destination(ctx):
    r = run_call(TREE_V1, PromptReadingPolicy(**RESCHED), faults=("drop_second",))
    mn = min_digits(TREE_V1, "resched")
    ok = r["final"] == "resched" and r["claim"] == "reached" and len(r["sent"]) > mn
    return ok, (f"second key sent but never received: digits sent={len(r['sent'])} (min {mn}), "
                f"received={''.join(r['received'])!r}, final node={r['final']}; the oracle is the node reached, "
                "not the digits sent")


def timing_self_checks():
    """Offline negative controls for menu deadlines and an early invalid-entry retry."""
    class DeadlinePolicy(PromptReadingPolicy):
        def __init__(self, offset, first_only=False):
            super().__init__(**RESCHED, loop_limit=10)
            self.offset, self.first_only, self.presses = offset, first_only, 0

        def decide(self, text, t_start, t_end):
            act = super().decide(text, t_start, t_end)
            if act[0] == "press":
                self.presses += 1
                if not self.first_only or self.presses == 1:
                    return ("press", act[1], t_end + 5 + self.offset)
            return act

    checks = []
    for label, offset in [("just inside", -0.01), ("at", 0.0)]:
        r = run_call(TREE_V1, DeadlinePolicy(offset))
        checks.append((f"{label} deadline accepted", r["final"] == "resched" and r["timeouts"] == 0
                       and len(r["sent"]) == 2 and no_early(r, TREE_V1)))
    r = run_call(TREE_V1, DeadlinePolicy(0.01, first_only=True))
    checks.append(("after deadline cancelled, retry recovers", r["final"] == "resched" and r["timeouts"] == 1
                   and len(r["sent"]) == 2
                   and sum(e[1] == "keypress_missed_deadline" for e in r["log"]) == 1))
    r = run_call(TREE_V1, DeadlinePolicy(0.01))
    checks.append(("no timely answer exhausts retries", r["final"] == "goodbye" and r["claim"] != "reached"
                   and r["timeouts"] == TREE_V1["nodes"]["main"]["max_retries"] + 1
                   and not r["sent"] and not r["received"]))

    class EarlyRepeatPolicy(PromptReadingPolicy):
        def __init__(self):
            super().__init__(**RESCHED, loop_limit=10)
            self.presses = 0

        def decide(self, text, t_start, t_end):
            act = super().decide(text, t_start, t_end)
            if act[0] == "press":
                self.presses += 1
                if self.presses == 2:
                    return ("press", act[1], t_start + 0.1)
            return act

    r = run_call(TREE_V1, EarlyRepeatPolicy(), faults=("flip_first",))
    checks.append(("early invalid-entry retry rejected", r["final"] == "resched" and r["invalids"] == 1
                   and r["discarded"] == 1 and not no_early(r, TREE_V1)))
    return checks


CASES = {"happy_path": case_happy_path, "menu_changed": case_menu_changed,
         "timeout_and_repeat": case_timeout_and_repeat, "wrong_digit_invalid_entry": case_wrong_digit,
         "premature_press": case_premature_press, "loop_to_root": case_loop,
         "human_answers_mid_tree": case_human, "voicemail_or_dead_end": case_voicemail_dead_end,
         "destination_reached": case_destination}

ivr_lab.py, main() (part f):

# ---------------------------------------------------------------- main
def main():
    results = []          # (name, PASS/FAIL, detail)
    print(f"ivr_lab.py  [{LABEL}]")
    print(f"Detector design choices: window {WINDOW} samples ({WINDOW / FS * 1000:.1f} ms), hop {HOP} samples "
          f"({HOP / FS * 1000:.0f} ms) at {FS} Hz; tone share >= {TONE_SHARE_MIN}, bin ratio >= {BIN_RATIO_MIN}, "
          f"|twist| <= {TWIST_MAX_DB} dB, debounce {DEBOUNCE_HOPS} hops. These illustrate detection; they are not "
          "ITU-T Q.24 values and the detector is not a Q.24 receiver.")

    print(f"\n== FIXTURE VALIDATION [{LABEL}] ==")
    for tr in FIXTURES:
        errs = validate_tree(tr)
        print(f"  {tr['name']}: fingerprint {fingerprint(tr)} -> {'ok' if not errs else errs}")
        results.append((f"fixture {tr['name']}", "PASS" if not errs else "FAIL", "; ".join(errs) or "valid"))
    bad = copy.deepcopy(TREE_V1)
    bad["nodes"]["main"]["options"][1] = "nowhere"     # int key and a dangling target
    bad["nodes"]["appts"]["timeout_s"] = 0
    bad_errs = validate_tree(bad)
    print(f"  validator demo on a deliberately malformed copy (not part of the suite): rejected with {bad_errs}")
    results.append(("validator rejects malformed copy", "PASS" if len(bad_errs) >= 3 else "FAIL", f"{len(bad_errs)} errors"))

    print(f"\n== (b) DETECTOR SELF-CHECKS [{LABEL}] ==")
    for name, ok in detector_self_checks():
        print(f"  {'PASS' if ok else 'FAIL'}  {name}")
        results.append((f"detector: {name}", "PASS" if ok else "FAIL", ""))
    dropout_check()
    sweep()

    print(f"\n== (a) WAV ROUND TRIP [{LABEL}] ==")
    wav = Path(__file__).with_name("acme_dtmf_fixture.wav")
    write_wav(wav, generate("1123*#"))
    back = detect(read_wav(wav))
    print(f"  wrote {wav.name} (16-bit, {FS} Hz, mono), decoded back {back!r}")
    results.append(("WAV write/read decode", "PASS" if back == "1123*#" else "FAIL", back))

    print(f"\n== (e) IN-BAND vs OUT-OF-BAND [{LABEL}] ==")
    s = "1123*#0"
    inband = detect(generate(s, 100, 100))
    events = to_rfc4733(s)
    oob = from_rfc4733(events)
    print(f"  digits {s!r}")
    print(f"  in-band, Goertzel decode: {inband!r}")
    print(f"  out-of-band RFC 4733 (event code, end bit, duration in 8000 Hz units): {events}")
    print(f"  out-of-band decode: {oob!r}; 40 ms = {to_rfc4733('5', 40)[0][2]} units")
    ok = inband == oob == s and to_rfc4733("5", 40)[0][2] == 320
    results.append(("in-band == out-of-band", "PASS" if ok else "FAIL", f"{inband!r} vs {oob!r}"))

    print(f"\n== (d) IVR HARNESS [{LABEL}] ==")
    print(f"  Simulated clock: {WORD_S} s per word, think {THINK_S} s, {KEY_S} s per key, IVR latency {IVR_LATENCY_S} s.")
    ctx, executed = {}, set()
    for name in CASE_REGISTRY:
        try:
            ok, detail = CASES[name](ctx)
            executed.add(name)
            results.append((f"case {name}", "PASS" if ok else "FAIL", detail))
            print(f"  {'PASS' if ok else 'FAIL'}  {name}: {detail}")
        except Exception as e:      # a crashed case is a FAIL, never a skip
            results.append((f"case {name}", "FAIL", f"crashed: {e!r}"))
            print(f"  FAIL  {name}: crashed: {e!r}")
    errs = suite_errors(CASE_REGISTRY, executed, FIXTURES)
    print(f"  suite completeness: {'ok' if not errs else errs}")
    results.append(("suite completeness", "PASS" if not errs else "FAIL", "; ".join(errs) or "9 of 9 required cases"))
    broken_reg = [n for n in CASE_REGISTRY if n != "destination_reached"] + ["happy_path"]
    demo_errs = suite_errors(broken_reg, executed - {"destination_reached"}, [])
    print(f"  completeness demo on a deliberately broken copy (not part of the suite): rejected with {demo_errs}; "
          f"that copy would exit 1")
    results.append(("completeness check rejects broken copy", "PASS" if len(demo_errs) >= 3 else "FAIL",
                    f"{len(demo_errs)} errors"))

    print(f"\n  Timing regression self-checks [{LABEL}]:")
    for name, ok in timing_self_checks():
        print(f"    {'PASS' if ok else 'FAIL'}  {name}")
        results.append((f"timing: {name}", "PASS" if ok else "FAIL", ""))

    print(f"\n  Per-call log, happy path [{LABEL}] (t s, event, node, detail):")
    for e in ctx.get("happy", {}).get("log", []):
        print(f"    {e}")

    print(f"\n  Regression rerun on menu change [{LABEL}]:")
    changed = fingerprint(TREE_V1) != fingerprint(TREE_V2)
    print(f"    stored baseline {TREE_V1['name']} {fingerprint(TREE_V1)}; live menu now {fingerprint(TREE_V2)} "
          f"-> {'changed: rerun the navigation cases against the new menu' if changed else 'unchanged'}")
    if changed:
        for faults in [(), ("garble_first",), ("flip_first",), ("drop_second",)]:
            rr = run_call(TREE_V2, PromptReadingPolicy(**RESCHED), faults=faults)
            ok = rr["final"] == "resched" and rr["claim"] == "reached"
            label = "+".join(faults) or "no fault"
            results.append((f"regression v2 {label}", "PASS" if ok else "FAIL", rr["final"]))
            print(f"    {'PASS' if ok else 'FAIL'}  v2 {label}: final={rr['final']} digits sent={len(rr['sent'])} "
                  f"(min {min_digits(TREE_V2, 'resched')}) time to goal={rr['t_end']} s (simulated)")

    print(f"\n== PLATFORM SNIPPETS ({NOT_EXEC}) ==")
    for title, url, date, code, note in PLATFORM_SNIPPETS:
        print(f"\n  [{title}] {url} (copied {date}) {NOT_EXEC}")
        for line in code.splitlines():
            print(f"    {line}")
        if note:
            print(f"    note: {note}")

    print(f"\n== (f) SUMMARY (fail-closed) [{LABEL}] ==")
    r = ctx.get("happy")
    if r:
        print(f"  happy path: digits sent {len(r['sent'])} vs minimum {min_digits(TREE_V1, 'resched')}, "
              f"time to goal {r['t_end']} s on the simulated clock")
    counts = {}
    for _n, st, _d in results:
        counts[st] = counts.get(st, 0) + 1
    print(f"  {counts}; platform snippets: {len(PLATFORM_SNIPPETS)} not executed by design ({NOT_EXEC})")
    failed = [x for x in results if x[1] != "PASS"]
    for n, st, d in failed:
        print(f"  {st}: {n} {d}")
    code = 1 if failed else 0
    print(f"  exit code {code}")
    return code


if __name__ == "__main__":
    sys.exit(main())

Join the four blocks as shown, two blank lines apart, for a runnable file. It printed:

== (d) IVR HARNESS [illustrative fixture, simulation, not recorded calls] ==
  Simulated clock: 0.35 s per word, think 0.3 s, 0.2 s per key, IVR latency 0.5 s.
  PASS  happy_path: final=resched digits sent=2 min=2 time to goal=18.45 s (simulated)
  PASS  menu_changed: v1 fingerprint fb4da4120c9e -> v2 2c84f533aef4; prompt-reading final=resched (2 digits, min 2); cached replay '12' final=goodbye (control must miss)
  PASS  timeout_and_repeat: first prompt unintelligible: timeouts=1 final=resched t=31.85 s; never understood: timeouts=3 (max_retries 2) final=goodbye claim=None
  PASS  wrong_digit_invalid_entry: first key received as '9' (not an option): invalid entries=1, re-pressed after the repeated prompt, final=resched, digits sent=3
  PASS  premature_press: prompt-reading: early presses=0 final=resched; eager control: early presses discarded=2 final=main
  PASS  loop_to_root: N=2: root heard 3 times, digits sent=2, outcome=agent_stopped_loop
  PASS  human_answers_mid_tree: person answered by t=19.5 s: digits after that=0, agent outcome=human; replay control kept pressing: 1 digit(s) into the person's ear
  PASS  voicemail_or_dead_end: voicemail -> claim=voicemail digits=0; closed -> claim=dead_end digits=0
  PASS  destination_reached: second key sent but never received: digits sent=3 (min 2), received='12', final node=resched; the oracle is the node reached, not the digits sent
  suite completeness: ok
  completeness demo on a deliberately broken copy (not part of the suite): rejected with ["duplicate cases ['happy_path']", "required cases not executed ['destination_reached']", 'no fixtures']; that copy would exit 1

  Timing regression self-checks [illustrative fixture, simulation, not recorded calls]:
    PASS  just inside deadline accepted
    PASS  at deadline accepted
    PASS  after deadline cancelled, retry recovers
    PASS  no timely answer exhausts retries
    PASS  early invalid-entry retry rejected
== (f) SUMMARY (fail-closed) [illustrative fixture, simulation, not recorded calls] ==
  happy path: digits sent 2 vs minimum 2, time to goal 18.45 s on the simulated clock
  {'PASS': 33}; platform snippets: 8 not executed by design (not executed: needs a telephony account, phone numbers and a live IVR)
  exit code 0

The Acme Clinic fixture and the policy stub

The five invented trees carry no real company or phone number, and digits stay strings because a Pipecat issue on YAML digit strings showed YAML turning values like 010 into other key sequences.

The stub waits for each prompt to end, the reverse of inbound barge-in: the fixture discards early keys, some real menus accept them, and the agent has not heard every option yet. Vapi’s guide agrees: “Wait for all options to be spoken before sending the first DTMF sequence”.

== FIXTURE VALIDATION [illustrative fixture, simulation, not recorded calls] ==
  acme_clinic_v1: fingerprint fb4da4120c9e -> ok
  acme_clinic_v2: fingerprint 2c84f533aef4 -> ok
  acme_clinic_loop: fingerprint 1a8979278327 -> ok
  acme_clinic_voicemail: fingerprint 1025291330a5 -> ok
  acme_clinic_closed: fingerprint a7bc4f4e630b -> ok
  validator demo on a deliberately malformed copy (not part of the suite): rejected with ['main: key 1 is not a DTMF key string', "main: option 1 -> missing 'nowhere'", 'appts: timeout_s must be > 0']

Human, voicemail and dead-end exits

When a person answers mid-tree, the agent stops pressing: 0 digits after the 19.5 s answer, while the replay control pressed 1 digit into the person’s ear. Voicemail and a closed line are terminal states the agent must name, not press through.

The hand to a human after navigation belongs to warm transfer testing for voice agents, and voicemail rules and compliance to lead qualification with AI voice callers.

A LiveKit issue on a disabled IVR loop detector, closed 2026-10-11, found that detector silently disabled, so the loop case asserts the stop itself.

A menu fingerprint that triggers the rerun

A menu you do not own changes without a release note, so store a fingerprint of every menu your agent navigates and rerun the navigation cases when the live fingerprint differs. In our fixture, the v1 to v2 change flipped the fingerprint, and all four reruns on v2 reached the rescheduling desk.

The lab keeps 12 hex characters of a SHA-256 over the fixture nodes, so any prompt, option, timeout or retry change flips it. On a real menu, hash a key-to-label option map parsed from what the agent heard, never raw speech-to-text.

The first call that hears a changed prompt raises the flag, and an unvisited branch stays unseen until a call reaches it. Rebuild the fixture from that transcript (the lab’s v2 tree stands in), rerun before the next batch, and keep must-pass cases.

IVR testing rerun on the Acme Clinic fixture, where the v1 to v2 menu change moves the fingerprint from fb4da4120c9e to 2c84f533aef4, the cached replay of 12 ends at goodbye and the prompt-reading agent presses 2 then 2 to reach the rescheduling desk

  Regression rerun on menu change [illustrative fixture, simulation, not recorded calls]:
    stored baseline acme_clinic_v1 fb4da4120c9e; live menu now 2c84f533aef4 -> changed: rerun the navigation cases against the new menu
    PASS  v2 no fault: final=resched digits sent=2 (min 2) time to goal=21.6 s (simulated)
    PASS  v2 garble_first: final=resched digits sent=2 (min 2) time to goal=38.15 s (simulated)
    PASS  v2 flip_first: final=resched digits sent=3 (min 2) time to goal=36.25 s (simulated)
    PASS  v2 drop_second: final=resched digits sent=3 (min 2) time to goal=35.15 s (simulated)

The per-call log a failed navigation needs

Log digits sent with timestamps and call leg, the prompt heard per node, the node reached, retries, timeouts, early presses and the outcome claim. The happy path below (illustrative fixture, simulation, not recorded calls) sent 2 digits against a minimum of 2 and reached the desk at 18.45 s simulated.

The leg matters: in a LiveKit issue on DTMF sent to the wrong leg, it happened inside a transfer task.

  Per-call log, happy path [illustrative fixture, simulation, not recorded calls] (t s, event, node, detail):
    (0.0, 'prompt', 'main', 'Thank you for calling Acme Clinic. For appointments, press 1. For lab results, press 2. For billing, press 3. For anything else, press 0.')
    (8.4, 'prompt_end', 'main', 'retries=0')
    (8.7, 'digit_sent', 'main', '1')
    (9.4, 'prompt', 'appts', 'To book a new appointment, press 1. To reschedule or cancel an appointment, press 2. To return to the main menu, press star.')
    (17.45, 'prompt_end', 'appts', 'retries=0')
    (17.75, 'digit_sent', 'appts', '2')
    (18.45, 'prompt', 'resched', 'You have reached the rescheduling desk. Please hold.')
    (21.25, 'prompt_end', 'resched', 'retries=0')

Outbound call scenarios in Future AGI Simulate

Future AGI Simulate can run your outbound agent’s calls as scenarios. In Phone mode, with the Inbound Calls toggle off, your agent places the call and Simulate waits for it. Each call is scored by the evals you attach, and pass/fail evals give a per-call verdict.

Simulate scenario flows use Conversation, End call and Transfer call nodes plus global nodes. Flows come from a workflow graph, dataset, script or SOP, one conversation per row, and cover the person reached after the menu and the Transfer hand-off.

With the Inbound Calls setting on, the simulated caller rings your agent; off, your agent places the call; with the Others platform it stays on. Each call gets an overall_score (CSAT 1 to 10), and customer_agent_task_completion returns Passed or Failed.

For a Vapi agent, tool call evaluation, once switched on, scores each call’s tool calls.

On a LiveKit agent set up with traceAI for LiveKit, a function tool call lands as a TOOL span with its name and arguments, created by LiveKit and mapped by traceAI.

Future AGI Cloud (plans that include it) or an Enterprise deployment hosts voice simulation runs, and the repository is Future AGI on GitHub.

Getting the clinic call to the rescheduling desk

The clinic call from the opening reaches the rescheduling desk once the agent reads the new prompt instead of replaying last month’s keys. Fingerprint the menu, rerun the nine cases when it changes, send digits in a form your trunk and the far end both support, and judge every call by the node it reached.

On v2 the prompt-reading agent presses 2, then 2, and hears “You have reached the rescheduling desk. Please hold.” Run ivr_lab.py with one fixture tree per number your agent calls and your agent’s decision step in place of decide(), then keep these cases on your platform’s send path.

Frequently Asked Questions

What is IVR testing?

IVR testing checks a phone menu with keypad and speech inputs, and for an outbound voice agent it asks whether your agent can press through another company's menu. You test the digits it sends, changed menus, timeouts, retries, whether it reaches the right destination and whether it stops when a person answers.

What are IVR testing tools?

IVR testing tools for an outbound agent need a DTMF generator, a tone decoder, fixture menu trees and a runner that grades each call by the node reached. A standard-library lab can cover all four, and your own agent then replaces the policy stub so it faces the same cases before any real call.

What is DTMF and how is it used in telecom?

DTMF, dual-tone multi-frequency signalling, turns each keypad press into two tones played together, one from a low frequency group and one from a high group. ITU-T Q.23 sets the low group at 697, 770, 852 and 941 Hz and the high group at 1209, 1336, 1477 and 1633 Hz, and IVRs read each pair as a key.

How do you test DTMF detection without a phone line?

Generate the tones in software, decode them with a Goertzel detector, and sweep tone length, pause length and noise before any call goes out. In our synthetic lab, the 40 ms tone and 40 ms pause cell decoded every trial: 3 of 3 clean, 6 of 6 at 20 dB SNR and 6 of 6 at 10 dB SNR.

Is RFC 2833 still the standard for DTMF?

No, RFC 4733 obsoleted RFC 2833 in December 2006, and RFC 4733 now defines how DTMF digits travel as RTP telephone events beside the call audio. Telnyx, for one, still labels its DTMF setting RFC 2833, so treat that label as the same out-of-band telephone-event mode.
Related Articles
View all