---
title: Real-time phone voice agent
url: https://gurkanozkan.ai/learn/design/applied-llm-sd-03/
markdown: https://gurkanozkan.ai/learn/design/applied-llm-sd-03.md
kind: design
role: Applied LLM
json: https://gurkanozkan.ai/api/learn/design/applied-llm-sd-03.json
---

# Real-time phone voice agent

Design a voice agent that answers restaurant and hotel phone lines: it books, changes and cancels reservations by calling the business's booking system, handles interruptions, and transfers to staff when stuck.

## What to cover

- **Requirements**: call volume and peak concurrency; languages and accents; latency target (turn gap); booking-system APIs and their latency; escalation rules; recording/consent requirements
- **Estimates**
- **API**
- **Data model**
- **Architecture**: SIP/telephony ingress (regional); streaming ASR + VAD/turn detection (or audio-native model); dialogue manager/state machine + LLM with tools; booking integration with timeouts and caching; streaming TTS with phrase chunking and response cache; barge-in handling (cancel TTS + generation); transfer to staff; per-stage tracing; eval sets from real calls; containment/resolution/caller-experience metrics
- **Deep dives**: booking API takes 3 s — what does the caller hear?; How do you measure and reduce p95 turn gap?; How do you test changes without risking live calls?
- **Trade-offs**: cascaded ASR→LLM→TTS vs speech-native models (control, logging, guardrails vs latency); endpointing aggressiveness; reasoning per turn vs latency; generic vs per-customer tuning
- **Evaluation**: explicit latency budget per stage with distributions; streaming and cancellation; graceful degradation; eval from real call recordings; telephony realities (codecs, regions, echo)

## Reference design

### Requirements

**Functional**: answer inbound calls for restaurants and hotels; check availability, book, change and cancel reservations; answer venue FAQs (hours, parking, dietary options); handle interruptions; transfer to staff with a summary; send an SMS confirmation.

**Assumptions to confirm**
- **Volume**: 5,000 venues × ~60 calls/day = 300k calls/day, average 2.5 minutes; Friday 17:00–19:00 peak.
- **Languages and accents**: UK English first with strong regional and non-native accent coverage; French, Spanish and German per venue later; narrowband 8 kHz phone audio.
- **Latency target**: caller-perceived turn gap (end of speech → first agent audio) p50 < 800 ms, p95 < 1.3 s.
- **Booking systems**: restaurant reservation platforms (e.g. ResDiary, OpenTable, SevenRooms) and hotel property-management systems (e.g. Opera, Mews), each integrated through whatever partner API it offers. Assume latency of 300 ms–3 s, rate limits and occasional outages.
- **Escalation rules**: caller asks for a person; two failed understanding attempts; parties above the venue's limit; complaints; allergies needing a guarantee; anything payment-related (no card details over the agent — send a payment link instead, keeping us out of PCI scope).
- **Recording and consent**: announce recording at call start; UK GDPR lawful basis and retention (e.g. 30 days audio, 90 days transcripts) set per venue; redact PII in stored transcripts; opt-out path to staff.
- **Non-goals**: outbound calling; taking payments.


### Estimates

