Technical Documentation

Voice AI Infrastructure
Built for Enterprise Scale

A technical deep-dive into Tunk.ai's voice agent platform — covering real-time WebSocket audio pipeline, LLM orchestration, batch calling at scale, sub-second latency, and autoscalable AWS ECS deployment.

740msMin E2E Latency
1290msMax E2E Latency
5–10sPost-Call Analytics
Batch Scale
99.9%Uptime SLA

What is Tunk.ai?

Tunk.ai is a production-grade Voice AI Agent platform for enterprise contact centres and customer experience teams. It automates inbound and outbound voice calls using a globally connected WebSocket architecture — handling real-time audio streaming, LLM reasoning, live API integrations, and batch call orchestration at any scale.

🔌

WebSocket-First Architecture

A global WebSocket server connects Tunk.ai to any telephony platform. Audio streams in real-time — no batch uploads, no polling. Every byte of customer speech is streamed continuously for the lowest possible latency.

Real-Time StreamingPlivo · Twilio
🧠

LLM Orchestration

Multi-provider LLM support (OpenAI, Gemini) with RAG knowledge grounding, tool-calling, and safety guardrails — all orchestrated within a single conversational turn under 300ms of reasoning time.

OpenAIGeminiRAG
📋

Batch Calling at Scale

Schedule, run, pause, resume, and terminate outbound call batches of any size. Built on Redis Bull MQ for durable job management with automatic retry logic and real-time progress tracking.

Redis Bull MQAuto-Retry

Agent Execution Pipeline

Every live call runs through a streaming WebSocket pipeline with six distinct stages — each optimised for minimum latency. Audio is never batched: it streams continuously from the customer's phone to our servers, through AI processing, and back to the caller.

TELEPHONY Plivo · Twilio Customer Phone 10–20ms tx WebSocket Stream STT ENGINE Deepgram · Smallest Azure · AssemblyAI WebSocket to STT API 100–300ms LLM ENGINE OpenAI · Gemini Intent · Dialogue System Prompt KB Retrieval · Tool Calls Streaming Token Output 200–300ms Knowledge Base (RAG) Vector DB · Semantic Search Tool Calling (MCP / APIs) CRM · Booking · Payment · ERP TTS ENGINE ElevenLabs · Deepgram Azure · Google · Polly WebSocket to TTS API 300–500ms TELEPHONY Audio Output Customer's Phone WebSocket Stream 10–20ms tx TOTAL END-TO-END LATENCY (UTTERANCE END → FIRST AUDIO BYTE) 740ms – 1,290ms · P50: ~850ms · P95: ~1,200ms POST-CALL (ASYNC — WITHIN 5–10 SECONDS OF CALL END) Recording generation · DB/Webhook transfer · Transcript analysis · Outcome classification · Info extraction · Summary · Sentiment WS WS WS

Stage-by-Stage Breakdown

1

Telephony WebSocket Connection — Audio Ingestion

Tunk.ai exposes a global WebSocket endpoint that telephony platforms (Plivo, Twilio, and others) connect to when a call is established. The customer's phone audio is captured at the dialer level and streamed to our servers in real-time binary streaming packets. This WebSocket handshake happens once per call; audio then flows continuously without reconnection overhead.

10–20 ms
2

STT Streaming — Real-Time Transcription

Our STT engine layer maintains a persistent WebSocket connection to the selected STT provider (Deepgram, Smallest.ai, Azure Speech, AssemblyAI, or others). Incoming audio packets are forwarded in real-time. The provider begins returning partial transcription results as the customer speaks — enabling the LLM pipeline to begin processing before the utterance ends. Final transcription arrives within 100–300ms depending on provider response speed.

100–300 ms
3

LLM Processing — Intent, Dialogue & Response Formulation

The transcribed utterance — together with the conversation history, system prompt rules, and any retrieved Knowledge Base context — is sent to the LLM (OpenAI or Gemini). The LLM acts as the agent's brain: understanding the spoken input, maintaining dialogue state, and formulating a natural response. Simultaneously, if a Knowledge Base lookup or Tool/API/MCP call is needed, those run in parallel during this stage. Response tokens stream back from the LLM immediately, fed directly to the TTS pipeline without waiting for the full response.

