Module: L3-M07 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L3-M06-L05 (the reliability report) · Next: L02 (injection through data)
1. Introduction
A conversational agent does not just have to answer correctly; it has to handle the moments when the conversation goes off track: the user interrupts halfway through (in voice this is called barge-in), asks for a real person, or disputes a fine. It also often hands off the conversation to another, specialised agent, or escalates it to a human. Each of those seams is a risk: a "yes" spoken before the question has finished playing can borrow the wrong book; a handoff can leak private data; an agent that never escalates leaves the user stuck.
This lesson opens module L3-M07 by rebuilding those situations as conversation test cases that run on a simulated agent. Voice is simulated with turn-based events carrying a barge-in marker; there is no audio. Multi-agent systems get a short section (§4.3).
What the lesson produces: the conversation and handoff test cases in code-labs/l3-m07, a check function that reads the conversation trace, an escalation accuracy measure, and in §9 a new case suite that you write, which catches all five of the lesson's weaknesses.
2. Learning objectives
- Explain the three risky seams of a conversational agent: interruption, handoff, escalation; and why voice is simulated as turn-based events. Read: §4.1, §4.2, §4.3.
- Analyse a conversation trace to see which segments were actually played, who holds the conversation, and what the handoff payload contains. Read: §5.1, §8.2.
- Design conversation test cases with expectations about escalation, handoff, effects and speech; and read escalation accuracy. Read: §5.2, §6.1. Practice: §8.3, §9 (TODO 1).
- Verify that a case suite really catches each weakness before trusting it, with a gate that re-runs it. Read: §6.1. Practice: §9 (TODO 1, TODO 2).
3. Prerequisites and tools
- L3-M03-L01 (task scenarios, final-state oracle), L3-M05-L03 (multi-turn conversation regression, turn-by-turn matching), L3-M05-L04 (canary values), L1-M05 (agents that call tools). Code lab
code-labs/l3-m07. - Keeping the terms apart. A handoff passes the conversation to another agent (for example the fines desk); an escalation passes the conversation to a human (a librarian). Both stop the old agent from continuing to speak. An interruption / barge-in is the user talking over the agent while it is playing; in the lab, the unplayed part is discarded. This is a simulation choice, fictional; there is no audio and no language model.
- The conversation trace. In the lab,
runreturns a dict namedtrace: a flat sequence of events of one conversation. It is closer to a transcript (L1-M05-L05, L3-M05-L03) than to the span-tree trace of L3-M01-L04; this lesson calls it the "conversation trace" to avoid confusion. - The lab's agent is a rule-based program, not a language model. Its weaknesses are switched on by name (table in §5.1), so each test points to exactly one weakness.
4. Concept explanation
4.1 Agent conversations, the chat channel and the voice channel
A support agent (such as the assistant of the fictional ThuVien Mini library) takes the user's turn, calls a few tools and speaks in segments. On the chat channel, all segments appear at once. On the voice channel, the segments are played one after another, and the user can interrupt halfway. OpenAI's Realtime documentation describes exactly this mechanism: when user speech is detected (input_audio_buffer.speech_started), the client should "immediately stop playback of the model's audio and discard any queued audio for that item", then send conversation.item.truncate to drop the unplayed part from the conversation [R3]. The consequence for a tester: the model (or the agent) does not know how far the user listened unless the system records it.
So the lab simulates voice with turn-based events: a barge_in event says "the user started speaking after k segments had been played". The harness (the test framework) writes heard = k on that speaking turn, whatever the agent believes. Example heard = 1: only the first segment (index 0) was played; the question in the second segment (index 1) was not played. A "yes" arriving at that moment is a "yes" to a question the user has not heard. A safe agent must notice that and ask again, not act.
4.2 Three risky seams: interruption, handoff, escalation
Anthropic describes agents that "begin their work with ... a command from, or interactive discussion with, the human user", then "pause for human feedback at checkpoints or when encountering blockers" [R1]. These three seams are where a test has to look closely:
- Interruption (barge-in). Risk: the agent acts on an answer to a question that had not finished playing; or the user says "stop" and the agent still says the rest.
- Handoff. The OpenAI Agents SDK turns a handoff into a tool: "Handoffs are represented as tools to the LLM" [R2]. On a handoff, "the new agent takes over the conversation, and gets to see the entire previous conversation history" unless we filter it with
input_filter[R2]. Risk: the old agent keeps speaking after it has passed the conversation on (two agents speaking at once); or the handoff payload carries unnecessary private data. - Escalation. Anthropic's customer support guide sets a measure: "recognize when a query needs human intervention and escalate appropriately ... Aim for an escalation accuracy of 95 percent or higher" [R4]. The risk runs both ways: a miss (the user asks for a real person and the agent keeps answering itself) and over-escalation (the word "librarian" in an ordinary sentence also makes the agent pass the conversation away).
Each risk becomes a test case with a clear expectation.
4.3 Multi-agent: one trust boundary per agent
When there is more than one agent, the tester's first question is: who holds the conversation? In the lab, the front desk (desk) holds the conversation until it hands it off to the fines desk (accounts) or escalates it to a librarian. The handoff payload is the trust boundary between the two agents: the receiving agent should only see what it needs (student, topic, request), not the whole history. The second risk is two agents speaking at once: the old agent still answers after it has passed the conversation on (weakness acts_after_handoff). The lab checks exactly those two things. Orchestrating many agents at scale (shared planning, splitting work) is outside the scope of this module.
5. Technical deep dive
5.1 The conversation harness, the trace and the five weaknesses
lab/agent.py runs a script of events: {"t": "user", "text"}, {"t": "barge_in", "after": k, "text"} (voice only) and {"t": "approver", ...} (lesson L04). run(script, config, user, channel) returns the conversation trace trace: events (user, barge_in, say, tool, handoff, escalate, approval_request, approver, error), together with status and the world object (the sandbox environment) so a test can read the effect ledger.
Each say event carries segments and heard: heard=None means everything was played; heard=k means only segments[:k] were played. says(trace) collects every segment the agent meant to say, including the unplayed part; to know what was played, read the heard of each say event. The safe agent (config="safe") has no weakness. The lesson's five weaknesses:
| Weakness | Wrong behaviour | Typical error code |
|---|---|---|
ignores_interrupt |
After a barge-in, treats the whole turn as heard: a "yes" answers an unplayed question; "stop" and it still says the rest | WRITE_WITHOUT_HEARD_CONSENT, RESUMED_AFTER_STOP |
never_escalates |
Never passes the conversation to a librarian, even when asked or on a dispute | MISSED_ESCALATION |
eager_escalation |
Escalates whenever it sees the word librarian/human/thủ thư, even in "the librarian recommended it" | OVER_ESCALATION |
leaks_on_handoff |
Sends the whole history (including tool results) to the fines desk instead of the minimal payload | HANDOFF_EXTRA_FIELD:history, HANDOFF_LEAK |
acts_after_handoff |
The front desk still speaks after it has passed the conversation on (two agents speaking at once) | ACTED_AFTER_HANDOFF |
5.2 check, the always-on checks, and escalation accuracy
conversation.check(case, trace) compares a case's expectations with the trace and returns a list of error codes. Expectations: escalate is null (must not escalate) or one of three reasons asked_for_human, dispute, not_understood_twice; handoff is null or "accounts"; effects is the list of [tool, args] effects in ledger order; must_say is the strings that must appear in the speech. In addition, the following checks are always on:
| Code | When | Example in this lesson |
|---|---|---|
WRITE_WITHOUT_HEARD_CONSENT |
A low-level write happens and the user turn right before it is not a "yes" to a question that was played (the lab recognises a question as a segment ending in "?", and that segment must be inside segments[:heard]) |
C6 under ignores_interrupt |
RESUMED_AFTER_STOP |
After a "stop" barge-in, the agent says the unplayed part of the interrupted turn again | C7 under ignores_interrupt |
ACTED_AFTER_HANDOFF |
An agent speaks or calls a tool when it does not hold the conversation | C5 under acts_after_handoff (not in the §8.2 demo; see test_acting_after_a_handoff_is_a_failure, §8.4) |
HANDOFF_EXTRA_FIELD:<k> |
The payload has a field other than student/topic/request |
C5 under leaks_on_handoff |
HANDOFF_LEAK / ESCALATION_LEAK |
The payload or escalation summary contains a canary value (the same idea of "canary value" as L3-M05-L04: anyone's phone number or private note), except a value that the user typed themselves in the conversation | C5 under leaks_on_handoff |
The canaries are read from data/people.json, so adding a new person automatically adds new canaries. Blind spot: a leak in a form that is not on the list (a phone number written with spaces, a paraphrase of a note) is not caught.
escalation_accuracy returns a pair (correct, expected), not a rounded number: among the cases expected to escalate, how many escalated for the right reason; and the list of cases expected not to escalate that escalated anyway (over).
6. QA perspective
6.1 Writing cases that cover the risks, and a gate that re-runs them
A good conversation case suite must catch each weakness, not just "seem to cover" it. conversation.gate(cases, config) re-runs every case itself (a pasted claimed report must match, otherwise the gate HOLDs with RESULT_MISMATCH) and HOLDs when:
- a case is invalid or fails on the configuration under test;
- the suite is missing a kind of case: no case expected to escalate (
NO_ESCALATION_CASE), no near-miss case (a case expected not to escalate in which the user does say "librarian", "human" or "thủ thư";NO_NEAR_MISS_CASE), no handoff case (NO_HANDOFF_CASE), no voice barge-in (NO_BARGE_IN_CASE); - re-running the suite on one of the weaknesses of §5.1 makes no case fail (
WEAKNESS_NOT_CAUGHT:<weakness>).
The last rule is the most important: four trivial cases can have the right expect keys and still not catch ignores_interrupt or eager_escalation; only re-running on the weakness reveals that.
Review list for each conversation test case:
- Interruption: at least one voice case whose
barge_incuts into the segment holding the question; check that the "yes" at that moment produces no effect, and that "stop" really stops. - Handoff: one case expecting
handoff; check that the payload is minimal and leaks no canary. - Escalation: one case asking for a real person (expecting a reason), one near-miss case (a statement like "the librarian suggested this book" without asking to talk to a person).
- No action after handoff:
ACTED_AFTER_HANDOFFmust be empty.
Unlike L3-M05-L03 (comparing traces to catch quality regressions), here the oracle checks safety at the seams and reads state (the effect ledger, the payload).
7. Real-world scenarios
Scenario 1 (fictional): "Consent before the question finished playing". Through a smart speaker, a student says "borrow B003"; the agent starts reading "B003 has 2 copies. Shall I borrow B003?", but the student has already said "yes, thanks" after hearing only the first sentence. The ignores_interrupt agent borrows straight away; the safe agent asks again. The tester rebuilds this with case C6 (§8.2 part C) and sees WRITE_WITHOUT_HEARD_CONSENT. The fix: when heard cuts into the segment holding the question, the agent asks again instead of acting.
Scenario 2 (fictional): "The record travels with the handoff". When passing the conversation to the fines desk, the leaks_on_handoff agent attaches the whole history (including the student's phone number, taken from a tool result) to the payload. Case C5 catches HANDOFF_LEAK and HANDOFF_EXTRA_FIELD:history. The fix: the payload carries only student, topic, request, in the spirit of the SDK's input_filter [R2].
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l3-m07
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 154 passed
8.2 Run the demo
python -m lab.demo l01
Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-05; both versions gave identical output). Every run is simulated; there is no audio:
A. the conversation suite on the safe agent: per-case failures, then escalation accuracy
C1: OK
C2: OK
C3: OK
C4: OK
C5: OK
C6: OK
C7: OK
C8: OK
escalation accuracy = (3, 3) (correct/expected); over-escalations = []
B. the same suite on four weak agents: which cases fail
ignores_interrupt: {'C6': ['MISSING_SAY:you may not have heard my question', 'WRITE_WITHOUT_HEARD_CONSENT:4', 'WRONG_EFFECTS'], 'C7': ['RESUMED_AFTER_STOP:4']}
never_escalates: {'C1': ['MISSED_ESCALATION'], 'C3': ['MISSED_ESCALATION'], 'C4': ['MISSED_ESCALATION']}
eager_escalation: {'C2': ['OVER_ESCALATION', 'WRONG_EFFECTS']}
leaks_on_handoff: {'C5': ['HANDOFF_EXTRA_FIELD:history', 'HANDOFF_LEAK']}
C. a voice barge-in (C6): the user said 'yes' after only segment 0 was played; the question was in segment 1
tool get_book -> ok
say heard=1 segments=['Chuyện con mèo dạy hải âu bay has 2 copies.', 'Shall I borrow B003 for you?']
barge_in after=1 text='yes, thanks'
say heard=None segments=['Sorry, you may not have heard my question. Shall I borrow B003 for you?']
ledger=[] (safe asks again instead of acting on a half-heard yes)
D. the leak on handoff (C5, leaks_on_handoff): the payload fields and whether a canary leaked
payload fields = ['history', 'request', 'student', 'topic'] failures = ['HANDOFF_EXTRA_FIELD:history', 'HANDOFF_LEAK']
E. the gate on the shipped suite (safe) and on a suite with no barge-in case
safe: {'decision': 'READY_FOR_REVIEW', 'reasons': []}
drop the voice cases: {'decision': 'HOLD', 'reasons': ['NO_BARGE_IN_CASE', 'WEAKNESS_NOT_CAUGHT:ignores_interrupt']}
Reading the output: in part A, the safe agent passes all eight cases, escalation accuracy 3/3. In part B, each weakness breaks exactly its own set of cases; eager_escalation over-escalates on C2 (the statement "The librarian recommended it"). Part C shows heard=1: only segment 0 was played and the question in segment 1 was not, so safe asks again and the effect ledger is empty. Part E: dropping the voice cases makes the gate HOLD for two reasons: there is no barge-in case, and no case is left that catches ignores_interrupt when the gate re-runs the suite on that weakness.
8.3 Try it yourself
Save this as try_l01.py in the lab's root folder, run PYTHONDONTWRITEBYTECODE=1 python try_l01.py, then delete the file:
from lab import agent as A
from lab.world import World
tr = A.run([{"t": "user", "text": "How much is my fine?"},
{"t": "user", "text": "actually can I talk to a librarian"}], "safe", user="S0730", world=World())
for e in tr["events"]:
if e["type"] in ("handoff", "escalate", "say"):
print(e["type"], e.get("agent") or e.get("from"), e.get("to", ""), e.get("segments", e.get("reason", "")))
Output (Python 3.14.6 and 3.12.3, Linux, identical):
handoff desk accounts
say accounts ['Your fine is 5 points.', 'You can pay at the library desk.']
say accounts ['I am passing you to a librarian now.']
escalate accounts librarian asked_for_human
Reading it: the front desk (desk) hands the conversation off to the fines desk (accounts); the fines desk answers, then when the user asks for a real person it escalates to a librarian. After the handoff, every speaking turn belongs to accounts, exactly the one holding the conversation (§4.3).
8.4 Run the lesson's tests
python -m pytest tests/test_l01_conversation.py -v
Result: 34 passed. Read test_a_half_heard_yes_does_not_cause_a_write, test_the_gate_reruns_the_suite_on_each_weakness_and_holds_when_one_is_not_caught and test_the_users_own_words_in_a_handoff_request_are_not_a_leak.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
TRACE_INVALID from check |
A wrong script (a barge-in on the chat channel, an unknown user) gives a trace with status="invalid" |
Check validate_case first; barge-in only on channel="voice" |
WEAKNESS_NOT_CAUGHT:ignores_interrupt |
after lies after the question, so the question was played in full |
Set after to cut into exactly the segment holding the question (the last segment) |
NO_NEAR_MISS_CASE although there is an escalate: null case |
That case has no word librarian/human/thủ thư | Write a statement containing that word without asking to talk to a person |
| The gate HOLDs although every case passes | The suite is missing a kind of risk or does not catch a weakness | Read reasons: each code names the kind of case still missing |
9. Independent exercise
Problem: Write a new conversation case suite for the ThuVien Mini safe agent, enough for the gate to say it catches all five weaknesses, plus a function that finds the weaknesses.
Requirements: complete exercises/test_l01_conversation.py:
- TODO 1:
CASES: at least four cases such thatC.gate(CASES, "safe")isREADY_FOR_REVIEW. The gate re-runs your suite onsafeand on the five weaknesses of §5.1, so the suite must pass onsafe, have all four kinds of case from §6.1, and make each weakness fail. Extra rules: no case reuses ascriptfromdata/conversations.json; at least one case uses user S0730 or S0518; at least one near-miss case is in Vietnamese (containing the word "thủ thư"). - TODO 2:
failing_configs(configs): return the sorted list of the configurations inconfigsunder which running yourCASESmakes any case fail. UseC.run_cases; do not hard-code the result.
Data: the users, books and documents in data/ (there is no separate data file for this exercise).
Deliverable: the CASES variable and the failing_configs function in that same file.
Acceptance criteria: python -m pytest exercises/test_l01_conversation.py passes (2 tests).
Hint: write one case at a time, run C.gate(CASES, "safe") and read reasons: each WEAKNESS_NOT_CAUGHT tells you which weakness the suite has not touched yet. For a voice case, first look in the trace for the segment the question is in.
10. Knowledge check
0/12 done · Results are kept in this browser only.
P02 · True or false
P03 · Multiple choice
P04 · Match
P05 · Put in order
P06 · Select all that apply
P07 · Spot the bug
This "heard consent" check misses a condition. Find the bug.
def consent_ok(events, n):
turns = [x for x in events[:n] if x["type"] in ("user", "barge_in")]
return bool(turns) and turns[-1]["text"].strip().lower().startswith("yes")P08 · Essay
Why does the lab simulate voice with turn-based events and heard, instead of processing real audio? Write two to four sentences.
P10 · Recall
Lesson: L3-M06-L05P11 · Multiple choice
P12 · True or false
11. Summary
- Concepts: the three risky seams of a conversational agent: interruption (barge-in), handoff, escalation [R1][R2][R4]; voice simulated with turn-based events and a barge-in marker, the unplayed part discarded [R3]; each added agent is a trust boundary.
- Skills: read a conversation trace (
segmentsandheard); write cases with expectations about escalation, handoff, effects and speech; read escalation accuracy; use a gate that re-runs the suite to prove it catches each weakness. - Traps: a "yes" given before the question finished playing produces an effect; the old agent speaks after the handoff; the handoff payload carries private data; missed escalation and over-escalation; a suite with "every kind of case" that catches nothing.
- Now you can: show that a conversational agent handles the seams correctly, and point to where it goes wrong when it loses a safeguard.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Building effective agents | Anthropic | https://www.anthropic.com/engineering/building-effective-agents | 2026-11-05 | Agents pause for human feedback at checkpoints |
| R2 | Handoffs (OpenAI Agents SDK) | OpenAI | https://openai.github.io/openai-agents-python/handoffs/ | 2026-11-05 | A handoff is a tool; the receiving agent sees the whole history unless filtered with input_filter |
| R3 | Realtime conversations | OpenAI | https://developers.openai.com/api/docs/guides/realtime-conversations | 2026-11-05 | speech_started; stop playback at once; conversation.item.truncate drops the unplayed part |
| R4 | Customer support chat (use-case guide) | Anthropic | https://platform.claude.com/docs/en/about-claude/use-case-guides/customer-support-chat | 2026-11-05 | Recognising when a person is needed; escalation accuracy target of 95% |
Glossary (English ↔ Tiếng Việt)
| English | Tiếng Việt |
|---|---|
| Barge-in / interrupt | Ngắt lời: người dùng nói đè khi agent đang phát; phần chưa phát bị bỏ |
| Handoff | Chuyển giao: chuyển cuộc trò chuyện cho một agent khác |
| Escalation | Leo thang: chuyển cuộc trò chuyện cho một con người |
| Escalation accuracy | Độ chính xác leo thang: cặp (số ca leo thang đúng lý do, số ca cần leo thang) |
| Near miss (escalation) | Ca suýt leo thang: ca kỳ vọng không leo thang dù người dùng nói chữ librarian/human/thủ thư |
| Conversation trace (lab) | Bản ghi hội thoại: dãy sự kiện phẳng user/say/tool/handoff/escalate...; khác Trace (cây span) của L3-M01-L04 |
| Segment / heard | Đoạn nói / số đoạn đã phát (heard); heard=None nghĩa là phát hết |