Articles

Speech Emotion Recognition for Voice Agents: Routing and Escalation Tests

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.

· 20 min read
speech-emotion-recognition voice-ai-agents voice-agent-testing call-escalation agent-simulation ai-agent-evaluation classifier-evaluation
A balance scale weighing the detector's annoyance score of 0.62 against the escalation rule's 0.7 threshold, so the call ends with no human.
Table of Contents

A caller is rescheduling a delivery for the third time and answers in short, clipped turns: “Okay. Thursday then.” The call is an illustrative fixture, not a recorded call, and its numbers are not measured customer results. Transcript sentiment reads the words as neutral, while the team’s vocal model scores annoyance at 0.62 on two consecutive turns.

Speech emotion recognition (SER) infers an emotion label from vocal cues; that 0.62 is its output. The escalation rule wants 0.7 on two consecutive turns (K=2), so the call ends with no human. In QA a reviewer annotates both turns as annoyance, and nobody can say whether the model, its confidence or the rule failed.

This guide scores the detector, then the rule, and attributes every escalation error to one of them. Routing here means the rule that sends a call to a human; the same oracle run and per-call 2x2 score any other route keyed on the vocal label.

TL;DR

  • Speech emotion recognition outputs a model-inferred label or score from vocal cues such as pitch, loudness and rate of speech; transcript sentiment reads the words, and neither one is the caller’s internal state.
  • Accuracy falls when the training and test corpora differ: EmoBox reports cross-corpus accuracy from 15.03% to 66.91% on balanced four-class tests where a uniform guess scores 25%.
  • RAVDESS and TESS are non-commercial, IEMOCAP’s license is for internal research only, MSP-Podcast’s academic agreement covers a research project, and CREMA-D is under ODbL 1.0; an Apache-2.0 model card says nothing about its training data.
  • Score the detector per class (precision, recall, F1, macro-F1, confidence bins), then score the escalation rule on annotated labels and on predictions as two separate runs.
  • A per-call 2x2 splits errors into policy-only, detector-induced and detector-masked. A labels-only run then splits the detector-induced and detector-masked cells by cause: predicted labels that alone flip the oracle’s call decision, against predicted labels that agree with the oracle and are overruled only by the threshold, so a threshold is never filed as a model error (all lab numbers are an illustrative fixture, not measured customer results).

What speech emotion recognition outputs and what it does not know

Speech emotion recognition outputs a model-inferred label or score for a stretch of audio, built from vocal cues such as pitch, loudness and the rate of speech. Transcript sentiment reads the words instead. Neither one tells you how the caller feels, so treat the vocal label as an inference to test.

A categorical model returns a label with a confidence; a dimensional one returns valence and arousal scores per turn or window. The GeMAPS feature set lists the inputs: pitch as log F0 on a semitone scale, loudness, and rate parameters such as loudness-peak rate and pseudo syllable rate, chosen for “their potential to index affective physiological changes in voice production”.

Eyben and colleagues published the Geneva Minimalistic Acoustic Parameter Set in IEEE Transactions on Affective Computing in 2016.

Per-turn sentiment trends in production are covered in voice agent conversation monitoring.

Article 5(1)(f) of Regulation (EU) 2024/1689 bans inferring emotions of people in the workplace and in education institutions, except for medical or safety reasons. A caller on a customer line is a different setting, yet emotion recognition systems still appear in Annex III, and Article 50(3) obliges deployers to inform the people exposed.

The official text is Regulation (EU) 2024/1689, and the dates sit in the EU AI Act timeline and the Digital Omnibus.

Vocal cues versus transcript sentiment

Transcript sentiment is lexical: it scores the words after speech-to-text. Speech emotion recognition is acoustic: it scores how those words were said. “Okay. Thursday then.” reads as neutral text whatever the delivery, because the words carry no complaint, so only the voice can carry the clipped tone.

Both signals are inferences, and they can disagree about the same turn. Log them as two columns, one per signal, each with its own model version and confidence, and never merge them into one “emotion” field, because a merged field hides which signal fired the rule.

Annotated labels, predicted labels and what neither one knows

Two terms are easy to blur here. An annotated label is what a human reviewer assigned after listening to a turn, following a written rubric. A predicted label is model-inferred, the detector’s output for that turn. Neither one is the caller’s internal state, so nothing below says how any caller felt.

Even benchmark labels are perception votes. CREMA-D labels its clips by crowd majority: 2,443 raters took part, 95% of clips have more than 7 ratings, and the audio-only majority label is the VoiceVote. A clip labelled sad means most raters heard sadness, a different claim from the actor feeling it.

Why speech emotion recognition accuracy drops on real calls

Speech emotion recognition accuracy drops when a model meets speakers, recording conditions or speaking styles it never trained on. EmoBox measured cross-corpus accuracy from 15.03% to 66.91% on balanced four-class tests, where a uniform guess scores 25%. EmoBox’s own dataset table marks 26 of its 32 corpora as acted speech.

A lab accuracy number and a call accuracy number measure different things. The first comes from audio like the training data, the second from your callers on your phone line, answering your agent’s prompts. Three gaps sit between them: acted versus natural speech, a new corpus, and valence that leans on the words.

Acted speech against natural speech

RAVDESS, SAVEE, TESS and CREMA-D record actors performing set sentences or words; CREMA-D’s 91 actors read 12 sentences. EmoBox’s Table 1 marks 26 of 32 corpora “Act”, IEMOCAP included, and the other six come from TV, media, podcast and talk-show speech. Its Table 2 labels IEMOCAP elicitation and MELD spontaneous.

Natural speech is also less balanced. The MSP-Podcast page, a natural-speech corpus, says “Most of the segments in a regular podcasts are neutral”. Our lab fixture leans neutral too, with 252 of 380 annotated turns, but that mix is our stated assumption, not a measured queue.

What the EmoBox cross-corpus results show

EmoBox (Ma et al., INTERSPEECH 2024) trains on one corpus and evaluates on another across IEMOCAP, MELD, RAVDESS and SAVEE. Each test set holds 240 clips, 60 each of angry, happy, neutral and sad, so a uniform guess scores 25%. That 25% is our arithmetic for four balanced classes, not the paper’s wording.

The cross-corpus tables are in the EmoBox paper.

Table 5 runs from 15.03%, HuBERT large trained on RAVDESS and scored on IEMOCAP, to 66.91%, Whisper large v3 trained on SAVEE and scored on RAVDESS, acted speech on both sides. Seventeen of the 120 values fall below 25%. A published accuracy says little about your line, so score the detector on your own labelled calls.

Valence, words and individual speakers

Wagner et al. (IEEE TPAMI 2023) explain the valence gains: “Finally, we are the first to show that their extraordinary success on valence is based on implicit linguistic information learnt during fine-tuning of the transformer layers, which explains why they perform on-par with recent multimodal approaches that explicitly utilise textual information.”

Their paper, “Dawn of the Transformer Era in Speech Emotion Recognition: Closing the Valence Gap” (DOI 10.1109/TPAMI.2023.3263585), is also a preprint on arXiv.