200–300 ms
4

TTS Synthesis — Audio Generation via WebSocket

LLM response text is streamed token-by-token to the TTS provider over a dedicated WebSocket connection. TTS synthesis begins the moment the first sentence is complete — not after the entire response is generated. The provider streams synthesised audio packets back to Tunk.ai as they are generated, achieving a low Time-To-First-Byte (TTFB) of 150–200ms on leading providers. Total audio generation takes 300–500ms depending on the provider's streaming speed and response length.

300–500 ms
5

Audio Delivery — Back to Customer Phone

Synthesised audio packets are transmitted in real-time back to the telephony platform over the existing WebSocket connection. The dialer plays audio to the customer's phone as it arrives — there is no buffering of the full audio before playback begins. Network transmission adds 10–20ms. The customer hears the agent's response almost immediately after the last TTS byte arrives.

10–20 ms
Audio Ingestion (WS)
20ms
STT Transcription
100–300ms
LLM Reasoning
200–300ms
TTS Synthesis
300–500ms
Audio Delivery (WS)
20ms
Network + Processing + VAD Buffer
120–150ms
Total End-to-End (Utterance End → First Audio Byte) 740ms – 1,290ms

After Call Termination — Within 5–10 Seconds

The moment a call ends, Tunk.ai kicks off a fully automated async processing pipeline. Every deliverable — recording, analytics, summary, CRM update — is ready within 5–10 seconds of call termination, with no manual intervention.

CALL ENDS t = 0 ASYNC TRIGGER Event-driven pipeline Redis job queue 🎙️ Recording Generation Dual-channel audio · S3 upload · AES-256 🔄 DB / Webhook Delivery HMAC-signed · Retry logic 🧠 Transcript Analysis Outcome · Info extraction 😊 Sentiment Analysis Utterance + call-level scores 📝 Summary Generation 2–3 sentence auto-summary CRM / CLIENT Webhook push Dashboard update CRM record update Audit log entry QA scoring Replay store ⚡ All Delivered Within 5–10s of call termination
🧠

Outcome Classification

The LLM analyses the full call transcript and classifies the final outcome (disposition) — e.g. booking_confirmed, payment_failed, callback_requested, or any custom outcome defined by the client.

📤

Data Extraction

Structured extraction of any information spoken by the user — names, dates, reference numbers, preferences, complaints — mapped to client-defined schema fields and pushed to the CRM or webhook endpoint.

😊

Sentiment & Summary

Utterance-level and call-level sentiment scoring alongside a concise 2–3 sentence call summary — both generated automatically and pushed to the client's dashboard and CRM within seconds.

WebSocket Telephony Connectivity

Tunk.ai provides a global WebSocket server that any WebSocket-capable telephony platform can connect to — enabling real-time bidirectional audio streaming without polling, buffering, or custom SDK installation.

🔌 Supported Telephony Platforms

PlatformIntegration TypeStatus
PlivoWebSocket Media Stream● Live
TwilioMedia Streams (WSS)● Live
VonageWebSocket Audio● Coming Soon
CarrierXSIP + WebSocket Bridge● Coming Soon
Custom SIPSIP + WebRTC Bridge● Coming Soon

📡 How the WebSocket Handshake Works

When an inbound or outbound call connects, the telephony platform initiates a WebSocket connection to Tunk.ai:

# Twilio TwiML — WebSocket media stream config <Connect> <Stream url="wss://ws.tunk.ai/v1/call" track="inbound_track" > <Parameter name="agent_id" value="agt_8f3a..."/> <Parameter name="caller" value="+12025550142"/> </Stream> </Connect> # Plivo — equivalent PHLO WebSocket config # Stream URL: wss://ws.tunk.ai/v1/call?agent=agt_8f3a

Supported STT & TTS Models

Tunk.ai is provider-agnostic — the optimal STT and TTS model is selected per client based on language requirements, latency targets, and voice quality preferences. Providers can be mixed per agent or per call leg.

🎤 Speech-to-Text (STT) Providers

