AI Voice Agent Architecture:
How Kestrel Voice Works
Custom Python orchestration, realtime voice, deterministic guardrails, RAG, business tools, fallback modes, and operational evidence — the complete architecture behind a production voice agent platform.
By Subodh KC · July 15, 2026 · 30 min read
Last reviewed: July 15, 2026
Scope: Production architecture for AI voice agent platforms — telephony, orchestration, RAG, tools, security, fallback modes, post-call intelligence, learning, and multi-channel coverage
Disclosure: Kestrel Voice and HAIEC are platforms developed by Subodh KC. This article refers to Kestrel as the product through which these architectural principles have been applied directly, and HAIEC as the companion AI security, governance, and compliance-readiness platform. Neither platform eliminates AI risk. Their purpose is to make that risk more visible, controlled, testable, and supportable with evidence.
Educational notice: This article provides general information about AI voice agent architecture. Legal and regulatory applicability depends on the use case, jurisdiction, data, call purpose, and caller population. Telephony-specific obligations such as TCPA, HIPAA, and state biometric laws require case-by-case analysis.
Table of Contents
Synopsis
A production AI voice agent is not a model connected to a phone number. It is a layered operational system coordinating telephony, tenant identity, deterministic rules, realtime AI, retrieval-augmented knowledge, tool execution, fallback modes, post-call intelligence, learning, and evidence. This article documents the architecture behind Kestrel Voice — the platform I built to handle real calls for service businesses — covering inbound and outbound call flows, adaptive orchestration, RAG, security, compliance, and the operational pipeline that makes the system trustworthy enough to answer a phone.
Most AI voice agent architecture discussions start and end with the model. Which frontier model powers the conversation? How natural is the voice? How low is the latency?
These questions matter. But they are the smallest part of a production system.
When I built Kestrel Voice, the model was the first decision I made and the easiest one to change. The harder work was everything around it: how to resolve which business a call belongs to, how to answer differently for a plumber versus a veterinary clinic, how to handle emergencies before the model speaks, how to ground answers in business-specific knowledge, how to verify that a booking actually succeeded before telling the caller it did, how to degrade gracefully when the realtime API fails, how to prevent toll fraud, how to record calls with proper consent, how to learn from patterns without introducing unsafe behavior, and how to produce evidence that a human can review after the call ends.
The model handles the conversation. The architecture handles the business.
This article documents that architecture — not as an abstract framework, but as the actual system running in production today.
The Direct Answer
Kestrel Voice is a multi-tenant AI voice agent platform built on FastAPI, deployed on Modal, and backed by Supabase and Postgres. When a call arrives, the system resolves the called number to a tenant, loads that tenant business configuration, selects an AI mode based on plan and credits, and routes the call through a layered orchestration pipeline: deterministic hard interrupts first, fast-path answers second, and realtime AI reasoning third. RAG grounds the model in tenant-specific knowledge. Tools execute bookings and CRM operations with result verification. A four-level degradation system handles failures. Post-call intelligence extracts structured outcomes. A learning pipeline promotes recurring patterns into fast paths. And every step produces evidence — transcripts, tool calls, prompt hashes, and outcome records — that a human can review.
The architecture is not a demo. It is an operational system handling real calls for real businesses.
Architecture at a Glance
Figure 1 — Five-layer architecture: Presentation (Next.js), Voice Runtime (FastAPI on Modal), Telephony (Twilio), Demand Engine, and Data (Supabase/Postgres with pgvector).
The diagram shows the five layers of the system. Telephony (Twilio) handles the phone call and media stream. The Voice Runtime (FastAPI on Modal) processes the call through tenant resolution, mode selection, deterministic intercepts, AI conversation, and tool execution. The Data Layer (Supabase/Postgres with pgvector) stores tenant configurations, call logs, RAG chunks, and analytics. The Demand Engine handles CRM, onboarding, and reporting. The Presentation Layer (Next.js) provides the dashboard, RAG management, and configuration UI.
These are logically separated services with a consolidated deployment option — the voice runtime, demand engine, and scrapers share a single Modal container for cost efficiency, while the frontend runs on Vercel. The separation is logical, not physical, which simplifies operations without sacrificing isolation.
What Happens When a Call Arrives
A call arrives at a Twilio phone number. What happens next is a nine-step sequence that runs before the AI ever speaks.
Phone rings
Tenant resolution
Mode selection
Session initialization
System prompt assembly
Deterministic intercept
AI conversation
Tool execution and verification
Evidence capture
Steps 1 through 5 happen in under a second. Step 6 runs on every user utterance. Steps 7 and 8 happen in real time during the conversation. Step 9 runs after the call ends without blocking teardown.
Four Ways Kestrel Can Handle Calls
Gather — Turn-Based Fallback
Realtime — WebSocket Streaming
Adaptive — Three-Layer Intent Router
IVR / Forwarding — Deterministic Routing
The mode is selected per call based on the tenant plan, available credits, and configuration. A smart mode router can escalate or downgrade mid-call based on conversation signals — for example, switching from adaptive to gather if the realtime API degrades.
Adaptive Orchestration
Adaptive mode is the most architecturally interesting mode. It runs a realtime AI session but intercepts every user utterance through a three-layer router before the model processes it. The goal: answer deterministic questions deterministically, reserve the model for reasoning.
Layer 1: Hard Interrupts
Layer 2: Fast Paths
Layer 3: AI Reasoning
Circuit Breaker
Gather Fallback
Tenant-Specific Business Runtime
Every tenant has a unique business configuration stored in Postgres: business name, industry type, greeting, communication style, services offered, service areas, business hours, transfer destination, emergency behavior, appointment settings, and FAQ entries. This configuration is assembled into a system prompt using a three-tier hierarchy.
Prompt Evidence Logged
The prompt includes temporal context — today date and time — injected automatically to prevent the model from hallucinating dates. "What is your earliest appointment?" gets an answer grounded in the actual calendar, not the model training data.
Deterministic vs Generative Answers
A common architecture mistake is sending every user utterance to the model. This increases cost, latency, and hallucination risk. Kestrel separates answers into three categories:
| Question Type | Answer Source | AI Involved? | Example |
|---|---|---|---|
| Hours, location, service area | Canonical tenant configuration | No | "What time do you close?" |
| Availability, booking | Live calendar system | No (tool call) | "Can I book for Tuesday?" |
| Policies, warranties, services | RAG (tenant-specific knowledge) | Yes (grounded) | "What is your warranty on repairs?" |
| Ambiguous, multi-part, contextual | AI reasoning | Yes (model) | "I think my AC is making a weird noise" |
The deterministic layer means "What are your hours?" never goes to the model. The answer comes from the tenant configured business hours, injected as a fast-path response. This costs zero AI tokens and returns in zero model-response time. The model is reserved for questions that actually require reasoning — and when it does answer, RAG grounds it in the tenant own knowledge base rather than the model training data.
Governed RAG
Kestrel Voice includes a retrieval-augmented generation system that grounds the AI in tenant-specific knowledge. The pipeline has four stages: ingestion, storage, retrieval, and refresh.
Figure 2 — RAG pipeline: ingestion from three source types, tenant-scoped storage with RLS, keyword-triggered retrieval with similarity threshold, and SHA-256-based refresh tracking.
Stage 1: Ingestion
Stage 2: Storage
Stage 3: Retrieval
Stage 4: Refresh
RAG is per-tenant and opt-out. Each tenant RAG enablement is checked and cached. The retrieval path tries the frontend API first, then falls back to a direct database RPC — ensuring retrieval works even if the frontend is temporarily unavailable.
Tools and Verified Actions
When a caller asks to book an appointment, the system follows a strict sequence to ensure the action is real, not assumed.
Calendar Service
CRM Integration
Extraction-to-Booking
Failure and Degraded Modes
Production systems fail. The architecture must handle failure without dropping the caller or producing unsafe behavior. Kestrel has a four-level degradation system.
Level 0: Full AI
Frontier model with premium voice synthesis. Best quality. Used when all services are healthy.
Level 1: Fast AI
Cost-efficient model with standard voice synthesis. Reduced latency and cost. Used when the frontier model API is degraded or rate-limited.
Level 2: Rule-Based
State machine only. No language model. Handles greetings, basic intent routing, and voicemail capture. Used when AI APIs are unavailable.
Level 3: Human Transfer
Transfer to a human or voicemail. Last resort. Used when all automated modes have failed.
| Failure | Response |
|---|---|
| Realtime WebSocket fails | Fall back to Gather (turn-based) |
| 3 WebSocket failures in 5 min | Circuit breaker trips → Gather mode |
| AI API degraded | Degrade to Fast AI or Rule-Based |
| All AI unavailable | Human transfer or voicemail |
| Tool fails | AI reports failure, offers alternative |
| Emergency detected | Immediate transfer, no AI deliberation |
The system tracks success and failure metrics at each level and can automatically recover when service health returns. Manual override is available for operators who need to force a specific level.
Post-Call Operations
After a call ends, an asynchronous pipeline runs without blocking call teardown. Two stages: intelligence extraction and action dispatch.
Intelligence Extracted
Action Engine
The call also produces a transcript, optional recording, tool call logs, prompt evidence with hash, and outcome classification. Calls can be replayed with audio and transcript sync, tagged for categorization, and reviewed in the dashboard.
Learning Pipeline
Kestrel Voice learns from call patterns. The learning pipeline promotes recurring fast-path patterns into active fast actions — but with guardrails.
Record
Promote
Review Window
Activate
Learning Guardrails
- Intent whitelist — Only approved intent types can be promoted
- Blocked phrases — Patterns containing blocked phrases are excluded
- Length limits — Pattern text must be within configured bounds
- Minimum occurrences — Patterns must appear multiple times before promotion
- Tenant-scoped — Patterns are never shared across tenants
Template FAQs
Pattern Versioning
Beyond Inbound: Outbound, Meetings, and Copilot
Kestrel Voice handles more than inbound calls. The platform supports outbound dialing, meeting bridges, live AI copilot, and sequential ring — each with its own state machine and guardrails.
Outbound Dialer
Meeting Bridge
AI Copilot
Sequential Ring
Multi-Channel: SMS, Video, and WebRTC
Voice is the primary channel, but Kestrel Voice also supports SMS, video sessions, and browser-based calling.
SMS
Video Sessions
WebRTC
Compliance
Security Architecture
Security in a voice agent platform spans telephony, API, data, and compliance. Kestrel implements defense-in-depth across six domains.
Telephony Authentication
API Key Management
Spam and Fraud Protection
Toll Fraud Prevention
Recording Consent
Tenant Isolation
Tenant Isolation — Five Concentric Layers
Additional measures include CORS policies restricting origins to the application domain, API documentation disabled in production, file upload security with MIME type whitelisting and virus scanning, and SSRF prevention in the RAG scraper (blocking private IPs, localhost, and internal domains).
Technology Decisions
The key technology decisions and why they were made. This is not an exhaustive dependency list — it covers the decisions that shaped the architecture.
FastAPI
OpenAI (API-based)
Twilio
Supabase + Postgres + pgvector
Modal
Redis (optional)
What the Architecture Does Not Guarantee
Honest architecture documentation includes what the system does not guarantee. The following limitations are inherent to AI voice agent platforms, including Kestrel Voice:
Zero hallucinations
The model may still invent facts, mishear information, or claim actions succeeded when they failed. Deterministic fast paths, RAG grounding, and tool-result verification reduce this risk but cannot eliminate it.
Perfect emergency detection
Regex-based emergency matching catches known phrases but cannot detect every possible emergency description. The system errs on the side of caution but cannot guarantee zero missed emergencies.
Legal compliance in every jurisdiction
TCPA, HIPAA, state biometric laws, and international regulations vary by use case and jurisdiction. The platform provides configurable controls but does not make any business compliant by default.
Permanent uptime
The system degrades gracefully but is not immune to provider outages, network failures, or infrastructure issues.
Complete immunity from attacks
Twilio signature validation, API key management, spam enforcement, and tenant isolation reduce attack surface but cannot prevent every possible attack vector.
Autonomous production improvement
The learning pipeline promotes patterns with guardrails and a review window, but it does not autonomously change business logic or override tenant configuration.
Frequently Asked Questions
What is an AI voice agent architecture?
An AI voice agent architecture is the complete system design that surrounds a voice AI model — including telephony integration, tenant configuration, deterministic rules, retrieval-augmented generation, tool execution, fallback modes, security, and post-call intelligence. The model handles conversation; the architecture handles the business process.
What is custom voice orchestration?
Custom voice orchestration is the practice of building application logic around the AI model to control business workflows, enforce safety rules, verify tool results, and produce evidence — rather than relying on the model alone to manage the call. Kestrel Voice uses custom Python orchestration via FastAPI.
What is adaptive AI voice?
Adaptive AI voice is a mode where the system runs a realtime AI session but intercepts every user utterance through a three-layer router: hard interrupts (emergencies, transfers), fast paths (hours, pricing, booking), and AI reasoning. Deterministic answers are injected without model involvement; the model handles only what requires reasoning.
Does Kestrel Voice use RAG?
Yes. Kestrel Voice includes a full RAG pipeline: website scraping, FAQ ingestion, and Google Drive integration as source types; chunking with sentence boundary detection; embedding generation; tenant-scoped storage in Postgres with pgvector; cosine similarity retrieval with a minimum threshold; and content refresh tracking with stale detection.
What happens when realtime AI fails?
The system falls back to Gather (turn-based) mode without dropping the caller. If three WebSocket failures occur within five minutes for a tenant, a circuit breaker trips and routes subsequent calls directly to Gather. The system also has a four-level degradation system: full AI, fast AI, rule-based, and human transfer.
Can Kestrel Voice make outbound calls?
Yes. The outbound dialer supports a full call state machine with three AI participation modes: silent (transcribe only), assist (suggestions), and active (speaks on behalf of the user). Credits are only consumed when the AI is actively engaged.
Does Kestrel Voice support video?
Yes. Video consultation sessions are available via Daily.co integration, with session management, recording, and participant tracking.
Can Kestrel Voice connect to my calendar or CRM?
Yes. Google Calendar sync is built in for booking, rescheduling, and cancellation. CRM integration supports lead creation and management in Postgres, with extensibility for Salesforce and HubSpot.
Does Kestrel Voice support multiple businesses?
Yes. The platform is multi-tenant with defense-in-depth isolation: ASGI middleware, parameter-scoped queries, Postgres row-level security, and server-side auth extraction. Each tenant has independent configuration, RAG, prompts, and call data.
How does Kestrel Voice handle spam and fraud?
Multi-layer protection: score-based spam enforcement with reputation memory, tenant-configurable sensitivity levels, whitelisting for false-positive protection, country-specific call rate limiting, and IRSF (International Revenue Share Fraud) prevention.
Is call recording compliant?
The system includes TCPA-compliant recording consent with state-aware prompting. Two-party consent states receive a consent prompt before recording begins. SMS handles STOP, HELP, and START keywords. Compliance depends on the use case and jurisdiction — the platform provides controls but does not make a business compliant by default.
Does Kestrel Voice learn from calls?
Yes. A learning pipeline records fast-path pattern matches, promotes recurring patterns above a threshold to active fast actions, and provides a time-delayed review window where tenants can reject promotions before they activate. Guardrails include intent whitelisting, blocked phrases, and length limits. Industry template FAQs provide a complementary mechanism for pre-written answers.
What is the AI copilot?
The copilot is a live call assistant that provides real-time notes, suggested responses, chat Q&A, and action item extraction to a human operator during an active call. It uses a cost-efficient model and integrates RAG for knowledge lookups. All copilot events are persisted for post-call review.
Can I use Kestrel Voice from my browser?
Yes. WebRTC support enables browser-based calling via Twilio Client, with a prebind session that ensures deterministic tenant resolution before the call connects.
What technology stack does Kestrel Voice use?
FastAPI (async voice runtime), OpenAI (realtime API, embeddings, copilot — all API-based, no local models), Twilio (telephony), Supabase and Postgres with pgvector (data, RAG, auth, RLS), Modal (serverless deployment), and Redis (optional session store with in-memory fallback). Next.js powers the frontend dashboard and RAG management.
Related Resources
Why AI Voice Agents Fail in Production
Kestrel Voice Platform
HAIEC Platform
Secure Enterprise RAG Architecture
How to Secure and Govern AI
AI Security Tools
AI Voice Agent Architecture Checklist
For the failure modes this architecture prevents, read Why AI Voice Agents Fail in Production. For the RAG governance framework behind the retrieval pipeline, read Secure Enterprise RAG Architecture. For the full AI compliance stack — NIST, ISO, SOC 2 — read How to Secure and Govern AI.