They also report that transformer models held up better than a CNN baseline under small perturbations and were fair across biological sex groups, but not toward individual speakers. A “vocal” valence score can carry the words, and per-speaker error needs its own slice, so add a speaker_id column, which our fixture lacks, when you label calls.

Speech emotion recognition datasets and licenses for commercial teams

A speech emotion recognition dataset is only useful to a product team if its license allows commercial use. RAVDESS and TESS are non-commercial, IEMOCAP needs a release form and license, and MSP-Podcast lists an academic license. CREMA-D is released under ODbL 1.0, which allows commercial use with share-alike terms.

Licensing decides the shortlist before accuracy does. Each license below was read on the dataset’s own page, and terms change, so read the current page before you download anything and take every open question to your own counsel.

DatasetSpeech typeSize and labelsLicense or access termsCommercial use as stated
CREMA-DActed, 91 actors reading 12 sentences7,442 clips; anger, disgust, fear, happy, neutral, sad; crowd-ratedODbL 1.0, contents under DbCL 1.0Allowed, share-alike on derived databases you publicly use
RAVDESSActed speech and song1,440 speech clips used by the ehcalabres card; eight emotionsCC BY-NC-SA 4.0 (Zenodo)Non-commercial; the page says commercial licenses can be purchased
TESSActed, two actresses2,800 stimuli; 200 target words; seven emotionsCC BY-NC-ND 4.0 (University of Toronto host)Non-commercial
IEMOCAPElicited dyadic sessions (EmoBox Table 2’s label)About 12 hours; categorical and dimensional labels from multiple annotatorsElectronic release form plus licenseNo: internal research only, no commercial purposes (license clauses 1 and 3)
MSP-PodcastNatural podcast speechv2.0 264,705 speaking turns (409 hours); categorical plus activation, dominance, valenceAcademic license signed by your institutionPage says commercial use is possible but offers only the academic license; ask the lab

CREMA-D uses the Open Database License 1.0, with its contents under the Database Contents License.

ODbL rights explicitly include commercial use, and its share-alike clause covers derivative databases you publicly use. Whether a model trained on CREMA-D is a produced work or a derivative database is a question for your counsel, and this post does not treat it as settled.

RAVDESS on Zenodo is CC BY-NC-SA 4.0, and the same page says commercial licenses “can also be purchased”; TESS at the University of Toronto is CC BY-NC-ND 4.0.

IEMOCAP is shared through an electronic release form and a license whose clause 1 limits the data to “internal research purposes only” and whose clause 3 bars use “for any commercial purposes”.

MSP-Podcast offers an academic license your institution signs, a data use agreement that limits use to a stated research project.

The MSP-Podcast page also says the corpus can be used “for commercial product”, yet the only license it offers is the academic one and it lists no commercial license. A commercial team should ask the lab before it plans a product on that corpus.

The Apache-2.0 model card trap

An Apache-2.0 license on a model card covers the published weights, not the terms of the data the model learned from. Two speech emotion checkpoints show the gap: both carry Apache-2.0 on their model cards, and both name a training set whose terms limit it to research or rule out commercial use.

The card for superb/wav2vec2-base-superb-er says it uses IEMOCAP, and ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition says it was fine-tuned on RAVDESS.

So this post presents neither of the two checkpoints we checked as commercially clean. Before you deploy any speech emotion model, read the training data’s terms beside the model license and take the question to counsel, because the card answers only half of it.

Building labelled fixtures for an escalation test

An escalation test needs fixtures where each turn carries an annotated label, a model-inferred label and a confidence, and each call carries a should-escalate verdict from a written rubric. With those columns you can score the detector and the rule apart. Our lab ships 60 such calls as an illustrative fixture.

Each row is one turn: call_id, turn, annotated_label, predicted_label, confidence, should_escalate and provenance. Labels are neutral, anger, annoyance, sadness and joy, a subset of the Tone eval labels; CREMA-D has no annoyance class, so it needs a stated mapping. The rubric: escalate when two or more turns are annotated anger or annoyance, consecutive or not.

Predictions come from a seeded generator (seed 7) and a stated confusion profile, so a re-run gives the same file, sha256 9d10f3e50f55dd9dfad8c2d85756b91671ac8b6155f4ed574063acf41de9d61d. The fixture makes the scoring method checkable and does not stand in for a model result, so do not read the 0.766 below as a benchmark. Every value is labelled illustrative fixture, not measured customer results.

The lab reads detector outputs instead of audio. The scorer needs only labels, predictions and confidences, audio licensing comes first, and the two checkpoints we checked were trained on IEMOCAP and RAVDESS. CREMA-D is the audio a team labels next, and --from-model swaps in predictions from any real model by call_id and turn.

Loading fails closed: a malformed or duplicate row, a gap in turn numbers, an unknown label, a confidence outside 0 to 1 or a should_escalate value that changes within a call stops the run with exit 1, so a broken export never becomes a clean-looking score.

Running the lab and its fail-closed checks

Save the script as ser_policy_lab.py. We tested end to end with the Python 3.12 standard library: --generate wrote 380 turns, 60 calls, seed 7; --selftest passed; and --from-model on preds_synthetic.csv, a synthetic stand-in for model outputs, printed the same detector, sweep and gate sections as the default run.

"""Score a speech emotion recognition (SER) detector and the escalation policy that acts on it,
separately, then attribute every per-call escalation error to the policy or the detector.

Every label, prediction, confidence, outcome and threshold in detector_outputs.csv and in this
script's printed numbers is an ILLUSTRATIVE FIXTURE, NOT MEASURED CUSTOMER RESULTS. No audio
is read and no model runs here: predictions are drawn from a seeded RNG and a stated confusion
profile (CONFUSION below), so anyone can re-run it and get the same file.

Vocabulary: annotated_label is what an annotator assigned from the written rubric below after
listening to a turn. predicted_label is a model-inferred label. Neither is knowledge of how a
caller feels inside.

Fixture label set: {neutral, anger, annoyance, sadness, joy}, a subset of the Future AGI Tone
eval labels. CREMA-D has no annoyance class (its six are anger, disgust, fear, happy, neutral,
sad), so audio labelled from CREMA-D would need a stated label mapping first.

Written rubric for should_escalate (per call, from annotated labels only): a call should go to
a human when two or more of its turns are annotated anger or annoyance (consecutive or not).

Policy scored here: escalate at the first turn where predicted_label is in {anger, annoyance}
with confidence >= THRESHOLD for K consecutive turns. The oracle run applies the same rule to
annotated_label with confidence treated as 1.0, so the oracle shows policy errors alone. A third,
labels-only run applies the rule to predicted_label with threshold 0.0, which splits each
detector-induced call into label-induced (the predicted labels alone get the call wrong) and
confidence-induced (the predicted labels get it right, the threshold blocks the escalation),
and each detector-masked call into label-masked (the predicted labels alone would not repeat the
rule's error) and threshold-masked (the predicted labels alone would repeat the rule's error, and
only the threshold kept the detector run from making it).
Oracle errors are also printed by annotated pattern (flagged turns, longest consecutive streak),
so the cause of each policy error comes from code, not from reading the table.

Usage:
  python3 ser_policy_lab.py --generate            write detector_outputs.csv (seed 7)
  python3 ser_policy_lab.py                       score detector_outputs.csv
  python3 ser_policy_lab.py --from-model preds.csv  replace predicted_label and confidence with
        predictions produced elsewhere (columns: call_id, turn, predicted_label, confidence)
  python3 ser_policy_lab.py --threshold 0.7 --k 2 --budget 0.10   gate operating point
  python3 ser_policy_lab.py --selftest            assert checks on SYNTHETIC fixture rows only

Fails closed (exit 1): a malformed or duplicated row, a gap in turn numbers, an unknown label,
a confidence outside [0, 1], should_escalate inconsistent within a call, a --from-model row
with no matching fixture row (or a fixture row with no prediction), a fixture with no
should_escalate call, a --threshold or --budget that is not a finite number in [0, 1], a --k
below 1, or a missed-escalation rate on should_escalate calls above --budget at the gated
operating point.
"""
import argparse, csv, math, os, random, sys, tempfile
from collections import Counter, defaultdict

