Skip to content

Encounter lifecycle

Start

demo_start / practice_start compile the chosen case and pin the compiled version (with its hash) inside the encounter. Later edits to the case file never affect a running encounter.

Store.check_case runs at start and on every turn:

  1. The pinned case must be compiled-case-v8 and its hash must still match its content.
  2. Cases without an approved release run only in demo practice and only with a demonstration* status.
  3. When FACULTY_REVIEW_GATE=enforce, any case with pending review items is refused.

A turn

sequenceDiagram
  participant L as Learner
  participant I as Interpreter
  participant P as Disclosure policy
  participant R as Realizer
  participant S as Store
  L->>I: utterance (text or transcript)
  I->>P: proposed fact id (at most one)
  P->>P: fact exists, prerequisites disclosed, epoch current
  P->>R: permitted patient-voice text only
  R-->>L: speech / text
  R->>S: event (sequence, epoch, fact_ids, delivery)
  L-->>S: playback completed / interrupted
  • Epochs: an interrupt increments the epoch; any in-flight result for an older epoch is discarded.
  • Idempotency: text actions carry a request_id; replays return the stored result, reuse with different input is refused.
  • Played vs planned: on the native path a fact counts as disclosed only after the client reports completed playback.

Typed learner actions

Every learner utterance, typed or spoken on any path, is interpreted into exactly one action before the policy runs. On the Gemini Live path the voice model never sees fact ids or categories: its answer_trainee tool sends the learner's words, and the server interprets its own transcript (the model's copy is only a fallback).

Action Result
ask_fact Next level of one available fact, spoken by the patient
exam, order Authored finding or result from the examiner channel
problem_representation, differential, management, prescription, past_medication, note Recorded in the encounter; the patient does not hear it
closure Brief patient acknowledgement
hint_request Next hint rung in teaching mode; refused in assessment mode
ask_unscripted Bounded plausible answer (see below)
unclear Patient asks the learner to rephrase (greetings, multiple questions)

The Gemini interpreter runs outside the database transaction; if it is unconfigured, the keyword interpreter answers. If a configured model is over budget or unavailable, the keyword interpreter may still route a question to the improviser or mark it unclear, but a fact question fails closed as unclear with reason interpreter_unavailable, so the patient asks the learner to repeat it instead of guessing a fact. The event records interpreter: keyword_fallback. Client-supplied actions are discarded. Idempotent replays return the stored result without re-interpreting. Every event stores the validated action.

Colloquial expressions and transcript safety

app/lexicon.py holds reviewed-draft entries for colloquial symptom expressions (पेट में गोला, घबराहट, चक्कर, कमज़ोरी, "I am okay", ...), each with possible meanings and clarification prompts.

  • When the patient or attendant says one, the event records it under lexicon_cues: an opportunity to clarify, not a diagnosis. Realizers are told to keep these expressions as said, never turned into medical terms. delhi_06 opens its pain fact with the paper's पेट में गोला example.
  • When a later learner utterance takes up a cue, its action records clarifies: [cue ids].
  • Spoken input stores text_original beside the normalized text (Unicode NFC, Devanagari digits to ASCII, whitespace). On speech only, conservative checks catch likely recognition errors: adjacent yes/no, two different duration units side by side, or a near-miss drug name. These produce a clarification turn ("आपने हाँ कहा या नहीं?") instead of an action, so a misheard question earns neither credit nor penalty. Typed input is never second-guessed; an unedited recorded transcript counts as speech.

Clinical reasoning events

Learners record reasoning with explicit controls (or say it and the interpreter types it): problem_representation (structured Who / When / What semantic-qualifier working summary; every mid-intake revision is kept via the Dynamic PR Scratchpad), differential (comma-separated; every revision is kept), management, prescription (a new medicine now), past_medication (a statement about medicines already taken), note and closure. These are separate events, never mixed with elicited history, and the patient does not hear them. Session review shows them under Clinical reasoning in encounter order (app/encounter/reasoning.py) and maps them to ART/IDEA anchors and a Lay → Clinical semantic qualifier diff in the debrief (app/observers.py, app/progress.py).

Examination and investigations

