how can we create a retell like product with livek...
# ask-ai
w
how can we create a retell like product with livekit. what would the backend look like?
t
Thanks for reaching out, Someshwar. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to build a Retell-like product with LiveKit and what the backend would look like — great question. To give a useful, focused answer I need one quick clarification: Which core features matter most for your product? • Real-time AI voice agents that join live rooms and converse (STT → LLM → TTS)? • Phone call support (inbound/outbound SIP trunks, DIDs)? • Call recording, transcripts and export? • Call routing/dispatch (DID-based routing, IVR, DTMF)? • Multi-tenant / enterprise scale (per-tenant agent versions, autoscale)? Pick the top 1–2 and I’ll return a concise backend architecture and recommended components (tokens, agent runtime, STT/TTS/LLM providers, deployment pattern, and starter templates). Sources: Agents (Python) | livekit/livekit_composite | DeepWiki | livekit/livekit_composite | DeepWiki | An open source stack for real-time multimodal AI | Deploy and scale agents on LiveKit Cloud | Live Conversations with AI using ChatGPT and WebRTC
w
• zReal-time AI voice agents that join live rooms and converse (STT → LLM → TTS)? • Phone call support (inbound/outbound SIP trunks, DIDs)?
t
Below is a concise backend architecture and concrete component list to build a Retell-like product with LiveKit that covers (A) real‑time AI voice agents (STT → LLM → TTS) and (B) phone call support (inbound/outbound SIP trunks, DIDs). I’ll keep it focused and actionable. High-level flow 1. User/Phone → LiveKit client or SIP trunk → LiveKit room (SFU) 2. Agent worker joins room as a participant, receives audio 3. Agent pipeline: VAD → Streaming STT → LLM → Streaming TTS → publish audio back 4. Optional: record/egress, transcripts, webhooks, CRM/API actions Core backend components • LiveKit Cloud (media + signaling) or self-hosted LiveKit server • Token service: issues JWTs with RoomConfiguration dispatch to spawn agents • Agent runtime (workers): Python or Node.js agent processes using LiveKit Agents SDK • Agent orchestrator: scale, deploy, health checks, versioning (Kubernetes or managed) • STT provider: streaming STT (Deepgram, AssemblyAI, Google, etc.) • LLM provider: OpenAI, Anthropic, Google Gemini, Ollama, etc. • TTS provider: streaming TTS (ElevenLabs, OpenAI TTS, Cartesia, etc.) • VAD: Silero VAD or equivalent to detect turn ends • Telephony/SIP gateway: Twilio/Telnyx/Plivo (SIP trunks + DIDs) • Dispatch/router: rules to route incoming calls to specific agent types (DID, headers, IVR) • Database: store call logs, transcripts, session metadata, user/context • Webhooks & event processor: handle LiveKit events (join/leave/recording_finished) • Egress/Recording: record audio and export to cloud storage • Observability: metrics, logs, tracing for agents and LiveKit sessions Agent pipeline (detailed) 1. Agent joins the LiveKit room as participant with microphone + speaker tracks. 2. Voice Activity Detection (VAD) detects speech segments; stream audio to STT as chunks. 3. Streaming STT returns interim/final transcripts for low latency. 4. Conversation manager collects transcript + context, formats prompt for LLM (tool calls or external APIs if needed). 5. LLM returns reply (streaming if supported). Optionally run safety filters / response formatting. 6. Streaming TTS converts LLM text to audio in near real time and agent publishes the audio track back into the room. 7. Save transcript and audio to DB/storage; emit webhooks/analytics. Phone (SIP) integration patterns • Inbound calls: a. SIP provider routes incoming call to your SIP gateway or PSTN connector. b. Gateway forwards media into a LiveKit room (or directly into an agent worker via WebRTC). c. Dispatch logic maps call to an agent (by DID, IVR input, API routing). • Outbound calls: a. Agent/orchestrator initiates outbound SIP call via provider API. b. When call is answered, media bridges into a LiveKit room where the agent participates. • Features supported: DTMF handling, call transfer (SIP REFER), caller ID/DID selection, call recording. Deployment & scaling recommendations • Start with LiveKit Cloud + managed agent workers (fastest path). • Use Kubernetes for self-hosted agent workers for production scale; autoscale based on concurrent sessions. • Run STT/LLM/TTS as external services (cloud vendors) or colocate models if latency/cost require. • Use edge regions for lower latency where users and SIP gateways are located. Security & access control • Use short‑lived JWT tokens with room config that dispatches the proper agent(s). • Isolate per-tenant data in DB and use scoped tokens/roles. • Audit logs for agent actions and webhooks for compliance. Latency & UX tips • Use streaming STT/TTS and streaming LLM where possible. • Use VAD + end-of-turn detection to avoid waiting for long silence. • Minimize prompt size and keep LLM responses concise to reduce TTS latency. • Use edge-hosted agents or LiveKit Cloud regions close to users/SIP gateways. Starter resources / templates • Use LiveKit agent starter templates (Python / Node) to boot the agent runtime and pipeline. • Use outbound-caller examples for SIP call flows and bridging into rooms. Next step Would you like: • a concise architecture diagram and a recommended component stack for a POC, or • a minimal step-by-step POC plan (repo to fork, quick config, and first call flow)? Pick one and I’ll provide the exact steps and config snippets.
w
• how do. these work (how do repos look like):Agent runtime (workers): Python or Node.js agent processes using LiveKit Agents SDK • Agent orchestrator: scale, deploy, health checks, versioning (Kubernetes or managed)
t
Thanks — I'll show exactly how those two pieces typically look and what files/behaviors you should expect in each repo. Agent runtime (worker) — what the repo looks like • Purpose: long‑lived process that accepts "jobs" (one job = one room/call), connects to LiveKit, runs VAD → streaming STT → LLM → streaming TTS, publishes audio back, saves transcripts/records. • Typical repo layout (Python example)
Copy code
agent-starter-python/
  ├── src/
  │   ├── agent.py            # entry: registers job handler, starts worker
  │   ├── voice_agent.py      # per-job logic: connect to room, pipeline (VAD/STT/LLM/TTS)
  │   ├── stt_client.py       # adapter for chosen STT (streaming)
  │   ├── tts_client.py       # adapter for chosen TTS (streaming)
  │   ├── llm_client.py       # adapter for LLM provider & prompt manager
  │   ├── utils/
  │   │   ├── vad.py
  │   │   ├── audio_io.py     # WAV/opus frames, buffering
  │   │   └── telemetry.py
  ├── Dockerfile
  ├── .env.example            # env vars: LIVEKIT_KEY/SECRET, STT/TTS/LLM keys
  ├── pyproject.toml
  └── tests/