ProviderModel(s)Latency (TTFT)LanguagesStreamingSpeciality
Deepgram Nova-2 · Nova-3 ~100ms 30+ ✓ WS Lowest latency, phone-optimised
Smallest.ai Lightning · Pro ~80ms 20+ ✓ WS Ultra-low latency, edge-optimised
Azure Speech Fast · Accurate ~150ms 140+ ✓ WS Enterprise multilingual, compliance
AssemblyAI universal-2 · universal-3.5-pro ~150ms 17+ ✓ WS High accuracy, turn detection, diarization
Google STT Chirp · Chirp 2 ~200ms 125+ ✓ gRPC Broadest language coverage
OpenAI Realtime gpt-realtime-whisper ~200ms 57+ ✓ WS Tunable latency, VAD-aware, noisy environments

🔊 Text-to-Speech (TTS) Providers

ProviderModel(s)TTFBLanguagesVoice CloneSSMLSpeciality
ElevenLabs Turbo v2.5 · Flash ~180ms 32+ ✓ Instant Most realistic, branded voices
Deepgram Aura Aura-2 · Asteria ~120ms 15+ Lowest latency at scale
Smallest.ai Lightning TTS ~90ms 10+ Partial Ultra-fast, sub-100ms TTFB
Azure Neural TTS Neural · HD ~140ms 140+ ✓ Custom ✓ Full Enterprise SSML, widest language
Google Cloud TTS WaveNet · Studio ~160ms 50+ ✓ Full Regulated sectors, multilingual
Amazon Polly Neural · Generative ~150ms 30+ ✓ Full AWS-native, low cost at volume
Cartesia Sonic-3 · Sonic-3.5 ~80ms 15+ ✓ Instant Partial Ultra-low TTFB, sub-100ms first byte

🌍 Language & Accent Support

Language is auto-detected from the caller's first utterance — TTS voice and LLM system prompt switch dynamically:

English (US/UK/AU/IN) Hindi Marathi Tamil Telugu Bengali Spanish French Arabic Mandarin German Portuguese Japanese Korean Russian

🎭 SSML Prosody Control

Fine-grained control over the agent's spoken delivery via SSML:

<speak> <prosody rate="medium" pitch="+2st"> I understand your concern. </prosody> <break time="350ms"/> <emphasis level="moderate"> Let me resolve this right away. </emphasis> </speak>

Knowledge Base

Every Tunk.ai agent is grounded in client-specific business data through a Retrieval-Augmented Generation (RAG) pipeline. This eliminates hallucinations without fine-tuning the base LLM — agents answer from your documents, not from model priors.

KNOWLEDGE BASE 📄 Product Docs / FAQs 📋 Policies & SOPs ingest EMBEDDING text-embedding-3 1536-dim vectors <5min update cycle index VECTOR STORE Milvus / Pinecone HNSW Index Cosine Similarity Top-K=5 Retrieval retrieve CONTEXT INJ. Top-K chunks → LLM Prompt <30ms added latency LLM Grounded Response ↓ Hallucination Rate ↑ Factual Accuracy Parallel retrieval runs during LLM prompt preparation · Adds <30ms to total latency · Updates propagate within 5 minutes of document upload
📁

Supported Document Formats

PDF DOCX XLSX CSV JSON Markdown HTML / Web Plain Text

Documents are automatically chunked, embedded, and indexed. Updates to any document propagate to the live agent in under 5 minutes with no downtime.

🗄️

Vector Store

Milvus stores high-dimensional embeddings with HNSW indexing for sub-millisecond approximate nearest-neighbour search across millions of document chunks. Pinecone supported as alternative.

MilvusPinecone1536-dimHNSW

Retrieval Performance

  • Top-K = 5 most relevant chunks per query
  • Cosine similarity for semantic matching
  • <30ms added latency to pipeline
  • Parallel to LLM prompt preparation
  • <5min document update propagation

Batch Calling Engine

Tunk.ai's batch calling engine lets you schedule, execute, monitor, and control outbound call campaigns at any scale — from a few dozen calls to millions. Built on Redis Bull MQ for durable, fault-tolerant job management with automatic retry logic.