app/encounter/services.py answers exam and order actions from authored content only, in the examiner channel (never in the patient's voice).

  • Examination is authored per system (vitals, general, throat, chest, abdomen, neck, ...). Requests are normalized through English and Hindi synonyms. A broad request ("examine him") follows the case's declared granularity: ask_to_specify asks which system; general_survey returns general findings and vitals.
  • Investigations map each authored test key to a concept with synonyms. A request naming more than one test waits for confirmation ("confirm") before any result is shown.
  • Unavailable (a recognised system or test the case does not author) and ambiguous ("some blood tests", "stool test" when two stool tests exist) get distinct replies. Nothing is invented.
  • Every event stores service: {items, status}; requesting an examination never demonstrates the learner can perform it.

Answering what the script does not cover

Learners can ask anything; the patient answers plausibly while clinical truth stays fixed (app/encounter/improviser.py).

1. Authored content is reachable. Facts carry an about description and optional attributes (for example the fever fact's onset, max_temperature, antipyretic_response), each with its own triggers and patient-voice levels. A specific question ("fever kitna jaata hai") gets that attribute's answer, not the next depth level. Devanagari triggers are expanded with Roman-Hinglish equivalents (bukhar, khansi, dard...). The interpreter sees each fact's about and attributes and can return fact_id + attribute.

2. Unscripted questions get bounded, plausible answers. A reasonable question no authored fact covers becomes ask_unscripted. The answer is one of:

Class Example Source of permission
consistent_negative "नहीं, ऐसा तो कुछ नहीं है।" to "कान में दर्द है?" The case's permitted_negatives (faculty-authored) or a reviewer's allow negative decision
everyday_detail who lives at home, work, diet, how they came Global everyday topics; off under FACULTY_REVIEW_GATE=enforce
unknown "पता नहीं, डॉक्टर साहब।" Always allowed

The Gemini improviser sees persona, patient knowledge, what was already said, permitted negatives, everyday topics and pinned answers, never truth, differential, kernel, rubric or rules. A validator rejects numbers, medicine names, tests, reports, diagnosis words and any positive symptom, and anything outside the allowed classes; rejection falls back to the deterministic answer (a permitted negative or "don't know"). Accepted answers are pinned so the patient never contradicts itself. A topic the case lists as absent wins over a generic word shared with an authored fact.

Per path: text validates before replying; Sarvam realizes the approved sentence and reverts to it if the realization breaks the bounds; Gemini Live is handed the approved sentence as say before speaking, and the spoken transcript is validated again afterwards (a mismatch is flagged as improvisation_warnings and not pinned). Gemini Live cannot be forced to speak verbatim, which is why the second check stays.

3. Scoring stays honest. Improvised answers never create evidence opportunities, kernel credit or critical-rule matches; review labels them and counts them only as coverage. Reviewers see every improvised claim (Improvised answers panel) and can promote it into a new draft case version, allow it as a permitted negative, or forbid it (the patient then says it does not know).

Progressive disclosure

Facts have 1–3 levels: gist → characterized → precise (a 2-level fact is gist → precise). Each delivery of a fact gives the next unheard level, so one question never jumps from a vague answer to precise numbers; asking again after the deepest level repeats it.

Path Depth advances when
Text the reply is returned
Sarvam cascade the reply is committed
Gemini Live the client reports completed playback (an interrupted gist is offered again)

Every patient event records disclosures: [{id, level, index}] so evidence can credit characterization separately from noticing.

Voice and emotion

Each case declares a voice: gender-matched Sarvam and Gemini voices, a baseline emotion, an emotion range and a pace range. Facts may carry their own affect (for example embarrassment about tobacco). Every patient turn gets a deterministic, per-turn prosody from app/encounter/prosody.py:

  • Emotion: the fact's affect if authored, otherwise the baseline most of the time and another in-range emotion otherwise.
  • Pace and temperature: varied within the case's range and nudged by emotion (tired is slower, hurried faster).
  • Within-response pauses: speech text gets a few unpredictable pauses at clause breaks and occasionally a filler (वो…, मतलब…). Never next to a negation or a number; removing them restores the exact wording (tested over every level of every case).
Path How emotion reaches the voice
Sarvam cascade Realizer prompt gets the emotion note; TTS gets persona speaker, per-turn pace and humanized text
Text + spoken reply Same speaker, pace, temperature and humanized text; record-only replies are never spoken
Gemini Live Persona voiceName and baseline emotion at setup; each fact tool result carries a per-answer delivery note

Gemini's affective-dialog flag is not used: support for the 3.8 Live model is unconfirmed and an unknown setup field would break the session. Sarvam bulbul:v3 has no pitch control, so variation comes from pace, temperature, pauses and wording.

See the listening checklist for live verification.

Attendants and interjections

A case may include an attendant (a family member or caregiver) with their own voice, emotion range and facts. Attendant facts use the same disclosure policy and levels as the patient's; every event records who spoke.

  • Direct questions to the attendant ("मम्मी जी, आप बताइए") are answered by the attendant; the patient stays silent.
  • Interjections are authored on attendant facts: {"after_fact": <patient fact>, "mode": "interrupt" | "after"} or {"after_turn": N, "mode": ...}. Each fires once, as a separate attendant_interjection event that names the patient event it interrupts.
  • interrupt mode cuts the patient off: the browser stops the patient's audio and the attendant talks over the end of it. The patient's turn is reported interrupted, so its fact counts as unheard and is offered again later.
Path Attendant speech
Text Shown inline, labelled with the relation
Text + spoken reply TTS in the attendant's voice; in interrupt mode it cuts in at ~70% of the patient's audio
Gemini Live The server synthesizes the line in the attendant's own voice (Gemini TTS, Sarvam fallback) and streams it; Gemini is told what was said as context only. Disclosure waits for confirmed playback.

Attendant lines restate family viewpoints, logistics or details already in the authored truth; they never add clinical findings. Draft attendants exist for delhi_02, delhi_08, onco_04 and onco_10, all pending review.

Speech plans: timing, disfluency and hedging

Every patient and attendant turn gets a deterministic speech plan (app/encounter/speech_plan.py), recorded on the event, based on the research in Patient speech realism:

Field Values
latency_class / latency_ms simple 150–400 ms; ordinary 300–800; recall (numbers, durations, drugs) 800–1500; dispreferred (denials, "don't know", sensitive topics) 700–2000; slower for age ≥65, pain, fatigue, breathlessness; faster for worry or hurry
disfluency_budget 0–3 events; about 45% of turns stay fully fluent
answer_shape minimal, minimal + expansion, narrative, off-target, trailing, don't-know
certainty confident / hedged / unsure, with hedged ≥ confident overall (real Indian patients hedge about 2:1)
markers matlab, woh, kya bolte hain, toh, haan, achha, bas, thoda, hai na, jaise; rotated, never repeated in a turn; "doctor sahab" in at most 1 in 5 turns

How it reaches the learner:

  • The realizer (Gemini by default, Sarvam as fallback; see Speech providers) writes the disfluency into the words from the plan (repeats before hard words, number repairs, restarts, trailing off, hedges). A guard then checks every number, duration and negation survives, number repairs end on the authored value, no filler sits next to a negation, and no tag na follows a negative; otherwise the clean permitted text is used.
  • Gemini speech renders the plan's pauses as Gemini 3.8 TTS tags: "…" becomes [medium pause] ([long pause] in a hedged or unsure turn), and in a disfluent turn a clause comma becomes [short pause]. No tag is placed before a negation or a number. The affect's delivery note is sent as the style prompt.
  • Sarvam speech (fallback; bulbul:v3 has no pause control) synthesizes disfluent turns per clause (up to three segments) with per-segment pace jitter and joins them with measured silences (200–450 ms, 450–900 ms after a trailing "…").
  • Gemini Live gets the plan in the per-answer delivery note; the browser holds the first audio of the turn until the planned latency has passed.
  • Text practice waits the planned latency before showing the reply.
  • Neutral-audio and text conditions keep timing but drop disfluency.

Speech providers

The request/response voice path (app/voice.py) handles text-mode replies, recorded turns, openings, attendant lines and patient or attendant audio. It runs on Gemini by default (app/gemini_speech.py):

Step Gemini (default) Sarvam (fallback)
Realizer, opening and attendant translation gemini-3.8-flash, low thinking, since 3.8 Flash rejects minimal, same prompts sarvam-105b
Recorded-turn transcription gemini-3.8-flash with inline WAV, verbatim, code-mixed kept as heard saaras:v3 codemix
Patient and attendant audio Gemini 3.8 TTS in the speaker's gemini_voice (same names as Live), pause tags, style prompt; PCM wrapped as WAV bulbul:v3, clause segments joined with silences

VOICE_PROVIDER picks the provider (default gemini when a Gemini key is set). A failed Gemini call is retried once on Sarvam unless SARVAM_FALLBACK=off. Each Gemini call is reserved against the same call caps. Each event records the realizer model that actually answered, and transcription and speech responses carry provider. Continuous voice uses Gemini Live; the Sarvam realtime socket (/api/realtime) is unchanged. The pre-speech gate stays Clef (Pre-speech gating).

Session statistics (latency, disfluencies per 100 words, fluent and hedged shares, answer length, honorific share) appear in the evaluation report with target bands; the comparison harness reports them per system.

Languages

Case content is authored once, in Hindi. app/languages.py holds a profile per dropdown language: Sarvam and Gemini codes (Odia is od-IN for Sarvam, or-IN for Gemini), script, a colloquial-register rule and review status.

  • Sarvam realizer and Gemini Live are told the source is Hindi and must be spoken in the selected language with every number, duration, negation and level of certainty kept, using that language's spoken register.
  • Opening: Gemini speaks its meaning in the selected language; text practice fetches a realized opening once per encounter (/api/opening, cached).
  • Wrong-language replies (mostly outside the selected script) are flagged on the event as output_language_warnings so they are not used for assessment.
  • The dropdown labels every language except Hindi as native review pending. A language code never validates a regional variety.

python3 -m app.tests.language_smoke runs a live opening and fact reply per language on the Sarvam path (needs SARVAM_API_KEY).

Patient voice vs clinical truth

Each fact carries two texts:

Field Audience Example
levels (from patient_voice["hi-IN"]) Patient realizer, one level per delivery (illustrative) बुखार 100 तक गया था, थर्मामीटर से नापा था।
clinical (from content) Assessor only (illustrative) Measured temperature 37.8 °C.

Tests fail if patient speech contains clinical units (°C, mg/dL, decimal temperatures) or note shorthand.