PROVENANCE = "illustrative fixture, not measured customer results"
LABELS = ["neutral", "anger", "annoyance", "sadness", "joy"]
ESCALATE_ON = {"anger", "annoyance"}
THRESHOLDS = (0.6, 0.7, 0.8)
KS = (1, 2, 3)
FIELDS = ["call_id", "turn", "annotated_label", "predicted_label", "confidence",
          "should_escalate", "provenance"]
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_CSV = os.path.join(HERE, "detector_outputs.csv")

# P(predicted | annotated), stated up front so readers can change it. Illustrative fixture.
CONFUSION = {
    "neutral":   {"neutral": .80, "annoyance": .08, "sadness": .07, "joy": .03, "anger": .02},
    "anger":     {"anger": .65, "annoyance": .20, "neutral": .10, "sadness": .05},
    "annoyance": {"annoyance": .50, "neutral": .30, "anger": .12, "sadness": .08},
    "sadness":   {"sadness": .60, "neutral": .25, "annoyance": .10, "anger": .05},
    "joy":       {"joy": .70, "neutral": .25, "annoyance": .05},
}
# Confidence: correct predictions uniform(0.55, 0.98), wrong ones uniform(0.40, 0.85).

# Annotated turn sequences per call shape (illustrative fixture). n = calls of that shape.
SHAPES = [
    ("calm", 14, lambda r, n: [r.choice(["neutral", "neutral", "joy"]) for _ in range(n)]),
    ("sad", 8, lambda r, n: ["neutral"] + [r.choice(["sadness", "neutral"]) for _ in range(n - 1)]),
    ("single_flare", 10, lambda r, n: _place(["neutral"] * n, r, ["annoyance"])),
    ("rising", 14, lambda r, n: ["neutral"] * (n - 3) + ["annoyance", "anger", "anger"]),
    ("short_burst", 8, lambda r, n: _place(["neutral"] * n, r, ["annoyance", "anger"])),
    ("intermittent", 6, lambda r, n: ["neutral", "annoyance", "neutral", "anger"] + ["neutral"] * (n - 4)),
]


def _place(seq, r, burst):
    i = r.randrange(1, len(seq) - len(burst) + 1)
    seq[i:i + len(burst)] = burst
    return seq


class FixtureError(ValueError):
    pass


def rubric(annotated):
    return sum(a in ESCALATE_ON for a in annotated) >= 2


def generate(path, seed=7):
    r = random.Random(seed)
    rows, cid = [], 0
    for _, count, make in SHAPES:
        for _ in range(count):
            cid += 1
            ann = make(r, r.randint(5, 8))
            esc = rubric(ann)
            for t, a in enumerate(ann, 1):
                labels, weights = zip(*CONFUSION[a].items())
                p = r.choices(labels, weights)[0]
                conf = r.uniform(0.55, 0.98) if p == a else r.uniform(0.40, 0.85)
                rows.append({"call_id": f"c{cid:03d}", "turn": t, "annotated_label": a,
                             "predicted_label": p, "confidence": f"{conf:.2f}",
                             "should_escalate": int(esc), "provenance": PROVENANCE})
    with open(path, "w", newline="") as f:
        w = csv.DictWriter(f, FIELDS)
        w.writeheader()
        w.writerows(rows)
    return len(rows), cid


def _conf(s, where):
    try:
        c = float(s)
    except ValueError:
        raise FixtureError(f"{where}: confidence {s!r} is not a number")
    if not (math.isfinite(c) and 0.0 <= c <= 1.0):
        raise FixtureError(f"{where}: confidence {s!r} outside [0, 1]")
    return c


def load(path, from_model=None):
    """Return {call_id: {"should": bool, "turns": [(annotated, predicted, conf), ...]}}."""
    with open(path, newline="") as f:
        rd = csv.DictReader(f)
        missing = set(FIELDS[:6]) - set(rd.fieldnames or [])
        if missing:
            raise FixtureError(f"{path}: missing columns {sorted(missing)}")
        rows = list(rd)
    if not rows:
        raise FixtureError(f"{path}: no rows")
    seen, calls = set(), defaultdict(dict)
    should = {}
    for i, row in enumerate(rows, 2):
        where = f"{os.path.basename(path)} line {i}"
        if None in row or any(row[k] in (None, "") for k in FIELDS[:6]):
            raise FixtureError(f"{where}: malformed row")
        try:
            turn = int(row["turn"])
        except ValueError:
            raise FixtureError(f"{where}: turn {row['turn']!r} is not an integer")
        key = (row["call_id"], turn)
        if key in seen:
            raise FixtureError(f"{where}: duplicate row for call {key[0]} turn {turn}")
        seen.add(key)
        for k in ("annotated_label", "predicted_label"):
            if row[k] not in LABELS:
                raise FixtureError(f"{where}: unknown {k} {row[k]!r}")
        if row["should_escalate"] not in ("0", "1"):
            raise FixtureError(f"{where}: should_escalate must be 0 or 1")
        s = row["should_escalate"] == "1"
        if should.setdefault(row["call_id"], s) != s:
            raise FixtureError(f"{where}: should_escalate differs within call {row['call_id']}")
        calls[row["call_id"]][turn] = [row["annotated_label"], row["predicted_label"],
                                       _conf(row["confidence"], where)]
    if from_model:
        _apply_model(from_model, calls)
    out = {}
    for cid, turns in calls.items():
        if sorted(turns) != list(range(1, len(turns) + 1)):
            raise FixtureError(f"call {cid}: turns {sorted(turns)} are not 1..n")
        out[cid] = {"should": should[cid], "turns": [tuple(turns[t]) for t in sorted(turns)]}
    return out