CLIENT Dashboard / API Batch job creation CSV · API payload REDIS BULL MQ Job Queue ⏱ Scheduled Jobs 🔄 Retry Queue (exp. backoff) ⏸ Pause / Resume State 🛑 Graceful Terminate Durable · FIFO · Priority WORKER POOL ECS Fargate tasks Worker 1 — 50 calls Worker 2 — 50 calls Worker N — autoscale ∞ horizontal scale TELEPHONY Plivo · Twilio Dial · Connect AI Agent → Call RESULTS ✅ Completed 🔄 Retrying (failed) ❌ Dead Letter Queue 📊 Progress Dashboard auto-retry (exponential backoff · configurable max attempts)

📋 Batch Job Controls

OperationBehaviour
🟢 ScheduleCreate a batch with start time, concurrency limit, calling window, and contact list
▶️ RunDispatch jobs from queue to worker pool; workers auto-scale with call volume
PauseHalt new job dispatch; active calls complete gracefully; state preserved in Redis
▶️ ResumeContinue dispatch from exact position; no duplicate calls; no data loss
🛑 TerminateCancel all pending jobs; active calls complete naturally; results flushed to DB

🔄 Retry Logic

Failed calls (no answer, busy, network error) are automatically retried with configurable backoff:

# Batch retry configuration retry_policy: max_attempts: 3 backoff: exponential initial_delay_min: 15 max_delay_min: 120 retry_on: ["no_answer", "busy", "network_error"] no_retry_on: ["opted_out", "invalid_number"] dead_letter_queue: true # after max_attempts
Exp. Backoff Dead-Letter Queue Real-Time Progress

Tool Calling & API Integrations

Tunk.ai agents can read and write live data across your entire tech stack during the call. Tool calling is natively wired into the LLM reasoning loop — the model decides when to call an API and what to do with the result.

📖

Read Operations

Fetch live customer data mid-call: account balance, order status, booking availability, CRM fields — enabling hyper-personalised responses without pre-scripting every scenario.

✏️

Write Operations

Create bookings, update CRM records, raise support tickets, trigger payment flows, send SMS confirmations, push call dispositions — all within the live conversation.

🔗

MCP Support

Model Context Protocol allows any third-party service to be connected as a tool without custom integration code — dramatically reducing new client onboarding time.

MCPNo-Code Connect
📞

Call Transfer

When the LLM detects that a situation requires human intervention — or the customer explicitly requests it and grants permission — the agent seamlessly transfers the live call to a human agent without dropping the connection. Transfer can be triggered autonomously by the agent or manually by the caller on the call.

Human HandoffSIP TransferPermission-GatedLLM-Triggered

📦 Webhook Payload — Post-Call JSON

// POST https://client.example.com/tunk/webhook // X-Tunk-Signature: sha256=... (HMAC-SHA256 · TLS 1.3 transport) { "version": "1.0", "call_id": "cid_7f3a9b2c1e", "direction": "inbound", "caller": "+12025550142", "duration_s": 143, "disposition": "booking_confirmed", "intent_primary": "appointment_scheduling", "sentiment": "positive", "csat_predicted": 4.7, "summary": "Caller booked a 2pm slot on 24th July. Confirmed via SMS.", "extracted_info": { "name": "Riya Sharma", "date": "2026-07-24" }, "tools_called": ["get_availability", "create_booking", "send_sms"], "latency_p95_ms": 1090, "recording_url": "https://static.tunk.ai/recordings/cid_7f3a9b2c1e", "analytics_ready_ms": 7200 // 7.2s after call end }

Anchor — Your AI Agent Builder

Anchor is Tunk.ai's chat-based agent orchestration interface. It lets non-technical users design, configure, and deploy fully functional voice AI agents in minutes — through a natural conversation, not forms or code.

Anchor
Create AI Fees Reminder Agent
Build Recruitment Agent
Add call cancellation flow
List the agent IDs
Link phone number
I want to create an AI agent for a fees reminder for students
Great! Here's how I'll guide you through creating a fees reminder agent:

1. Purpose & Audience: The agent will call students to remind them about pending fees.
2. Knowledge Base: Should it answer questions from your documents? (payment methods, deadlines, etc.?)
3. Language: English, Hindi, or both?
4. Calling: Outbound calls to students, or inbound from them?

