AI and voice
Three AI jobs run on every call (a fourth, the Dispatcher Copilot, answers the dispatcher's questions; see section 4):
- Understanding: the language pipeline plus LLM triage turn the caller's words into findings and a severity distribution.
- Talking: the AI call-taker decides what to say to the caller.
- Hearing and speaking: the real-time voice line does speech-to-text, turn-taking and text-to-speech.
1. Language pipeline and triage
caller text (or Whisper transcript)
│
├─ nlp/langid.py script detection (Tamil Unicode?) + fastText lid.176 + wordfreq code-mix ratio
│ → "ta" | "en" | "mixed"/"latin" (Tanglish when ≥ 25 % of tokens are not English)
├─ nlp/transliterate.py Tanglish → Tamil script via the IndicXlit service (:8095)
├─ nlp/translate.py Tamil → English via IndicTrans2 dist-200M (MPS on a macOS host, CPU in Docker)
│
└─ triage/extractor.py LLM × N samples (default 5, temperature 0.8), JSON schema:
findings[{concept (ontology), status present|absent|uncertain, evidence quote}],
patient {age, sex}, location_text, severity vote
evidence check: each quote must occur in the caller's words or a machine view,
otherwise the finding is rejected and counted (hallucination containment)
triage/pipeline.py severity distribution = smoothed vote over samples
confidence = vote share × agreement × input quality
explain = all views, findings, denied, rejected, patient, location text
- The LLM is chosen by
llm/client.py::get_llm():VAAZHVU_LLM_PROVIDER=openaiwith DeepSeek (deepseek-flash) as primary, with thinking disabled. Faster and more accurate for this extraction on the synthetic Tanglish set (Tanglish evaluation): about 3 s for 5 samples (observed in dev, not a benchmark).- Ollama
gemma3:4bas the automatic fallback. - Ollama alone when the provider is
ollama.
- No keyword rules. There is no regex symptom list anywhere in triage. Tests use
ScriptedLLM, never regex. The ontology (triage/ontology.py) defines concepts, their red-flag status, required capabilities and agencies, not the words that express them (and no per-concept severity: acuity comes from the whole call).triage/conditions.pymaps concepts to condition groups for dispatch. - If the LLM is unavailable (
VAAZHVU_LLM=0, no provider reachable, or no answer withintriage_deadline_sinconfig/policy.yaml, 15 s), triage abstains:- the safety policy sends ALS provisionally and requires a human (rule R3);
- the rule-only escalation phrase detector (
safety/escalation.py, both pipelines) still reads the caller's words, and a non-negated high-risk phrase floors severity at critical (R12); - a call with no clinical reading at all does not take the last
als_reserve_no_signalfree ALS units (config/dispatch.yaml); - the console shows a DEGRADED banner (
ops.degraded/ops.recovered); - after a timeout, the model keeps running in the background and its late answer re-triages the incident (
triage.updatedwithtrigger: "late model answer"), so the safety-floor dispatch is refined, or escalated, as soon as the reading exists.
- Every model call is observed (LLMOps,
llm/telemetry.py, Monitoring and logs): provider, model, operation, latency, time to first token, tokens, cost, the reason for any cloud → local handover, prompt and config versions. The triage assessment carries a content-free summary inexplain.llm(trace id, who served it, samples, tokens), and each handover is anllm.fallback/llm.recoveredevent. No caller words or model output are recorded.
Pipeline v2: span-aware Tanglish (VAAZHVU_TANGLISH_PIPELINE=v2, behind a flag)
v1 above decides "Tanglish" for the whole utterance and transliterates the entire sentence in one pass. That Tamilizes English words, numbers and places, and loses negation: illa becomes இல்லா. v2 (nlp/utterance.py, nlp/spans.py, nlp/analysis.py, triage/extractor.py::extract_grounded, safety/escalation.py) instead works like this:
utterance/1 record raw text immutable · typed | asr · Whisper segments/confidence · alternative hypotheses
│
├─ per-token labels script (tamil/latin/digit) + language (ta | en | place | number | uncertain)
│ signals: English word frequency vs Tamil frequency of the best transliteration
│ candidate · OSM place names (unless the word is common Tamil, e.g. "chinna")
│ · neighbour context only when both scores are known · reversible normalisation
│ (raw kept, rules listed)
├─ Tamil spans only IndicXlit top-k (beam 8) per word, reranked by READ-BACK (romanise the candidate,
│ compare to what the caller typed — வலி "vali" beats வழி "vazhi") + Tamil frequency;
│ close calls kept as "{a|b}"; every piece aligned to raw character offsets
├─ English gloss IndicTrans2 on the top reading — machine-generated, no alignment, context only
├─ grounded LLM evidence must be the caller's words (raw / normalised / aligned Tamil view);
│ each finding cites raw offsets; translation-only evidence → uncertain;
│ evidence on an unsettled span via a transformed view → uncertain
└─ escalation-only config/escalation_phrases.yaml (DRAFT, not clinician-reviewed): a non-negated
phrase detector high-risk phrase that triage missed → human review + ALS (policy R10); negation
cues, fused verb negation ("valikala"), scope stops at "but"/"aana"; never rules out
The policy adds R11 language review: a red-flag finding resting on unsettled transliteration, disagreeing ASR hypotheses, an IndicXlit outage, or ≥ 30% uncertain spans requires a human. Provisional dispatch still applies. Any dependency outage keeps the raw text, records the outage in degraded, and lowers input quality; nothing is fabricated.
Evaluation: scripts/eval_tanglish.py runs on tests/fixtures/tanglish/eval_v1.jsonl (370 synthetic utterances, unreviewed); see Tanglish evaluation. v1 stays the default until Tamil-speaking clinical reviewers sign it off (clinician review is on the blocked-on-people list in todo/NOW.md).
2. The AI call-taker (ops/calltaker.py, brief in config/calltaker.yaml)
Every sentence a caller hears or reads is written by the model. There is no scripted greeting and no "சரி" acknowledgement list. What to ask next comes from a checklist (below); the model chooses only the wording and the language.
Call-taking checklist (config/calltaker.yaml: protocol, calltaker.protocol_state). Modelled on the Danish Index for Emergency Care (Dansk Indeks v1.10, public PDF); not MPDS, which is proprietary, and no protocol is validated on Indian calls. Slot contents are marked [NEEDS CLINICAL VALIDATION].
- Universal six, in order: where, callback number, what happened, age, awake/responding, breathing normally.
- Key questions per condition group (
triage/conditions.pygroup belief from the findings; groups within half the top group's belief): cardiac arrest (breathing, responding, CPR/defibrillator), chest pain (age, sweating, breathlessness, known heart disease), stroke (face droop, arm weakness, speech, time last seen well), major trauma (anyone trapped, heavy bleeding, scene safe / attacker still there, head injury), breathing, obstetric (weeks pregnant, bleeding, contractions), poisoning / bites (what substance or animal, when, how much), burns (how much of the body, face/airway, still burning), plus a paediatric card whenchild_patientis asserted. - Scene safety ("is anyone trapped?", "is the scene safe / is the attacker still there?") is added for trauma, assault and fire calls.
- A slot is answered only from structured fields: location verified, caller number known, a finding present or denied, patient age / conscious state, a reported hazard. Never from regex on the caller's words. Slots no field can settle (e.g. "sweating", "time last seen well") are marked
conversation_only; the model skips them once the caller has answered. - SITUATION carries
protocol: {groups, next, answered}(nextcapped atmax_next). The brief tells the model to ask the firstnextslot after WHERE andto_confirm.
What the model sees each turn
- System brief (
config/calltaker.yaml: system):- its role;
- what dispatch needs (where, what happened, then whether the patient is awake and breathing, age, how many hurt, dangers);
- how to talk: short, one question, no filler acknowledgements, ask again when the caller's words are garbled;
- which pre-arrival instructions are allowed (including hands-only CPR guidance);
- what it must never do (diagnose, name medicines, invent ETAs, tell the caller to drive to hospital or to call 108).
- Language and channel notes: spoken Chennai Tamil in Tamil script, or plain English; text-to-speech rules for voice, SMS length for text.
- The conversation so far, as user and assistant turns. Turns from the other channel are prefixed
[said earlier on the voice call]/[sent earlier by text message], so nothing is asked twice, but the agent replies only in its own channel. - The final user message:
CALLER:their latest words;EVENT:call connected / caller spoke / unclear audio / status changed;SITUATION:JSON with the service, status and its meaning, last status told to the caller, location (verified? place? GPS or words?), assessment (severity, confidence, findings with the caller's quotes, ruled out, patient, whether a human is reviewing),to_confirm,protocol(the checklist slots still to ask, in order, and those answered),caller_form_answers(what the caller already answered on the/callerquestionnaire, in plain words, so it is never asked again), response (ambulance, ALS/BLS level, ETA in minutes, hospital, others sent);- the turn instruction.
Guards (deterministic, per sentence, before anything reaches the caller)
- Must be in the caller's script: Tamil characters for a Tamil caller.
- May not contain numbers that appear neither in SITUATION nor in the caller's words, so it cannot invent an ETA or a unit.
- At most
generation.max_sentences(2) sentences. - Labels and quotes are stripped.
- If no model produces anything, the configured
offlineline is used. This is the only fixed text, and it exists so the caller never meets silence.
Status announcements. When the incident status changes to an announce status (en route, on scene, transporting, at hospital, resolved) and that status hasn't been told yet (told_status):
- voice: the agent says it as soon as the line is quiet;
- text: it sends a message.
Two conversations, one incident. Voice messages carry channel: "voice" and text ones channel: "text". The citizen's Message screen shows only text; the Call screen shows only the call; the dispatcher console and the crew app show both, labelled.
Latency (DeepSeek, warm connection; observed in dev, no latency benchmark is checked in): the first token arrives after a median of ~1.4 s. The first spoken sentence starts ~1.5–2 s after the caller's transcript. A pooled keep-alive HTTP client plus keep_warm() (pings every 45 s) avoid a TLS handshake per turn. If nothing arrives within generation.first_token_timeout_s (4 s), the local model answers instead.
3. The real-time voice line (voice/agent.py)
phone mic ─PCM16 16 kHz─► WebSocket ─► Silero VAD ─► Whisper ─► IntakeAgent ─► TTS ─PCM16─► phone speaker
start 0.2 s primed with the streams call-taker
stop 0.7 s agent's last words sentences into TTS
Engines by deployment. In the Docker api (the default stack), Whisper is faster-whisper on CPU and TTS is
espeak-ng, because containers on macOS have no Metal GPU and no say. Run on a macOS host (make run), the
same pipeline uses MLX Whisper on the GPU and the macOS Vani (Tamil) / Tara (English) voices. Timings below were measured on the
macOS host path; expect lower Tamil accuracy and more latency from the Docker engines.
| Behaviour | How |
|---|---|
| Greets first | On connect, the agent is asked to open the call, so the greeting is generated, not canned. |
| Detects end of turn | Silero VAD: 0.7 s of silence ends the caller's turn. |
| Fast reply | Streams the LLM; each sentence goes to TTS as soon as it is complete, while the next is still being generated. |
| Full duplex / barge-in | Caller speech that overlaps the agent for ≥ VAAZHVU_BARGE_IN_SEC (0.5 s; shorter blips are treated as echo) cancels the reply, flushes queued audio, and sends interrupt to the phone. |
| Pause mid-sentence | If the caller resumes before the agent has spoken, the pending reply is dropped and regenerated for the whole turn. If the extra speech produced no transcript, the reply is regenerated after VAAZHVU_TRANSCRIPT_GRACE_SEC. |
| Robust transcription | MLX whisper-large-v3 on the Apple GPU when the api runs natively on macOS (make voice); faster-whisper (VAAZHVU_WHISPER_MODEL, CPU) in the Docker api. Each turn: one language-ID pass picks the main language (Tamil unless Whisper's top pick is English), then two decodes, Tamil and English, because Whisper writes one language per decode and code-mixed callers lose their English words in the Tamil decode and their Tamil in the English one. The main decode is the transcript; the other is an ASR alternative that triage reads and accepts as evidence (re-triage gets every turn's alternative). No decoder prompt: Whisper echoes prompts into the transcript on short or unclear turns (the agent's last words came back as "என்ன ஆச்சு, சொல்லுங்க", a register prompt as "பண்றேன், please சீக்கிரம் வாங்க"), and on a 108 line no transcript may contain words the caller did not say; the Tamil decode is also most accurate without one. English words then come out in Tamil letters in the main transcript and in Latin script in the English alternative, which the voice line also sends to the client. Repetition loops are cut back to one copy (not dropped), temperature fallback 0 → 0.2 → 0.4, and output in an unexpected script (e.g. Hangul) is dropped and the caller asked to repeat. |
| Background work never blocks | The first turn creates the incident; later turns are appended and fully re-triaged / re-dispatched in a thread. The reply does not wait for them. |
| Caller cannot speak | The iOS citizen app counts seconds of silence on the call after an SOS (agent speech and server listening not counted; the caller's first transcript stops it). From 20 s it shows a countdown ("I can talk" / "Send now"); at 30 s, or on "I can't talk", it repeats the SOS with cannot_speak and police + ambulance are sent (config/app.yaml sos_silence, docs/DISPATCH.md). The line stays open and moves to the earpiece; the call-taker then asks nothing that needs a spoken answer (caller_cannot_speak in SITUATION). A call that joined an incident and ends with no caller word flags it silent_call. |
| Records everything | Every caller turn and agent sentence is written to the incident thread (channel: voice), so the dashboard shows the call live. |
Observed end-to-end (one simulated Tamil call over the tailnet, not a benchmark):
- the greeting arrives 2 s after connecting;
- the transcript arrives ~0.3–0.5 s after the caller stops speaking;
- the first reply sentence follows 1.5–1.9 s after the transcript;
- no filler acknowledgements.
Client side (iOS VoiceLink in ios/Vaazhvu/Citizen/CallView.swift)
- Audio session: AVAudioSession
playAndRecord/voiceChat, defaulting to the speaker. AVAudioEngine runs with voice processing (echo cancellation). - Engine build: the engine is built only after the session is active, retried while the audio route settles, and rebuilt without voice processing if the mic delivers nothing for 2 s.
- Configuration changes: restart the existing engine; they never trigger a rebuild loop.
- Early audio: agent audio that arrives before the engine runs is held and played afterwards.
Debugging the voice line
- Web:
/debug/voiceshows timings and raw messages, and saves the uplink as a WAV. - Replay:
scripts/voice_call_sim.py a.wav b.wav --url ws://…/api/ops/voice/ws?caller=x&lang=taplays WAV turns into the line and prints a timeline. - iOS: the
[voice]console lines:session active,audio up,microphone audio flowing,socket open,<- greeting …. - Server log:
vaazhvu.calltaker INFO first sentence in X s (model)anddropped sentence …(guards).
4. The Dispatcher Copilot (copilot.py, config in config/copilot.yaml)
A tool-calling LLM for the dispatcher. It reaches Vaazhvu only through the MCP tools (AI access and the Copilot): reading incidents, the engine's recorded decisions, units and hospitals, and running labelled simulations. It has no tool that dispatches, approves, overrides or reroutes.
- Model:
llm/client.pychat(messages, tools, tool_choice=)on the configured provider (OpenAI-compatible, e.g. DeepSeek, with native tool calling), falling back to local Ollama (/api/chatwithtools). The last allowed round usestool_choice: "none"so a turn always ends in an answer. - Grounding: the brief requires every fact to come from a tool result in the conversation, explanations to be read rather than re-derived, severity to be reported as a distribution, and simulated data to be called SIMULATED.
- Telemetry: each turn is one
copilot.turnscope; every round is achattrace with tokens and cost, and no content, like every other model call. - Offline: with no model, the panel still answers with the facts from
get_incidentandexplain_dispatch, marked model offline.