def _apply_model(path, calls):
    with open(path, newline="") as f:
        rd = csv.DictReader(f)
        need = {"call_id", "turn", "predicted_label", "confidence"}
        if not need <= set(rd.fieldnames or []):
            raise FixtureError(f"{path}: needs columns {sorted(need)}")
        seen = set()
        for i, row in enumerate(rd, 2):
            where = f"{os.path.basename(path)} line {i}"
            if None in row or any(row[k] in (None, "") for k in need):
                raise FixtureError(f"{where}: malformed row")
            try:
                key = (row["call_id"], int(row["turn"]))
            except ValueError:
                raise FixtureError(f"{where}: turn {row['turn']!r} is not an integer")
            if key in seen:
                raise FixtureError(f"{where}: duplicate prediction for {key}")
            seen.add(key)
            if key[1] not in calls.get(key[0], {}):
                raise FixtureError(f"{where}: no fixture row for call {key[0]} turn {key[1]}")
            if row["predicted_label"] not in LABELS:
                raise FixtureError(f"{where}: unknown predicted_label {row['predicted_label']!r}")
            calls[key[0]][key[1]][1:] = [row["predicted_label"], _conf(row["confidence"], where)]
    expected = {(c, t) for c, ts in calls.items() for t in ts}
    if expected - seen:
        raise FixtureError(f"{path}: {len(expected - seen)} fixture turns have no prediction, "
                           f"first {sorted(expected - seen)[0]}")


# ---------- detector scoring ----------

def score_detector(calls):
    pairs = [(a, p, c) for call in calls.values() for a, p, c in call["turns"]]
    cm = Counter((a, p) for a, p, _ in pairs)
    print(f"DETECTOR (per turn, n={len(pairs)}) [{PROVENANCE}]")
    print("confusion matrix: rows = annotated_label, columns = predicted_label (model-inferred)")
    print(f"{'':>10} " + " ".join(f"{l:>9}" for l in LABELS))
    for a in LABELS:
        print(f"{a:>10} " + " ".join(f"{cm[(a, p)]:>9}" for p in LABELS))
    print(f"\n{'label':>10} {'precision':>9} {'recall':>7} {'f1':>6} {'support':>7}")
    f1s = []
    for l in LABELS:
        tp = cm[(l, l)]
        pp = sum(cm[(a, l)] for a in LABELS)
        sup = sum(cm[(l, p)] for p in LABELS)
        prec = tp / pp if pp else 0.0
        rec = tp / sup if sup else 0.0
        f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
        f1s.append(f1)
        print(f"{l:>10} {prec:>9.3f} {rec:>7.3f} {f1:>6.3f} {sup:>7}")
    macro = sum(f1s) / len(f1s)
    acc = sum(cm[(l, l)] for l in LABELS) / len(pairs)
    print(f"macro-F1 {macro:.3f}   accuracy {acc:.3f}   (macro-F1 weights every class equally)")
    print("\nconfidence-bin reliability (does stated confidence match observed accuracy?)")
    print(f"{'bin':>11} {'turns':>6} {'mean conf':>9} {'accuracy':>8} {'gap':>7}")
    edges = [0.0, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0001]
    for lo, hi in zip(edges, edges[1:]):
        b = [(a == p, c) for a, p, c in pairs if lo <= c < hi]
        if not b:
            continue
        mc = sum(c for _, c in b) / len(b)
        ac = sum(ok for ok, _ in b) / len(b)
        print(f"[{lo:.1f},{min(hi, 1.0):.1f}{')' if hi < 1 else ']'} {len(b):>6} {mc:>9.3f} {ac:>8.3f} {ac - mc:>+7.3f}")
    return macro


# ---------- policy scoring ----------

def escalation_turn(turns, threshold, k, oracle):
    streak = 0
    for t, (a, p, c) in enumerate(turns, 1):
        label, conf = (a, 1.0) if oracle else (p, c)
        streak = streak + 1 if (label in ESCALATE_ON and conf >= threshold) else 0
        if streak >= k:
            return t
    return None


def p95(xs):
    xs = sorted(xs)
    return xs[max(0, math.ceil(0.95 * len(xs)) - 1)] if xs else None


def flagged_pattern(annotated):
    """(flagged annotated turns, longest consecutive flagged streak) for one call."""
    n = best = run = 0
    for a in annotated:
        run = run + 1 if a in ESCALATE_ON else 0
        n += a in ESCALATE_ON
        best = max(best, run)
    return n, best


def oracle_errors(calls, k):
    """Counter of (error kind, flagged turns, longest streak) over the oracle run's wrong calls."""
    out = Counter()
    for call in calls.values():
        ann = [a for a, _, _ in call["turns"]]
        fired = escalation_turn(call["turns"], 1.0, k, True) is not None
        if fired != call["should"]:
            out[("false" if fired else "missed",) + flagged_pattern(ann)] += 1
    return out


def score_policy(calls, threshold, k):
    cells = Counter()
    stats = {"split": Counter()}
    for name, oracle in (("oracle", True), ("detector", False)):
        fe = me = 0
        tte = []
        for call in calls.values():
            t = escalation_turn(call["turns"], threshold, k, oracle)
            fired = t is not None
            if fired and not call["should"]:
                fe += 1
            if call["should"] and not fired:
                me += 1
            if call["should"] and fired:
                tte.append(t)
            call[name] = fired
        stats[name] = (fe, me, tte)
    for call in calls.values():
        o_ok = call["oracle"] == call["should"]
        d_ok = call["detector"] == call["should"]
        cell = {(True, True): "both_correct", (False, False): "policy_only",
                (True, False): "detector_induced", (False, True): "detector_masked"}[(o_ok, d_ok)]
        cells[cell] += 1
        if cell == "detector_induced":
            # labels-only run: same rule on predicted_label, threshold 0.0 (confidence ignored)
            lab_ok = (escalation_turn(call["turns"], 0.0, k, False) is not None) == call["should"]
            stats["split"]["confidence_induced" if lab_ok else "label_induced"] += 1
        elif cell == "detector_masked":
            # same labels-only run: if the labels alone repeat the oracle's error, the threshold masked it
            lab_ok = (escalation_turn(call["turns"], 0.0, k, False) is not None) == call["should"]
            stats["split"]["label_masked" if lab_ok else "threshold_masked"] += 1
    return cells, stats