- **Concurrency (Little's law)**: peak hour ≈ 12% of 300k = 36k calls/h = 10 calls/s × 150 s ≈ **1,500 concurrent calls**; provision for 2,500.
- **Turns**: ~12 caller turns per call → 3.6M LLM turns/day; at peak 1,500 calls ÷ ~12.5 s per turn ≈ **120 turns/s**.
- **ASR**: 1,500 streams at ~200 streams/GPU ≈ 8 GPUs.
- **TTS**: agent speaks ~40% of the time → ~600 concurrent synthesis streams at ~100/GPU ≈ 6 GPUs.
- **LLM**: ~3k-token context (2.5k cached venue/system prefix), ~60 output tokens. Peak prefill 120 × 500 uncached ≈ 60k tokens/s, decode 120 × 60 ≈ 7k tokens/s → a mid-size model on ~4–8 GPUs.
- **Fleet**: ~20–25 GPUs at peak, doubled across two London zones ≈ 40–50 GPUs. At ~$2.5/GPU-hour: 45 × 24 × 2.5 ≈ $2.7k/day ÷ 750k call-minutes ≈ **$0.004/min**, plus an assumed ~$0.004/min for the SIP trunk (check the carrier's rate) → ~$0.008/min, **under 1p per minute** before margin.
- **Turn-gap budget**: semantic endpointing 250 ms + ASR final 80 ms + LLM first clause 250 ms + TTS first audio 150 ms + telephony and jitter buffer 100 ms ≈ **830 ms**.
- **Storage**: 750k min/day of 8 kHz audio at ~8 KB/s ≈ 360 GB/day; 30-day retention ≈ 11 TB.


### API

```
Telephony ingress: SIP trunk (or Twilio/Vonage media streams) → WS /calls/{id}/media
                   8 kHz μ-law frames in and out; DTMF events; REFER for transfer

Tools the dialogue manager exposes to the LLM (venue bound from the dialled number):
  check_availability(date, time_window, party_size)      → [{slot_id, time}]
  create_booking(slot_id, name, phone, party_size, notes, idempotency_key) → {booking_ref}
  find_booking(phone | name + date)                      → [{booking_ref, ...}]
  modify_booking(booking_ref, changes, idempotency_key)
  cancel_booking(booking_ref, idempotency_key)
  get_venue_info(topic)                                  → approved FAQ text
  transfer_to_staff(reason, summary)
  send_sms(template_id, params)

Venue admin API:
  GET/PUT /venues/{id}/config   hours, policies, max party, transfer number, voice, languages
  GET     /venues/{id}/calls    outcomes, recordings (role-restricted)
```


### Data model

- **Venue**: id, type, booking integration and credentials reference, policies (max party, deposit rules, cancellation window), FAQ entries, transfer rules and hours, voice, languages, custom vocabulary (venue and dish names).
- **Call**: id, venue_id, caller number (hashed for analytics), started/ended, consent announced, outcome (booked | changed | cancelled | info | transferred | abandoned), transfer reason, recording URI, retention date.
- **Turn**: call_id, index, ASR text and confidence, endpoint timestamps, dialogue state, LLM input hash, tool calls with latencies, spoken text, barge-in flag, per-stage timings.
- **DialogueState**: current step (greet, collect, confirm, execute, close) and slots (date, time, party size, name, phone, booking_ref) with confirmation status.
- **AvailabilityCache**: venue_id, date → slots, fetched_at, TTL 60 s.
- **EvalCase**: caller audio or simulated persona, venue fixture, expected booking end state.

Postgres for venues, calls and bookings audit; Redis for dialogue state and availability cache; object storage for recordings; ClickHouse for per-stage traces.


### Architecture

```
PSTN ─► SIP trunk (London region) ─► Media gateway: RTP, jitter buffer,
        echo cancellation, codec handling (G.711), DTMF
   ├─► VAD + semantic turn detector ─► streaming ASR (partials/finals,
   │                                    venue vocabulary boosting)
   ▼
Dialogue manager (state machine: greet → collect → confirm → execute → close)
   + LLM with tools for language understanding and phrasing
   ├─► Booking adapter: timeouts, retries, idempotency, circuit breaker,
   │   availability prefetch at call start ─► ResDiary / OpenTable / PMS
   ▼
Streaming TTS (first clause early, phrase chunking, cached common phrases)
   ─► media gateway ─► caller
Barge-in: caller speech during playback → stop audio within ~100 ms,
          cancel in-flight LLM and TTS, keep heard-text in context
Transfer: warm transfer (REFER or bridge) with a whispered summary to staff
Tracing: OpenTelemetry spans per stage per turn; recordings + transcripts → eval store
```
The state machine owns the flow and confirmation of every slot; the LLM interprets and phrases, so dates, party sizes and names are always read back before a booking is created.


### Deep dives

**The booking API takes 3 s — what does the caller hear?** Start the availability call as soon as date, time and party size are known, while the agent is still confirming. Within ~300 ms play a cached filler ("Let me check that for you"); at 1.5 s a second, different filler. Prefetch today's and tomorrow's availability at call start and serve from a 60 s cache. Hard timeout at 5 s: offer to text confirmation once it completes, or transfer. Idempotency keys stop retries double-booking, and the agent never says "booked" until the API confirms.

**Measuring and reducing p95 turn gap.** Timestamp end of speech, ASR final, LLM first token, first TTS byte and first RTP packet for every turn; chart distributions per stage, venue and time of day. Levers: a semantic endpointer that ends sooner when the utterance is complete; starting the LLM on stable partials; prefix caching of the venue prompt; a small model for routine turns; speaking the first clause before the rest is generated; colocating all stages in one region; keeping tool calls off the critical path through prefetch.

**Testing without risking live calls.** Simulated callers: LLM personas with goals, voiced by varied TTS accents, pushed through the real 8 kHz codec with noise and packet loss, against sandbox booking systems. Replay recorded caller audio for ASR and endpointing regressions. Then shadow mode on live calls (new stack listens and proposes, never speaks), then a canary of opted-in venues behind feature flags.


### Trade-offs

- **Cascaded ASR → LLM → TTS vs speech-native models**: cascaded gives text logs, deterministic tool calls, guardrails on text, per-stage upgrades and debugging; speech-native removes stage hand-offs, which can save a few hundred milliseconds, and can sound more natural, but is harder to constrain, audit and evaluate. For bookings, where names, numbers and dates must be exact, start cascaded and A/B a speech-native front end later.
- **Endpointing aggressiveness**: aggressive cuts people off while they read out phone numbers; conservative feels slow. Make it state-dependent: longer silence thresholds when collecting digits or names.
- **Reasoning per turn vs latency**: the state machine handles flow so most turns need no deliberation; allow a larger model only on rare complex turns, covered by a filler.
- **Generic vs per-customer tuning**: one model per vertical (restaurant, hotel) plus per-venue configuration, FAQs and vocabulary; no per-venue fine-tunes, which would not scale to 5,000 venues.


### Evaluation

- **Latency**: turn gap p50/p95/p99 per stage with distributions, not averages; alert when p95 > 1.3 s.
- **Outcome metrics**: containment (handled without transfer), resolution (booking exists and matches the transcript — checked against the booking system), booking slot error rate (date, time, party size, name) < 0.5%, appropriate transfer rate.
- **Caller experience**: hang-ups during agent speech, repeated requests, barge-in frequency, post-call SMS rating, venue complaints.
- **Eval from real calls**: consented recordings labelled into scenario sets per venue type and accent; WER on names and numbers; regression suite run on every model, prompt or endpointer change.
- **Graceful degradation**: ASR or TTS provider failover; smaller LLM fallback; booking system down → take details and send a confirmation once it recovers, or transfer; total outage → calls forward straight to the venue line.
- **Telephony realities**: narrowband G.711 audio, echo from our own TTS triggering false barge-ins (needs echo cancellation), packet loss, regional media servers, DTMF fallback for digits.


## What a strong design shows

- Gives an explicit turn-gap budget per stage and measures distributions, not averages.
- Streams everywhere and implements real barge-in: stop playback and cancel in-flight generation and synthesis.
- Keeps the booking system off the critical path (prefetch, fillers, timeouts, idempotency) and never claims success before confirmation.
- Tests with simulated callers through real codecs, shadow mode and per-venue canaries rather than on live callers.
- Knows telephony realities: 8 kHz audio, echo, regions, consent announcements and PCI avoidance.

---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