• Node.js variant is analogous: ◦
src/index.js
(worker bootstrap) ◦
src/agent.js
(job handler) ◦ provider adapters under
src/providers/*
◦
package.json
,
Dockerfile
,
.env.example
Key runtime behaviors • Worker process registers with LiveKit Agents framework and exposes a job handler. • When a job arrives, spawn an isolated job context (task/thread/async task) that: a. Connects to the specified LiveKit room as a participant (mic + speaker). b. Subscribes to remote audio tracks and uses VAD to cut speech segments. c. Streams audio chunks to STT; receives interim/final transcripts. d. Passes transcripts + convo context to LLM (streaming if available). e. Streams LLM output to TTS and publishes audio track(s) back. f. Persists transcripts/recording metadata and emits webhooks/events. • Provide graceful shutdown: finish active jobs or checkpoint, close streams, deregister. • Expose health endpoint (
/health
) and basic metrics (active_jobs, cpu, mem). Agent orchestrator — how the repo/infrastructure looks • Purpose: manage worker deployment, autoscaling, health checks, and versioned releases. • Two deployment models: a. LiveKit Cloud (managed) — CLI-driven deploys; less infra work. b. Self-hosted (Kubernetes) — full control; typical production choice. Typical infra repo layout (Kubernetes / GitOps)
Copy code
agents-infra/
├── charts/                   # Helm charts for agent service
│   └── agent/
│       ├── templates/deployment.yaml
│       ├── templates/hpa.yaml
│       └── values.yaml
├── k8s/
│   ├── namespace.yaml
│   └── secrets.yaml          # reference to .env (from CI/CD secret store)
├── ci/
│   ├── pipeline.yaml         # build image, run tests, push image
│   └── deploy.yaml           # deploy to cluster via helm
└── README.md
Orchestrator responsibilities / configs • Deployment (Deployment/StatefulSet): ◦ Container image built from agent repo Dockerfile. ◦ Readiness/Liveness probes:
/health
and optionally
/ready
. ◦
terminationGracePeriodSeconds
set high (allow active calls to finish). • Autoscaling: ◦ Horizontal Pod Autoscaler (HPA) based on custom metrics (active_jobs, CPU) or KEDA for event-driven scaling. ◦ Scale-up threshold lower than worker `load_threshold`; scale-down cooldown to avoid killing active calls. • Load & job acceptance: ◦ Each worker reports a load function (CPU or custom metric). LiveKit (or the orchestrator) uses this to decide whether to dispatch jobs to that worker. • Versioning & rollout: ◦ Rolling updates with graceful drain (stop accepting new jobs, wait for active jobs to finish). ◦ Blue/green or canary via Helm values and labels. • Observability: ◦ Export metrics (Prometheus): active_jobs, job_duration_seconds, stt_latency, tts_latency. ◦ Centralized logs and traces (ELK / Datadog / Tempo). • High availability: ◦ Multi‑AZ or multi‑region clusters; colocate agents near SIP trunks or user population for lower latency. Concrete operational notes • Health check endpoints must reflect ability to accept new jobs (e.g., return unhealthy when load > load_threshold). • Worker image should include a small supervisor script to restart crashed tasks and to ensure graceful signal handling. • Keep secrets out of the image; inject via k8s secrets or the managed platform’s secret store. • For SIP bridging, run a small stateless service that converts SIP <-> WebRTC and creates the LiveKit room; this service can live in same infra repo. If you want, I can: • Produce a minimal POC repo skeleton (Dockerfile + basic
agent.py
job handler + k8s manifests) you can fork, or • Show a concrete job handler code snippet (Python) that demonstrates subscribing to audio, streaming to STT, and publishing TTS audio back. Which would help you next? Sources: Deploying to custom environments | LiveKit Docs | An open source stack for real-time multimodal AI | livekit/livekit_composite | DeepWiki | Agents (Python) | livekit/livekit_composite | DeepWiki | examples/frontdesk | livekit/livekit_composite | DeepWiki
w
are we not using agent framework here
t
Yes — you should use the LiveKit Agents framework here. Quick confirmation and why: • The Agents framework is the runtime API that lets server-side processes register as worker pools, accept job requests, and spawn per-room agent jobs. It’s what the agent runtime (Python/Node workers) implements to join rooms, handle audio I/O, and run the STT→LLM→TTS pipeline. • The orchestrator (Kubernetes or LiveKit Cloud) manages those Agents: deploying worker containers, autoscaling the pool, health checks/readiness, and versioned rollouts. LiveKit dispatches jobs to available agent workers based on their reported load. How the pieces map: • Agent Framework = worker process API + job lifecycle (connect, handle tracks, publish audio, finish job). • Agent runtime repo = implementation of that framework (job handler, STT/LLM/TTS adapters, VAD, health endpoint, Dockerfile). • Orchestrator repo/infra = deployment manifests/helm/CI that build the worker image, run it, autoscale it, and provide metrics/rollout strategy. If you want, I can: • Show the minimal Python job-handler that uses the Agents API to accept a job and run STT→LLM→TTS, or • Generate a small repo skeleton + k8s manifests that use the Agents framework and demonstrate graceful shutdown and autoscaling. Which would you prefer?
w
Why do we need provider adapters? What does the code for that file look like?
t
Good question — short answer: provider adapters abstract each external AI vendor so your agent logic stays simple, portable, and testable. Why you need them • Encapsulate vendor APIs (auth, streaming protocols, retries, rate limits). • Present a consistent interface (start_stream, push_frame, end_stream, events) so the agent pipeline (VAD → STT → LLM → TTS) doesn’t change when you swap providers. • Enable fallbacks and vendor-specific tuning without touching core logic. • Make testing and local dev easier (mock adapters). Minimal adapter shape (Python) • Exposes a small, consistent API your agent uses during a job: ◦ async
start_stream()
→ returns a stream object ◦ async
push_frame(frame)
→ send audio frames ◦ async
end_stream()
→ finish input ◦ async iterator or callback for transcript/response events ◦
close()
/ cleanup Example STT adapter (Deepgram-like)
Copy code
# src/adapters/stt/deepgram_adapter.py
class DeepgramSTTAdapter:
    def __init__(self, api_key, model="nova-2"):
        self.api_key = api_key
        self.model = model

    async def start_stream(self):
        # open websocket / streaming client to provider
        self.stream = DeepgramClient(self.api_key, model=self.model).open_stream()
        return self.stream

    async def push_frame(self, pcm_frame: bytes):
        await self.stream.send_audio(pcm_frame)

    async def end_stream(self):
        await self.stream.finish_input()

    async def results(self):
        # async iterator yielding transcript events
        async for ev in self.stream:
            yield ev

    async def close(self):
        await self.stream.close()
Example LLM adapter (OpenAI-like)
Copy code
# src/adapters/llm/openai_adapter.py
class OpenAIAdapter:
    def __init__(self, api_key, model="gpt-4o-mini"):
        self.api_key = api_key
        self.model = model

    async def generate(self, prompt, stream=False):
        if stream:
            # return async generator of partial tokens
            async for chunk in openai_client.stream_completion(self.api_key, self.model, prompt):
                yield chunk
        else:
            return await openai_client.complete(self.api_key, self.model, prompt)
Example TTS adapter (ElevenLabs-like)
Copy code
# src/adapters/tts/elevenlabs_adapter.py
class ElevenLabsTTSAdapter:
    def __init__(self, api_key, voice="alloy"):
        self.api_key = api_key
        self.voice = voice

    async def synthesize_stream(self, text):
        # returns async iterator of audio chunks (pcm/opus)
        async for audio_chunk in eleven_client.stream_tts(self.api_key, self.voice, text):
            yield audio_chunk
How your agent uses adapters (pseudo-workflow) 1. job starts → create adapters from config (stt = DeepgramSTTAdapter(...), llm = OpenAIAdapter(...), tts = ElevenLabsTTSAdapter(...)) 2. stt_stream = await stt.start_stream() 3. while receiving audio frames from LiveKit: ◦ feed frames into
stt.push_frame(frame)
◦ read interim transcripts from
stt.results()
and update convo context 1. when end-of-turn detected, assemble prompt and call
llm.generate(prompt, stream=True)
2. stream llm output into
tts.synthesize_stream(...)
and publish audio chunks back to LiveKit 3. persist transcripts/metadata, close adapters Benefits in code • Agent core only calls the small adapter API — switching providers is just instantiating a different adapter class. • Fallbacks: wrap adapters in a
FallbackAdapter([primary, backup])
that tries next on errors. • Easier to mock in tests: replace adapters with in-memory implementations. If you want, I can: • generate a minimal repo scaffold (Python) with one STT, one LLM, one TTS adapter + a simple job handler that wires them together, or • produce a concrete code example showing the async loop that reads LiveKit audio, sends to STT, calls LLM, and streams TTS back. Which would you prefer? Sources: Agents (Python) | livekit/livekit_composite | DeepWiki | Text-to-speech (TTS) models | LiveKit Docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Agents Framework | livekit/livekit_composite | DeepWiki | Models | LiveKit Docs
w
Would I really need this? Doesn't agent framework have support for this?
t
Short answer: you don’t have to implement adapters from scratch for common providers — the Agents framework already includes built‑in plugins/adapters — but you do need to pick/configure them (or write one only if you need a custom provider/behavior). What the Agents framework gives you • Many ready-made adapters/plugins for STT, LLM, TTS, and VAD (Deepgram, AssemblyAI, OpenAI, Anthropic, ElevenLabs, Silero, Cartesia, etc.). • A unified API (
AgentSession
/ plugin classes) so your job handler calls a consistent interface (start_stream, push_frame, end_stream, async results, synthesize_stream). • Convenience features: string-based model/provider shorthand for LiveKit Inference (e.g., "assemblyai/universal-streaming:en"), fallback adapters, and plugin registration. When you don’t need custom adapters • You use supported cloud vendors and the framework’s plugin classes or the Inference string syntax. • You want standard streaming STT → LLM → TTS flows with typical provider options and sensible defaults. When you do need a custom adapter • You require a vendor not supported by the framework, or need nonstandard auth/protocols. • You need special behaviors (custom retry/backoff, audio pre/post processing, bespoke streaming semantics). • You want to mock or simulate provider behavior for advanced tests beyond built-in mocks. Practical choices • Fast path (recommended for POC): use built-in plugins or Inference strings in your
AgentSession
— no adapter code needed. • Production/customization: use provided adapters but wrap them with small glue classes (or implement one) for feature toggles, telemetry, and fallback logic. If you want, I can: • Show the minimal config / code that wires built-in plugins into an
AgentSession
(Python or Node), or • Generate a tiny custom adapter example (if you plan a provider not yet supported). Which would you like?