def policy_sweep(calls):
    n_pos = sum(c["should"] for c in calls.values())
    n_neg = len(calls) - n_pos
    print(f"\nPOLICY SWEEP (per call, {len(calls)} calls: {n_pos} should_escalate, {n_neg} should not)"
          f" [{PROVENANCE}]")
    print("oracle = same rule on annotated_label (confidence 1.0, so threshold does not bind)")
    print(f"{'thr':>4} {'K':>2} | {'oracle FE':>9} {'oracle ME':>9} | {'det FE':>6} {'det ME':>6} "
          f"{'TTE mean':>8} {'TTE p95':>7} | {'ok':>3} {'pol-only':>8} {'det-ind':>7} {'lab/conf':>8} "
          f"{'det-mask':>8} {'lab/thr':>7}")
    for thr in THRESHOLDS:
        for k in KS:
            cells, st = score_policy(calls, thr, k)
            ofe, ome, _ = st["oracle"]
            dfe, dme, tte = st["detector"]
            sp = st["split"]
            mean = f"{sum(tte) / len(tte):.2f}" if tte else "n/a"
            print(f"{thr:>4} {k:>2} | {ofe:>9} {ome:>9} | {dfe:>6} {dme:>6} {mean:>8} "
                  f"{p95(tte) if tte else 'n/a':>7} | {cells['both_correct']:>3} {cells['policy_only']:>8} "
                  f"{cells['detector_induced']:>7} {str(sp['label_induced']) + '/' + str(sp['confidence_induced']):>8} "
                  f"{cells['detector_masked']:>8} {str(sp['label_masked']) + '/' + str(sp['threshold_masked']):>7}")
    print("FE = false escalations, ME = missed escalations, TTE = turn index at which the detector run"
          " escalated, over correctly escalated should_escalate calls")
    print("lab/conf = detector-induced calls split by a labels-only run (threshold 0.0): label-induced /"
          " confidence-induced")
    print("lab/thr = detector-masked calls split by the same labels-only run: label-masked / threshold-masked")
    print("\nORACLE ERRORS BY ANNOTATED PATTERN (oracle run does not depend on threshold)")
    for k in KS:
        errs = oracle_errors(calls, k)
        parts = [f"{n} {kind} with {fl} flagged turn{'s' * (fl != 1)}, longest consecutive streak {st}"
                 for (kind, fl, st), n in sorted(errs.items())]
        print(f"K={k}: " + ("; ".join(parts) if parts else "none"))


def check_params(threshold, k, budget):
    for name, v in (("threshold", threshold), ("budget", budget)):
        if not (isinstance(v, (int, float)) and math.isfinite(v) and 0.0 <= v <= 1.0):
            raise FixtureError(f"--{name} {v!r} is not a finite number in [0, 1]")
    if not (isinstance(k, int) and k >= 1):
        raise FixtureError(f"--k {k!r} must be an integer >= 1")


def gate(calls, threshold, k, budget):
    check_params(threshold, k, budget)
    n_pos = sum(c["should"] for c in calls.values())
    if n_pos == 0:
        raise FixtureError("no should_escalate call in the fixture, so the missed-escalation rate is undefined")
    cells, st = score_policy(calls, threshold, k)
    ofe, ome, _ = st["oracle"]
    dfe, dme, tte = st["detector"]
    print(f"\nGATED OPERATING POINT threshold={threshold} K={k} [{PROVENANCE}]")
    print("per-call 2x2 (rows: oracle decision, columns: detector-run decision)")
    print(f"{'':>17} {'detector correct':>17} {'detector wrong':>15}")
    print(f"{'oracle correct':>17} {cells['both_correct']:>17} {cells['detector_induced']:>15}"
          "   <- wrong cell = detector-induced error")
    print(f"{'oracle wrong':>17} {cells['detector_masked']:>17} {cells['policy_only']:>15}"
          "   <- left = detector-masked, right = policy-only")
    sp = st["split"]
    print(f"detector-induced split (labels-only run, threshold 0.0): {sp['label_induced']} label-induced, "
          f"{sp['confidence_induced']} confidence-induced")
    print(f"detector-masked split (same labels-only run): {sp['label_masked']} label-masked, "
          f"{sp['threshold_masked']} threshold-masked")
    print(f"oracle: {ofe} false, {ome} missed escalations   detector run: {dfe} false, {dme} missed")
    if tte:
        print(f"turns to escalation (detector run): mean {sum(tte) / len(tte):.2f}, p95 {p95(tte)}, "
              f"n={len(tte)}")
    rate = dme / n_pos
    print(f"missed-escalation rate on should_escalate calls: {dme}/{n_pos} = {rate:.3f}; budget {budget:.3f}")
    if rate > budget:
        print("GATE: FAIL (exit 1)")
        return 1
    print("GATE: PASS")
    return 0


def run(path, from_model, threshold, k, budget):
    check_params(threshold, k, budget)
    calls = load(path, from_model)
    if not any(c["should"] for c in calls.values()):  # fail before printing, gate() checks again
        raise FixtureError("no should_escalate call in the fixture, so the missed-escalation rate is undefined")
    src = f"predictions from {from_model}" if from_model else "predictions from the fixture file"
    print(f"input {os.path.basename(path)}: {len(calls)} calls, {src}\n")
    score_detector(calls)
    policy_sweep(calls)
    return gate(calls, threshold, k, budget)


# ---------- selftest (SYNTHETIC fixture rows only) ----------

