Skip to content

Examples and guides for using the OpenAI API

Minh/realtime eval guide (#2397)

Minhajul Hoque9085ae61536b
diff --git a/examples/Realtime_eval_guide.ipynb b/examples/Realtime_eval_guide.ipynb
new file mode 100644
index 00000000..db10a5bc
--- /dev/null
+++ b/examples/Realtime_eval_guide.ipynb
@@ -0,0 +1,616 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "fba401c1",
+ "metadata": {},
+ "source": [
+ "# Realtime Eval Guide"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fafa08e6",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_01_image_01.png\" alt=\"Diagram from page 1\" style=\"width: 30%; height: auto;\"/>\n",
+ " </div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7553621b",
+ "metadata": {},
+ "source": [
+ "## Introduction\n",
+ "\n",
+ "Evals are what turn a voice demo into something people can rely on. The gap between “seems fine” and “works every day” is almost always evals.\n",
+ "\n",
+ "This guide shows how to evaluate voice systems by slowly building complexity: start simple (Crawl), add realism (Walk), then test multi-turn (Run). Along the way, you’ll learn to build the three things that make results robust: a dataset, graders, and an eval harness, plus a production flywheel so real failures become new tests.\n",
+ "\n",
+ "Teams that invest in evals can ship to production **5–10× faster** because they can see what’s failing, pinpoint why, and fix it with confidence.\n",
+ "\n",
+ "## Part I: Foundations\n",
+ "\n",
+ "### 1) Why realtime evals are hard\n",
+ "\n",
+ "Realtime is harder than text because you are grading a **streaming interaction** with two outputs: what the **assistant doe**s and **how it sounds**. A response can be “right” and still sound broken.\n",
+ "\n",
+ "#### 1.1 The 2 axes of realtime quality\n",
+ "\n",
+ "Text evals mostly ask if the content is right. Realtime adds a second axis: audio quality. Content and audio can fail independently, so a single score can hide real problems.\n",
+ "\n",
+ "**Most realtime evals can reduce to two independent axes:**\n",
+ "\n",
+ "1. Content quality: Did the assistant understand the user and do the right thing? Correctness, helpfulness, tool choice, tool arguments, and instruction following.\n",
+ "\n",
+ "2. Audio quality: Did the assistant sound acceptable? Naturalness, prosody, pronunciation, stability, and how it behaves under noise and imperfect capture.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5d420dfa",
+ "metadata": {},
+ "source": [
+ "#### 1.2 Hard to debug\n",
+ "\n",
+ "With the **Responses API**, the mental model is simple: **request in → response out**. With the **Realtime API**, a “turn” is a s**titched pipeline**. That orchestration makes voice apps easy to build, but for evals, you must log stages so you can isolate failures and find root causes."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "89dd169b",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_02_image_01.png\" alt=\"Diagram from page 2\" style=\"width: auto; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "becc23dc",
+ "metadata": {},
+ "source": [
+ "A “turn” is a chain of events (speech start/stop → commit → response.create → audio deltas → done), and failures can happen at any stage. If you treat the system as a black box, you’ll chase “model issues” that are actually turn detection, buffering, or tool-integration issues.\n",
+ "\n",
+ "**Example:**\n",
+ "\n",
+ "- Content is correct but the experience is broken: audio gets chopped during barge-in because the interruption boundary is wrong.\n",
+ "\n",
+ "- Answer is “right” but feels slow: latency came from network quality, turn detection slowness, not the model’s reasoning. You can learn more about the various events that the Realtime API triggers here.\n",
+ "\n",
+ "You can learn more about the various events that the Realtime API triggers [here](https://platform.openai.com/docs/api-reference/realtime-server-events).\n",
+ "\n",
+ "#### 1.3 Transcript ≠ ground truth\n",
+ "\n",
+ "In realtime api, the ground truth for “what the user said” is **the actual audio signal** (what the microphone captured and what the model heard). A transcript is not ground truth, it’s a **model-produced interpretation** of that audio. It can be wrong because it’s constrained by **transcription model errors**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7c9550c7",
+ "metadata": {},
+ "source": [
+ "**If you treat transcripts as truth, your evals can be misleading:**\n",
+ "\n",
+ "- False fail: ASR drops a digit, but the model heard it and called the tool correctly → your LLM grader marks “wrong.”\n",
+ "\n",
+ "- False pass: transcript looks clean, but audio was clipped and the model guessed → you miss the real problem.\n",
+ "\n",
+ "**Best Practices:**\n",
+ "\n",
+ "- **Improve transcription:** Iterate on transcription [prompts](https://platform.openai.com/docs/guides/speech-to-text#prompting), try different [models](https://platform.openai.com/docs/guides/speech-to-text), try different methods such as [oob transcription](https://cookbook.openai.com/examples/realtime_out_of_band_transcription).\n",
+ "\n",
+ "- **Use transcripts for scale:** run most automated grading on **transcripts + traces**.\n",
+ "\n",
+ "- **Calibrate graders on messy reality:** iterate graders on **production-like, noisy transcripts** (not clean text) so they don’t overreact to ASR errors.\n",
+ "\n",
+ "- **Add an audio audit loop:** spot-check **~1–5%** of sessions end-to-end."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2ec20772",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\" style=\"text-align: center;\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_03_image_01.png\" alt=\"Diagram from page 3\" style=\"width: 50%; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3033c18a",
+ "metadata": {},
+ "source": [
+ "## Part II: Strategy\n",
+ "\n",
+ "### 2) Crawl / Walk / Run\n",
+ "\n",
+ "Realtime evals feel overwhelming when teams start at the hardest setting: real audio, multi-turn dialogue and real tools. The fix is to build **complexity in steps**. If your system **cannot crawl, it will not run**. Early evals should be simple enough that failures are diagnosable, repeatable, and cheap to iterate on. You can increase complexity in two independent axes.\n",
+ "\n",
+ "#### 2.1 Isolating input conditions: clean vs production audio\n",
+ "\n",
+ "This axis is about what the model hears. By controlling input audio conditions, you can separate failures in model intelligence from failures in speech perception.\n",
+ "\n",
+ "- **Start with synthetic audio → tests intelligence:**\n",
+ " - Use clean, synthetic repeatable audio (e.g., TTS) when you want to measure the model’s reasoning and decision-making without audio variance muddying the signal → helps isolate intent routing, tool calling, instruction following\n",
+ "\n",
+ "- **Move to noisy, production-like audio → tests audio perception:**\n",
+ " - Once intelligence is stable, introduce audio that resembles production: compression, echo, far-field capture, background noise, hesitations/self-corrections. This tests whether the system still behaves correctly when the input is ambiguous, messy, or partially lost → helps measure mishearing words, robustness to acoustic variations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "48a6c62b",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_04_image_01.png\" alt=\"Diagram from page 4\" style=\"width: auto; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "daac735f",
+ "metadata": {},
+ "source": [
+ "#### 2.2 Isolating interaction conditions: single-turn vs multi-turn\n",
+ "\n",
+ "This axis is about what you are evaluating: are you evaluating the next turn or the full **conversation**.\n",
+ "\n",
+ "- **Start single-turn → tests core competence:**\n",
+ " - Run one request → one response when you want the cleanest signal on fundamentals: correct intent routing, correct tool choice, valid arguments, and basic instruction following. If the system can’t reliably pick the right tool or produce a valid schema here, evaluating more turns won’t help.\n",
+ "\n",
+ "- **Move to multi-turn → tests robustness:**\n",
+ " - Once single-turn is stable, move to multi-turn where the system must hold goals and constraints across turns, sequence tools correctly, recover from tool failures and handle user corrections. Multi-turn shifts you from turn-level correctness to **episode-level outcomes**: did it complete the goal, how many turns did it take, and did it recover cleanly when something went wrong?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4427dd03",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_04_image_02.png\" alt=\"Diagram from page 4\" style=\"width: auto; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3b83d021",
+ "metadata": {},
+ "source": [
+ "Single-turn tells you *can win the battle*; multi-turn tells you *can win the war*.\n",
+ "\n",
+ "#### 2.3 Eval Quadrants\n",
+ "\n",
+ "Use a 2x2 map for evaluation: **right** = more realistic audio, **up** = more realistic interaction. Start bottom-left, increasing difficulty one axis at a time."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "87a1e0a7",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_05_image_01.png\" alt=\"Diagram from page 5\" style=\"width: auto; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "deec8bae",
+ "metadata": {},
+ "source": [
+ "**Eval modes (increasing complexity):**\n",
+ "\n",
+ "1. Crawl (bottom-left): synthetic audio + single-turn\n",
+ "\n",
+ "2. Walk (move right): real noisy audio + single-turn\n",
+ "\n",
+ "3. Run (move up): synthetic audio + multi-turn simulation Top-right (real audio + full multi-turn flow) is manual eval: run end-to-end sessions the way users do in production. Keep it in the loop for the entire project lifecycle."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cec946d3",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_05_image_02.png\" alt=\"Diagram from page 5\" style=\"width: auto/; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "70590579",
+ "metadata": {},
+ "source": [
+ "**Example:**\n",
+ "\n",
+ "User: “Change my reservation to 7pm.”\n",
+ "\n",
+ "- **Crawl:** You feed deterministic TTS for “Change my reservation to 7pm,” then grade only the next assistant turn: it should route to the reservation-update tool and pass the correct time=7pm (or ask one tight clarifying question if a required identifier is missing).\n",
+ "- **Walk:** Record a human-mic version of “Change my reservation to 7pm,” then replay the same utterance with phone-bandwidth compression and light background noise; the system should still hear “7pm” (not “7” or “7:15”) and produce the same correct tool call.\n",
+ "- **Run:** Model simulating a user outputs “Change my reservation to 7pm,” then simulates realistic follow-ups (“It’s under Minhajul for tonight… actually make it 7:30… wait, tomorrow”) plus an injected tool error once; the agent should clarify only what’s missing, keep state consistent, recover cleanly, and end with a single correct update tool call reflecting the final expected outcome.\n",
+ "\n",
+ "You can find reference implementations that you can start from and adapt here [realtime eval start](./evals/realtime_evals)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "52bc0ec2",
+ "metadata": {},
+ "source": [
+ "## Part III: The three building blocks\n",
+ "\n",
+ "### 4) Data: building a benchmark\n",
+ "\n",
+ "#### 4.1 Start with a “gold” seed set (10–50)\n",
+ "\n",
+ "Cover the flows you cannot afford to fail: core intents, must-work tool calls, escalation and refusal behaviors. Generate quickly, then have humans review for realism and gaps.\n",
+ "\n",
+ "**The goal is to start, not to perfect.**\n",
+ "\n",
+ "#### 4.2 Build for iteration, not just volume\n",
+ "\n",
+ "Eval datasets exist to drive iteration, not to look big. The loop is the product: **run evals → localize failures to a specific behavior → change one thing → re-run → confirm the fix improved without regressions**. A benchmark is “good” if it makes that loop fast, repeatable, and easy to diagnose.\n",
+ "\n",
+ "That requires coverage, not raw count: you need to represent the actual user behaviors and the specific edge cases that cause production failures. Size alone won’t surface fragility; the right coverage will. \n",
+ "\n",
+ "Coverage also has to be balanced. For every behavior, include both positives (the system should do X) and negatives (the system should not do X). Without negatives, you reward shortcuts.\n",
+ "\n",
+ ">**Customer Example:** A team built a voice support bot and optimized hard for the “escalate_to_human” tool call. Their offline score hit 98 percent on escalation. In dogfooding, the bot started escalating for almost everything. The root cause was dataset imbalance. They had many “must escalate” cases and almost no “do not escalate” cases, so the model learned a shortcut: escalate whenever uncertain. \n",
+ "\n",
+ "Finally, you must precisely tag your data to enable fine-grain evaluations. These tags should provide the necessary detail to move from a general observation, like \"score dropped,\" to a specific root cause, such **as \"this intent fails under these audio conditions with this policy boundary.\"**\n",
+ "\n",
+ "Example of tags could be:\n",
+ "\n",
+ "- intent, expected outcome, audio condition, language, and expected tool call. Tagged data enables teams to run fine-grain evaluations leading to faster iteration loops."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a591cdb",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_07_image_01.png\" alt=\"Diagram from page 7\" style=\"width: auto; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3c7cfb13",
+ "metadata": {},
+ "source": [
+ "#### 4.3 Expand from production failures\n",
+ "\n",
+ "Offline evals are how you iterate fast. They are also easy to outgrow. If you keep optimizing against a fixed benchmark, **scores can rise while real quality (reality) stalls** because users do things your dataset does not cover."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "68be4755",
+ "metadata": {},
+ "source": [
+ " <div class=\"diagram\" style=\"text-align: center;\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_07_image_02.png\" alt=\"Diagram from page 7\" style=\"width: 60%; height: auto; display: inline-block;\"/>\n",
+ " </div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3b23efdf",
+ "metadata": {},
+ "source": [
+ "The operating model is a loop: production expands the benchmark. A new failure shows up, you reproduce it, you label it, and you add it. Over time, your offline suite should grow with the product.\n",
+ "\n",
+ "**A simple way to manage this is three sets:**\n",
+ "\n",
+ "- **Regression suite:** hard cases you already fixed. Run on every prompt, model, and tool change. This is your “do not break” contract.\n",
+ "\n",
+ "- **Rolling discovery set:** fresh failures from production and near misses. This is where you learn what you are missing and what to prioritize next. If they trigger failure modes, promote them to **your offline dataset. Teams usually fill this by:**\n",
+ "\n",
+ " - Running online graders to catch failures directly, and/or\n",
+ "\n",
+ " - Watching proxy metrics (latency, tool error rates, escalation rate, retries) and sampling data when they drift.\n",
+ "- **Holdout set:** a subset of the offline test which stays untouched that you run occasionally to detect benchmark overfitting. If test scores climb while holdout stays flat, you are training for the test."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "785fa85a",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\" style=\"text-align: center;\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_08_image_01.png\" alt=\"Diagram from page 8\" style=\"width: 60%; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "996ceb4e",
+ "metadata": {},
+ "source": [
+ "### 5) Graders\n",
+ "\n",
+ "Graders are your **measurement instruments**. They turn a messy, real-time voice session into **signals you can trust**.\n",
+ "\n",
+ "#### 5.1 Manual review (highest leverage)\n",
+ "\n",
+ "Manual review = listen to real audio + read full traces end-to-end. It’s the fastest way to build product intuition and catch the failures users notice instantly. Automated evals tell you what you can measure. Manual review tells you what you should be measuring.\n",
+ "\n",
+ "**What automation routinely underweights (but users feel immediately):**\n",
+ "\n",
+ "- Turn-taking failures: awkward gaps, double-talk, model cutting the user off.\n",
+ "\n",
+ "- Pacing & prosody: model speech is too fast/slow, rambling, flat, jittery, “robot polite.”\n",
+ "\n",
+ "- Transcript mismatch: ASR lag/drops/normalization → you end up grading the wrong thing.\n",
+ "\n",
+ "- Eval-system bugs: missing coverage in the golden set, mislabeled expectations, graders that are systematically too strict/lenient. \n",
+ "\n",
+ "> **Customer Example:** one large company had execs spend **~3 hours/day** just listening to sessions and scanning traces. They surfaced “hidden” issues, early cutoffs, phantom interruptions, awkward prosody, that would’ve sailed past offline evals.\n",
+ "\n",
+ "#### 5.2 Automated graders\n",
+ "\n",
+ "Humans don’t scale. Without automation, regressions slip through and “improvements” turn into vibes.\n",
+ "\n",
+ "**Use a layered grader stack:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0157c176",
+ "metadata": {},
+ "source": [
+ "1. **Deterministic graders** for anything objective and machine-checkable. They’re fast, cheap, and stable, perfect for tight iteration loops and regression gates (tool calling, JSON validity, string and pattern checks).\n",
+ "\n",
+ "2. **LLM graders** help you measure the things that matter but don’t fit neatly into deterministic rules: correctness, instruction following, whether a clarification was appropriate, completeness, and helpfulness.\n",
+ "\n",
+ "3. **Audio graders** because users experience the voice, not the transcript. Audio is still the hardest to judge reliably, so don’t wait for a single perfect scorer, start with simple, measurable checks (silence, overlap, interruption handling) and layer richer rubrics over time."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "28efb845",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_09_image_01.png\" alt=\"Diagram from page 9\" style=\"width: auto; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ee3252bf",
+ "metadata": {},
+ "source": [
+ "### 6) Eval Harness\n",
+ "\n",
+ "A realtime eval is only as trustworthy as the harness that runs it. A good harness has one job: **make runs comparable**. If the same input can’t be replayed under the same settings and produce similar outcomes, it makes it hard to measure and iterate.\n",
+ "\n",
+ "#### 6.1 Start with single-turn replay (the “Crawl” harness)\n",
+ "\n",
+ "Start here. Single-turn replay gives the fastest, cleanest signal because you can keep almost everything fixed. Keep the exact audio bytes, preprocessing, VAD configuration, codec, and chunking strategy identical across runs.\n",
+ "\n",
+ "In practice, it’s often best to start with voice activity detection (VAD) turned off so you remove one major source of variance. With VAD off, you decide exactly when a user turn ends.\n",
+ "\n",
+ "**A simple single-turn harness looks like:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "65abb0c8",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_10_image_01.png\" alt=\"Diagram from page 10\" style=\"width: auto; height: auto;\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0bd80a2d",
+ "metadata": {},
+ "source": [
+ "**More explicitly (in Realtime API terms):**\n",
+ "\n",
+ "1. Generate or load input audio\n",
+ "\n",
+ " - If the datapoint is text, generate TTS audio.\n",
+ " - Often, starting with text → TTS → audio is the best first step because it enables much faster iteration. It’s easier to tweak and refine the eval when you can iterate on text quickly.\n",
+ "\n",
+ "2. Stream audio into the input buffer\n",
+ "\n",
+ " - Send audio in fixed-size chunks (for example: consistent frame size per chunk).\n",
+ "\n",
+ " - Important: chunking and timing affect behavior. Pick a standard and stick to it. For example, 20 ms per chunk is a good balance of responsiveness and overhead.\n",
+ "\n",
+ "3. Commit the user audio\n",
+ "\n",
+ " - (Recommended) With VAD off: commit immediately after the last audio chunk.\n",
+ "\n",
+ " - With VAD on: the server detects turns boundaries.\n",
+ "\n",
+ "4. Trigger the assistant response\n",
+ "\n",
+ " - With VAD off: Call response.create to start generation.\n",
+ "\n",
+ " - With VAD on: It is automatic.\n",
+ "\n",
+ "5. Collect outputs\n",
+ "\n",
+ " - Output audio chunks (streaming deltas)\n",
+ "\n",
+ " - Output transcript (if enabled)\n",
+ "\n",
+ " - Tool calls / tool arguments (if any)\n",
+ "\n",
+ " - Final completion event\n",
+ "\n",
+ "6. Grade and persist\n",
+ " - Run graders\n",
+ "\n",
+ " - Save results"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "56bbacd7",
+ "metadata": {},
+ "source": [
+ "#### 6.2 Replaying saved audio (the “Walk” harness)\n",
+ "\n",
+ "When you move from synthetic TTS to real recordings, the harness changes in one important way: **you are streaming audio buffers from saved realistic audio.**\n",
+ "\n",
+ "**For saved audio, the flow becomes:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4eb150f0",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_10_image_02.png\" alt=\"Diagram from page 10\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ca3f4dbc",
+ "metadata": {},
+ "source": [
+ "**How to make the evals realistic in practice:**\n",
+ "\n",
+ "- **Preprocessing must match production**\n",
+ " - Same resampling, normalization, channel handling, noise suppression (if used), and encoding.\n",
+ "\n",
+ " - Store preprocessing config alongside results so you can explain score changes.\n",
+ "\n",
+ "- **Streaming policy must be explicit**\n",
+ "\n",
+ " - If you care about latency: send chunks on a fixed cadence (e.g., “every 20ms, send 20ms of audio”).\n",
+ "\n",
+ " - If you only care about iteration speed: you can stream faster, but keep chunk size constant.\n",
+ "\n",
+ "- **Turn boundaries must be repeatable**\n",
+ "\n",
+ " - Prefer VAD off + manual commit for offline reproducibility.\n",
+ "\n",
+ " - If you must use VAD on (to match production), log VAD settings and track boundary events so you can debug failures.\n",
+ "\n",
+ "#### 6.3 Model-simulated multi-turn (the “Run” harness)\n",
+ "\n",
+ "Model-simulated multi-turn uses a **user simulator** to generate the next user turn for a full conversation. It can increase coverage of scenarios, but only if episodes stay comparable across runs.\n",
+ "\n",
+ "**Common loop:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ea242990",
+ "metadata": {},
+ "source": [
+ "<div class=\"diagram\">\n",
+ " <img src=\"../images/realtime_eval_guide/page_11_image_01.png\" alt=\"Diagram from page 11\"/>\n",
+ "</div>"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7acb75df",
+ "metadata": {},
+ "source": [
+ "**Best practice for simulations:**\n",
+ "\n",
+ "- **Pin and version the simulator prompt:** Treat it like code. A small prompt edit can shift behavior more than a model change.\n",
+ "\n",
+ "- **Constrain randomness:** Fix temperature and sampling settings. Use a seed if available. Use deterministic turns where it makes sense (i.e User greetings).\n",
+ "\n",
+ "- **Mock tools deterministically:** Define expected tool output mocks for the scenario and return those exact outputs when the assistant calls tools. This keeps the environment stable and makes runs comparable.\n",
+ "\n",
+ "- **Record the full trajectory:** Store every generated user text turn plus the final audio bytes you streamed. Persist tool calls, tool returns, and timestamps. Simulation is a discovery engine. When it finds a real failure mode, you backfill it into a deterministic scripted episode for the crawl or walk method."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "749dc2cd",
+ "metadata": {},
+ "source": [
+ "## Part IV: Case study\n",
+ "\n",
+ "#### 7.1 Customer support voice bot\n",
+ "\n",
+ "**Product goal and constraints**\n",
+ "\n",
+ "Resolve common support requests through tools, quickly and safely. The bot must collect the right details, call the right backend actions, and comply with policy. It must escalate cleanly when it cannot help. It must handle frustrated callers without becoming verbose or brittle.\n",
+ "\n",
+ "**Crawl, Walk, Run plan**\n",
+ "\n",
+ "**Crawl: synthetic + single-turn**\n",
+ "\n",
+ "Focus on routing and policy. Given a short request, the bot should pick the right intent, request missing info, and avoid unsafe actions. Use deterministic synthetic audio so you can rapidly iterate on tool schemas and prompts.\n",
+ "\n",
+ "**Walk: real + single-turn**\n",
+ "\n",
+ "Test understanding under realistic capture. Use synthetic or real recordings in noisy environments and telephony-like quality. This is where order numbers, names, and addresses break on noisy audio. Evaluate whether the bot asks clarifying questions instead of guessing.\n",
+ "\n",
+ "**Run: synthetic + multi-turn simulations**\n",
+ "\n",
+ "Simulate full workflows with simulated users with gpt-realtime and tool mocks: authentication, account lookup, order status, return eligibility, refund, ticket creation, escalation. Add adversarial but realistic patterns: caller changes goal midstream, provides partial info, talks over the assistant, or answers a different question than asked.\n",
+ "\n",
+ "**Manual Review:**\n",
+ "\n",
+ "Run internal call sessions against staging systems. This catches UX failures that graders miss: overlong disclaimers, repetitive questions, poor turn-taking during authentication.\n",
+ "\n",
+ "**Core dataset buckets and useful slices**\n",
+ "\n",
+ "- Top intents: order status, return, refund, cancel, billing issue, password reset, appointment scheduling.\n",
+ "\n",
+ "- Missing and conflicting info: wrong order number, two accounts, caller provides a nickname, caller refuses to authenticate.\n",
+ "\n",
+ "- Policy edges: out-of-window returns, restricted items, partial refunds, subscription cancellation rules.\n",
+ "\n",
+ "- Escalation triggers: the bot should hand off when confidence is low or tools fail.\n",
+ "\n",
+ "- Emotional tone: angry, rushed, confused. The content goal stays the same, but delivery matters.\n",
+ "\n",
+ "**Graders used**\n",
+ "\n",
+ "- Deterministic: tool selection, tool argument validity, policy phrases if required.\n",
+ "\n",
+ "- LLM rubric grader: instruction following, resolution correctness, empathetic tone, whether it avoided hallucinating policy, whether it escalated appropriately, and whether it stayed concise.\n",
+ "\n",
+ "- Audio grader: long silences, interruption handling."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "openai",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.9"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/examples/evals/realtime_evals/README.md b/examples/evals/realtime_evals/README.md
new file mode 100644
index 00000000..19bdc949
--- /dev/null
+++ b/examples/evals/realtime_evals/README.md
@@ -0,0 +1,92 @@
+# Realtime Evals
+
+This folder contains three evaluation harnesses for the Realtime API that increase in complexity:
+**crawl → walk → run**.
+
+- **crawl**: synthetic single-turn (TTS → stream → grade)
+- **walk**: deterministic replay of saved phone-audio (more realistic, still comparable)
+- **run**: model-simulated multi-turn conversations (finds multi-turn/tooling failures)
+
+Depending on your realtime eval maturity, point Codex (or your preferred coding assistant) to the folder that fits your use case so it can adapt the harness and bootstrap sample data; you can also have it run the included tests to confirm everything works.
+
+## Quickstart
+
+Python 3.9+ required.
+
+```bash
+pip install -r requirements.txt
+export OPENAI_API_KEY="your_api_key"
+```
+
+Run a first command per harness:
+
+- Crawl: `python crawl_harness/run_realtime_evals.py`
+- Walk: install ffmpeg (`brew install ffmpeg`), then:
+ - `python walk_harness/generate_audio.py`
+ - `python walk_harness/run_realtime_evals.py`
+- Run: `python run_harness/run_realtime_evals.py --max-examples 1`
+
+## [Crawl (synthetic single-turn)](./crawl_harness)
+
+**Best for:** Fast iteration and controlled comparisons.
+
+- Uses text prompts from a CSV and synthesizes TTS audio per row.
+- Streams fixed-size audio chunks into a realtime session.
+- Captures the first assistant turn and grades tool-call correctness.
+- Writes results, summary metrics, audio, and event logs per datapoint.
+
+Run:
+
+```
+python crawl_harness/run_realtime_evals.py
+```
+
+## [Walk (saved audio replay)](./walk_harness)
+
+**Best for:** Realism with reproducibility.
+
+- Replays saved, phone-compressed audio (G.711 mu-law WAV at 8 kHz).
+- Keeps chunking and turn boundaries fixed (VAD off).
+- Captures responses, tool calls, latencies, and event logs per datapoint.
+- Output audio is saved as PCM16 WAV for easy listening.
+
+Run:
+
+```
+python walk_harness/generate_audio.py
+python walk_harness/run_realtime_evals.py
+```
+
+## [Run (multi-turn simulation)](./run_harness)
+
+**Best for:** Discovering multi-turn failures and tool behavior.
+
+- Uses a simulator model to generate user turns and an assistant model under test.
+- Streams simulator audio into the assistant with fixed chunking.
+- Mocks tool outputs deterministically and grades with LLM-as-judge.
+- Writes results, summaries, transcripts, and event logs per simulation.
+
+Run:
+
+```
+python run_harness/run_realtime_evals.py
+```
+
+## Results layout
+
+Each harness writes into its own `results/` folder:
+
+- `results/<run_id>/results.csv`: per-example outputs and grades
+- `results/<run_id>/summary.json`: aggregate metrics
+- `results/<run_id>/events/*.jsonl`: full realtime event stream per datapoint
+
+## Common CLI flags
+
+All harnesses share a core set of flags so you can switch between them easily:
+
+- `--data-csv`, `--results-dir`, `--run-name`
+- `--model` (assistant under test), `--system-prompt-file`, `--tools-file`
+- `--chunk-ms`, `--sample-rate-hz`, `--real-time`
+- `--max-examples` (quick smoke tests)
+
+Run harness adds multi-turn and simulator-specific flags (see its README).
diff --git a/examples/evals/realtime_evals/crawl_harness/README.md b/examples/evals/realtime_evals/crawl_harness/README.md
new file mode 100644
index 00000000..04bb02c5
--- /dev/null
+++ b/examples/evals/realtime_evals/crawl_harness/README.md
@@ -0,0 +1,80 @@
+# Crawl Harness
+
+Deterministic single-turn replay for Realtime evals. This harness feeds fixed audio
+inputs to a Realtime session so you can compare runs with minimal variance.
+It is best for quick iteration and controlled comparisons.
+
+## What it does
+
+- Loads a CSV of eval prompts from `crawl_harness/data/`.
+- Uses TTS to synthesize a fixed input audio file per row.
+- Streams audio into the Realtime API in fixed-size chunks.
+- Captures the first assistant turn (text/audio/tool calls).
+- Grades tool-call correctness and tool-call-arg correctness only.
+- Writes artifacts into `crawl_harness/results/<run_id>/`.
+
+## Inputs
+
+CSV columns (required):
+
+- `example_id`: Unique ID for the datapoint.
+- `user_text`: Text prompt to synthesize into audio.
+- `gt_tool_call`: Expected tool name or empty if no tool call is expected.
+- `gt_tool_call_arg`: Expected tool arguments as JSON string or empty.
+
+## Outputs
+
+Each run writes:
+
+- `results.csv`: Per-example outputs and grades.
+- `summary.json`: Aggregate metrics (latency + correctness).
+- `audio/<example_id>/input.wav`: The TTS input audio.
+- `audio/<example_id>/output.wav`: The model output audio (if any).
+- `events/<example_id>.jsonl`: Realtime event stream for the datapoint.
+
+## How it works
+
+1. TTS generates PCM audio for each row.
+2. PCM is wrapped into a WAV file for easy playback.
+3. Audio is streamed into a Realtime session with fixed chunk sizes.
+4. The harness listens for `response.done` and records tool calls + output.
+5. Grades are computed:
+ - `tool_call_correctness`: correct tool chosen (or no tool call when none expected).
+ - `tool_call_arg_correctness`: expected args present in the tool call.
+
+## Run
+
+From repo root:
+
+```bash
+python crawl_harness/run_realtime_evals.py
+```
+
+Common options:
+
+- `--data-csv`: Path to a CSV file.
+- `--results-dir`: Output folder (defaults to `crawl_harness/results`).
+- `--run-name`: Optional run name (defaults to timestamp).
+- `--model`: Realtime model name.
+- `--tts-model`: TTS model name.
+- `--system-prompt-file`: System prompt file path.
+- `--tools-file`: Tools JSON file path.
+- `--voice`: Output voice name.
+- `--chunk-ms`: Audio chunk size in ms.
+- `--sample-rate-hz`: Input sample rate in Hz.
+- `--input-audio-format`: Input audio format (default `pcm16`).
+- `--output-audio-format`: Output audio format (default `pcm16`).
+- `--real-time`: Stream audio in real-time cadence.
+- `--max-examples`: Limit number of examples for quick checks.
+
+## Adapt
+
+- Add or replace rows in `crawl_harness/data/customer_service_synthetic.csv`.
+- Change tools or system prompt in `shared/`.
+- Update grading logic in `run_realtime_evals.py`.
+
+## Notes
+
+- The harness only evaluates the first assistant turn and does not provide tool outputs.
+- `results.csv` includes an `event_log_path` column pointing to the JSONL trace.
+- If you expect tools to be called reliably, adjust the system prompt or tool choice.
diff --git a/examples/evals/realtime_evals/crawl_harness/data/customer_service_synthetic.csv b/examples/evals/realtime_evals/crawl_harness/data/customer_service_synthetic.csv
new file mode 100644
index 00000000..8cda0454
--- /dev/null
+++ b/examples/evals/realtime_evals/crawl_harness/data/customer_service_synthetic.csv
@@ -0,0 +1,12 @@
+example_id,user_text,gt_tool_call,gt_tool_call_arg
+cs_001,"Hi, can you check the status of my order A12345?",get_order_status,"{""order_id"":""A12345""}"
+cs_002,"My order B67890 arrived damaged. I want a refund.",refund_order,"{""order_id"":""B67890""}"
+cs_003,"Please change the shipping address on order C24680 to 123 Pine St, Austin TX.",update_shipping_address,"{""order_id"":""C24680"",""new_address"":""123 Pine St, Austin TX""}"
+cs_004,"Where is my package for order D13579? It is late.",get_order_status,"{""order_id"":""D13579""}"
+cs_005,"I need to cancel order E11223 before it ships.",refund_order,"{""order_id"":""E11223""}"
+cs_006,"I was double charged for order F44556 and need help.",refund_order,"{""order_id"":""F44556""}"
+cs_007,"What is the estimated delivery date for order G77889?",get_order_status,"{""order_id"":""G77889""}"
+cs_008,"Update the shipping address for order H99001 to 55 Market St, San Francisco.",update_shipping_address,"{""order_id"":""H99001"",""new_address"":""55 Market St, San Francisco""}"
+cs_009,"Thanks for the help earlier. That's all I needed.",,
+cs_010,"Hello, I just want to leave positive feedback about your support team.",,
+cs_011,"What are your customer support hours?",,
diff --git a/examples/evals/realtime_evals/crawl_harness/run_realtime_evals.py b/examples/evals/realtime_evals/crawl_harness/run_realtime_evals.py
new file mode 100644
index 00000000..09e825c4
--- /dev/null
+++ b/examples/evals/realtime_evals/crawl_harness/run_realtime_evals.py
@@ -0,0 +1,398 @@
+"""Realtime eval crawl harness runner.
+
+Deterministic single-turn replay for the Realtime API. This script:
+- Loads a CSV of text prompts.
+- Generates TTS audio for each row.
+- Streams audio in fixed-size chunks into a Realtime session.
+- Captures the first assistant turn (text/audio/tool calls).
+- Grades tool-call correctness and arg extraction.
+- Saves per-example audio and run artifacts in results/.
+
+Run:
+ python crawl_harness/run_realtime_evals.py
+
+Key outputs:
+ crawl_harness/results/<run_id>/results.csv
+ crawl_harness/results/<run_id>/summary.json
+ crawl_harness/results/<run_id>/audio/<example_id>/input.wav
+ crawl_harness/results/<run_id>/audio/<example_id>/output.wav
+"""
+
+import argparse
+import asyncio
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, cast
+
+import pandas as pd
+from openai import AsyncOpenAI, OpenAI
+from openai.types.realtime import (
+ RealtimeResponseCreateParamsParam,
+ RealtimeSessionCreateRequestParam,
+)
+from tqdm import tqdm
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+if str(ROOT_DIR) not in sys.path:
+ sys.path.insert(0, str(ROOT_DIR))
+
+from shared.graders import compute_tool_call_grade
+from shared.metrics_utils import add_numeric_summaries, order_columns
+from shared.realtime_harness_utils import (
+ audio_format_config,
+ collect_realtime_response,
+ ensure_dir,
+ stream_audio_to_connection,
+ write_pcm16_wav,
+)
+
+SHARED_DIR = ROOT_DIR / "shared"
+DEFAULT_DATA_CSV = (
+ ROOT_DIR / "crawl_harness" / "data" / "customer_service_synthetic.csv"
+)
+DEFAULT_RESULTS_DIR = ROOT_DIR / "crawl_harness" / "results"
+DEFAULT_SYSTEM_PROMPT_PATH = SHARED_DIR / "system_prompt.txt"
+DEFAULT_TOOLS_PATH = SHARED_DIR / "tools.json"
+
+DEFAULT_MODEL = "gpt-realtime"
+DEFAULT_TTS_MODEL = "gpt-4o-mini-tts"
+DEFAULT_VOICE = "marin"
+DEFAULT_CHUNK_MS = 20
+DEFAULT_SAMPLE_RATE_HZ = 24000
+DEFAULT_INPUT_AUDIO_FORMAT = "pcm16"
+DEFAULT_OUTPUT_AUDIO_FORMAT = "pcm16"
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Run realtime crawl evals with deterministic single-turn replay."
+ )
+ parser.add_argument("--data-csv", type=Path, default=DEFAULT_DATA_CSV)
+ parser.add_argument("--results-dir", type=Path, default=DEFAULT_RESULTS_DIR)
+ parser.add_argument("--run-name", type=str, default="")
+ parser.add_argument("--model", type=str, default=DEFAULT_MODEL)
+ parser.add_argument(
+ "--system-prompt-file", type=Path, default=DEFAULT_SYSTEM_PROMPT_PATH
+ )
+ parser.add_argument("--tools-file", type=Path, default=DEFAULT_TOOLS_PATH)
+ parser.add_argument("--voice", type=str, default=DEFAULT_VOICE)
+ parser.add_argument("--tts-model", type=str, default=DEFAULT_TTS_MODEL)
+ parser.add_argument("--chunk-ms", type=int, default=DEFAULT_CHUNK_MS)
+ parser.add_argument("--sample-rate-hz", type=int, default=DEFAULT_SAMPLE_RATE_HZ)
+ parser.add_argument(
+ "--input-audio-format", type=str, default=DEFAULT_INPUT_AUDIO_FORMAT
+ )
+ parser.add_argument(
+ "--output-audio-format", type=str, default=DEFAULT_OUTPUT_AUDIO_FORMAT
+ )
+ parser.add_argument(
+ "--real-time", action="store_true", help="Send audio at real-time cadence."
+ )
+ parser.add_argument(
+ "--max-examples",
+ type=int,
+ default=0,
+ help="Limit number of examples for quick checks.",
+ )
+ return parser.parse_args()
+
+
+def load_system_prompt(path: Path) -> str:
+ return path.read_text(encoding="utf-8").strip()
+
+
+def load_tools(path: Path) -> List[Dict[str, Any]]:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def load_dataset(path: Path) -> pd.DataFrame:
+ data = pd.read_csv(path)
+ required_columns = {
+ "example_id",
+ "user_text",
+ "gt_tool_call",
+ "gt_tool_call_arg",
+ }
+ missing = required_columns.difference(data.columns)
+ if missing:
+ raise ValueError(f"Missing required columns: {sorted(missing)}")
+ return data
+
+
+def tts_to_pcm_bytes(client: OpenAI, text: str, model: str, voice: str) -> bytes:
+ with client.audio.speech.with_streaming_response.create(
+ model=model,
+ voice=voice,
+ input=text,
+ response_format="pcm",
+ ) as response:
+ audio_chunks = [chunk for chunk in response.iter_bytes()]
+ return b"".join(audio_chunks)
+
+async def run_single_eval(
+ async_client: AsyncOpenAI,
+ tts_client: OpenAI,
+ row: pd.Series,
+ system_prompt: str,
+ tools: List[Dict[str, Any]],
+ run_audio_dir: Path,
+ run_events_dir: Path,
+ config: Dict[str, Any],
+) -> Dict[str, Any]:
+ example_id = str(row["example_id"])
+ user_text = str(row["user_text"])
+ expected_tool_call = (
+ "" if bool(pd.isna(row["gt_tool_call"])) else str(row["gt_tool_call"])
+ )
+ expected_tool_call_arg = (
+ "" if bool(pd.isna(row["gt_tool_call_arg"])) else str(row["gt_tool_call_arg"])
+ )
+
+ example_audio_dir = run_audio_dir / example_id
+ ensure_dir(example_audio_dir)
+ input_audio_path = example_audio_dir / "input.wav"
+ input_audio_bytes = tts_to_pcm_bytes(
+ tts_client, user_text, config["tts_model"], config["voice"]
+ )
+ write_pcm16_wav(input_audio_path, input_audio_bytes, config["sample_rate_hz"])
+
+ async with async_client.realtime.connect(model=config["model"]) as connection:
+ # Disable VAD/turn detection so turn boundaries are controlled explicitly via
+ # `input_audio_buffer.commit()` for reproducibility across runs.
+ session = {
+ "type": "realtime",
+ "instructions": system_prompt,
+ "tools": tools,
+ "tool_choice": "auto",
+ "output_modalities": ["audio"],
+ "audio": {
+ "input": {
+ "format": audio_format_config(
+ config["input_audio_format"], config["sample_rate_hz"]
+ ),
+ "turn_detection": None,
+ },
+ "output": {
+ "format": audio_format_config(
+ config["output_audio_format"], config["sample_rate_hz"]
+ ),
+ "voice": config["voice"],
+ },
+ },
+ }
+ await connection.session.update(
+ session=cast(RealtimeSessionCreateRequestParam, session)
+ )
+
+ await stream_audio_to_connection(
+ connection,
+ input_audio_bytes,
+ config["chunk_ms"],
+ config["sample_rate_hz"],
+ config["input_audio_format"],
+ config["real_time"],
+ )
+
+ response_payload: RealtimeResponseCreateParamsParam = {}
+ events_path = run_events_dir / f"{example_id}.jsonl"
+ with events_path.open("w", encoding="utf-8") as log_file:
+ # Record the full event stream so regressions are easy to debug later.
+ response_result = await collect_realtime_response(
+ connection, response_payload, log_file=log_file
+ )
+
+ assistant_text = response_result["assistant_text"]
+ tool_calls = response_result["tool_calls"]
+ output_audio_bytes = response_result["output_audio_bytes"]
+ tool_call_grade_data = compute_tool_call_grade(
+ expected_tool_call, expected_tool_call_arg, tool_calls
+ )
+ tool_call_correctness = tool_call_grade_data["tool_call_correctness"]
+ tool_call_arg_correctness = tool_call_grade_data["tool_call_arg_correctness"]
+ grade = 1 if tool_call_correctness == 1 and tool_call_arg_correctness == 1 else 0
+
+ output_audio_path = ""
+ if output_audio_bytes:
+ output_audio_path = str(example_audio_dir / "output.wav")
+ write_pcm16_wav(
+ Path(output_audio_path), output_audio_bytes, config["sample_rate_hz"]
+ )
+
+ usage_data = response_result["usage"]
+ usage_output_tokens = usage_data.get("output_tokens", None)
+ usage_output_audio_tokens = None
+ usage_output_text_tokens = None
+ if "output_token_details" in usage_data:
+ output_details = usage_data["output_token_details"]
+ usage_output_audio_tokens = output_details.get("audio_tokens")
+ usage_output_text_tokens = output_details.get("text_tokens")
+
+ return {
+ "example_id": example_id,
+ "user_text": user_text,
+ "gt_tool_call": expected_tool_call,
+ "gt_tool_call_arg": expected_tool_call_arg,
+ "input_audio_path": str(input_audio_path),
+ "assistant_text": assistant_text,
+ "output_audio_path": output_audio_path,
+ "event_log_path": str(events_path),
+ "tool_calls": json.dumps(tool_calls),
+ "pred_tool_call": tool_call_grade_data["pred_tool_call"],
+ "pred_tool_call_arg": tool_call_grade_data["pred_tool_call_arg"],
+ "tool_call_correctness": tool_call_correctness,
+ "tool_call_arg_correctness": tool_call_arg_correctness,
+ "grade": grade,
+ "latency_first_audio_ms": response_result["first_audio_time_ms"],
+ "latency_first_text_ms": response_result["first_text_time_ms"],
+ "latency_response_done_ms": response_result["response_done_time_ms"],
+ "output_tokens": usage_output_tokens,
+ "output_audio_tokens": usage_output_audio_tokens,
+ "output_text_tokens": usage_output_text_tokens,
+ }
+
+
+def compute_summary(results: pd.DataFrame) -> Dict[str, Any]:
+ summary: Dict[str, Any] = {
+ "total_examples": int(results.shape[0]),
+ "grade_mean": float(results["grade"].mean()) if not results.empty else 0.0,
+ }
+ if "tool_call_correctness" in results.columns and not results.empty:
+ summary["tool_call_correctness_mean"] = float(
+ results["tool_call_correctness"].mean()
+ )
+ if "tool_call_arg_correctness" in results.columns and not results.empty:
+ summary["tool_call_arg_correctness_mean"] = float(
+ results["tool_call_arg_correctness"].mean()
+ )
+
+ add_numeric_summaries(
+ summary,
+ results,
+ [
+ "latency_first_audio_ms",
+ "latency_first_text_ms",
+ "latency_response_done_ms",
+ "output_tokens",
+ "output_audio_tokens",
+ "output_text_tokens",
+ ],
+ )
+
+ return summary
+
+
+def order_result_columns(results: pd.DataFrame) -> pd.DataFrame:
+ preferred = [
+ "example_id",
+ "user_text",
+ "gt_tool_call",
+ "pred_tool_call",
+ "gt_tool_call_arg",
+ "pred_tool_call_arg",
+ "tool_call_correctness",
+ "tool_call_arg_correctness",
+ "grade",
+ "assistant_text",
+ "tool_calls",
+ "event_log_path",
+ "input_audio_path",
+ "output_audio_path",
+ "latency_first_audio_ms",
+ "latency_first_text_ms",
+ "latency_response_done_ms",
+ "output_tokens",
+ "output_audio_tokens",
+ "output_text_tokens",
+ ]
+ return order_columns(results, preferred)
+
+
+async def run_evals() -> None:
+ args = parse_args()
+
+ system_prompt = load_system_prompt(args.system_prompt_file)
+ tools = load_tools(args.tools_file)
+ dataset = load_dataset(args.data_csv)
+ if args.max_examples > 0:
+ dataset = dataset.head(args.max_examples)
+
+ run_timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
+ run_name = args.run_name or run_timestamp
+ run_dir = args.results_dir / run_name
+ run_audio_dir = run_dir / "audio"
+ run_events_dir = run_dir / "events"
+ ensure_dir(run_audio_dir)
+ ensure_dir(run_events_dir)
+
+ config = {
+ "model": args.model,
+ "tts_model": args.tts_model,
+ "voice": args.voice,
+ "chunk_ms": args.chunk_ms,
+ "sample_rate_hz": args.sample_rate_hz,
+ "input_audio_format": args.input_audio_format,
+ "output_audio_format": args.output_audio_format,
+ "real_time": args.real_time,
+ }
+
+ async_client = AsyncOpenAI()
+ tts_client = OpenAI()
+
+ results: List[Dict[str, Any]] = []
+ total_examples = int(dataset.shape[0])
+ print(f"Running crawl evals: {total_examples} examples -> {run_dir}")
+ for _, row in tqdm(dataset.iterrows(), total=total_examples, desc="Crawl evals"):
+ result = await run_single_eval(
+ async_client,
+ tts_client,
+ row,
+ system_prompt,
+ tools,
+ run_audio_dir,
+ run_events_dir,
+ config,
+ )
+ results.append(result)
+
+ results_df = pd.DataFrame(results)
+ results_df = order_result_columns(results_df)
+ results_csv_path = run_dir / "results.csv"
+ results_df.to_csv(results_csv_path, index=False)
+
+ summary = compute_summary(results_df)
+ summary.update(
+ {
+ "run_name": run_name,
+ "model": args.model,
+ "tts_model": args.tts_model,
+ "voice": args.voice,
+ "chunk_ms": args.chunk_ms,
+ "sample_rate_hz": args.sample_rate_hz,
+ "input_audio_format": args.input_audio_format,
+ "output_audio_format": args.output_audio_format,
+ "real_time": args.real_time,
+ "data_csv": str(args.data_csv),
+ "system_prompt_file": str(args.system_prompt_file),
+ "tools_file": str(args.tools_file),
+ }
+ )
+
+ summary_path = run_dir / "summary.json"
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
+ print(
+ "Summary:"
+ f" grade_mean={summary.get('grade_mean', 0):.3f}"
+ f" tool_call_correctness_mean={summary.get('tool_call_correctness_mean', 0):.3f}"
+ f" tool_call_arg_correctness_mean={summary.get('tool_call_arg_correctness_mean', 0):.3f}"
+ )
+ print(f"Wrote results to {run_dir}")
+
+
+def main() -> None:
+ asyncio.run(run_evals())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/evals/realtime_evals/requirements.txt b/examples/evals/realtime_evals/requirements.txt
new file mode 100644
index 00000000..b4697da5
--- /dev/null
+++ b/examples/evals/realtime_evals/requirements.txt
@@ -0,0 +1,2 @@
+openai==2.15.0
+pandas==2.3.3
diff --git a/examples/evals/realtime_evals/run_harness/README.md b/examples/evals/realtime_evals/run_harness/README.md
new file mode 100644
index 00000000..589f501e
--- /dev/null
+++ b/examples/evals/realtime_evals/run_harness/README.md
@@ -0,0 +1,64 @@
+# Run Harness
+
+Model-simulated multi-turn eval harness for the Realtime API. This harness uses
+one realtime model as the user simulator (audio-only) and another realtime model
+as the assistant under test. It replays fixed chunking (VAD off), mocks tools
+from the simulation JSON, and records full traces.
+
+## What it does
+
+- Loads `run_harness/data/simulations.csv` with pandas.
+- Reads per-simulation JSON files defining scenario, simulator identity, tool mocks,
+ and LLM-as-judge grading criteria.
+- Generates user audio turns via a realtime simulator model (audio-only).
+- Streams user audio to the assistant in fixed-size chunks and commits manually.
+- Captures assistant audio/text, tool calls, tool outputs, and latencies.
+- Grades turn-level and trace-level criteria with an LLM-as-judge.
+- Writes `results.csv`, `summary.json`, and full trace logs under `run_harness/results/`.
+
+## Files
+
+- `run_harness/run_realtime_evals.py`: Run harness script.
+- `run_harness/data/simulations.csv`: Index of simulation files.
+- `run_harness/data/sim_*.json`: Simulation definitions (this repo currently ships 3 examples).
+- `run_harness/results/<run_id>/events/*.jsonl`: Full event trace per simulation.
+- `run_harness/results/<run_id>/conversations/*.txt`: Human-readable transcript with tool calls.
+
+## Simulation definitions (high level)
+
+Each `sim_*.json` file defines:
+
+- **the scenario** (what the user is trying to do)
+- **tool mocks** (what each tool should return when called)
+- **judge rubric** (what should be graded per turn / overall)
+
+This lets you run repeatable multi-turn evals without needing live backend integrations.
+
+## How to run
+
+From repo root:
+
+```bash
+python run_harness/run_realtime_evals.py --max-examples 1
+```
+
+Common options:
+
+- `--data-csv`: Simulation index CSV.
+- `--model`: Alias for the assistant model under test.
+- `--assistant-model`: Realtime model under test (overrides `--model`).
+- `--simulator-model`: Realtime model used as the user.
+- `--system-prompt-file`: Alias for assistant system prompt file.
+- `--tools-file`: Alias for assistant tools file.
+- `--assistant-system-prompt-file`: Override assistant system prompt file (more specific).
+- `--assistant-tools-file`: Override tools file for the assistant (more specific).
+- `--simulator-system-prompt`: Override simulator system prompt (string).
+- `--chunk-ms`, `--sample-rate-hz`, `--real-time`.
+- `--max-turns`, `--max-examples`.
+
+Notes:
+
+- Temperature and max output tokens are intentionally not supported.
+- The simulator emits audio only. Transcripts are captured from audio deltas if available.
+- Tool outputs are mocked deterministically from each simulation JSON.
+- `results.csv` includes an `event_log_path` column pointing to the JSONL trace.
diff --git a/examples/evals/realtime_evals/run_harness/data/sim_cs_address_update.json b/examples/evals/realtime_evals/run_harness/data/sim_cs_address_update.json
new file mode 100644
index 00000000..43cee793
--- /dev/null
+++ b/examples/evals/realtime_evals/run_harness/data/sim_cs_address_update.json
@@ -0,0 +1,66 @@
+{
+ "simulation_id": "sim_cs_address_update",
+ "scenario": "User updates shipping address for a specific order.",
+ "assistant": {
+ "system_prompt_file": "shared/system_prompt.txt",
+ "tools_file": "shared/tools.json",
+ "model": "gpt-realtime"
+ },
+ "simulator": {
+ "system_prompt": "You are the user in a voice call. Stay in character and only say what the user would say. Never answer as the assistant.\n\nUser persona:\n- Name: Morgan Patel\n- Order ID: ORD-3003\n- Email: [email protected]\n- New address: 12 Harbor St, Apt 4B, Seattle, WA 98101\n- Goal: Update the shipping address and receive confirmation.\n- Style: Friendly, brief.\n\nRules:\n- Reply in 1-2 short sentences as the user.\n- If asked for the address or order ID, use the persona details.\n- Only use persona facts when asked. Do not invent new details.\n- Do not mention tools or system messages.\n- When the goal is satisfied, reply with exactly the single token: END_CALL (no other words or punctuation).",
+ "model": "gpt-realtime",
+ "voice": "marin"
+ },
+ "audio": {
+ "input_format": "pcm16",
+ "output_format": "pcm16",
+ "sample_rate_hz": 24000,
+ "chunk_ms": 20,
+ "real_time": true
+ },
+ "turns": {
+ "fixed_first_user_turn": "Please update the shipping address for order ORD-3003 to 12 Harbor St, Apt 4B, Seattle, WA 98101.",
+ "max_turns": 6
+ },
+ "tool_mocks": [
+ {
+ "name": "update_shipping_address",
+ "output": {
+ "order_id": "ORD-3003",
+ "status": "Address updated",
+ "address": "12 Harbor St, Apt 4B, Seattle, WA 98101"
+ }
+ }
+ ],
+ "expected_tool_call": {
+ "name": "update_shipping_address",
+ "arguments": {
+ "order_id": "ORD-3003",
+ "new_address": "12 Harbor St, Apt 4B, Seattle, WA 98101"
+ }
+ },
+ "graders": {
+ "turn_level": [
+ {
+ "id": "address_update_tool_call",
+ "type": "tool_call"
+ },
+ {
+ "id": "address_update_tool_call_args",
+ "type": "tool_call_args"
+ },
+ {
+ "id": "address_confirmation",
+ "type": "llm_as_judge",
+ "criteria": "Assistant confirms the address update in clear language."
+ }
+ ],
+ "trace_level": [
+ {
+ "id": "goal_completion",
+ "type": "llm_as_judge",
+ "criteria": "User goal is satisfied and the conversation ends politely."
+ }
+ ]
+ }
+}
diff --git a/examples/evals/realtime_evals/run_harness/data/sim_cs_order_status.json b/examples/evals/realtime_evals/run_harness/data/sim_cs_order_status.json
new file mode 100644
index 00000000..f890168c
--- /dev/null
+++ b/examples/evals/realtime_evals/run_harness/data/sim_cs_order_status.json
@@ -0,0 +1,65 @@
+{
+ "simulation_id": "sim_cs_order_status",
+ "scenario": "User asks for the status of a specific order and wants the estimated delivery date.",
+ "assistant": {
+ "system_prompt_file": "shared/system_prompt.txt",
+ "tools_file": "shared/tools.json",
+ "model": "gpt-realtime"
+ },
+ "simulator": {
+ "system_prompt": "You are the user in a voice call. Stay in character and only say what the user would say. Never answer as the assistant.\n\nUser persona:\n- Name: Jordan Lee\n- Order ID: ORD-1001\n- Email: [email protected]\n- Goal: Get the latest status and estimated delivery date for the order.\n- Style: Polite, brief, direct.\n\nRules:\n- Reply in 1-2 short sentences as the user.\n- Only use persona facts when asked. Do not invent new details.\n- Do not mention tools or system messages.\n- When the goal is satisfied, reply with exactly the single token: END_CALL (no other words or punctuation).",
+ "model": "gpt-realtime",
+ "voice": "marin"
+ },
+ "audio": {
+ "input_format": "pcm16",
+ "output_format": "pcm16",
+ "sample_rate_hz": 24000,
+ "chunk_ms": 20,
+ "real_time": true
+ },
+ "turns": {
+ "fixed_first_user_turn": "Hi, can you check the status of order ORD-1001?",
+ "max_turns": 6
+ },
+ "tool_mocks": [
+ {
+ "name": "get_order_status",
+ "output": {
+ "order_id": "ORD-1001",
+ "status": "In transit",
+ "estimated_delivery": "2026-01-25"
+ }
+ }
+ ],
+ "expected_tool_call": {
+ "name": "get_order_status",
+ "arguments": {
+ "order_id": "ORD-1001"
+ }
+ },
+ "graders": {
+ "turn_level": [
+ {
+ "id": "order_status_tool_call",
+ "type": "tool_call"
+ },
+ {
+ "id": "order_status_tool_call_args",
+ "type": "tool_call_args"
+ },
+ {
+ "id": "status_response_quality",
+ "type": "llm_as_judge",
+ "criteria": "Assistant clearly states the order status and delivery estimate after tool results."
+ }
+ ],
+ "trace_level": [
+ {
+ "id": "goal_completion",
+ "type": "llm_as_judge",
+ "criteria": "User goal is satisfied and conversation ends politely."
+ }
+ ]
+ }
+}
diff --git a/examples/evals/realtime_evals/run_harness/data/sim_cs_refund.json b/examples/evals/realtime_evals/run_harness/data/sim_cs_refund.json
new file mode 100644
index 00000000..dfc56327
--- /dev/null
+++ b/examples/evals/realtime_evals/run_harness/data/sim_cs_refund.json
@@ -0,0 +1,65 @@
+{
+ "simulation_id": "sim_cs_refund",
+ "scenario": "User requests a refund for a specific order.",
+ "assistant": {
+ "system_prompt_file": "shared/system_prompt.txt",
+ "tools_file": "shared/tools.json",
+ "model": "gpt-realtime"
+ },
+ "simulator": {
+ "system_prompt": "You are the user in a voice call. Stay in character and only say what the user would say. Never answer as the assistant.\n\nUser persona:\n- Name: Casey Kim\n- Order ID: ORD-2002\n- Email: [email protected]\n- Refund reason: Item arrived damaged.\n- Goal: Request a refund and receive confirmation.\n- Style: Polite, concise.\n\nRules:\n- Reply in 1-2 short sentences as the user.\n- If asked for a reason, use the persona reason.\n- Only use persona facts when asked. Do not invent new details.\n- Do not mention tools or system messages.\n- When the goal is satisfied, reply with exactly the single token: END_CALL (no other words or punctuation).",
+ "model": "gpt-realtime",
+ "voice": "marin"
+ },
+ "audio": {
+ "input_format": "pcm16",
+ "output_format": "pcm16",
+ "sample_rate_hz": 24000,
+ "chunk_ms": 20,
+ "real_time": true
+ },
+ "turns": {
+ "fixed_first_user_turn": "I want a refund for order ORD-2002.",
+ "max_turns": 6
+ },
+ "tool_mocks": [
+ {
+ "name": "refund_order",
+ "output": {
+ "order_id": "ORD-2002",
+ "status": "Refund requested",
+ "refund_reference": "RF-20002"
+ }
+ }
+ ],
+ "expected_tool_call": {
+ "name": "refund_order",
+ "arguments": {
+ "order_id": "ORD-2002"
+ }
+ },
+ "graders": {
+ "turn_level": [
+ {
+ "id": "refund_tool_call",
+ "type": "tool_call"
+ },
+ {
+ "id": "refund_tool_call_args",
+ "type": "tool_call_args"
+ },
+ {
+ "id": "refund_confirmation",
+ "type": "llm_as_judge",
+ "criteria": "Assistant confirms the refund request and provides a reference if available."
+ }
+ ],
+ "trace_level": [
+ {
+ "id": "goal_completion",
+ "type": "llm_as_judge",
+ "criteria": "User receives a clear refund confirmation and the conversation ends politely."
+ }
+ ]
+ }
+}
diff --git a/examples/evals/realtime_evals/run_harness/data/simulations.csv b/examples/evals/realtime_evals/run_harness/data/simulations.csv
new file mode 100644
index 00000000..bab4c0db
--- /dev/null
+++ b/examples/evals/realtime_evals/run_harness/data/simulations.csv
@@ -0,0 +1,4 @@
+simulation_id,simulation_path,enabled,notes,max_turns_override
+sim_cs_order_status,sim_cs_order_status.json,true,Order status with tool call,0
+sim_cs_refund,sim_cs_refund.json,true,Refund request with tool call,0
+sim_cs_address_update,sim_cs_address_update.json,true,Address update with tool call,0
diff --git a/examples/evals/realtime_evals/run_harness/run_realtime_evals.py b/examples/evals/realtime_evals/run_harness/run_realtime_evals.py
new file mode 100644
index 00000000..07f539bf
--- /dev/null
+++ b/examples/evals/realtime_evals/run_harness/run_realtime_evals.py
@@ -0,0 +1,808 @@
+"""Realtime eval run harness runner.
+
+Model-simulated multi-turn harness that uses a realtime model as the user
+(simulator) and another realtime model as the assistant under test. It streams
+simulator audio into the assistant with fixed chunking, mocks tools
+deterministically, and records full traces.
+
+Results:
+ run_harness/results/<run_id>/results.csv
+ run_harness/results/<run_id>/summary.json
+ run_harness/results/<run_id>/events/<simulation_id>.jsonl
+"""
+
+import argparse
+import asyncio
+import concurrent.futures
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, cast
+
+import pandas as pd
+from openai import AsyncOpenAI, BadRequestError, OpenAI
+from openai.types.realtime import RealtimeSessionCreateRequestParam
+from tqdm import tqdm
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+if str(ROOT_DIR) not in sys.path:
+ sys.path.insert(0, str(ROOT_DIR))
+
+from shared.graders import compute_tool_call_grade
+from shared.metrics_utils import add_grade_means, add_numeric_summaries, order_columns
+from shared.realtime_harness_utils import (
+ audio_format_config,
+ collect_realtime_response,
+ ensure_dir,
+ stream_audio_to_connection,
+ write_pcm16_wav,
+)
+
+DEFAULT_DATA_CSV = ROOT_DIR / "run_harness" / "data" / "simulations.csv"
+DEFAULT_RESULTS_DIR = ROOT_DIR / "run_harness" / "results"
+DEFAULT_ASSISTANT_MODEL = "gpt-realtime"
+DEFAULT_SIMULATOR_MODEL = "gpt-realtime"
+DEFAULT_JUDGE_MODEL = "gpt-5.1"
+DEFAULT_CHUNK_MS = 20
+DEFAULT_SAMPLE_RATE_HZ = 24000
+DEFAULT_INPUT_AUDIO_FORMAT = "pcm16"
+DEFAULT_OUTPUT_AUDIO_FORMAT = "pcm16"
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Run realtime multi-turn evals with a user simulator."
+ )
+ parser.add_argument("--data-csv", type=Path, default=DEFAULT_DATA_CSV)
+ parser.add_argument("--results-dir", type=Path, default=DEFAULT_RESULTS_DIR)
+ parser.add_argument("--run-name", type=str, default="")
+ parser.add_argument("--model", type=str, default="")
+ parser.add_argument("--assistant-model", type=str, default="")
+ parser.add_argument("--simulator-model", type=str, default="")
+ parser.add_argument("--system-prompt-file", type=Path, default=None)
+ parser.add_argument("--tools-file", type=Path, default=None)
+ parser.add_argument("--assistant-system-prompt-file", type=Path, default=None)
+ parser.add_argument("--assistant-tools-file", type=Path, default=None)
+ parser.add_argument("--simulator-system-prompt", type=str, default="")
+ parser.add_argument("--chunk-ms", type=int, default=DEFAULT_CHUNK_MS)
+ parser.add_argument("--sample-rate-hz", type=int, default=DEFAULT_SAMPLE_RATE_HZ)
+ parser.add_argument(
+ "--input-audio-format", type=str, default=DEFAULT_INPUT_AUDIO_FORMAT
+ )
+ parser.add_argument(
+ "--output-audio-format", type=str, default=DEFAULT_OUTPUT_AUDIO_FORMAT
+ )
+ parser.add_argument(
+ "--real-time", action="store_true", help="Send audio at real-time cadence."
+ )
+ parser.add_argument("--max-turns", type=int, default=0)
+ parser.add_argument("--max-examples", type=int, default=0)
+ parser.add_argument("--judge-model", type=str, default=DEFAULT_JUDGE_MODEL)
+ return parser.parse_args()
+
+
+def resolve_path(path_value: str, base_dir: Path) -> Path:
+ if not path_value:
+ raise ValueError("Path value is empty")
+ candidate = Path(path_value)
+ if not candidate.is_absolute():
+ candidate = base_dir / candidate
+ return candidate
+
+
+def load_system_prompt(path: Path) -> str:
+ return path.read_text(encoding="utf-8").strip()
+
+
+def load_tools(path: Path) -> List[Dict[str, Any]]:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def load_simulation_index(path: Path) -> pd.DataFrame:
+ data = pd.read_csv(path)
+ required_columns = {"simulation_id", "simulation_path"}
+ missing = required_columns.difference(data.columns)
+ if missing:
+ raise ValueError(f"Missing required columns: {sorted(missing)}")
+ return data
+
+
+def load_simulation(path: Path) -> Dict[str, Any]:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def extract_json_object(text: str) -> Dict[str, Any]:
+ if not text:
+ return {}
+ start = text.find("{")
+ end = text.rfind("}")
+ if start == -1 or end == -1 or end <= start:
+ return {}
+ try:
+ return json.loads(text[start : end + 1])
+ except json.JSONDecodeError:
+ return {}
+
+
+def compute_tool_outputs(
+ tool_calls: List[Dict[str, Any]], tool_mocks: Dict[str, Dict[str, Any]]
+) -> List[Dict[str, Any]]:
+ outputs = []
+ for call in tool_calls:
+ tool_name = call.get("name", "")
+ output = tool_mocks.get(tool_name, {"status": "Unsupported tool"})
+ outputs.append(
+ {
+ "call_id": call.get("call_id", ""),
+ "name": tool_name,
+ "arguments": call.get("arguments", {}),
+ "output": output,
+ }
+ )
+ return outputs
+
+
+def build_simulator_prompt_text(
+ history: List[Dict[str, str]], fixed_first_turn: str, turn_index: int
+) -> str:
+ if turn_index == 1:
+ return f"Repeat exactly the following user utterance:\n{fixed_first_turn}"
+
+ lines = ["Conversation so far:"]
+ for message in history:
+ role = message["role"].capitalize()
+ lines.append(f"{role}: {message['text']}")
+ lines.append("Next user response:")
+ return "\n".join(lines)
+
+
+def build_turn_context(
+ simulation_id: str,
+ scenario: str,
+ turn_index: int,
+ user_text: str,
+ assistant_text: str,
+ tool_calls: List[Dict[str, Any]],
+ tool_outputs: List[Dict[str, Any]],
+) -> str:
+ return (
+ f"Simulation: {simulation_id}\n"
+ f"Scenario: {scenario}\n"
+ f"Turn: {turn_index}\n"
+ f"User: {user_text}\n"
+ f"Assistant: {assistant_text}\n"
+ f"Tool Calls: {json.dumps(tool_calls)}\n"
+ f"Tool Outputs: {json.dumps(tool_outputs)}\n"
+ )
+
+
+def build_trace_context(
+ simulation_id: str,
+ scenario: str,
+ transcript_lines: List[str],
+ tool_summaries: List[str],
+) -> str:
+ transcript_text = "\n".join(transcript_lines)
+ tool_text = "\n".join(tool_summaries)
+ return (
+ f"Simulation: {simulation_id}\n"
+ f"Scenario: {scenario}\n"
+ "Conversation:\n"
+ f"{transcript_text}\n"
+ "Tools:\n"
+ f"{tool_text}\n"
+ )
+
+
+def run_llm_grade(
+ client: OpenAI,
+ model: str,
+ criteria: str,
+ context_text: str,
+) -> Dict[str, Any]:
+ instructions = (
+ "You are a strict evaluator. Return JSON only with keys "
+ "grade (0 or 1) and rationale (short)."
+ )
+ response_input = f"Criteria:\n{criteria}\n\nContext:\n{context_text}"
+ # A strict schema makes grading deterministic and easy to parse downstream.
+ grade_schema = {
+ "type": "object",
+ "additionalProperties": False,
+ "properties": {
+ "grade": {"type": "integer", "enum": [0, 1]},
+ "rationale": {"type": "string"},
+ },
+ "required": ["grade", "rationale"],
+ }
+ try:
+ # Structured outputs keeps grading deterministic and easier to parse.
+ response = client.responses.create(
+ model=model,
+ instructions=instructions,
+ input=response_input,
+ text={
+ "format": {
+ "type": "json_schema",
+ "name": "grade_result",
+ "strict": True,
+ "schema": grade_schema,
+ }
+ },
+ )
+ except BadRequestError:
+ # Some judge models may not support json_schema yet; keep a tight fallback.
+ response = client.responses.create(
+ model=model,
+ instructions=instructions,
+ input=response_input,
+ )
+
+ output_text = response.output_text.strip()
+ try:
+ parsed = json.loads(output_text)
+ except json.JSONDecodeError:
+ # This should be rare with structured outputs, but handle it defensively.
+ parsed = extract_json_object(output_text)
+ grade_value = parsed.get("grade")
+ normalized_grade = 1 if grade_value in (1, True) else 0
+ return {
+ "grade": normalized_grade,
+ "rationale": parsed.get("rationale", ""),
+ "raw_output": output_text,
+ }
+
+
+def execute_grade_job(job: Dict[str, Any]) -> Dict[str, Any]:
+ client = OpenAI()
+ grade_result = run_llm_grade(client, job["model"], job["criteria"], job["context"])
+ return {
+ "row_indices": job["row_indices"],
+ "grader_id": job["grader_id"],
+ "grade": grade_result["grade"],
+ "rationale": grade_result["rationale"],
+ }
+
+
+def compute_summary(results: pd.DataFrame) -> Dict[str, Any]:
+ summary: Dict[str, Any] = {
+ "total_rows": int(results.shape[0]),
+ }
+
+ add_grade_means(summary, results)
+ add_numeric_summaries(
+ summary,
+ results,
+ [
+ "latency_first_audio_ms",
+ "latency_first_text_ms",
+ "latency_response_done_ms",
+ "output_tokens",
+ "output_audio_tokens",
+ "output_text_tokens",
+ ],
+ )
+
+ return summary
+
+
+def order_result_columns(results: pd.DataFrame) -> pd.DataFrame:
+ preferred = [
+ "simulation_id",
+ "assistant_model",
+ "simulator_model",
+ "turn_index",
+ "user_text",
+ "assistant_text",
+ "tool_calls",
+ "tool_outputs",
+ "pred_tool_call",
+ "pred_tool_call_arg",
+ "user_audio_path",
+ "assistant_audio_path",
+ "latency_first_audio_ms",
+ "latency_first_text_ms",
+ "latency_response_done_ms",
+ "output_tokens",
+ "output_audio_tokens",
+ "output_text_tokens",
+ ]
+ return order_columns(results, preferred)
+
+
+async def run_simulation(
+ async_client: AsyncOpenAI,
+ simulation_row: pd.Series,
+ args: argparse.Namespace,
+ run_dir: Path,
+) -> Dict[str, Any]:
+ simulation_path = resolve_path(
+ str(simulation_row["simulation_path"]), args.data_csv.parent
+ )
+ simulation = load_simulation(simulation_path)
+
+ simulation_id = simulation.get(
+ "simulation_id", str(simulation_row["simulation_id"])
+ )
+ scenario = simulation.get("scenario", "")
+
+ assistant_config = simulation.get("assistant", {})
+ simulator_config = simulation.get("simulator", {})
+ audio_config = simulation.get("audio", {})
+ turns_config = simulation.get("turns", {})
+
+ assistant_model = (
+ args.assistant_model
+ or args.model
+ or assistant_config.get("model", DEFAULT_ASSISTANT_MODEL)
+ )
+ simulator_model = args.simulator_model or simulator_config.get(
+ "model", DEFAULT_SIMULATOR_MODEL
+ )
+
+ assistant_prompt_path = args.assistant_system_prompt_file or args.system_prompt_file
+ if assistant_prompt_path is None:
+ assistant_prompt_path = resolve_path(
+ assistant_config.get("system_prompt_file", ""), ROOT_DIR
+ )
+
+ assistant_tools_path = args.assistant_tools_file or args.tools_file
+ if assistant_tools_path is None:
+ assistant_tools_path = resolve_path(
+ assistant_config.get("tools_file", ""), ROOT_DIR
+ )
+
+ simulator_prompt = args.simulator_system_prompt or simulator_config.get(
+ "system_prompt", ""
+ )
+
+ if not simulator_prompt:
+ raise ValueError(f"Missing simulator system_prompt in {simulation_path}")
+
+ system_prompt = load_system_prompt(assistant_prompt_path)
+ tools = load_tools(assistant_tools_path)
+
+ input_audio_format = audio_config.get("input_format", args.input_audio_format)
+ output_audio_format = audio_config.get("output_format", args.output_audio_format)
+ sample_rate_hz = int(audio_config.get("sample_rate_hz", args.sample_rate_hz))
+ chunk_ms = int(audio_config.get("chunk_ms", args.chunk_ms))
+ real_time = bool(audio_config.get("real_time", args.real_time))
+
+ max_turns = int(turns_config.get("max_turns", 0))
+ if args.max_turns > 0:
+ max_turns = args.max_turns
+ if max_turns <= 0:
+ max_turns = 1
+
+ fixed_first_turn = turns_config.get("fixed_first_user_turn", "")
+ tool_mocks_list = simulation.get("tool_mocks", [])
+ tool_mocks = {
+ entry.get("name", ""): entry.get("output", {}) for entry in tool_mocks_list
+ }
+ expected_tool_call = simulation.get("expected_tool_call", {})
+ expected_tool_name = str(expected_tool_call.get("name", "")).strip()
+ expected_tool_args = expected_tool_call.get("arguments", {})
+ expected_tool_args_text = (
+ json.dumps(expected_tool_args) if expected_tool_args else ""
+ )
+
+ graders = simulation.get("graders", {})
+ turn_level_graders = graders.get("turn_level", [])
+ trace_level_graders = graders.get("trace_level", [])
+ tool_call_grader_ids = [
+ grader.get("id", "tool_call")
+ for grader in turn_level_graders
+ if grader.get("type") == "tool_call"
+ ]
+ tool_call_args_grader_ids = [
+ grader.get("id", "tool_call_args")
+ for grader in turn_level_graders
+ if grader.get("type") == "tool_call_args"
+ ]
+
+ run_audio_dir = run_dir / "audio" / simulation_id
+ run_events_dir = run_dir / "events"
+ run_conv_dir = run_dir / "conversations"
+ ensure_dir(run_audio_dir)
+ ensure_dir(run_events_dir)
+ ensure_dir(run_conv_dir)
+
+ trace_path = run_events_dir / f"{simulation_id}.jsonl"
+ transcript_path = run_conv_dir / f"{simulation_id}.txt"
+
+ conversation_history: List[Dict[str, str]] = []
+ transcript_lines: List[str] = []
+ tool_summaries: List[str] = []
+
+ results_rows: List[Dict[str, Any]] = []
+ turn_grade_requests: List[Dict[str, Any]] = []
+ trace_grade_requests: List[Dict[str, Any]] = []
+ any_tool_call_correctness = 0
+ any_tool_call_arg_correctness = 0
+ tool_call_correctness_flags: List[int] = []
+
+ assistant_voice = assistant_config.get("voice", "")
+ simulator_voice = simulator_config.get("voice", "")
+
+ # Disable turn detection (VAD) for both connections so this harness controls turn
+ # boundaries explicitly via `input_audio_buffer.commit()` (important for comparability).
+ assistant_session: Dict[str, Any] = {
+ "type": "realtime",
+ "instructions": system_prompt,
+ "tools": tools,
+ "tool_choice": "auto",
+ "audio": {
+ "input": {
+ "format": audio_format_config(input_audio_format, sample_rate_hz),
+ "turn_detection": None,
+ },
+ "output": {
+ "format": audio_format_config(output_audio_format, sample_rate_hz)
+ },
+ },
+ }
+ if assistant_voice:
+ assistant_session["audio"]["output"]["voice"] = assistant_voice
+
+ simulator_session: Dict[str, Any] = {
+ "type": "realtime",
+ "instructions": simulator_prompt,
+ "tools": [],
+ "tool_choice": "none",
+ "audio": {
+ "input": {
+ "format": audio_format_config(input_audio_format, sample_rate_hz),
+ "turn_detection": None,
+ },
+ "output": {
+ "format": audio_format_config(output_audio_format, sample_rate_hz)
+ },
+ },
+ }
+ if simulator_voice:
+ simulator_session["audio"]["output"]["voice"] = simulator_voice
+
+ event_index_state = {"value": 0}
+
+ # Keep both sessions open across turns; rely on server-side conversation state.
+ async with async_client.realtime.connect(
+ model=simulator_model
+ ) as simulator_connection, async_client.realtime.connect(
+ model=assistant_model
+ ) as assistant_connection:
+ await simulator_connection.session.update(
+ session=cast(RealtimeSessionCreateRequestParam, simulator_session)
+ )
+ await assistant_connection.session.update(
+ session=cast(RealtimeSessionCreateRequestParam, assistant_session)
+ )
+
+ with trace_path.open("w", encoding="utf-8") as trace_file:
+ for turn_index in range(1, max_turns + 1):
+ if turn_index == 1 and not fixed_first_turn:
+ raise ValueError(
+ f"Missing fixed_first_user_turn for {simulation_id}"
+ )
+
+ simulator_prompt_text = build_simulator_prompt_text(
+ conversation_history, fixed_first_turn, turn_index
+ )
+
+ simulator_payload: Dict[str, Any] = {}
+ if turn_index == 1:
+ simulator_payload["instructions"] = (
+ "Output exactly this user utterance and nothing else: "
+ f"{fixed_first_turn}"
+ )
+ simulator_payload["input"] = [
+ {
+ "type": "message",
+ "role": "user",
+ "content": [
+ {"type": "input_text", "text": simulator_prompt_text}
+ ],
+ }
+ ]
+ # Keep simulator turns out of the assistant's conversation state.
+ simulator_payload["conversation"] = "none"
+
+ # Collect the simulator's audio/text output and log the full event stream.
+ simulator_result = await collect_realtime_response(
+ simulator_connection,
+ simulator_payload,
+ log_file=trace_file,
+ event_index_state=event_index_state,
+ source="simulator",
+ turn_index=turn_index,
+ )
+
+ user_text = simulator_result["assistant_text"] or fixed_first_turn
+ user_audio_bytes = simulator_result["output_audio_bytes"]
+
+ user_audio_path = run_audio_dir / f"turn_{turn_index:02d}_user.wav"
+ if user_audio_bytes:
+ write_pcm16_wav(user_audio_path, user_audio_bytes, sample_rate_hz)
+
+ transcript_lines.append(f"TURN {turn_index} USER: {user_text}")
+ if "END_CALL" in user_text.upper():
+ break
+ conversation_history.append({"role": "user", "text": user_text})
+
+ await stream_audio_to_connection(
+ assistant_connection,
+ user_audio_bytes,
+ chunk_ms,
+ sample_rate_hz,
+ input_audio_format,
+ real_time,
+ # Pad very short utterances so the assistant reliably responds.
+ minimum_duration_seconds=0.1,
+ )
+
+ assistant_payload: Dict[str, Any] = {}
+
+ assistant_result = await collect_realtime_response(
+ assistant_connection,
+ assistant_payload,
+ log_file=trace_file,
+ event_index_state=event_index_state,
+ source="assistant",
+ turn_index=turn_index,
+ tool_mocks=tool_mocks,
+ )
+
+ assistant_text = assistant_result["assistant_text"]
+ assistant_audio_bytes = assistant_result["output_audio_bytes"]
+ tool_calls = assistant_result["tool_calls"]
+ tool_outputs = compute_tool_outputs(tool_calls, tool_mocks)
+ tool_call_grade_data = compute_tool_call_grade(
+ expected_tool_name,
+ expected_tool_args_text,
+ tool_calls,
+ )
+ # Track whether any turn matched the expected tool behavior.
+ tool_call_correctness_flags.append(
+ tool_call_grade_data.get("tool_call_correctness", 0)
+ )
+ if tool_call_grade_data.get("tool_call_correctness") == 1:
+ any_tool_call_correctness = 1
+ if tool_call_grade_data.get("tool_call_arg_correctness") == 1:
+ any_tool_call_arg_correctness = 1
+
+ assistant_audio_path = (
+ run_audio_dir / f"turn_{turn_index:02d}_assistant.wav"
+ )
+ if assistant_audio_bytes:
+ write_pcm16_wav(
+ assistant_audio_path, assistant_audio_bytes, sample_rate_hz
+ )
+
+ transcript_lines.append(
+ f"TURN {turn_index} ASSISTANT: {assistant_text}"
+ )
+ conversation_history.append(
+ {"role": "assistant", "text": assistant_text}
+ )
+
+ if tool_calls:
+ tool_summary = (
+ f"TURN {turn_index} TOOL_CALLS: {json.dumps(tool_calls)} "
+ f"TOOL_OUTPUTS: {json.dumps(tool_outputs)}"
+ )
+ tool_summaries.append(tool_summary)
+ transcript_lines.append(tool_summary)
+
+ turn_context = build_turn_context(
+ simulation_id,
+ scenario,
+ turn_index,
+ user_text,
+ assistant_text,
+ tool_calls,
+ tool_outputs,
+ )
+
+ usage_data = assistant_result.get("usage", {})
+ output_tokens = usage_data.get("output_tokens")
+ output_audio_tokens = None
+ output_text_tokens = None
+ if "output_token_details" in usage_data:
+ output_details = usage_data["output_token_details"]
+ output_audio_tokens = output_details.get("audio_tokens")
+ output_text_tokens = output_details.get("text_tokens")
+
+ row_data = {
+ "simulation_id": simulation_id,
+ "assistant_model": assistant_model,
+ "simulator_model": simulator_model,
+ "turn_index": turn_index,
+ "user_text": user_text,
+ "assistant_text": assistant_text,
+ "tool_calls": json.dumps(tool_calls),
+ "tool_outputs": json.dumps(tool_outputs),
+ "pred_tool_call": tool_call_grade_data.get("pred_tool_call", ""),
+ "pred_tool_call_arg": tool_call_grade_data.get(
+ "pred_tool_call_arg", ""
+ ),
+ "user_audio_path": str(user_audio_path),
+ "assistant_audio_path": str(assistant_audio_path),
+ "event_log_path": str(trace_path),
+ "latency_first_audio_ms": assistant_result["first_audio_time_ms"],
+ "latency_first_text_ms": assistant_result["first_text_time_ms"],
+ "latency_response_done_ms": assistant_result[
+ "response_done_time_ms"
+ ],
+ "output_tokens": output_tokens,
+ "output_audio_tokens": output_audio_tokens,
+ "output_text_tokens": output_text_tokens,
+ }
+ results_rows.append(row_data)
+ for grader in turn_level_graders:
+ if grader.get("type") != "llm_as_judge":
+ continue
+ if not tool_calls:
+ # Skip judge calls when the assistant made no tool call.
+ continue
+ turn_grade_requests.append(
+ {
+ "simulation_id": simulation_id,
+ "turn_index": turn_index,
+ "grader_id": grader.get("id", "turn_grader"),
+ "criteria": grader.get("criteria", ""),
+ "model": grader.get("model", args.judge_model),
+ "context": turn_context,
+ }
+ )
+
+ trace_context = build_trace_context(
+ simulation_id, scenario, transcript_lines, tool_summaries
+ )
+
+ transcript_path.write_text("\n".join(transcript_lines), encoding="utf-8")
+ if not expected_tool_name and tool_call_correctness_flags:
+ if all(flag == 1 for flag in tool_call_correctness_flags):
+ any_tool_call_correctness = 1
+ any_tool_call_arg_correctness = 1
+ else:
+ any_tool_call_correctness = 0
+ any_tool_call_arg_correctness = 0
+
+ if tool_call_grader_ids or tool_call_args_grader_ids:
+ for row_data in results_rows:
+ for grader_id in tool_call_grader_ids:
+ row_data[f"{grader_id}_grade"] = any_tool_call_correctness
+ row_data[f"{grader_id}_rationale"] = ""
+ for grader_id in tool_call_args_grader_ids:
+ row_data[f"{grader_id}_grade"] = any_tool_call_arg_correctness
+ row_data[f"{grader_id}_rationale"] = ""
+
+ for grader in trace_level_graders:
+ if grader.get("type") != "llm_as_judge":
+ continue
+ trace_grade_requests.append(
+ {
+ "simulation_id": simulation_id,
+ "grader_id": grader.get("id", "trace_grader"),
+ "criteria": grader.get("criteria", ""),
+ "model": grader.get("model", args.judge_model),
+ "context": trace_context,
+ }
+ )
+
+ return {
+ "rows": results_rows,
+ "turn_grade_requests": turn_grade_requests,
+ "trace_grade_requests": trace_grade_requests,
+ "simulation_id": simulation_id,
+ }
+
+
+async def run_evals() -> None:
+ args = parse_args()
+
+ dataset = load_simulation_index(args.data_csv)
+
+ if "enabled" in dataset.columns:
+ dataset = dataset[dataset["enabled"].astype(str).str.lower() == "true"]
+
+ if args.max_examples > 0:
+ dataset = dataset.head(args.max_examples)
+
+ run_timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
+ run_name = args.run_name or run_timestamp
+ run_dir = args.results_dir / run_name
+ ensure_dir(run_dir)
+
+ async_client = AsyncOpenAI()
+
+ all_rows: List[Dict[str, Any]] = []
+ turn_grade_requests: List[Dict[str, Any]] = []
+ trace_grade_requests: List[Dict[str, Any]] = []
+ simulation_row_indices: Dict[str, List[int]] = {}
+
+ total_simulations = int(dataset.shape[0])
+ print(f"Running run harness: {total_simulations} simulations -> {run_dir}")
+ for _, row in tqdm(dataset.iterrows(), total=total_simulations, desc="Run evals"):
+ simulation_result = await run_simulation(async_client, row, args, run_dir)
+ rows = simulation_result["rows"]
+ simulation_id = simulation_result["simulation_id"]
+ offset = len(all_rows)
+ all_rows.extend(rows)
+ simulation_row_indices[simulation_id] = list(range(offset, offset + len(rows)))
+
+ for request in simulation_result["turn_grade_requests"]:
+ row_index = offset + request["turn_index"] - 1
+ turn_grade_requests.append(
+ {
+ "row_indices": [row_index],
+ "grader_id": request["grader_id"],
+ "criteria": request["criteria"],
+ "model": request["model"],
+ "context": request["context"],
+ }
+ )
+
+ for request in simulation_result["trace_grade_requests"]:
+ row_indices = simulation_row_indices.get(request["simulation_id"], [])
+ trace_grade_requests.append(
+ {
+ "row_indices": row_indices,
+ "grader_id": request["grader_id"],
+ "criteria": request["criteria"],
+ "model": request["model"],
+ "context": request["context"],
+ }
+ )
+
+ grade_jobs = turn_grade_requests + trace_grade_requests
+ if grade_jobs:
+ max_workers = min(8, len(grade_jobs))
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
+ for result in executor.map(execute_grade_job, grade_jobs):
+ for row_index in result["row_indices"]:
+ all_rows[row_index][f"{result['grader_id']}_grade"] = result[
+ "grade"
+ ]
+ all_rows[row_index][f"{result['grader_id']}_rationale"] = result[
+ "rationale"
+ ]
+
+ results_df = pd.DataFrame(all_rows)
+ results_df = order_result_columns(results_df)
+ results_csv_path = run_dir / "results.csv"
+ results_df.to_csv(results_csv_path, index=False)
+
+ summary = compute_summary(results_df)
+ summary.update(
+ {
+ "run_name": run_name,
+ "assistant_model_default": args.assistant_model or args.model or "",
+ "simulator_model_default": args.simulator_model or "",
+ "input_audio_format": args.input_audio_format,
+ "output_audio_format": args.output_audio_format,
+ "chunk_ms": args.chunk_ms,
+ "sample_rate_hz": args.sample_rate_hz,
+ "real_time": args.real_time,
+ "data_csv": str(args.data_csv),
+ }
+ )
+
+ summary_path = run_dir / "summary.json"
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
+ grade_keys = sorted(key for key in summary.keys() if key.endswith("_grade_mean"))
+ grade_notes = " ".join(f"{key}={summary.get(key, 0):.3f}" for key in grade_keys)
+ print(
+ "Summary:"
+ f" total_rows={summary.get('total_rows', 0)}"
+ f"{(' ' + grade_notes) if grade_notes else ''}"
+ )
+ print(f"Wrote results to {run_dir}")
+
+
+def main() -> None:
+ asyncio.run(run_evals())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/evals/realtime_evals/shared/graders.py b/examples/evals/realtime_evals/shared/graders.py
new file mode 100644
index 00000000..3bf7524e
--- /dev/null
+++ b/examples/evals/realtime_evals/shared/graders.py
@@ -0,0 +1,119 @@
+import json
+import re
+from typing import Any, Dict, List
+
+
+def parse_json_dict(json_text: str) -> Dict[str, Any]:
+ if not json_text:
+ return {}
+ try:
+ parsed = json.loads(json_text)
+ except json.JSONDecodeError:
+ return {}
+ if isinstance(parsed, dict):
+ return parsed
+ return {}
+
+
+def normalize_text(text: str) -> str:
+ if not text:
+ return ""
+ normalized = text.lower().strip()
+ normalized = re.sub(r"[^\w\s]", " ", normalized)
+ normalized = re.sub(r"\s+", " ", normalized)
+ return normalized.strip()
+
+
+def normalize_address(address: str) -> str:
+ normalized = normalize_text(address)
+ tokens = normalized.split()
+ substitutions = {
+ "st": "street",
+ "ave": "avenue",
+ "blvd": "boulevard",
+ "rd": "road",
+ "dr": "drive",
+ "ln": "lane",
+ "ct": "court",
+ "tx": "texas",
+ "ca": "california",
+ "ny": "new york",
+ }
+ expanded_tokens = []
+ for token in tokens:
+ expanded_tokens.append(substitutions.get(token, token))
+ return " ".join(expanded_tokens).strip()
+
+
+def normalize_order_id(order_id: str) -> str:
+ return normalize_text(order_id).replace(" ", "")
+
+
+def expected_args_subset(expected_args: Dict[str, Any], actual_args: Dict[str, Any]) -> bool:
+ for key, expected_value in expected_args.items():
+ if key not in actual_args:
+ return False
+ actual_value = actual_args.get(key)
+ if key == "new_address":
+ if normalize_address(str(expected_value)) != normalize_address(str(actual_value)):
+ return False
+ elif key == "order_id":
+ if normalize_order_id(str(expected_value)) != normalize_order_id(str(actual_value)):
+ return False
+ else:
+ if normalize_text(str(expected_value)) != normalize_text(str(actual_value)):
+ return False
+ return True
+
+
+def compute_tool_call_grade(
+ expected_tool_name: str,
+ expected_tool_args_text: str,
+ tool_calls: List[Dict[str, Any]],
+) -> Dict[str, Any]:
+ expected_tool_name = expected_tool_name.strip()
+ expected_args = parse_json_dict(expected_tool_args_text.strip())
+
+ if not expected_tool_name:
+ if not tool_calls:
+ return {
+ "tool_call_correctness": 1,
+ "tool_call_arg_correctness": 1,
+ "pred_tool_call": "",
+ "pred_tool_call_arg": "",
+ }
+ first_call = tool_calls[0]
+ return {
+ "tool_call_correctness": 0,
+ "tool_call_arg_correctness": 0,
+ "pred_tool_call": first_call.get("name", ""),
+ "pred_tool_call_arg": json.dumps(first_call.get("arguments", {})),
+ }
+
+ matching_call = None
+ for call in tool_calls:
+ if call.get("name") == expected_tool_name:
+ matching_call = call
+ break
+
+ if not matching_call:
+ first_call = tool_calls[0] if tool_calls else {}
+ return {
+ "tool_call_correctness": 0,
+ "tool_call_arg_correctness": 0,
+ "pred_tool_call": first_call.get("name", ""),
+ "pred_tool_call_arg": json.dumps(first_call.get("arguments", {})),
+ }
+
+ actual_args = matching_call.get("arguments", {})
+ if expected_args:
+ args_match = 1 if expected_args_subset(expected_args, actual_args) else 0
+ else:
+ args_match = 1
+
+ return {
+ "tool_call_correctness": 1,
+ "tool_call_arg_correctness": args_match,
+ "pred_tool_call": matching_call.get("name", ""),
+ "pred_tool_call_arg": json.dumps(actual_args),
+ }
diff --git a/examples/evals/realtime_evals/shared/metrics_utils.py b/examples/evals/realtime_evals/shared/metrics_utils.py
new file mode 100644
index 00000000..d6a6dfb6
--- /dev/null
+++ b/examples/evals/realtime_evals/shared/metrics_utils.py
@@ -0,0 +1,43 @@
+"""Shared metrics helpers for the realtime eval harnesses."""
+
+from typing import Any, Dict, Iterable, List
+
+import pandas as pd
+
+
+def add_grade_means(summary: Dict[str, Any], results: pd.DataFrame) -> None:
+ """Add mean values for any columns that end with `_grade`."""
+ grade_columns = [column for column in results.columns if column.endswith("_grade")]
+ for column in grade_columns:
+ series = results[column].dropna()
+ if series.empty:
+ continue
+ summary[f"{column}_mean"] = float(series.mean())
+
+
+def add_numeric_summaries(
+ summary: Dict[str, Any], results: pd.DataFrame, columns: Iterable[str]
+) -> None:
+ """Add avg and percentile stats for the requested numeric columns."""
+ for column in columns:
+ if column not in results.columns:
+ continue
+ series = results[column].dropna()
+ if series.empty:
+ continue
+ summary[f"{column}_avg"] = float(series.mean())
+ summary[f"{column}_p50"] = float(series.quantile(0.5))
+ summary[f"{column}_p95"] = float(series.quantile(0.95))
+ summary[f"{column}_p99"] = float(series.quantile(0.99))
+
+
+def order_columns(results: pd.DataFrame, preferred_columns: List[str]) -> pd.DataFrame:
+ """Reorder columns so the most important fields are grouped first."""
+ remaining_columns = [
+ column for column in results.columns if column not in preferred_columns
+ ]
+ ordered_columns = [
+ column for column in preferred_columns if column in results.columns
+ ] + remaining_columns
+ return results.loc[:, ordered_columns]
+
diff --git a/examples/evals/realtime_evals/shared/realtime_harness_utils.py b/examples/evals/realtime_evals/shared/realtime_harness_utils.py
new file mode 100644
index 00000000..e6b2e159
--- /dev/null
+++ b/examples/evals/realtime_evals/shared/realtime_harness_utils.py
@@ -0,0 +1,220 @@
+"""Shared realtime harness helpers for audio streaming and response collection."""
+
+import asyncio
+import base64
+import json
+import wave
+from pathlib import Path
+from typing import Any, Dict, List, Optional, TextIO
+
+from shared.realtime_utils import ToolCallAccumulator
+from shared.trace_utils import build_event_record
+
+
+def ensure_dir(path: Path) -> None:
+ path.mkdir(parents=True, exist_ok=True)
+
+
+def bytes_per_sample_for_format(audio_format: str) -> int:
+ if audio_format == "pcm16":
+ return 2
+ if audio_format in {"g711_ulaw", "g711_alaw"}:
+ # G.711 variants are 8-bit companded audio.
+ return 1
+ raise ValueError(f"Unsupported audio format: {audio_format}")
+
+
+def audio_format_config(audio_format: str, sample_rate_hz: int) -> Dict[str, Any]:
+ if audio_format == "pcm16":
+ return {"type": "audio/pcm", "rate": sample_rate_hz}
+ if audio_format == "g711_ulaw":
+ return {"type": "audio/pcmu"}
+ if audio_format == "g711_alaw":
+ return {"type": "audio/pcma"}
+ raise ValueError(f"Unsupported audio format: {audio_format}")
+
+
+def compute_bytes_per_chunk(
+ sample_rate_hz: int, chunk_ms: int, bytes_per_sample: int
+) -> int:
+ # Ensure we always send at least one byte even for tiny chunk sizes.
+ computed = int(sample_rate_hz * (chunk_ms / 1000.0) * bytes_per_sample)
+ return max(1, computed)
+
+
+def chunk_audio_bytes(audio_bytes: bytes, bytes_per_chunk: int) -> List[bytes]:
+ audio_chunks: List[bytes] = []
+ for offset in range(0, len(audio_bytes), bytes_per_chunk):
+ audio_chunks.append(audio_bytes[offset : offset + bytes_per_chunk])
+ return audio_chunks
+
+
+def write_pcm16_wav(output_path: Path, pcm_bytes: bytes, sample_rate_hz: int) -> None:
+ ensure_dir(output_path.parent)
+ with wave.open(str(output_path), "wb") as wav_file:
+ wav_file.setnchannels(1)
+ wav_file.setsampwidth(2)
+ wav_file.setframerate(sample_rate_hz)
+ wav_file.writeframes(pcm_bytes)
+
+
+async def stream_audio_to_connection(
+ connection: Any,
+ audio_bytes: bytes,
+ chunk_ms: int,
+ sample_rate_hz: int,
+ input_audio_format: str,
+ real_time: bool,
+ minimum_duration_seconds: float = 0.0,
+) -> None:
+ bytes_per_sample = bytes_per_sample_for_format(input_audio_format)
+ minimum_audio_bytes = int(
+ sample_rate_hz * minimum_duration_seconds * bytes_per_sample
+ )
+ if minimum_audio_bytes > 0 and len(audio_bytes) < minimum_audio_bytes:
+ # Very short turns can be ignored by the model; pad with silence when requested.
+ padding_bytes = minimum_audio_bytes - len(audio_bytes)
+ audio_bytes = audio_bytes + (b"\x00" * padding_bytes)
+
+ bytes_per_chunk = compute_bytes_per_chunk(
+ sample_rate_hz, chunk_ms, bytes_per_sample
+ )
+ audio_chunks = chunk_audio_bytes(audio_bytes, bytes_per_chunk)
+
+ await connection.input_audio_buffer.clear()
+ for audio_chunk in audio_chunks:
+ # Realtime expects base64-encoded audio bytes per append event.
+ await connection.input_audio_buffer.append(
+ audio=base64.b64encode(audio_chunk).decode("ascii")
+ )
+ if real_time:
+ # Optional: emulate wall-clock streaming instead of sending as fast as possible.
+ await asyncio.sleep(chunk_ms / 1000.0)
+ # Mark end-of-user-turn (required when `turn_detection` is disabled).
+ await connection.input_audio_buffer.commit()
+
+
+def _next_event_index(event_index_state: Optional[Dict[str, int]]) -> int:
+ if event_index_state is None:
+ return -1
+ # Keep a single monotonically increasing index across interleaved streams.
+ event_index_state["value"] = event_index_state["value"] + 1
+ return event_index_state["value"]
+
+
+async def collect_realtime_response(
+ connection: Any,
+ response_payload: Dict[str, Any],
+ log_file: Optional[TextIO] = None,
+ event_index_state: Optional[Dict[str, int]] = None,
+ source: Optional[str] = None,
+ turn_index: Optional[int] = None,
+ tool_mocks: Optional[Dict[str, Dict[str, Any]]] = None,
+) -> Dict[str, Any]:
+ """Collect a realtime response and optionally log each event as JSONL."""
+ assistant_text_parts: List[str] = []
+ output_audio_bytes = bytearray()
+ tool_call_accumulator = ToolCallAccumulator()
+ # Track tool calls we've already responded to so follow-up responses are clean.
+ responded_call_ids: set[str] = set()
+
+ first_audio_time_ms: Optional[float] = None
+ first_text_time_ms: Optional[float] = None
+ response_done_time_ms: Optional[float] = None
+ usage_data: Dict[str, Any] = {}
+ awaiting_followup = False
+
+ loop = asyncio.get_running_loop()
+ response_start_time = loop.time()
+ await connection.response.create(response=response_payload)
+
+ local_event_index = 0
+ async for event in connection:
+ event_time_ms = (loop.time() - response_start_time) * 1000
+ if event_index_state is None:
+ # Use a local counter when the caller does not need cross-stream ordering.
+ local_event_index += 1
+ event_index = local_event_index
+ else:
+ event_index = _next_event_index(event_index_state)
+
+ if log_file is not None:
+ log_entry = build_event_record(
+ event,
+ event_time_ms=event_time_ms,
+ event_index=event_index,
+ source=source,
+ turn_index=turn_index,
+ )
+ log_file.write(json.dumps(log_entry))
+ log_file.write("\n")
+
+ payload = event.model_dump()
+ event_type = payload.get("type", "")
+
+ if event_type == "response.output_audio.delta":
+ if first_audio_time_ms is None:
+ first_audio_time_ms = event_time_ms
+ output_audio_bytes.extend(base64.b64decode(payload.get("delta", "")))
+
+ if event_type == "response.output_audio_transcript.delta":
+ if first_text_time_ms is None:
+ first_text_time_ms = event_time_ms
+ assistant_text_parts.append(payload.get("delta", ""))
+
+ if event_type == "response.output_text.delta":
+ if first_text_time_ms is None:
+ first_text_time_ms = event_time_ms
+ assistant_text_parts.append(payload.get("delta", ""))
+
+ if event_type == "response.done":
+ response_done_time_ms = event_time_ms
+ tool_call_accumulator.handle_event_payload(payload)
+ response = payload.get("response") or {}
+ usage_data = response.get("usage") or {}
+
+ tool_calls = tool_call_accumulator.build_tool_calls()
+ # Only respond to newly observed tool calls; some calls may repeat in follow-ups.
+ pending_tool_calls = [
+ call
+ for call in tool_calls
+ if call.get("call_id") and call.get("call_id") not in responded_call_ids
+ ]
+ if tool_mocks is not None and pending_tool_calls:
+ for call in pending_tool_calls:
+ call_id = call.get("call_id", "")
+ if not call_id:
+ continue
+ tool_name = call.get("name", "")
+ # Provide deterministic mock outputs so multi-turn runs stay comparable.
+ tool_output = tool_mocks.get(
+ tool_name, {"status": "Unsupported tool"}
+ )
+ await connection.conversation.item.create(
+ item={
+ "type": "function_call_output",
+ "call_id": call_id,
+ "output": json.dumps(tool_output),
+ }
+ )
+ responded_call_ids.add(call_id)
+ # After providing tool output(s), explicitly request the assistant to continue.
+ await connection.response.create()
+ awaiting_followup = True
+ continue
+
+ if awaiting_followup:
+ # This `response.done` corresponds to the post-tool-call follow-up response.
+ awaiting_followup = False
+ break
+
+ tool_calls = tool_call_accumulator.build_tool_calls()
+ return {
+ "assistant_text": "".join(assistant_text_parts).strip(),
+ "output_audio_bytes": bytes(output_audio_bytes),
+ "tool_calls": tool_calls,
+ "first_audio_time_ms": first_audio_time_ms,
+ "first_text_time_ms": first_text_time_ms,
+ "response_done_time_ms": response_done_time_ms,
+ "usage": usage_data,
+ }
diff --git a/examples/evals/realtime_evals/shared/realtime_utils.py b/examples/evals/realtime_evals/shared/realtime_utils.py
new file mode 100644
index 00000000..d840e038
--- /dev/null
+++ b/examples/evals/realtime_evals/shared/realtime_utils.py
@@ -0,0 +1,71 @@
+"""Small helpers shared across the realtime eval harnesses."""
+
+from typing import Any, Dict, List
+
+from shared.graders import parse_json_dict
+
+
+class ToolCallAccumulator:
+ """Accumulates tool calls from the Realtime event stream.
+
+ For these eval harnesses we only track tool calls from `response.done`, which
+ includes a fully materialized `response` payload with `response["output"]`.
+
+ This helper normalizes `response.output[]` items of type `function_call` into
+ a stable list of tool calls: `{name, arguments, raw_arguments, call_id}`
+ ordered by first appearance across the stream.
+ """
+
+ def __init__(self) -> None:
+ self._tool_calls_by_id: Dict[str, Dict[str, Any]] = {}
+ self._tool_call_order: List[str] = []
+
+ def _ensure_entry(self, call_id: str, tool_name: str) -> Dict[str, Any]:
+ entry = self._tool_calls_by_id.get(call_id)
+ if entry is None:
+ entry = {"name": tool_name, "raw_arguments": "", "call_id": call_id}
+ self._tool_calls_by_id[call_id] = entry
+ self._tool_call_order.append(call_id)
+ elif tool_name:
+ entry["name"] = tool_name
+ return entry
+
+ def handle_event_payload(self, payload: Dict[str, Any]) -> None:
+ """Update state from a single event payload (`event.model_dump()`)."""
+ event_type = payload.get("type", "")
+ if event_type != "response.done":
+ return
+
+ response_payload = payload.get("response") or {}
+ for output_item in response_payload.get("output") or []:
+ if output_item.get("type") != "function_call":
+ continue
+ call_id = output_item.get("call_id") or output_item.get("id") or ""
+ if not call_id:
+ continue
+ tool_name = output_item.get("name", "")
+ entry = self._ensure_entry(call_id, tool_name)
+ arguments_text = output_item.get("arguments", "") or ""
+ if arguments_text:
+ entry["raw_arguments"] = arguments_text
+
+ def get_call(self, call_id: str) -> Dict[str, Any]:
+ """Return the partially-built entry for a call id (or `{}` if missing)."""
+ return self._tool_calls_by_id.get(call_id, {})
+
+ def build_tool_calls(self) -> List[Dict[str, Any]]:
+ """Return the final ordered list of tool calls with parsed JSON args."""
+ tool_calls: List[Dict[str, Any]] = []
+ for call_id in self._tool_call_order:
+ entry = self._tool_calls_by_id.get(call_id, {})
+ raw_arguments = entry.get("raw_arguments", "")
+ parsed_arguments = parse_json_dict(raw_arguments)
+ tool_calls.append(
+ {
+ "name": entry.get("name", ""),
+ "arguments": parsed_arguments,
+ "raw_arguments": raw_arguments,
+ "call_id": call_id,
+ }
+ )
+ return tool_calls
diff --git a/examples/evals/realtime_evals/shared/system_prompt.txt b/examples/evals/realtime_evals/shared/system_prompt.txt
new file mode 100644
index 00000000..d6d3ce43
--- /dev/null
+++ b/examples/evals/realtime_evals/shared/system_prompt.txt
@@ -0,0 +1,85 @@
+## Role & Objective
+You are **Acme Support**, a realtime **voice-to-voice customer service assistant**.
+Your goal is to resolve the caller’s request quickly and accurately: check order status, issue refunds, or update a shipping address (when allowed).
+
+## Personality & Tone
+## Identity
+- Helpful Acme Support representative for phone-style customer service.
+
+## Tone
+- Clear, concise, confident, never fawning.
+- Use plain language; avoid jargon.
+
+## Length
+- Keep turns **short**: usually **1–2 sentences**, up to **3** when needed.
+- Ask **one question at a time**.
+
+## Conversation Flow
+- Start with a brief greeting and ask how you can help.
+- When you need details, say why in one short phrase (e.g., “So I can pull up the right order…”).
+- Reduce repetition: vary confirmations and transitions; don’t reuse the exact same opener repeatedly.
+- Before ending, confirm the user is satisfied and offer one brief follow-up (e.g., “Anything else I can help with?”).
+
+## Unclear / Noisy Audio
+- Respond in the same language the user is speaking, when clear.
+- **Only respond to clear input.** If you did not fully hear or understand, do not guess.
+- Use short clarification prompts such as:
+ - “Sorry, I didn’t catch that. Could you repeat it?”
+ - “I heard part of that—what was the order ID?”
+ - “Could you spell that email for me?”
+
+## Safety & Sensitive Requests
+- If the user expresses self-harm intent, immediate danger, or threats: be supportive, encourage contacting local emergency services, and avoid giving tactical guidance.
+- Do not request or repeat full payment card numbers, passwords, or one-time codes. If the user offers them, stop and redirect.
+
+## Tools
+You have the following tools. Use them to take real actions.
+
+## Tool Calling Rule (EAGER)
+- As soon as you have **all required fields** for a tool, **call the tool immediately**. Do not delay tool calls to ask for optional fields.
+- Optional fields should **never block** a tool call. If the user already provided an optional field, include it. If not, **omit it** (do not send empty strings).
+- Do not call tools with guessed values.
+If the user asks for something outside these tools, say what you *can* do (status, refund, address update) and ask a brief question to proceed.
+
+## Tool Call Preamble (MANDATORY)
+- When you call a tool, you MUST output a short spoken preamble at the same time in your assistant response, e.g.:
+ - “One moment while I check that.”
+ - “Let me pull that up.”
+ - “Okay, I’m taking care of that now.”
+- Never mention tool/function names (or that you are “calling a tool”). Describe the action at a high level only.
+
+### 1) get_order_status
+- Purpose: Look up the latest status for a customer order.
+- Required: `order_id`
+- Optional: `email` (use when available to disambiguate)
+- When to use: The user asks where an order is, delivery timing, shipment status, or tracking-style updates.
+- Tool-call behavior:
+ - If you have `order_id`, call immediately.
+ - Include `email` only if the user already provided it or you need it to disambiguate.
+- WHEN NOT TO USE:
+ - If the user wants a refund or cancellation (use `refund_order`).
+ - If the user wants to change the shipping address (use `update_shipping_address`).
+ - If you do not have an order ID yet (ask for it first; do not guess).
+
+### 2) refund_order
+- Purpose: Create a refund request for an order.
+- Required: `order_id`
+- Optional: `reason` (short, caller-provided reason). Do not ask the user for a reason if it was not provided.
+- When to use: The user asks for a refund, cancellation with refund, or reports issues that require refund processing.
+- Tool-call behavior:
+ - If you have `order_id`, call immediately.
+ - Include `reason` only if the user already provided it; otherwise omit it.
+- WHEN NOT TO USE:
+ - If the user is only asking for shipping/delivery updates (use `get_order_status`).
+ - If the user is only trying to change where the order ships (use `update_shipping_address`).
+
+### 3) update_shipping_address
+- Purpose: Update the shipping address on an order before it ships.
+- Required: `order_id`, `new_address` (full address)
+- When to use: The user wants to change the shipping address.
+- Tool-call behavior:
+ - If `new_address` is missing, ask for the full new address.
+ - As soon as you have `order_id` and `new_address`, call immediately.
+- WHEN NOT TO USE:
+ - If the user is only asking where the order is (use `get_order_status`).
+ - If the user wants a refund (use `refund_order`).
diff --git a/examples/evals/realtime_evals/shared/tools.json b/examples/evals/realtime_evals/shared/tools.json
new file mode 100644
index 00000000..24c7b0b0
--- /dev/null
+++ b/examples/evals/realtime_evals/shared/tools.json
@@ -0,0 +1,66 @@
+[
+ {
+ "type": "function",
+ "name": "get_order_status",
+ "description": "Look up the latest status for a customer order.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "order_id": {
+ "type": "string",
+ "description": "Order ID, e.g. A12345."
+ },
+ "email": {
+ "type": "string",
+ "description": "Customer email on the order."
+ }
+ },
+ "required": [
+ "order_id"
+ ]
+ }
+ },
+ {
+ "type": "function",
+ "name": "refund_order",
+ "description": "Create a refund request for an order.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "order_id": {
+ "type": "string",
+ "description": "Order ID to refund."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Short reason for the refund."
+ }
+ },
+ "required": [
+ "order_id"
+ ]
+ }
+ },
+ {
+ "type": "function",
+ "name": "update_shipping_address",
+ "description": "Update the shipping address on an order before it ships.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "order_id": {
+ "type": "string",
+ "description": "Order ID to update."
+ },
+ "new_address": {
+ "type": "string",
+ "description": "Full new shipping address."
+ }
+ },
+ "required": [
+ "order_id",
+ "new_address"
+ ]
+ }
+ }
+]
diff --git a/examples/evals/realtime_evals/shared/trace_utils.py b/examples/evals/realtime_evals/shared/trace_utils.py
new file mode 100644
index 00000000..21dcc4eb
--- /dev/null
+++ b/examples/evals/realtime_evals/shared/trace_utils.py
@@ -0,0 +1,56 @@
+from typing import Any, Optional
+
+
+def event_to_dict(event: Any) -> dict[str, Any]:
+ if isinstance(event, dict):
+ return event
+ return event.model_dump()
+
+
+def truncate_string(value: str, max_length: int) -> str:
+ if len(value) <= max_length:
+ return value
+ truncated = value[:max_length]
+ omitted = len(value) - max_length
+ return f"{truncated}...[truncated {omitted} chars]"
+
+
+def sanitize_value(value: Any, max_string_length: int) -> Any:
+ if isinstance(value, dict):
+ return sanitize_dict(value, max_string_length)
+ if isinstance(value, list):
+ return [sanitize_value(item, max_string_length) for item in value]
+ if isinstance(value, str):
+ return truncate_string(value, max_string_length)
+ return value
+
+
+def sanitize_dict(payload: dict[str, Any], max_string_length: int) -> dict[str, Any]:
+ sanitized: dict[str, Any] = {}
+ for key, value in payload.items():
+ sanitized[key] = sanitize_value(value, max_string_length)
+ return sanitized
+
+
+def build_event_record(
+ event: Any,
+ event_time_ms: Optional[float] = None,
+ event_index: Optional[int] = None,
+ source: Optional[str] = None,
+ turn_index: Optional[int] = None,
+ max_string_length: int = 400,
+) -> dict[str, Any]:
+ payload = event_to_dict(event)
+ event_type = payload.get("type", "unknown")
+
+ record: dict[str, Any] = {"type": event_type}
+ if source is not None:
+ record["source"] = source
+ if turn_index is not None:
+ record["turn_index"] = turn_index
+ if event_index is not None:
+ record["event_index"] = event_index
+ if event_time_ms is not None:
+ record["event_time_ms"] = event_time_ms
+ record["event"] = sanitize_value(payload, max_string_length)
+ return record
diff --git a/examples/evals/realtime_evals/walk_harness/README.md b/examples/evals/realtime_evals/walk_harness/README.md
new file mode 100644
index 00000000..f2fa0039
--- /dev/null
+++ b/examples/evals/realtime_evals/walk_harness/README.md
@@ -0,0 +1,69 @@
+# Walk Harness
+
+The walk harness replays saved audio to make realtime eval runs comparable.
+It streams G.711 mu-law WAV files in fixed-size chunks, commits the user turn
+manually (VAD off), and records responses, tool calls, and latency metrics.
+
+## What it does
+
+- Loads a CSV with the crawl columns (excluding `expected_keywords`) plus `audio_path`.
+- Streams saved audio in fixed chunk sizes (default 20 ms) at a deterministic cadence.
+- Commits the input buffer explicitly to avoid VAD variability.
+- Captures transcript deltas, audio deltas, tool calls, and completion events.
+- Writes `results.csv` and `summary.json` with accuracy and latency stats.
+- Stores a JSONL stream of all realtime events per example under `results/<run>/events/`.
+
+## Files
+
+- `walk_harness/generate_audio.py`: Generates G.711 mu-law WAV files from the
+ crawl CSV using TTS + ffmpeg.
+- `walk_harness/data/customer_service_synthetic.csv`: Walk dataset with
+ `audio_path` pointing to WAV files.
+- `walk_harness/run_realtime_evals.py`: Runs the walk evals.
+- `walk_harness/results/<run>/events/*.jsonl`: Event logs per datapoint.
+- `walk_harness/results/<run>/audio/<example_id>/output.wav`: Assistant output audio per datapoint.
+
+## How to run
+
+1) Install ffmpeg (required for mu-law WAV encoding):
+
+```
+brew install ffmpeg
+```
+
+2) Generate audio assets:
+
+```
+python walk_harness/generate_audio.py
+```
+
+3) Run the eval harness:
+
+```
+python walk_harness/run_realtime_evals.py
+```
+
+4) Quick smoke test:
+
+```
+python walk_harness/run_realtime_evals.py --max-examples 2
+```
+
+## Inputs and audio format
+
+- The dataset CSV must include an `audio_path` column pointing to WAV files.
+- This harness currently expects **G.711 mu-law** audio at **8 kHz** (`g711_ulaw`), which
+ is a common telephony format and makes runs more realistic than pure PCM.
+- Output audio is saved as **PCM16 WAV** (typically 24 kHz) for easy playback.
+
+## Adapting the harness
+
+- Change the model or voice via CLI flags (`--model`, `--voice`).
+- Override the system prompt and tools with `--system-prompt-file` and `--tools-file`.
+- Update chunking and cadence with `--chunk-ms` and `--real-time`.
+- Swap datasets with `--data-csv` (ensure it includes `audio_path`).
+- Use a different audio format only if the Realtime API supports it. The default
+ is `g711_ulaw` at 8 kHz to match the saved WAV files. Output audio is stored
+ as PCM16 WAV for easy listening.
+- Replace `walk_harness/data/customer_service_synthetic.csv` with your own CSV
+ and regenerate audio assets using `generate_audio.py`.
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_001.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_001.wav
new file mode 100644
index 00000000..55f16ca3
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_001.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_002.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_002.wav
new file mode 100644
index 00000000..be260060
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_002.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_003.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_003.wav
new file mode 100644
index 00000000..bf5a83a6
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_003.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_004.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_004.wav
new file mode 100644
index 00000000..e52544be
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_004.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_005.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_005.wav
new file mode 100644
index 00000000..dd7f4773
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_005.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_006.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_006.wav
new file mode 100644
index 00000000..6485e7d1
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_006.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_007.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_007.wav
new file mode 100644
index 00000000..d2d88be1
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_007.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_008.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_008.wav
new file mode 100644
index 00000000..d07d04c0
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_008.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_009.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_009.wav
new file mode 100644
index 00000000..8011b87b
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_009.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_010.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_010.wav
new file mode 100644
index 00000000..f6cc355c
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_010.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/audio/cs_011.wav b/examples/evals/realtime_evals/walk_harness/data/audio/cs_011.wav
new file mode 100644
index 00000000..810847ee
Binary files /dev/null and b/examples/evals/realtime_evals/walk_harness/data/audio/cs_011.wav differ
diff --git a/examples/evals/realtime_evals/walk_harness/data/customer_service_synthetic.csv b/examples/evals/realtime_evals/walk_harness/data/customer_service_synthetic.csv
new file mode 100644
index 00000000..8fdfdda9
--- /dev/null
+++ b/examples/evals/realtime_evals/walk_harness/data/customer_service_synthetic.csv
@@ -0,0 +1,12 @@
+example_id,user_text,gt_tool_call,gt_tool_call_arg,audio_path
+cs_001,"Hi, can you check the status of my order A12345?",get_order_status,"{""order_id"":""A12345""}",audio/cs_001.wav
+cs_002,My order B67890 arrived damaged. I want a refund.,refund_order,"{""order_id"":""B67890""}",audio/cs_002.wav
+cs_003,"Please change the shipping address on order C24680 to 123 Pine St, Austin TX.",update_shipping_address,"{""order_id"":""C24680"",""new_address"":""123 Pine St, Austin TX""}",audio/cs_003.wav
+cs_004,Where is my package for order D13579? It is late.,get_order_status,"{""order_id"":""D13579""}",audio/cs_004.wav
+cs_005,I need to cancel order E11223 before it ships.,refund_order,"{""order_id"":""E11223""}",audio/cs_005.wav
+cs_006,I was double charged for order F44556 and need help.,refund_order,"{""order_id"":""F44556""}",audio/cs_006.wav
+cs_007,What is the estimated delivery date for order G77889?,get_order_status,"{""order_id"":""G77889""}",audio/cs_007.wav
+cs_008,"Update the shipping address for order H99001 to 55 Market St, San Francisco.",update_shipping_address,"{""order_id"":""H99001"",""new_address"":""55 Market St, San Francisco""}",audio/cs_008.wav
+cs_009,Thanks for the help earlier. That's all I needed.,,,audio/cs_009.wav
+cs_010,"Hello, I just want to leave positive feedback about your support team.",,,audio/cs_010.wav
+cs_011,What are your customer support hours?,,,audio/cs_011.wav
diff --git a/examples/evals/realtime_evals/walk_harness/generate_audio.py b/examples/evals/realtime_evals/walk_harness/generate_audio.py
new file mode 100644
index 00000000..a40be8d1
--- /dev/null
+++ b/examples/evals/realtime_evals/walk_harness/generate_audio.py
@@ -0,0 +1,150 @@
+"""Generate walk-harness audio assets from the crawl CSV.
+
+Requires ffmpeg: `brew install ffmpeg`
+"""
+
+import argparse
+import subprocess
+from pathlib import Path
+
+import pandas as pd
+from openai import OpenAI
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+DEFAULT_SOURCE_CSV = (
+ ROOT_DIR / "crawl_harness" / "data" / "customer_service_synthetic.csv"
+)
+DEFAULT_OUTPUT_DIR = ROOT_DIR / "walk_harness" / "data" / "audio"
+DEFAULT_OUTPUT_CSV = (
+ ROOT_DIR / "walk_harness" / "data" / "customer_service_synthetic.csv"
+)
+
+DEFAULT_TTS_MODEL = "gpt-4o-mini-tts"
+DEFAULT_VOICE = "alloy"
+DEFAULT_TTS_SAMPLE_RATE_HZ = 24000
+DEFAULT_TARGET_SAMPLE_RATE_HZ = 8000
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Generate G.711 mu-law WAV files for the walk harness. Requires ffmpeg: `brew install ffmpeg`.",
+ )
+ parser.add_argument("--source-csv", type=Path, default=DEFAULT_SOURCE_CSV)
+ parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
+ parser.add_argument("--output-csv", type=Path, default=DEFAULT_OUTPUT_CSV)
+ parser.add_argument("--tts-model", type=str, default=DEFAULT_TTS_MODEL)
+ parser.add_argument("--voice", type=str, default=DEFAULT_VOICE)
+ parser.add_argument(
+ "--tts-sample-rate-hz", type=int, default=DEFAULT_TTS_SAMPLE_RATE_HZ
+ )
+ parser.add_argument(
+ "--target-sample-rate-hz", type=int, default=DEFAULT_TARGET_SAMPLE_RATE_HZ
+ )
+ parser.add_argument(
+ "--overwrite",
+ action="store_true",
+ help="Regenerate audio even if output exists.",
+ )
+ return parser.parse_args()
+
+
+def ensure_dir(path: Path) -> None:
+ path.mkdir(parents=True, exist_ok=True)
+
+
+def load_dataset(path: Path) -> pd.DataFrame:
+ dataset = pd.read_csv(path)
+ required_columns = {"example_id", "user_text", "gt_tool_call", "gt_tool_call_arg"}
+ missing = required_columns.difference(dataset.columns)
+ if missing:
+ raise ValueError(f"Missing required columns: {sorted(missing)}")
+ return dataset
+
+
+def tts_to_pcm_file(
+ client: OpenAI, text: str, output_path: Path, model: str, voice: str
+) -> None:
+ ensure_dir(output_path.parent)
+ with client.audio.speech.with_streaming_response.create(
+ model=model,
+ voice=voice,
+ input=text,
+ response_format="pcm",
+ ) as response:
+ response.stream_to_file(output_path)
+
+
+def encode_pcm_to_ulaw_wav(
+ input_pcm_path: Path,
+ output_wav_path: Path,
+ input_sample_rate_hz: int,
+ target_sample_rate_hz: int,
+) -> None:
+ ensure_dir(output_wav_path.parent)
+ command = [
+ "ffmpeg",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-f",
+ "s16le",
+ "-ar",
+ str(input_sample_rate_hz),
+ "-ac",
+ "1",
+ "-i",
+ str(input_pcm_path),
+ "-ar",
+ str(target_sample_rate_hz),
+ "-ac",
+ "1",
+ "-c:a",
+ "pcm_mulaw",
+ str(output_wav_path),
+ ]
+ subprocess.run(command, check=True)
+
+
+def main() -> None:
+ args = parse_args()
+ dataset = load_dataset(args.source_csv)
+
+ ensure_dir(args.output_dir)
+ ensure_dir(args.output_csv.parent)
+
+ client = OpenAI()
+
+ audio_paths: list[str] = []
+ for _, row in dataset.iterrows():
+ example_id = str(row["example_id"]).strip()
+ user_text = str(row["user_text"]).strip()
+ if not example_id:
+ raise ValueError("example_id is empty")
+
+ output_wav_path = args.output_dir / f"{example_id}.wav"
+ audio_paths.append(str(output_wav_path.relative_to(args.output_csv.parent)))
+
+ if output_wav_path.exists() and not args.overwrite:
+ continue
+
+ temp_pcm_path = args.output_dir / f"{example_id}.pcm"
+ tts_to_pcm_file(client, user_text, temp_pcm_path, args.tts_model, args.voice)
+
+ encode_pcm_to_ulaw_wav(
+ temp_pcm_path,
+ output_wav_path,
+ input_sample_rate_hz=args.tts_sample_rate_hz,
+ target_sample_rate_hz=args.target_sample_rate_hz,
+ )
+
+ temp_pcm_path.unlink(missing_ok=True)
+
+ output_dataset = dataset.copy()
+ if "expected_keywords" in output_dataset.columns:
+ output_dataset = output_dataset.drop(columns=["expected_keywords"])
+ output_dataset["audio_path"] = audio_paths
+ output_dataset.to_csv(args.output_csv, index=False)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/evals/realtime_evals/walk_harness/run_realtime_evals.py b/examples/evals/realtime_evals/walk_harness/run_realtime_evals.py
new file mode 100644
index 00000000..f2960ece
--- /dev/null
+++ b/examples/evals/realtime_evals/walk_harness/run_realtime_evals.py
@@ -0,0 +1,467 @@
+"""Realtime eval walk harness runner.
+
+Replay saved G.711 mu-law WAV audio deterministically with fixed chunking and
+manual turn commits (VAD off) to keep runs comparable.
+
+How to run:
+1) Generate audio (one-time): python walk_harness/generate_audio.py
+2) Run evals: python walk_harness/run_realtime_evals.py
+3) Quick check: python walk_harness/run_realtime_evals.py --max-examples 2
+"""
+
+import argparse
+import asyncio
+import json
+import struct
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, cast
+
+import pandas as pd
+from openai import AsyncOpenAI
+from openai.types.realtime import (
+ RealtimeResponseCreateParamsParam,
+ RealtimeSessionCreateRequestParam,
+)
+from tqdm import tqdm
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+if str(ROOT_DIR) not in sys.path:
+ sys.path.insert(0, str(ROOT_DIR))
+
+from shared.graders import compute_tool_call_grade
+from shared.metrics_utils import add_numeric_summaries, order_columns
+from shared.realtime_harness_utils import (
+ audio_format_config,
+ collect_realtime_response,
+ ensure_dir,
+ stream_audio_to_connection,
+ write_pcm16_wav,
+)
+
+SHARED_DIR = ROOT_DIR / "shared"
+DEFAULT_DATA_CSV = ROOT_DIR / "walk_harness" / "data" / "customer_service_synthetic.csv"
+DEFAULT_RESULTS_DIR = ROOT_DIR / "walk_harness" / "results"
+DEFAULT_SYSTEM_PROMPT_PATH = SHARED_DIR / "system_prompt.txt"
+DEFAULT_TOOLS_PATH = SHARED_DIR / "tools.json"
+
+DEFAULT_MODEL = "gpt-realtime"
+DEFAULT_VOICE = "marin"
+DEFAULT_CHUNK_MS = 20
+DEFAULT_SAMPLE_RATE_HZ = 8000
+DEFAULT_INPUT_AUDIO_FORMAT = "g711_ulaw"
+DEFAULT_OUTPUT_AUDIO_FORMAT = "pcm16"
+DEFAULT_OUTPUT_SAMPLE_RATE_HZ = 24000
+DEFAULT_MAX_OUTPUT_TOKENS = 512
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Run realtime walk evals with saved-audio replay."
+ )
+ parser.add_argument("--data-csv", type=Path, default=DEFAULT_DATA_CSV)
+ parser.add_argument("--results-dir", type=Path, default=DEFAULT_RESULTS_DIR)
+ parser.add_argument("--run-name", type=str, default="")
+ parser.add_argument("--model", type=str, default=DEFAULT_MODEL)
+ parser.add_argument(
+ "--system-prompt-file", type=Path, default=DEFAULT_SYSTEM_PROMPT_PATH
+ )
+ parser.add_argument("--tools-file", type=Path, default=DEFAULT_TOOLS_PATH)
+ parser.add_argument("--voice", type=str, default=DEFAULT_VOICE)
+ parser.add_argument("--chunk-ms", type=int, default=DEFAULT_CHUNK_MS)
+ parser.add_argument("--sample-rate-hz", type=int, default=DEFAULT_SAMPLE_RATE_HZ)
+ parser.add_argument(
+ "--input-audio-format", type=str, default=DEFAULT_INPUT_AUDIO_FORMAT
+ )
+ parser.add_argument(
+ "--output-audio-format", type=str, default=DEFAULT_OUTPUT_AUDIO_FORMAT
+ )
+ parser.add_argument(
+ "--output-sample-rate-hz", type=int, default=DEFAULT_OUTPUT_SAMPLE_RATE_HZ
+ )
+ parser.add_argument(
+ "--max-output-tokens", type=int, default=DEFAULT_MAX_OUTPUT_TOKENS
+ )
+ parser.add_argument(
+ "--real-time", action="store_true", help="Send audio at real-time cadence."
+ )
+ parser.add_argument(
+ "--max-examples",
+ type=int,
+ default=0,
+ help="Limit number of examples for quick checks.",
+ )
+ return parser.parse_args()
+
+
+def load_system_prompt(path: Path) -> str:
+ return path.read_text(encoding="utf-8").strip()
+
+
+def load_tools(path: Path) -> List[Dict[str, Any]]:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def load_dataset(path: Path) -> pd.DataFrame:
+ data = pd.read_csv(path)
+ required_columns = {
+ "example_id",
+ "user_text",
+ "gt_tool_call",
+ "gt_tool_call_arg",
+ "audio_path",
+ }
+ missing = required_columns.difference(data.columns)
+ if missing:
+ raise ValueError(f"Missing required columns: {sorted(missing)}")
+ return data
+
+
+def read_ulaw_wav(audio_path: Path, expected_sample_rate_hz: int) -> bytes:
+ data = audio_path.read_bytes()
+ if len(data) < 12:
+ raise ValueError(f"Invalid WAV header in {audio_path}")
+
+ riff_id = data[0:4]
+ wave_id = data[8:12]
+ if riff_id != b"RIFF" or wave_id != b"WAVE":
+ raise ValueError(f"Expected RIFF/WAVE header in {audio_path}")
+
+ offset = 12
+ fmt_info: Dict[str, int] = {}
+ data_bytes = None
+
+ while offset + 8 <= len(data):
+ chunk_id = data[offset : offset + 4]
+ chunk_size = struct.unpack_from("<I", data, offset + 4)[0]
+ chunk_start = offset + 8
+ chunk_end = chunk_start + chunk_size
+ if chunk_end > len(data):
+ raise ValueError(f"Invalid chunk size in {audio_path}")
+
+ if chunk_id == b"fmt ":
+ if chunk_size < 16:
+ raise ValueError(f"Invalid fmt chunk in {audio_path}")
+ (
+ audio_format,
+ num_channels,
+ sample_rate_hz,
+ byte_rate,
+ block_align,
+ bits_per_sample,
+ ) = struct.unpack_from("<HHIIHH", data, chunk_start)
+ fmt_info = {
+ "audio_format": audio_format,
+ "num_channels": num_channels,
+ "sample_rate_hz": sample_rate_hz,
+ "byte_rate": byte_rate,
+ "block_align": block_align,
+ "bits_per_sample": bits_per_sample,
+ }
+ elif chunk_id == b"data":
+ data_bytes = data[chunk_start:chunk_end]
+
+ offset = chunk_end if chunk_size % 2 == 0 else chunk_end + 1
+
+ if not fmt_info:
+ raise ValueError(f"Missing fmt chunk in {audio_path}")
+ if data_bytes is None:
+ raise ValueError(f"Missing data chunk in {audio_path}")
+
+ if fmt_info["audio_format"] != 7:
+ raise ValueError(f"Expected mu-law WAV format tag 7 in {audio_path}")
+ if fmt_info["num_channels"] != 1:
+ raise ValueError(f"Expected mono audio in {audio_path}")
+ if fmt_info["bits_per_sample"] != 8:
+ raise ValueError(f"Expected 8-bit mu-law audio in {audio_path}")
+ if fmt_info["sample_rate_hz"] != expected_sample_rate_hz:
+ raise ValueError(
+ f"Expected sample rate {expected_sample_rate_hz} Hz but got {fmt_info['sample_rate_hz']} in {audio_path}"
+ )
+
+ return data_bytes
+
+
+def resolve_audio_path(audio_path_value: str, dataset_path: Path) -> Path:
+ if not audio_path_value:
+ raise ValueError("audio_path is empty")
+ audio_path = Path(audio_path_value)
+ if not audio_path.is_absolute():
+ audio_path = dataset_path.parent / audio_path
+ return audio_path
+
+
+async def run_single_eval(
+ async_client: AsyncOpenAI,
+ row: pd.Series,
+ system_prompt: str,
+ tools: List[Dict[str, Any]],
+ run_audio_dir: Path,
+ events_dir: Path,
+ config: Dict[str, Any],
+ dataset_path: Path,
+) -> Dict[str, Any]:
+ example_id = str(row["example_id"])
+ user_text = str(row["user_text"])
+ expected_tool_call = (
+ "" if bool(pd.isna(row["gt_tool_call"])) else str(row["gt_tool_call"])
+ )
+ expected_tool_call_arg = (
+ "" if bool(pd.isna(row["gt_tool_call_arg"])) else str(row["gt_tool_call_arg"])
+ )
+
+ audio_path = resolve_audio_path(str(row["audio_path"]), dataset_path)
+
+ if config["input_audio_format"] != "g711_ulaw":
+ raise ValueError("This walk harness expects g711_ulaw input audio.")
+
+ input_audio_bytes = read_ulaw_wav(audio_path, config["sample_rate_hz"])
+
+ event_log_path = events_dir / f"{example_id}.jsonl"
+
+ async with async_client.realtime.connect(model=config["model"]) as connection:
+ # Disable VAD/turn detection so turn boundaries are controlled explicitly via
+ # `input_audio_buffer.commit()` (keeps replay runs comparable).
+ session = {
+ "type": "realtime",
+ "instructions": system_prompt,
+ "tools": tools,
+ "tool_choice": "auto",
+ "output_modalities": ["audio"],
+ "audio": {
+ "input": {
+ "format": audio_format_config(
+ config["input_audio_format"], config["sample_rate_hz"]
+ ),
+ "turn_detection": None,
+ },
+ "output": {
+ "format": audio_format_config(
+ config["output_audio_format"],
+ config["output_sample_rate_hz"],
+ ),
+ "voice": config["voice"],
+ },
+ },
+ "max_output_tokens": config["max_output_tokens"],
+ }
+ await connection.session.update(
+ session=cast(RealtimeSessionCreateRequestParam, session)
+ )
+
+ await stream_audio_to_connection(
+ connection,
+ input_audio_bytes,
+ config["chunk_ms"],
+ config["sample_rate_hz"],
+ config["input_audio_format"],
+ config["real_time"],
+ )
+
+ response_payload: RealtimeResponseCreateParamsParam = {}
+ with event_log_path.open("w", encoding="utf-8") as log_file:
+ # Persist the full event stream so latency/tool-call issues are traceable.
+ response_result = await collect_realtime_response(
+ connection, response_payload, log_file=log_file
+ )
+
+ assistant_text = response_result["assistant_text"]
+ tool_calls = response_result["tool_calls"]
+ output_audio_bytes = response_result["output_audio_bytes"]
+ tool_call_grade_data = compute_tool_call_grade(
+ expected_tool_call, expected_tool_call_arg, tool_calls
+ )
+ tool_call_correctness = tool_call_grade_data["tool_call_correctness"]
+ tool_call_arg_correctness = tool_call_grade_data["tool_call_arg_correctness"]
+ grade = 1 if tool_call_correctness == 1 and tool_call_arg_correctness == 1 else 0
+
+ output_audio_path = ""
+ if output_audio_bytes:
+ example_audio_dir = run_audio_dir / example_id
+ ensure_dir(example_audio_dir)
+ output_audio_path = str(example_audio_dir / "output.wav")
+ write_pcm16_wav(
+ Path(output_audio_path),
+ bytes(output_audio_bytes),
+ config["output_sample_rate_hz"],
+ )
+
+ usage_data = response_result["usage"]
+ usage_output_tokens = usage_data.get("output_tokens", None)
+ usage_output_audio_tokens = None
+ usage_output_text_tokens = None
+ if "output_token_details" in usage_data:
+ output_details = usage_data["output_token_details"]
+ usage_output_audio_tokens = output_details.get("audio_tokens")
+ usage_output_text_tokens = output_details.get("text_tokens")
+
+ return {
+ "example_id": example_id,
+ "user_text": user_text,
+ "gt_tool_call": expected_tool_call,
+ "gt_tool_call_arg": expected_tool_call_arg,
+ "audio_path": str(audio_path),
+ "assistant_text": assistant_text,
+ "output_audio_path": output_audio_path,
+ "event_log_path": str(event_log_path),
+ "tool_calls": json.dumps(tool_calls),
+ "pred_tool_call": tool_call_grade_data["pred_tool_call"],
+ "pred_tool_call_arg": tool_call_grade_data["pred_tool_call_arg"],
+ "tool_call_correctness": tool_call_correctness,
+ "tool_call_arg_correctness": tool_call_arg_correctness,
+ "grade": grade,
+ "latency_first_audio_ms": response_result["first_audio_time_ms"],
+ "latency_first_text_ms": response_result["first_text_time_ms"],
+ "latency_response_done_ms": response_result["response_done_time_ms"],
+ "output_tokens": usage_output_tokens,
+ "output_audio_tokens": usage_output_audio_tokens,
+ "output_text_tokens": usage_output_text_tokens,
+ }
+
+
+def compute_summary(results: pd.DataFrame) -> Dict[str, Any]:
+ summary: Dict[str, Any] = {
+ "total_examples": int(results.shape[0]),
+ "grade_mean": float(results["grade"].mean()) if not results.empty else 0.0,
+ }
+ if "tool_call_correctness" in results.columns and not results.empty:
+ summary["tool_call_correctness_mean"] = float(
+ results["tool_call_correctness"].mean()
+ )
+ if "tool_call_arg_correctness" in results.columns and not results.empty:
+ summary["tool_call_arg_correctness_mean"] = float(
+ results["tool_call_arg_correctness"].mean()
+ )
+
+ add_numeric_summaries(
+ summary,
+ results,
+ [
+ "latency_first_audio_ms",
+ "latency_first_text_ms",
+ "latency_response_done_ms",
+ "output_tokens",
+ "output_audio_tokens",
+ "output_text_tokens",
+ ],
+ )
+
+ return summary
+
+
+def order_result_columns(results: pd.DataFrame) -> pd.DataFrame:
+ preferred = [
+ "example_id",
+ "user_text",
+ "gt_tool_call",
+ "pred_tool_call",
+ "gt_tool_call_arg",
+ "pred_tool_call_arg",
+ "tool_call_correctness",
+ "tool_call_arg_correctness",
+ "grade",
+ "assistant_text",
+ "tool_calls",
+ "event_log_path",
+ "audio_path",
+ "output_audio_path",
+ "latency_first_audio_ms",
+ "latency_first_text_ms",
+ "latency_response_done_ms",
+ "output_tokens",
+ "output_audio_tokens",
+ "output_text_tokens",
+ ]
+ return order_columns(results, preferred)
+
+
+async def run_evals() -> None:
+ args = parse_args()
+
+ system_prompt = load_system_prompt(args.system_prompt_file)
+ tools = load_tools(args.tools_file)
+ dataset = load_dataset(args.data_csv)
+
+ if args.max_examples > 0:
+ dataset = dataset.head(args.max_examples)
+
+ run_timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
+ run_name = args.run_name or run_timestamp
+ run_dir = args.results_dir / run_name
+ run_audio_dir = run_dir / "audio"
+ run_events_dir = run_dir / "events"
+ ensure_dir(run_audio_dir)
+ ensure_dir(run_events_dir)
+
+ config = {
+ "model": args.model,
+ "chunk_ms": args.chunk_ms,
+ "sample_rate_hz": args.sample_rate_hz,
+ "input_audio_format": args.input_audio_format,
+ "output_audio_format": args.output_audio_format,
+ "output_sample_rate_hz": args.output_sample_rate_hz,
+ "max_output_tokens": args.max_output_tokens,
+ "real_time": args.real_time,
+ "voice": args.voice,
+ }
+
+ async_client = AsyncOpenAI()
+
+ results: List[Dict[str, Any]] = []
+ total_examples = int(dataset.shape[0])
+ print(f"Running walk evals: {total_examples} examples -> {run_dir}")
+ for _, row in tqdm(dataset.iterrows(), total=total_examples, desc="Walk evals"):
+ result = await run_single_eval(
+ async_client,
+ row,
+ system_prompt,
+ tools,
+ run_audio_dir,
+ run_events_dir,
+ config,
+ args.data_csv,
+ )
+ results.append(result)
+
+ results_df = pd.DataFrame(results)
+ results_df = order_result_columns(results_df)
+ results_csv_path = run_dir / "results.csv"
+ results_df.to_csv(results_csv_path, index=False)
+
+ summary = compute_summary(results_df)
+ summary.update(
+ {
+ "run_name": run_name,
+ "model": args.model,
+ "chunk_ms": args.chunk_ms,
+ "sample_rate_hz": args.sample_rate_hz,
+ "input_audio_format": args.input_audio_format,
+ "output_audio_format": args.output_audio_format,
+ "output_sample_rate_hz": args.output_sample_rate_hz,
+ "max_output_tokens": args.max_output_tokens,
+ "real_time": args.real_time,
+ "voice": args.voice,
+ "data_csv": str(args.data_csv),
+ "system_prompt_file": str(args.system_prompt_file),
+ "tools_file": str(args.tools_file),
+ }
+ )
+
+ summary_path = run_dir / "summary.json"
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
+ print(
+ "Summary:"
+ f" grade_mean={summary.get('grade_mean', 0):.3f}"
+ f" tool_call_correctness_mean={summary.get('tool_call_correctness_mean', 0):.3f}"
+ f" tool_call_arg_correctness_mean={summary.get('tool_call_arg_correctness_mean', 0):.3f}"
+ )
+ print(f"Wrote results to {run_dir}")
+
+
+def main() -> None:
+ asyncio.run(run_evals())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/images/realtime_eval_guide/page_01_image_01.png b/images/realtime_eval_guide/page_01_image_01.png
new file mode 100644
index 00000000..72e036ef
Binary files /dev/null and b/images/realtime_eval_guide/page_01_image_01.png differ
diff --git a/images/realtime_eval_guide/page_02_image_01.png b/images/realtime_eval_guide/page_02_image_01.png
new file mode 100644
index 00000000..4fbdfdbd
Binary files /dev/null and b/images/realtime_eval_guide/page_02_image_01.png differ
diff --git a/images/realtime_eval_guide/page_03_image_01.png b/images/realtime_eval_guide/page_03_image_01.png
new file mode 100644
index 00000000..464b6a9f
Binary files /dev/null and b/images/realtime_eval_guide/page_03_image_01.png differ
diff --git a/images/realtime_eval_guide/page_04_image_01.png b/images/realtime_eval_guide/page_04_image_01.png
new file mode 100644
index 00000000..60a43aad
Binary files /dev/null and b/images/realtime_eval_guide/page_04_image_01.png differ
diff --git a/images/realtime_eval_guide/page_04_image_02.png b/images/realtime_eval_guide/page_04_image_02.png
new file mode 100644
index 00000000..09330847
Binary files /dev/null and b/images/realtime_eval_guide/page_04_image_02.png differ
diff --git a/images/realtime_eval_guide/page_05_image_01.png b/images/realtime_eval_guide/page_05_image_01.png
new file mode 100644
index 00000000..ed58cc68
Binary files /dev/null and b/images/realtime_eval_guide/page_05_image_01.png differ
diff --git a/images/realtime_eval_guide/page_05_image_02.png b/images/realtime_eval_guide/page_05_image_02.png
new file mode 100644
index 00000000..32bce6de
Binary files /dev/null and b/images/realtime_eval_guide/page_05_image_02.png differ
diff --git a/images/realtime_eval_guide/page_07_image_01.png b/images/realtime_eval_guide/page_07_image_01.png
new file mode 100644
index 00000000..b8c23776
Binary files /dev/null and b/images/realtime_eval_guide/page_07_image_01.png differ
diff --git a/images/realtime_eval_guide/page_07_image_02.png b/images/realtime_eval_guide/page_07_image_02.png
new file mode 100644
index 00000000..a5e95162
Binary files /dev/null and b/images/realtime_eval_guide/page_07_image_02.png differ
diff --git a/images/realtime_eval_guide/page_08_image_01.png b/images/realtime_eval_guide/page_08_image_01.png
new file mode 100644
index 00000000..113a441a
Binary files /dev/null and b/images/realtime_eval_guide/page_08_image_01.png differ
diff --git a/images/realtime_eval_guide/page_09_image_01.png b/images/realtime_eval_guide/page_09_image_01.png
new file mode 100644
index 00000000..a56314d1
Binary files /dev/null and b/images/realtime_eval_guide/page_09_image_01.png differ
diff --git a/images/realtime_eval_guide/page_10_image_01.png b/images/realtime_eval_guide/page_10_image_01.png
new file mode 100644
index 00000000..915155e1
Binary files /dev/null and b/images/realtime_eval_guide/page_10_image_01.png differ
diff --git a/images/realtime_eval_guide/page_10_image_02.png b/images/realtime_eval_guide/page_10_image_02.png
new file mode 100644
index 00000000..3fe81e6a
Binary files /dev/null and b/images/realtime_eval_guide/page_10_image_02.png differ
diff --git a/images/realtime_eval_guide/page_11_image_01.png b/images/realtime_eval_guide/page_11_image_01.png
new file mode 100644
index 00000000..c196fe0a
Binary files /dev/null and b/images/realtime_eval_guide/page_11_image_01.png differ
diff --git a/registry.yaml b/registry.yaml
index f7db3079..05ee321d 100644
--- a/registry.yaml
+++ b/registry.yaml
@@ -4,6 +4,19 @@
# should build pages for, and indicates metadata such as tags, creation date and
# authors for each page.
+- title: Realtime Eval Guide
+ path: examples/Realtime_eval_guide.ipynb
+ slug: realtime-eval-guide
+ date: 2026-01-25
+ authors:
+ - minh-hoque
+ tags:
+ - realtime
+ - speech
+ - audio
+ - responses
+ - evals
+
- title: Build your own content fact checker with gpt-oss-120B, Cerebras, and Parallel
path: articles/gpt-oss/build-your-own-fact-checker-cerebras.ipynb
slug: build-your-own-fact-checker-cerebras
@@ -3029,7 +3042,7 @@
- msingh-openai
- emreokcular
tags:
- - images
+ - images
- vision
- title: Prompt Personalities