Please confirm your preferences!
I need an Indian female voice who can speak English and tell them they are calling from Tunk Institute
⚙️ Executed voice_capabilities_list · succeeded
Here's the proposed setup for your fees reminder agent:

Purpose: Outbound calls reminding students about pending fees, introducing as Tunk Institute.
Language: English (Indian accent)
Voice: Indian female — Aditi, Kajal, or Raveena (Amazon Polly)
Knowledge Base: Standard reminder script (attach docs to customise)
STT: Deepgram Nova-2  ·  TTS: Amazon Polly (Aditi)
Ask Anchor to build, update, or inspect your agents...
Send

Agent in 5 Minutes

Describe your use case in plain English — Anchor configures the agent's system prompt, selects the optimal STT/TTS providers, links your knowledge base, and connects your telephony number automatically.

🔧

Full Configuration Access

Anchor exposes the full agent config — voice selection, system prompt rules, retry settings, tool connections, knowledge base uploads, and batch campaign parameters — all via natural language or direct UI.

🛡️

Approval Gating

Sensitive actions — telephony changes, agent deletion, new integrations — require explicit user approval before execution. Anchor never makes destructive changes autonomously.

Human-in-the-loop

AWS ECS Autoscaling Deployment

Tunk.ai runs on a fully containerised, cloud-native infrastructure on Amazon Web Services. The platform autoscales horizontally in response to inbound call volume — adding capacity without operator intervention or service disruption.

AWS REGION (PRIMARY · Multi-AZ) VPC — Private Subnets (10.0.0.0/16) Application Load Balancer WebSocket-aware ECS CLUSTER — FARGATE Voice Agent 2 vCPU · 4 GB agent-svc:latest WS handler Batch Worker 2 vCPU · 4 GB batch-svc:latest Bull MQ consumer Batch Scheduler 1 vCPU · 2 GB scheduler:latest Cron + Queue mgmt Post-Call Worker 2 vCPU · 4 GB analytics:latest Transcript · Sentiment ↕ Target Tracking · ConcurrentActiveCalls metric (CloudWatch) Min: 2 tasks · Target: 50 calls/task · Max: 500 tasks · Scale-out: 30s · Scale-in: 5min Rolling deploys · Minimum healthy 100% · Health-gated task replacement · Auto-rollback on P95 breach Zero cold-start · Pre-warmed connection pools · Predictive scheduling on weekday peaks GitHub → CodePipeline → CodeBuild → ECR (vuln scan) → ECS rolling deploy → CloudWatch alarms → auto-rollback RDS PostgreSQL Plain RDS · Multi-AZ Call records · Users Redis (EC2) Self-hosted · EC2 Session · Bull MQ S3 Recordings · Transcripts AES-256 · Versioned CloudWatch Metrics · OTel Traces X-Ray · Grafana Secrets Mgr API Keys · KMS Zero plaintext ECR Container Registry Image Scanning DR REGION Active-Passive RTO <60s Route53 health S3 cross-region RDS replica Auto failover 99.9% Uptime SLA · <60s DR Failover · <2min Auto-Rollback · ~25,000 Max Concurrent Calls · CodePipeline CI/CD OpenTelemetry instrumentation · AWS X-Ray tracing · Grafana dashboards · PagerDuty alerting · Immutable audit logs
99.9%
Uptime SLA
<60s
DR Failover RTO
<2min
Auto-Rollback

Enterprise-Grade Security

Defence-in-depth across every layer — from WebSocket ingress to long-term archival storage.

🔐 Data Protection

🔒AES-256 at Rest
🔗TLS 1.3 in Transit
🔑AWS KMS
✍️HMAC-SHA256 Webhooks

🔏 Identity & Access

👥RBAC
🔐MFA Required
🇪🇺GDPR Compliant
📝Immutable Audit Logs
LayerControlStandardDetail
TransportTLS 1.3 onlyRFC 8446All APIs, webhooks, WebSocket streams
StorageAES-256 encryptionFIPS 197S3, RDS, Redis (EC2), Vector DB
SecretsAWS Secrets ManagerKMS + IAMZero plaintext secrets in env or code
NetworkVPC + Security GroupsAWS VPCPrivate subnets, no public ECS IPs
IdentityRBAC + MFAOWASP IAMShort-lived tokens, all admin requires MFA
WebhooksHMAC-SHA256 signingRFC 2104Replay protection via nonce + timestamp
PrivacyGDPR DPAs availableGDPR Art.28Right-to-erasure supported, data residency options