def selftest():
    d = tempfile.mkdtemp()
    p = os.path.join(d, "fx.csv")
    hdr = ",".join(FIELDS) + "\n"
    PQ = f'"{PROVENANCE}"'  # quoted: the provenance text contains a comma

    def write(name, body):
        q = os.path.join(d, name)
        with open(q, "w") as f:
            f.write(body)
        return q

    def bad(fn, *a):
        try:
            fn(*a)
        except FixtureError as e:
            return str(e)
        raise AssertionError(f"expected FixtureError from {a}")

    good = hdr + "".join(f"c1,{t},{a},{pr},0.9,1,{PQ}\n" for t, a, pr in
                         [(1, "neutral", "neutral"), (2, "annoyance", "neutral"), (3, "anger", "anger"),
                          (4, "anger", "annoyance")])
    good += f"c2,1,neutral,anger,0.95,0,{PQ}\nc2,2,neutral,anger,0.65,0,{PQ}\n"
    calls = load(write("good.csv", good))
    # c1: oracle K=2 fires at turn 3 (annoyance, anger); detector fires at turn 4 (anger, annoyance).
    assert escalation_turn(calls["c1"]["turns"], 0.7, 2, True) == 3
    assert escalation_turn(calls["c1"]["turns"], 0.7, 2, False) == 4
    # c2: detector fires at K=2 only when threshold <= 0.65: false escalation, detector-induced.
    assert escalation_turn(calls["c2"]["turns"], 0.6, 2, False) == 2
    assert escalation_turn(calls["c2"]["turns"], 0.7, 2, False) is None
    cells, st = score_policy(calls, 0.6, 2)
    assert cells == Counter(both_correct=1, detector_induced=1), cells
    # K=3: oracle fires on c1 at turn 4, detector has only a 2-turn streak: detector-induced miss.
    cells, _ = score_policy(calls, 0.6, 3)
    assert cells == Counter(both_correct=1, detector_induced=1), cells
    # policy-only: intermittent call (rubric says escalate) has no 2-turn streak in either run.
    pc = load(write("pol.csv", hdr + "".join(f"c3,{t},{a},{a},0.9,1,{PQ}\n" for t, a in
                                              enumerate(["annoyance", "neutral", "anger"], 1))))
    assert score_policy(pc, 0.6, 2)[0] == Counter(policy_only=1)
    # detector-masked: oracle K=1 escalates a single flare (rubric says no), detector misses the flare.
    mc = load(write("mask.csv", hdr + f"c4,1,annoyance,neutral,0.9,0,{PQ}\n"
                                      f"c4,2,neutral,neutral,0.9,0,{PQ}\n"))
    cells, st = score_policy(mc, 0.6, 1)
    assert cells == Counter(detector_masked=1) and st["split"] == Counter(label_masked=1)
    # threshold-masked: the flare is predicted annoyance at 0.65, so a 0.8 threshold alone hides the rule error.
    tc = load(write("tmask.csv", hdr + f"c9,1,annoyance,annoyance,0.65,0,{PQ}\n"
                                       f"c9,2,neutral,neutral,0.9,0,{PQ}\n"))
    cells, st = score_policy(tc, 0.8, 1)
    assert cells == Counter(detector_masked=1) and st["split"] == Counter(threshold_masked=1)
    assert rubric(["annoyance", "neutral", "anger"]) and not rubric(["anger", "neutral"])
    assert p95([1, 2, 3, 4]) == 4 and p95([5]) == 5
    # fail-closed cases
    assert "duplicate" in bad(load, write("dup.csv", good + f"c2,2,neutral,joy,0.5,0,{PQ}\n"))
    assert "malformed" in bad(load, write("short.csv", good + "c3,1,neutral\n"))
    assert "unknown" in bad(load, write("lab.csv", hdr + f"c1,1,fear,neutral,0.5,0,{PQ}\n"))
    assert "outside" in bad(load, write("cf.csv", hdr + f"c1,1,joy,joy,1.2,0,{PQ}\n"))
    assert "not 1..n" in bad(load, write("gap.csv", hdr + f"c1,1,joy,joy,0.5,0,{PQ}\n"
                                                         f"c1,3,joy,joy,0.5,0,{PQ}\n"))
    assert "differs" in bad(load, write("sh.csv", hdr + f"c1,1,joy,joy,0.5,0,{PQ}\n"
                                                        f"c1,2,joy,joy,0.5,1,{PQ}\n"))
    # --from-model: replaces predictions, rejects unknown keys and missing turns
    g = write("g.csv", good)
    preds = "call_id,turn,predicted_label,confidence\n" + "".join(
        f"c1,{t},anger,0.9\n" for t in range(1, 5)) + "c2,1,neutral,0.8\nc2,2,neutral,0.8\n"
    m = load(g, write("m.csv", preds))
    assert m["c1"]["turns"][0] == ("neutral", "anger", 0.9) and m["c2"]["turns"][1][1] == "neutral"
    assert "no fixture row" in bad(load, g, write("m2.csv", preds + "c9,1,joy,0.5\n"))
    assert "no prediction" in bad(load, g, write("m3.csv", preds.rsplit("c2,2", 1)[0]))
    assert "duplicate" in bad(load, g, write("m4.csv", preds + "c2,2,joy,0.5\n"))
    # gate exits 1 when the missed rate is over budget (c1 missed at K=3)
    assert gate(load(g), 0.6, 3, 0.0) == 1 and gate(load(g), 0.6, 2, 0.0) == 0
    # the gate fails closed instead of passing vacuously
    assert "no should_escalate" in bad(gate, load(write("neg.csv", hdr + f"c1,1,joy,joy,0.9,0,{PQ}\n")), 0.7, 2, 0.1)
    assert "budget" in bad(gate, load(g), 0.7, 2, float("nan"))
    assert "budget" in bad(gate, load(g), 0.7, 2, 1.5)
    assert "threshold" in bad(gate, load(g), -0.1, 2, 0.1)
    assert "--k" in bad(gate, load(g), 0.7, 0, 0.1)
    # detector-induced split: two consecutive correct annoyance turns at 0.62 under a 0.7 threshold
    # (K=2, rubric says escalate) is confidence-induced; a call whose predicted labels miss is label-induced.
    sc = load(write("split.csv", hdr + f"c5,1,neutral,neutral,0.9,1,{PQ}\nc5,2,annoyance,annoyance,0.62,1,{PQ}\n"
                                       f"c5,3,annoyance,annoyance,0.62,1,{PQ}\n"
                                       f"c6,1,annoyance,neutral,0.9,1,{PQ}\nc6,2,anger,anger,0.9,1,{PQ}\n"))
    cells, st = score_policy(sc, 0.7, 2)
    assert cells == Counter(detector_induced=2) and st["split"] == Counter(confidence_induced=1, label_induced=1)
    # oracle error patterns: single flare is a false escalation at K=1, intermittent a miss at K=2
    oc = load(write("oe.csv", hdr + "".join(f"c7,{t},{a},{a},0.9,0,{PQ}\n" for t, a in
                                            enumerate(["neutral", "annoyance", "neutral"], 1))
                    + "".join(f"c8,{t},{a},{a},0.9,1,{PQ}\n" for t, a in
                              enumerate(["annoyance", "neutral", "anger"], 1))))
    assert oracle_errors(oc, 1) == Counter({("false", 1, 1): 1})
    assert oracle_errors(oc, 2) == Counter({("missed", 2, 1): 1})
    print("\nselftest OK (synthetic fixture rows only)")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("csv", nargs="?", default=DEFAULT_CSV)
    ap.add_argument("--generate", action="store_true")
    ap.add_argument("--seed", type=int, default=7)
    ap.add_argument("--from-model", dest="from_model")
    ap.add_argument("--threshold", type=float, default=0.7)
    ap.add_argument("--k", type=int, default=2)
    ap.add_argument("--budget", type=float, default=0.10,
                    help="max missed-escalation rate on should_escalate calls (illustrative)")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        selftest()
        return 0
    if a.generate:
        n, c = generate(a.csv, a.seed)
        print(f"wrote {os.path.basename(a.csv)}: {n} turns, {c} calls, seed {a.seed} [{PROVENANCE}]")
        return 0
    try:  # bad --threshold, --k, --budget or an all-negative fixture also fail closed here
        return run(a.csv, a.from_model, a.threshold, a.k, a.budget)
    except (FixtureError, OSError) as e:
        print(f"FAIL CLOSED: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
python3 ser_policy_lab.py --generate
python3 ser_policy_lab.py --selftest
python3 ser_policy_lab.py
python3 ser_policy_lab.py --threshold 0.6 --k 1
python3 ser_policy_lab.py --from-model preds_synthetic.csv
wrote detector_outputs.csv: 380 turns, 60 calls, seed 7 [illustrative fixture, not measured customer results]

The four synthetic inputs are each made from detector_outputs.csv by the one-line command shown below. The duplicate and the truncated file each print one FAIL CLOSED line and exit 1, so neither file reaches the detector or the policy sections of the report.

cut -d, -f1,2,4,5 detector_outputs.csv > preds_synthetic.csv
{ cat detector_outputs.csv; sed -n 2p detector_outputs.csv; } > dup.csv
{ cat detector_outputs.csv; echo "c001,9,neutral"; } > short.csv
awk -F, 'NR==1 || $6==0' detector_outputs.csv > no_positive.csv
FAIL CLOSED: dup.csv line 382: duplicate row for call c001 turn 1
FAIL CLOSED: short.csv line 382: malformed row

Scoring the detector per class before any routing

Score the detector on its own first, per class, with precision, recall, F1 and support, a confusion matrix and macro-F1. In our illustrative fixture of 380 turns, accuracy is 0.766 but macro-F1 is 0.649, because neutral dominates and annoyance and sadness score F1 0.467 and 0.462.

State the support before any number: neutral 252, anger 42, annoyance 38, sadness 22 and joy 26 annotated turns. Fixture labels and predictions share one label set, so no class mapping is needed. With a real model whose classes differ, write the mapping down before you score anything.

DETECTOR (per turn, n=380) [illustrative fixture, not measured customer results]
confusion matrix: rows = annotated_label, columns = predicted_label (model-inferred)
             neutral     anger annoyance   sadness       joy
   neutral       207         5        15        15        10
     anger         3        30         9         0         0
 annoyance         7         7        21         3         0
   sadness         4         0         6        12         0
       joy         4         0         1         0        21

     label precision  recall     f1 support
   neutral     0.920   0.821  0.868     252
     anger     0.714   0.714  0.714      42
 annoyance     0.404   0.553  0.467      38
   sadness     0.400   0.545  0.462      22
       joy     0.677   0.808  0.737      26
macro-F1 0.649   accuracy 0.766   (macro-F1 weights every class equally)

Rows are annotated labels, columns predicted labels. Two readings matter for routing: 15 neutral turns and 9 anger turns were predicted annoyance, while 7 annoyance turns were predicted neutral. The neutral cell feeds false escalations and the annoyance cell feeds misses.

Per class, F1 runs from 0.868 for neutral down to 0.467 for annoyance and 0.462 for sadness, with every precision and recall in the printed table. Accuracy flatters an imbalanced queue: neutral is about two thirds of turns, so the score stays high while annoyance, one of the two classes the rule acts on, stays weak.

The same scoring logic for intent classifiers is in per-intent precision, recall and calibration for classifiers.

Confidence bins against observed accuracy

A confidence threshold only works if stated confidence tracks accuracy. The reliability table bins every turn by confidence and compares each bin’s mean confidence with the share of correct predictions in it, exactly as the script printed it for this fixture:

confidence-bin reliability (does stated confidence match observed accuracy?)
        bin  turns mean conf accuracy     gap
[0.0,0.5)     20     0.446    0.000  -0.446
[0.5,0.6)     53     0.564    0.698  +0.134
[0.6,0.7)     83     0.646    0.699  +0.053
[0.7,0.8)     85     0.748    0.800  +0.052
[0.8,0.9)     86     0.839    0.872  +0.033
[0.9,1.0]     53     0.944    1.000  +0.056

From 0.5 up, accuracy sits at or above mean confidence in every bin. The 20 turns under 0.5 score 0.000 only because the fixture draws correct predictions from 0.55 to 0.98 and wrong ones from 0.40 to 0.85. That comes from the profile, not a model, so bin your own fixtures first.

Scoring the escalation policy on its own

Score the escalation rule separately by running it twice: once on annotated labels, the oracle run, and once on predicted labels. The oracle shows errors the rule makes with a perfect detector. In our illustrative fixture, the oracle at K=2 already misses 6 of 28 should-escalate calls before the detector adds any error.

The rule escalates at the first turn where predicted_label is anger or annoyance with confidence at or above the threshold for K consecutive turns; the oracle uses confidence 1.0, so the threshold never binds. Thresholds 0.6, 0.7 and 0.8 and K 1, 2 and 3 are parameters under test, never recommendations.

Flow of one escalation rule on speech emotion recognition labels, run three times on the same 60 illustrative fixture calls: an oracle run on annotated labels, a detector run on predicted labels with the threshold, and a labels-only run at threshold 0.0, whose decisions place each call in a 2x2 cell and split it by cause

A false escalation fires on a call the rubric says should stay; a missed escalation is a should-escalate call where the rule never fires. Turns to escalation is the turn index where the detector run fired, as mean and p95 over correctly escalated calls. A third, labels-only run follows. Every number below is an illustrative fixture, not measured customer results.

ThresholdKOracle false / missedDetector run false / missedTurns to escalation mean / p95Policy-only / detector-induced (label / confidence) / detector-masked (label / threshold)
0.6110 / 014 / 03.89 / 78 / 6 (6 / 0) / 2 (1 / 1)
0.620 / 61 / 145.21 / 85 / 10 (4 / 6) / 1 (1 / 0)
0.630 / 140 / 257.67 / 814 / 11 (6 / 5) / 0
0.7110 / 08 / 44.29 / 74 / 8 (4 / 4) / 6 (1 / 5)
0.720 / 60 / 185.50 / 85 / 13 (3 / 10) / 1 (1 / 0)
0.730 / 140 / 278.00 / 814 / 13 (6 / 7) / 0
0.8110 / 03 / 84.70 / 73 / 8 (0 / 8) / 7 (1 / 6)
0.820 / 60 / 257.33 / 86 / 19 (3 / 16) / 0
0.830 / 140 / 28none escalated14 / 14 (6 / 8) / 0

In the printed patterns the oracle’s 10 false escalations at K=1 have one flagged turn, though the rubric needs two. Its 6 misses at K=2 are the only calls missed because their two flagged turns are not adjacent. Its 14 misses at K=3 add 8 calls whose two adjacent flagged turns fall one short of three.

ORACLE ERRORS BY ANNOTATED PATTERN (oracle run does not depend on threshold)
K=1: 10 false with 1 flagged turn, longest consecutive streak 1
K=2: 6 missed with 2 flagged turns, longest consecutive streak 1
K=3: 6 missed with 2 flagged turns, longest consecutive streak 1; 8 missed with 2 flagged turns, longest consecutive streak 2

The escalation signals and the sentiment-scorer choice are laid out in how to improve voice agent CSAT with analytics.

False escalations, missed escalations and turns to escalation

At 0.6 and K=1 the detector run makes 14 false and 0 missed escalations, turns to escalation mean 3.89 and p95 7. At 0.8 and K=1 it makes 3 false and 8 missed, mean 4.70, p95 7. At 0.7 and K=2, 0 false and 18 missed, mean 5.50, p95 8.

The detector run never correctly escalates a call at 0.8 and K=3: 28 missed and no turn index. The trade-off reads in turns, not seconds, because the fixture carries no timestamps, and in this sweep each step up in threshold or K lowers or holds false escalations and raises misses.

Separating detector errors from policy errors on every call

Put every call in a 2x2: was the oracle decision right, and was the detector-run decision right. Oracle right and detector wrong is detector-induced. Both wrong is policy-only. Oracle wrong but detector right is detector-masked: a wrong or missed predicted label, or a confidence under the threshold, cancelled a rule error that one accuracy number never shows.

GATED OPERATING POINT threshold=0.7 K=2 [illustrative fixture, not measured customer results]
per-call 2x2 (rows: oracle decision, columns: detector-run decision)
                   detector correct  detector wrong
   oracle correct                41              13   <- wrong cell = detector-induced error
     oracle wrong                 1               5   <- left = detector-masked, right = policy-only
detector-induced split (labels-only run, threshold 0.0): 3 label-induced, 10 confidence-induced
detector-masked split (same labels-only run): 1 label-masked, 0 threshold-masked
oracle: 0 false, 6 missed escalations   detector run: 0 false, 18 missed
turns to escalation (detector run): mean 5.50, p95 8, n=10
missed-escalation rate on should_escalate calls: 18/28 = 0.643; budget 0.100
GATE: FAIL (exit 1)

At 0.7 and K=2 the gate fails: 18 of 28 should-escalate calls missed, 0.643 against a 0.100 budget. A labels-only run, the same rule on predicted labels at threshold 0.0, splits the 13 detector-induced calls into 3 label-induced and 10 confidence-induced, where the labels would have fired and the 0.7 threshold blocked them.

Per-call 2x2 of speech emotion recognition escalation errors at threshold 0.7 and K=2 on the illustrative fixture: 41 calls both correct, 13 detector-induced split 3 label-induced and 10 confidence-induced, 1 detector-masked that is label-masked, and 5 policy-only, with 18 of 28 should-escalate calls missed and the gate failing

Most of that cell is a threshold question: in 10 of its 13 calls the predicted labels alone fire the rule. At 0.8 and K=1 all 8 detector-induced calls are confidence-induced, and at 0.6 and K=1 all 6 are label-induced. File confidence-induced calls as model errors and a team retrains before it checks the threshold.

Detector-masked calls hide errors the other way. At 0.8 and K=1 the detector run shows 3 false escalations against the oracle’s 10, because 7 calls are masked: 1 label-masked, where the predicted labels alone do not repeat the rule’s error, and 6 threshold-masked, where they do and only the 0.8 threshold stopped it.

In one of those six, c030, the flagged turn was predicted sadness and only a mislabelled neutral turn would fire the rule. The 6 masked calls at 0.7 and K=1 split 1 and 5, so at those points the threshold, rather than the model, hides most of the rule’s errors.

At 0.7 and K=2 the one masked call, c057, is label-masked in the other direction. The oracle misses it because its two flagged turns are not consecutive, and a neutral turn wrongly predicted annoyance hands the detector run its two-turn streak. A model with fewer label errors would turn it into a visible miss.

The gate passes at 0.6 and K=1 with 0 of 28 missed, yet the 2x2 still shows 8 policy-only and 6 detector-induced errors and 14 false escalations. A passing missed-escalation gate covers misses only, so tag each failing call with its cell, which points at its own fix:

  • Label-induced: read the label confusions, then a better model or fixtures.
  • Confidence-induced: read the confidence bin around the threshold, then the threshold, before any model change.
  • Policy-only: change the rule or the rubric.
  • Label-masked: fix the rule before you change the model, because a model with fewer label errors will surface the rule’s error.
  • Threshold-masked: fix the rule before you lower the threshold, for the same reason.

Once the rule fires at turn N, the transfer that follows has its own checks, covered in warm transfer testing for voice agents.

A release gate that fails closed

The gate exits 1 when the missed-escalation rate exceeds the stated budget, on any malformed, duplicated or inconsistent row, and in three cases that would otherwise pass vacuously: no should-escalate call, a budget or threshold that is not a finite number in [0, 1], and K below 1.

FAIL CLOSED: no should_escalate call in the fixture, so the missed-escalation rate is undefined
FAIL CLOSED: --budget nan is not a finite number in [0, 1]
FAIL CLOSED: --k 0 must be an integer >= 1

The budget, 0.10 by default, is a team decision stated in the run, never a recommendation. A re-run at a threshold that clears it does not clear the false-escalation and detector-masked counts, which stay in the report beside the verdict.

Repeatable frustrated-caller tests with Future AGI Simulate and the Tone eval

Future AGI Simulate runs repeatable frustrated-caller conversations from custom personas and scenario rows, and each call is scored by the evals you attach. The Tone eval labels the emotional tone of the transcript it is mapped to, so you get a transcript-side label to set beside your own speech emotion model.

Custom personas carry voice traits (accent, languages, conversation speed, background sound, interrupt sensitivity and finished-speaking sensitivity), behaviour such as personality and communication style, and free-form instructions. A frustrated caller is set through personality, communication style, the instructions and the scenario row.

Scenarios run a flow of Conversation, End call and Transfer call nodes over a table of rows, each row its own conversation.

A row such as “Frustrated caller” and its flow run again on every release, so the hard calls come back without anyone staging them. The Tone eval is LLM-as-Judge, with one required input named output, and returns a Result with a Reason.

The Tone template in the open-source future-agi/future-agi repo lists nine labels: neutral, joy, love, fear, surprise, sadness, anger, annoyance and confusion.

When mapping eval inputs in a simulation, you pick a call column for each input; the docs’ default, and the one shown for Tone, is call.transcript.

That column is the whole conversation, so the Tone label covers both the caller’s and the agent’s turns. Each call carries its transcript, its recording and the scores of the evals you attach, and Future AGI reports the Tone label as a model inference while the routing rule stays your own.

Annotators still label the recordings for the 2x2, since your rule acts on the vocal label and Tone labels the transcript it is mapped to. Voice simulation and Tone, like the other AgentEvaluator evals, run on Future AGI Cloud (plans that include it) or an Enterprise deployment.

Getting the clipped Thursday caller to a human on the right turn

The delivery caller from the opening gets a human once the team knows which part failed. Score the vocal model per class on annotated fixtures, run the rule on annotated labels and on predictions, read the 2x2, and only then move the threshold, the K value or the model.

That call (illustrative, not a recorded call) sits in the confidence-induced part of the detector-induced cell. The rubric says escalate, the oracle run escalates, and the labels-only run escalates too, so the labels were right and the next check is the confidence bin around 0.6, then the threshold, before any model change.

Label your own turns against a written rubric until each escalation label has enough support that you would trust its recall number, with CREMA-D audio as a licensable start. Export your SER model’s predictions, run ser_policy_lab.py with --from-model, and keep the fail-closed gate in CI.

Frequently Asked Questions

What is speech emotion recognition?

Speech emotion recognition is a machine learning task that infers an emotion label or score from how something is said, using pitch, loudness and the rate of speech. The output is a model's estimate for a stretch of audio, separate from transcript sentiment, and never a reading of the speaker's actual feelings.

Can you hear sadness in someone's voice?

Listeners and speech emotion models can pick up vocal cues such as pitch, loudness and rate of speech that may go with sadness, but neither can confirm the feeling. A model outputs an inferred label with a confidence, and benchmark labels are perception votes too: CREMA-D's labels are majority votes over multiple raters.

Which speech emotion recognition dataset can a commercial team use?

Of the five datasets compared here, CREMA-D is the only one whose license allows commercial use: ODbL 1.0, with share-alike terms on derived databases you publicly use. RAVDESS and TESS are non-commercial, IEMOCAP requires a release form and license, and MSP-Podcast lists an academic license.

How does voice agent emotion detection decide when to escalate a call?

Voice agent emotion detection decides nothing on its own; a separate rule turns its labels into an escalation, such as anger or annoyance above a confidence threshold for several turns. Test that rule on annotated labels and on model predictions separately, so you can tell rule errors from detector errors.

Can AI detect emotions?

AI can infer an emotion label from a voice or a transcript, but it cannot detect what a person feels. Speech emotion recognition accuracy also depends on how close your audio is to the training data, and EmoBox reports cross-corpus accuracy from 15.03% to 66.91% on balanced four-class tests.
Related Articles
View all