Introduction
A real-time voice assistant needs a reliable audio path, clear turn ownership, interruption handling, and tools that report what actually happened. Flutter can provide the mobile interface while a FastAPI gateway manages sessions and provider connections. WebSockets are one transport option; they do not by themselves guarantee accurate speech recognition or a particular response time.
This architecture guide is for mobile and backend developers planning a voice-AI prototype. It separates a proposed Flutter audio path from my KisanDostAI work, which used a Twilio telephone interface and an asynchronous FastAPI bridge. That project was a research prototype, not evidence of a native Flutter voice app operating at field scale.
The earlier version of this guide used illustrative latency numbers as if they were measured results. This refresh removes those claims and replaces the simulated speech gateway with an explicit contract and a testable turn-ownership example. The Python example was checked with Python 3.14; it does not include a speech model or claim end-to-end device testing.
Choose the voice path before choosing the transport
| Product path | Typical interface | Engineering boundary |
|---|---|---|
| Push-to-talk assistant | Record, submit, receive a reply | Simpler turn boundaries; appropriate when the user accepts a deliberate pause |
| Live mobile conversation | Stream microphone and playback audio | Audio session, buffering, echo handling, interruption, reconnect |
| Telephone assistant | Programmable voice provider carries call audio | Telephony codec, stream events, call identity, and provider controls |
These are different systems. A telephone caller may not need mobile data, while the backend and providers still need network connectivity. That does not establish local SIM reachability, a free call, or affordability for every caller.
Twilio's Media Streams documentation explains its bidirectional telephone path and constraints. Do not reuse a raw PCM mobile protocol as if it were a Twilio stream protocol.
For a broader comparison of mobile AI deployment options, read on-device versus cloud AI, checking the chosen provider's current capabilities before implementation.
Define the client, gateway, and provider contracts
| Component | Responsibility | Failure behavior to define |
|---|---|---|
| Flutter client | Permission, recording state, capture/playback, explicit stop | Permission denied, interrupted session, route change, offline state |
| Session gateway | Authentication, bounds, turn IDs, provider lifecycle | Expired session, queue overflow, timeout, disconnect |
| Speech adapter | Accepted codec and rate, transcripts or speech events | Unsupported format, partial result, provider failure |
| Tool layer | Validated arguments, authorization, action receipt | Ambiguous intent, unavailable dependency, duplicate request |
| Playback path | Ordered audio and current-turn ownership | Old-turn audio, jitter, cancellation, route change |
FastAPI supports asynchronous WebSocket endpoints, but the application must define authentication, message validation, timeouts, and cleanup. Its WebSocket guide provides the framework behavior rather than a complete voice service.
For a PCM teaching example, 16,000 samples per second multiplied by 2 bytes per sample and one channel is 32,000 bytes per second. A 40 ms chunk is 1,280 bytes. This arithmetic describes a payload format, not network throughput or a provider requirement. Confirm capture output and provider input formats before sending audio; resampling and encoding belong at an explicit boundary.
Treat interruption as a state transition
When a user interrupts a spoken reply, stopping model generation alone is insufficient. Audio may already be waiting in a server queue or a device playback buffer.
A useful design assigns every reply a turn ID. When a new turn starts:
- Mark the previous reply as obsolete.
- Cancel its active generation or tool work where cancellation is supported.
- Clear queued playback through the client/provider's supported mechanism.
- Reject late packets belonging to the obsolete turn.
- Return to the intended listening state.
Here is a small, transport-independent ownership guard:
from dataclasses import dataclass
@dataclass
class TurnOwner:
current: int = 0
def begin(self) -> int:
self.current += 1
return self.current
def accepts(self, turn_id: int) -> bool:
return turn_id == self.current
owner = TurnOwner()
first = owner.begin()
assert owner.accepts(first)
second = owner.begin()
assert not owner.accepts(first)
assert owner.accepts(second)
This only checks whether output belongs to the current turn. A gateway still needs serialized state transitions or appropriate synchronization, task cleanup, and a final ownership check before output is sent. Cancellation also does not undo a reminder or other side effect that has already completed. Track the result of each tool action separately.
Avoid interpreting an empty audio queue as the end of an utterance. Network gaps and scheduling delays can empty a queue while the person is still speaking. Use a defined turn boundary, an explicit user action, or a suitable speech endpointing mechanism, then test it with representative speech.
Ask for clarification before an uncertain action
Transcription accuracy and safe task execution are different measurements. A transcript can be mostly correct while the reminder time or target list is wrong.
For a command such as “remind me tomorrow evening,” determine what the product considers a complete reminder: action, date, time, time zone, and user confirmation where required. If the command lacks a necessary detail, ask for it. Do not convert an incomplete command into an invented time.
Keep a structured result for each tool action: requested action, validated arguments, status, and created record ID. The assistant should claim success only after the action returns a successful result. Require explicit confirmation for product-defined sensitive actions, and apply authorization in the backend rather than trusting a model's tool selection.
Test Urdu and English at several levels
A useful evaluation set includes native Urdu, native English, code-switching, names, numbers, dates, accents, background noise, and incomplete instructions. Have representative speakers provide recordings and expected outcomes with permission. Keep evaluation recordings separate from tuning examples.
| Test layer | Measure | What it does not establish |
|---|---|---|
| Transcription | Word or character error rate against a reviewed transcript | Whether the intended task was understood |
| Intent and arguments | Correct action plus required fields | Whether the database action succeeded |
| Ambiguity handling | Correct clarification or abstention | General accuracy on unrelated commands |
| Tool execution | Correct record, authorization, retry behavior | Quality of the spoken explanation |
| End-to-end audio | Completed task, first audible reply, interruption behavior | Performance on every network and device |
A voice product should track wrong actions and missed clarifications alongside successful commands. Do not present a text-only evaluation as a voice-recognition benchmark. Do not label a handful of successful calls as general Urdu accuracy.
My KisanDostAI project documentation separates programmable telephone checks from text-session answer evaluation and records limitations of the telephony setup. That distinction matters when describing what a prototype proves to a client.
Measure latency with named timestamps
There is no universal sub-second result guaranteed by Flutter, FastAPI, or WebSockets. Define what the user experiences and measure it on the intended path.
| Timestamp | Why it matters |
|---|---|
| User finishes speaking | Starting point for perceived response delay |
| End-of-turn detected | Measures endpointing delay |
| First model output arrives | Separates model startup from playback |
| Tool starts and finishes | Exposes external lookup delays |
| First reply audio becomes audible | Captures the user-visible delay |
| Interrupted audio stops | Measures how quickly control returns to the user |
Report sample count, device, language, network, provider/model version, and median and tail latency. A text-tool duration is not end-to-end telephone latency. A first-token measurement is not first audible speech. Streaming can overlap stages, so adding unrelated stage averages does not produce a valid turnaround benchmark.
Plan lifecycle, security, and recovery
Request microphone access in context and explain recording state visibly. Add platform permissions and background behavior only for the capabilities you actually implement. Device audio routes, foreground/background transitions, and Bluetooth support need platform-specific validation.
Bound audio queues and message sizes. Define an overload response instead of allowing an unlimited backlog. Close provider sessions and cancel remaining tasks on disconnect. A reconnect should reconcile the current session and completed actions; blindly resending a command can create duplicate reminders or list entries. See reliable offline-first synchronization for retry-safe state changes.
Keep provider credentials on the server, validate session access, and set retention and deletion rules for audio and transcripts. Retrieve only the context the user is authorized to access. RAG can provide supporting material, but it does not guarantee that an answer is correct; the RAG fundamentals guide explains the retrieval boundary.
Conclusion
Voice-AI quality comes from the behavior of the whole system, including what happens when speech, tools, or the connection are uncertain.
- Choose a mobile, push-to-talk, or telephone path deliberately.
- Define audio formats, turn ownership, and interruption behavior.
- Ask for clarification when required arguments are missing.
- Test transcription, intent, action execution, and audible response separately.
- Describe measured results with their actual conditions and limitations.
Planning a bilingual voice assistant? Book a project discussion to define a prototype scope and the evidence needed before a wider release.
A related project: KisanDostAI
A programmable telephone assistant connecting spoken Urdu questions to agricultural documents, weather tools, and an AI response workflow.
Read the case study