Voice Channel — Architecture
The voice channel is the telephony surface of the pilot search system built for Ziekenhuis Oost-Limburg (ZOL). It is documentation of a PXL University College graduation project and is not an official ZOL publication. A caller dialling the Belgian phone number reaches a self-hosted SIP gateway, which bridges into a LiveKit room (@livekit_agents_docs) where a voice agent worker runs Deepgram Nova-3 streaming speech recognition (@deepgram_nova3) on the inbound audio and ElevenLabs Multilingual v2 (@elevenlabs_multilingual_v2) on the outbound. Per-turn cognition is delegated over a live connection to the backend, where the voice orchestrator runs the rule-based pre-filter, then a GPT-4.1 tool-call loop, then a safety post-filter and an answer-shaper, as described below.
This page documents the composition principle, the per-turn flow, the cross-component sequence, and the architectural trade-offs that shaped the current design.
The composition principle
The voice channel is agentic-only: a single GPT-4.1 agent with three tools is the cognition layer. ADR-0049 and ADR-0051 retired the legacy 8-stage orchestrator (deleted on 2026-05-02, roughly 7,000 lines of code removed) in favour of an LLM agent that calls the existing retrieval pipeline directly through a search tool, with the request flagged as the voice channel.
ADR-0053 (2026-05-22) further established native streaming-with-tools as the dispatch pattern: each tool-decision iteration is a single streamed OpenAI call rather than the earlier two-call pattern (non-streaming tool decision, then a separate streaming final). For direct-response queries ("Do you speak English?", "Wat zijn jullie openingsuren?"), this halves OpenAI round-trips: one call from query to last token. For tool-using queries, the loop is N+1 calls (one per iteration, one for the final synthesis), all streamed. Both cases produce a stream of answer chunks that the voice agent turns into sentence-sized speech requests via a sentence buffer.
The sequence for each turn is:
- The voice agent sends the transcribed utterance to the backend.
- The voice orchestrator applies the rule-based pre-filter.
- If the utterance falls through, a GPT-4.1 tool loop runs (at most 3 iterations) with three tools: search the hospital knowledge base, transfer to the helpdesk, end the call.
- A safety post-filter inspects the LLM output.
- The answer shaper formats the text for speech.
- A medical-content disclaimer is prepended if the shaper detects medical content.
The retrieval pipeline is unchanged from the chat channel. Flagging the request as voice activates voice-specific behaviours inside it: the Value Framework affinity rerank (@cormack2009rrf is the rank-fusion lineage; the project extends it with a categorical-affinity multiplier, see Value Framework), citation derivation from chunks rather than inline [N] markers (see Citation Pipeline), and a voice-shaped LLM system prompt.
Architectural trade-offs
Four foundational decisions define the voice channel's shape; each is captured in an ADR with the alternatives that were considered and rejected.
| Decision | Chosen | Alternatives considered | Rejected because |
|---|---|---|---|
| Cognition topology | Agentic LLM with tools (ADR-0051) | 8-stage deterministic pipeline; thin pipeline (rule-based pre-filter, FAQ, RAG, no LLM agent) | The 8-stage pipeline accumulated roughly 7,000 lines of code, six dangling feature flags and a low cache hit rate on speculative STT (project estimate); the thin pipeline could not handle compound queries ("which doctor at cardiology AND what are the visiting hours") without re-introducing intent state. The agentic LLM lets the model decide tool dispatch per turn without persisted dialogue state. |
| Telephony stack | Self-hosted Twilio SIP + LiveKit (ADR-0050, kept in the project's private repository) | LiveKit Cloud managed SIP gateway; Twilio voice with no LiveKit | The managed gateway is priced per participant-hour, a recurring cost at the brief's projected volume (vendor pricing at decision time); self-hosting has no marginal gateway fee. Twilio voice without LiveKit ties cognition to Twilio call-flow control, foreclosing the agent runtime. (RFC 3261) |
| Mid-call language | Locked at first utterance (ADR-0052) | Multi-language Deepgram on every turn; switch tool for explicit language requests | Multi-language Deepgram degraded Flemish accuracy in informal tests ("bezoekuren" heard as "bezukjuren"); the switch tool was structurally broken because Deepgram emits zero transcripts on speech in the locked-out language, leaving no signal for any detector. See Language Locking. |
| Citation strategy | Chunk-derived fallback (no inline markers in the answer) | Inline [N] markers as on chat | TTS reads [1] as "open bracket one close bracket"; the voice prompt strips markers, so the chat channel's marker extractor produces empty citations. See Citation Pipeline. |
Components
The backend voice code is organised around these parts:
- the voice orchestrator, the single integration point (ADR-0051);
- the rule-based pre-filter and its shared helpers;
- a unified routing-rule dispatcher for deterministic, rule-bound responses;
- the answer shaper, which formats text for speech and prepends the disclaimer;
- database-driven FAQ answer renderers;
- caller-ID pseudonymisation;
- a per-turn LLM-as-judge scorer for diagnostics;
- a concurrency limiter and a per-caller rate limiter for inbound calls;
- the tenant overlay package (see Tenant Overlay System);
- the Value Framework package (intent-to-category affinity rerank, telemetry and unit-mismatch admission).
The implementation is kept in the project's private repository.
Per-turn flow
The tool-call loop is capped at 3 iterations. On overflow the orchestrator emits a fixed transfer text rather than continuing to spend tokens. A second short-circuit guards against the gibberish-rephrase loop pattern seen in the 2026-05-07 traffic: two consecutive searches that return nothing force a transfer to the helpdesk.
Latency budget per stage
The per-turn latency budget below is taken from local development measurement; production pilot measurement is pending (self-reported). * markers indicate stages whose timings have not yet been pinned to a histogram on the pilot.
| Stage | Local-dev p50 | Notes |
|---|---|---|
| Rule-based pre-filter | < 1 ms | Deterministic |
| GPT-4.1 first token (tool decision) | 300–600 ms* | OpenAI chat completion with tools; bounded by network and LLM provider |
| Search round-trip (retrieval inner loop) | 600–1 200 ms* | Embedding + pgvector + BM25 + rerank + LLM stream |
| Safety post-filter | < 1 ms | Deterministic |
| Answer shaper | 5–20 ms* | Six rule-based transforms + medical-content detector |
| ElevenLabs TTS first audio chunk | 200–400 ms* | Multilingual v2 streaming |
* Per Beyer et al. 2016 §4 (Service Level Objectives), latency SLOs should be written at p95/p99, not the mean. A pilot measurement pass (Phase 5 of the readiness plan) will replace the development p50s above with pilot p95s. Nielsen 1993
Voice agent filler ladder and grace tuning
The voice agent runs a three-tier filler ladder concurrently with the backend retrieval call. Each tier asks a small, pure decision function: "given the current state, should I fire?" The decision is a few boolean conditions, but its correctness has bitten the pilot more than once, so it is captured here for future maintainers.
Tier model
| Tier | Grace before firing | Purpose | Example phrase |
|---|---|---|---|
| Tier 1 | 1,500 ms (was 800 ms before the 2026-05-23 retune) | Natural pause bridge: masks the gap between the start of the turn and the first sentence from the backend | "Een ogenblikje", "Let me check that for you" |
| Tier 2 | 4,000 ms | Acknowledge ongoing search | "Almost there, just another second." |
| Tier 3 | 10,000 ms | Unusual delay: acknowledge once, then go silent | "Almost ready, I have nearly all the information." |
Each tier is cancelled the moment the first streamed sentence arrives from the backend.
Grace tuning chain (2026-05-22 to 2026-05-26)
The tier-1 grace was tuned several times in rapid succession after the LLM-first agentic pipeline (ADR-0053) shifted the latency distribution. Each retune is preserved here because the reasoning is not obvious from the constants alone:
| Date | Change | Reason |
|---|---|---|
| (before) | 800 ms | Original value: between the 600 ms human-noticed-silence floor (arXiv 2507.22352) and the roughly 1 s mark where the answer LLM typically produced its first complete sentence under the older two-call pattern |
| 2026-05-23 | 800 to 1,500 ms | A pilot call with "Do you speak English?" fired a spurious "Let me search that for you" filler before the actual answer. The backend turn took 622 ms, but media-server and SIP transport add 50–200 ms each way, so the first sentence landed right at the original threshold. The transport latency on the SIP path had not been accounted for. |
| 2026-05-23 | Added a "language switch recent" gate | The first turn after a language switch has a gap of about 3.3 s while the STT/TTS plugins reload; the 1,500 ms grace expired during the reload. Tier 1 is now skipped if a language switch happened within a 5 s window. Tier 2 at 4 s still fires for genuine stalls. |
| 2026-05-26 | Same-language probe no longer flags as a switch | A pilot trace showed turn 1 of every call firing tier 2 at about 7 s instead of tier 1 at 1.5 s. The first-utterance language probe flips Deepgram from multi-language to single-language mode even when the detected language equals the current one, and the old code recorded that as a language switch, so the new gate suppressed tier 1 for the whole window on every first turn. The timestamp is now only set when the language actually changes. This saved roughly 5.5 s of perceived silence on the first turn of calls. |
Skip conditions
Tier 1 fires only when none of these hold:
- The backend has already returned the full response (non-streaming path).
- The first sentence has already arrived and the agent is speaking.
- The caller said a farewell, handoff or appointment phrase: the backend short-circuits and a filler would finish before the terminal response.
- A language switch is in progress: the STT/TTS reload means the request has not even reached the backend. This flag is set only when the language actually changed (per the 2026-05-26 fix).
The decision function is a pure module, unit-tested without any media-server fixtures. Adding a fifth skip condition touches only the predicate and a new test.
Session-start cache warm-up — disabled by default
A cache warm-up exists but is off by default. When enabled, the agent fires the four most common questions at the backend immediately after the greeting, in parallel, to pre-populate the semantic cache. The intent was sub-100 ms first answers when the caller's question matched one of the warm-up queries.
In practice the warm-up queries serialise on the backend (each takes 4–7 s, one after another) and the caller's actual first query waits 15–20 s behind them, so the filler ladder plays tier-2 and tier-3 fillers. The setting was re-enabled briefly during streaming validation on 2026-05-22 and disabled again on 2026-05-23 after a pilot call reproduced the failure. The underlying serialisation has not been fixed; the warm-up stays off until a backend concurrency investigation produces a fix.
Post-refit fixes (2026-05-26 evening)
Two more fixes landed the same day, on different layers but from the same pilot trace session. Neither touches the filler ladder; they belong to the wider "things that happen between STT and the LLM" surface.
| Layer | Change | Reason |
|---|---|---|
| Voice agent, short-clarification check | Bare emphasis affirmations ("ja graag", "yes please", "graag", "ja alsjeblieft", "yes thank you") no longer trigger FAQ-followup context carry; the turn falls through to the LLM as a fresh utterance. | A pilot call showed the agent stitching the previous question with the caller's bare "ja graag" into a malformed compound query. Emphasis-only affirmations carry no new content to combine with the prior turn. |
| Backend tenant overlay | A new routing rule matches the Belgian public-service numbers (112 emergency, 1733 out-of-hours GP service, and the hospital emergency line) in the four languages and returns deterministic text listing them. | A pilot call showed the agent refusing to read out 112 and 1733 as "specific medical advice". These are national public-service numbers; refusing them is unsafe. The rule fires before the LLM sees the query. Regular doctor and department phone lookups still flow through retrieval. |
The second fix sits in the unified routing-rule dispatcher, whose rule order (crisis, emergency, PII refusal, identity, clarification, symptom triage, out-of-scope redirect, FAQ) comes from default rules plus per-tenant overlays. Any rule whose pattern matches short-circuits the LLM with the rule's response text; the fall-through set is what reaches the GPT-4.1 tool loop.
Cross-component sequence (voice agent and backend)
Two views of the same conversation are maintained side by side. The summary view shows the orchestrator and retrieval split and the role of the Value Framework. The full view shows every external SaaS call, every short-circuit before the LLM, the tool loop, the streaming-audio return and the post-turn evaluator: the operational reality of a single call from dial to hang-up.
Summary view
The Value Framework is a child of the retrieval pipeline, not a peer of the orchestrator. This separation matters because the chat channel benefits from the same affinity rerank without requiring orchestrator changes.
Full view — dial through hang-up
This view expands the summary in five ways. (1) Two short-circuits before the LLM: the pre-filter and the unified routing-rule dispatcher (including the public-service-numbers rule) together handle a share of real-world traffic at zero LLM cost. (2) The GPT-4.1 tool loop is the actual control flow of agentic-only voice (at most 3 iterations, with a guard that escalates after 2 consecutive empty searches). (3) The retrieval sub-pipeline reached through the search tool (semantic cache, intent classification, hybrid retrieval over pgvector, BM25 and taxonomy, Value Framework rerank, doctor-list injection, context assembly, response generation) is drawn explicitly. (4) The external SaaS calls (Deepgram, OpenAI, ElevenLabs) get their own lanes because they dominate the latency budget. (5) The concurrent filler ladder that masks backend latency on the caller side gets its own parallel block.
Honesty caveats on the full view. Three places where the diagram simplifies real behaviour:
- The parallel block for the filler ladder depicts three concurrent timers, which is correct, but a real call only fires the tier(s) whose timeout expires before the streamed answer starts. In practice you see one filler (or none if the backend is fast enough), not all three.
- Block F (post-turn evaluator) is drawn after E for visual clarity, but in practice it runs as a fire-and-forget background task, so caller-perceived latency does not include it.
- The database lane rolls up four very different stores: pgvector (semantic similarity), BM25 (lexical), taxonomy (relational), and telemetry tables. A presentation that needs to make the storage diversity explicit should split this lane.
Where voice differs from chat
| Concern | Chat channel | Voice channel |
|---|---|---|
| Citations | Marker-based extractor ([1], [2], ...) | Chunk-derived fallback: the voice prompt strips inline markers (un-speakable), and citations are derived from the retrieved chunks directly |
| Language | Per-query detection, can switch any turn | Locked at first STT-confirmed utterance for the duration of the call (ADR-0052) |
| LLM model | GPT-4.1 (quality-first) | GPT-4.1 with tool use (latency-conscious; max 3 tool iterations) |
| Follow-up suggestions | Rendered in widget | Suppressed: no UI to display them |
| Markdown | Rendered by widget | Stripped: ElevenLabs speaks raw text |
| Answer length | Up to 500 tokens | Capped at 2 sentences by the system prompt and the shaper |
| Error routing | HTTP error / chat error message | Transfer-to-helpdesk tool call, then a call transfer |
| STT | Not applicable | Deepgram Nova-3, Dutch-primary, language locked at first utterance |
| Disclaimer | Shown inline | Spoken; auto-detected from the answer text |
| Structured-output safety | A thin helper over the OpenAI client at 8 LLM call sites (turn evaluator, intent classifier, etc.), replacing a framework on 2026-05-12 | Same; the change applies channel-uniformly |
Operator settings (current)
| Setting | Status |
|---|---|
| Spoken disclaimer | On by default: the medical disclaimer is prepended on detected medical content (post-LLM, post-shape). |
| STT-ambiguity guardrail setting | Dangling. The module it controlled was deleted on 2026-05-02; safety refusal is now always on inside the pre-filter. The setting is read but has no consumer. Removal pending. |
| Escalation confidence threshold | Dangling. Its consumer was deleted on 2026-05-02. Removal pending. |
| Conversational-intent resolver model | Dangling. Its consumer was deleted on 2026-05-02. Removal pending. |
| Tool-loop iteration cap (3) | On overflow the orchestrator emits a fixed transfer text. |
The three dangling settings form a cleanup batch for a follow-up sprint. They persist for now because removing them mid-deployment would break existing operator configurations.
Per-channel LLM fallback
A fallback-chain utility is still registered, but the agentic path goes directly to GPT-4.1. On any tool or LLM exception, the orchestrator returns the escalate intent and the voice agent transfers the caller to the hospital helpdesk. There is no "fall back to thin" path; ADR-0051 removed it.
Structured-output safety
Eight LLM call sites, including the intent classifier, the conversation classifier and the per-turn evaluator, use a thin helper that wraps the OpenAI client with JSON output, validates the result against a typed model, and retries once on a validation error before raising a typed fallback. The design intent is that malformed JSON does not reach downstream code. The per-turn evaluator depends on this contract: a malformed score would otherwise silently degrade the diagnostic.
Voice ops infrastructure
A two-day calibration sprint ending 2026-05-23 hardened the voice path against failure modes that surfaced during eight weeks of pilot call testing. Five changes shipped as a bundle:
| Change | Reason |
|---|---|
| Rule 4.5 in the system prompt: no repeated clarifications | A voice eval showed agents asking the same clarification 3 times in one conversation; the rule forbids it and commits the agent to a search or handoff after one clarification |
| Temperature lowered from 0.3 to 0.0 | Removes per-turn answer variance; the agent's job is to commit to a single grounded response, not to sample creatively |
| Rule 6.5 in the system prompt: list what the corpus lists | Procedure questions ("How does an MRI work?") now surface the corpus's actual content instead of generic answers |
| Tier-0 acknowledgment removed, tier-1 session rate limit added | Pilot calls accumulated "mhm" acknowledgments that read as nervous; tier 0 was disabled and tier 1 capped at one per 3 turns |
| STT phonetic-recovery sweep (80 Belgian-Dutch medical terms) | Dutch and Limburgish dialect mishearings (for example a garbled "elektrocardiogram") are recovered before intent classification |
The bundle was checked against a 10-scenario, 89-turn voice eval scored by an LLM judge (self-reported): 88 of 89 turns were rated production quality. The one outlier (a cancer-staging interpretation question) was investigated and attributed to OpenAI token-level non-determinism at temperature 0 (0 of 8 reproductions across replay and live re-runs), not to a deterministic prompt deficiency.
Diagnostic toolchain: trace, replay, SLO
A three-tool diagnostic chain was added and is described in an internal operator runbook. The discipline is enforcement by visible artifact: do not patch a voice prompt rule without using these tools first.
| Tool | Question it answers |
|---|---|
| Trace | What actually happened on each turn? Events, telemetry, computed latencies. |
| Replay | Does the current code produce a different answer on this exact input? Retrieval is mocked with the original payload so the LLM's decision is what is tested. |
| SLO report | Is the typical call meeting its time-to-first-audio, clarification-rate and filler-rate targets? |
The first use of this chain (2026-05-23) caught a phantom safety bug: a "no cancer staging" prompt rule that would have shipped on a single-sample signal had the tools not been available. Replay refused 3 of 3 times on the same input, and five live re-runs refused 5 of 5. The proposed rule was withdrawn.
References
- ADR-0051: The agentic voice orchestrator is the only voice path (2026-05-07)
- ADR-0049: Thin Voice Architecture (2026-04-30), a superseded stepping stone that documents the 8-stage to 3-stage simplification rationale
- ADR-0050: Twilio + LiveKit SIP Integration (kept in the project's private repository)
- ADR-0052: Voice Language Locked at First Utterance
- ADR-0053: LLM-First Agentic Voice Pipeline (2026-05-22), the native streaming-with-tools dispatch pattern (kept in the project's private repository)
- Lewis et al. 2020: original RAG architecture; the orchestrator's search tool is the agentic equivalent of the RAG retriever stage
- LiveKit Agents Documentation: the runtime that hosts the voice agent
- Deepgram Nova-3: STT model used in the pilot
- ElevenLabs Multilingual v2: TTS model used in the pilot