Go-Live in 5 Steps — Under 7 Days

01

Discovery & Setup

Requirements gathering, telephony platform selection, DID number provisioning, and success KPI definition. Anchor account configured and team access provisioned.

Day 1
02

Agent & Integration Build

Agent built via Anchor: system prompt, voice selection, knowledge base ingestion, and CRM/API tool connections configured. WebSocket link to telephony platform established.

Days 2–3
03

Testing & Refinement

Internal sandbox testing across happy paths, edge cases, and adversarial inputs. Conversation flow refined via Anchor. Latency verified within acceptable range.

Days 3–4
04

Pilot Go-Live

Limited live rollout (10–20% of call volume) with real-time post-call analytics monitoring. Rapid iteration based on first live call data — most agents are production-ready within hours.

Days 5–6
05

Full Scale

Full production rollout across all call volume. Ongoing monitoring, continuous agent optimisation, and monthly performance reviews.

Day 7 → Ongoing

Upcoming Features

🎛️

DTMF & IVR Navigation Upcoming

Full DTMF tone detection enabling agents to navigate legacy IVR trees, accept PIN inputs, and route calls through existing telephony infrastructure without system replacement.

DTMFIVR Navigation
📞

Expanded Telephony & Custom SIP Upcoming

Direct native integrations with Vonage and CarrierX, alongside Custom SIP trunking capabilities to connect any enterprise PBX directly into Tunk.ai's high-speed WebSocket pipeline.

VonageCarrierXCustom SIP
📜

vCon Standard Integration Upcoming

Full adoption of the IETF vCon (Virtual Conversation) open standard — packaging call recordings, multi-channel transcripts, AI analysis, metadata, and cryptographic consent records into standardized JSON containers for seamless enterprise data portability and compliance.

IETF vConOpen ContainerData Compliance
🤖

Multi-Agent System & Single-Call Handoff Upcoming

Orchestrate specialized sub-agents working in tandem within a single call. A primary triage agent can dynamically transfer control to specialized sub-agents (e.g. billing, technical support, booking) mid-call, resolving complex multi-domain workflows seamlessly.

Multi-AgentDynamic HandoffUnified Call
🌍

Single-Agent Multi-Language & Customized Prompts Upcoming

Enable a single agent instance to dynamically switch languages mid-conversation while executing dedicated, language-customized system prompts and cultural guidelines for each supported dialect.

Multi-LangCustom PromptsAuto-Switching

Technical Glossary

TermDefinition
LLMLarge Language Model — the AI engine powering intent detection, dialogue management, and response generation (OpenAI, Gemini)
RAGRetrieval-Augmented Generation — injecting retrieved knowledge base chunks into the LLM prompt to ground responses in factual, client-specific data
STTSpeech Recognition — conversion of streaming audio into text transcript via WebSocket connection to providers like Deepgram, Smallest.ai, Azure, or AssemblyAI
TTSText-to-Speech — synthesis of LLM-generated text into human-like audio via WebSocket to providers like ElevenLabs, Deepgram Aura, Azure, Google, or Amazon Polly
Bull MQRedis-backed durable job queue library used for batch call scheduling, execution, pause/resume, and retry management
VADVoice Activity Detection — detects when a caller is speaking vs. silent; used for utterance segmentation and barge-in interruption
DispositionThe final outcome classification of a completed call — e.g. booking_confirmed, payment_failed, callback_requested, escalated_to_human
SSMLSpeech Synthesis Markup Language — XML-based markup for controlling TTS prosody, rate, pitch, and pausing
MCPModel Context Protocol — open standard for connecting AI models to external tools and data sources without custom integration code
HMACHash-based Message Authentication Code — cryptographic mechanism for signing and verifying webhook payloads
TTFBTime To First Byte — latency from TTS synthesis start to first audio byte ready for playback
AnchorTunk.ai's chat-based agent orchestration interface — allows users to design, configure, and deploy voice AI agents in under 5 minutes through natural conversation