Building AI Voice Agents with LiveKit — Complete 2026 Guide

How to build a LiveKit voice agent

A LiveKit voice agent uses the LiveKit Agents Python SDK with three components: an STT (speech-to-text) model like Deepgram Nova-2, an LLM like GPT-4o, and a TTS (text-to-speech) model like ElevenLabs. The VoicePipelineAgent class orchestrates these in a streaming pipeline. Install with: pip install livekit-agents[deepgram,openai,elevenlabs,silero]. LiveKit voice agents can receive inbound PSTN calls via SIP trunk integration and connect to existing Asterisk or FreeSWITCH PBX systems.

LiveKitVoice AI

Building AI Voice Agents with LiveKit
Complete 2026 Guide

Production guide to the LiveKit Agents SDK: streaming STT→LLM→TTS pipeline, semantic turn detection, tool calling, SIP integration, and Asterisk bridge. With complete Python code examples.

Kaushik Parmar — VoIP Architect, CelloIP 14 min read LiveKit · Voice AI · Python SDK
< 500ms
Agent Response Latency
Python
Primary SDK Language
10+
AI Provider Integrations
SIP Ready
PSTN Call Handling

LiveKit is an open-source WebRTC platform used by 300,000+ developers handling 3+ billion real-time calls annually. Its Agents SDK (Python and Node.js) lets you build AI voice agents that join real-time rooms as participants — receiving audio from users, processing it through an STT → LLM → TTS pipeline, and speaking responses back in under 500ms. Integrated with LiveKit's SIP service, these agents can answer inbound PSTN phone calls via any SIP trunk or your existing Asterisk/FreeSWITCH PBX.

1. Voice Agent Pipeline Architecture

A LiveKit voice agent's core is the VoicePipelineAgent — a high-level abstraction that orchestrates three streaming stages:

User Speech
Microphone / Phone call
VAD
Silero — turn detection
STT
Deepgram Nova-2 (~200ms)
LLM
GPT-4o streaming (~300ms)
TTS
ElevenLabs (~200ms)
Audio Out
Speaker / Phone playback

All stages stream concurrently — first audio byte typically delivered in 400–600ms

The key innovation is streaming overlap: STT sends partial transcripts to the LLM before the user finishes speaking; the LLM streams tokens to TTS before generating a complete response; TTS begins synthesising audio before receiving all tokens. This parallel execution cuts latency from 2–4 seconds (sequential) to under 600ms in production.

2. Installation and First Voice Agent

Install the LiveKit Agents SDK with the plugins for your chosen providers:

Terminal

# Install LiveKit Agents and plugins
pip install "livekit-agents[deepgram,openai,elevenlabs,silero]~=1.0"

A complete voice agent that answers questions using GPT-4o and speaks responses with ElevenLabs:

agent.py — Minimal LiveKit voice agent

import asyncio
from livekit import agents
from livekit.agents import AutoSubscribe, JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram, openai, elevenlabs, silero

async def entrypoint(ctx: JobContext):
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)

    session = AgentSession(
        vad=silero.VAD.load(),                       # Voice Activity Detection
        stt=deepgram.STT(model="nova-2"),            # Speech-to-Text
        llm=openai.LLM(model="gpt-4o-mini"),        # Language Model
        tts=elevenlabs.TTS(voice="Rachel"),          # Text-to-Speech
    )

    await session.start(
        ctx.room,
        agent=Agent(
            instructions="""You are a friendly customer service agent for CelloIP Technologies.
            Help callers with VoIP development enquiries, pricing, and project scope.
            Keep responses concise — under 3 sentences for voice delivery.
            If the caller wants to speak to a human, say you will transfer them.""",
        ),
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))

3. STT / LLM / TTS Provider Comparison

LiveKit Agents supports any combination of providers. Choose based on latency, quality, cost, and data residency requirements:

STT Providers

ProviderLatencyQualitySelf-HostableBest For
Deepgram Nova-2~200ms★★★★★Cloud onlyBest overall, lowest latency
OpenAI Whisper~400ms★★★★On-premise / GDPR
AssemblyAI~250ms★★★★Cloud onlyHigh accuracy + speaker diarisation
Azure Speech~300ms★★★★Cloud onlyEnterprise / Microsoft stack

LLM Providers

ProviderLatencyQualitySelf-HostableBest For
OpenAI GPT-4o~300ms first token★★★★★Cloud onlyBest reasoning + function calling
Anthropic Claude 3.5 Haiku~200ms★★★★★Cloud onlyFast, smart, safe
LLaMA 3 (Ollama)~100ms (GPU)★★★★On-premise / air-gapped GDPR
Mistral 7B~150ms★★★★EU data residency, fast inference

TTS Providers

ProviderLatencyQualitySelf-HostableBest For
ElevenLabs Turbo v2~200ms★★★★★Cloud onlyMost natural voice quality
Cartesia Sonic~100ms★★★★★Cloud onlyLowest latency TTS
OpenAI TTS-1-HD~300ms★★★★Cloud onlySimple + high quality
Coqui TTS / Piper~150ms★★★Free, self-hosted

4. Key Agent Capabilities

Semantic Turn Detection

Transformer-based model detects when the user is genuinely done speaking — not just paused. Dramatically reduces false interruptions vs simple VAD silence detection. Built into livekit-agents 1.x as the default turn detector.

Streaming STT→LLM→TTS

All three stages run concurrently in a streaming pipeline. STT streams partial transcripts to LLM; LLM streams tokens to TTS; TTS begins generating audio before full LLM response. First audio byte under 500ms in optimal conditions.

Tool / Function Calling

Agents can call external tools mid-conversation: CRM lookup (Salesforce, HubSpot), database queries, calendar booking (Google Calendar), REST APIs, and MCP (Model Context Protocol) servers. LLM decides when to call which tool.

Interruption Handling

When the user speaks while the agent is talking, VAD detects barge-in. The agent gracefully stops TTS playback, discards queued audio, and re-enters listening state. interruption_min_words parameter prevents premature stops on short utterances.

Multi-language Support

Automatic language detection with Deepgram or Azure STT. Agents can detect mid-call language switch and reconfigure STT/TTS providers on-the-fly. LiveKit supports building multilingual agents that switch languages without call restart.

DTMF + Fallback IVR

Handle keypress input when speech fails. Agent listens for DTMF events (0-9, *, #) as a fallback when speech confidence is low. Useful for call centre menus, PIN entry, and legacy callers who prefer keypress navigation.

5. Function / Tool Calling — CRM + SIP Transfer

Agents become truly useful when they can act on information — looking up customer records, booking appointments, or transferring calls. The @function_tool decorator registers a Python function that the LLM can call:

tools.py — CRM lookup + SIP REFER transfer

# Add function/tool calling — CRM lookup example
from livekit.agents import function_tool
from livekit.agents.voice import Agent, AgentSession

@function_tool
async def lookup_account(phone_number: str) -> str:
    """Look up customer account by phone number."""
    # Replace with real CRM API call
    customer = await crm_api.get_customer(phone=phone_number)
    if customer:
        return f"Found account: {customer.name}, Plan: {customer.plan}"
    return "No account found for this number."

@function_tool
async def transfer_to_human(department: str) -> str:
    """Transfer caller to a human agent in the specified department."""
    # Trigger SIP REFER transfer back to Asterisk
    await sip_client.transfer_participant(
        room_name=ctx.room.name,
        participant_identity="phone_caller",
        transfer_to=f"sip:+1800{department}@asterisk.company.com"
    )
    return f"Transferring to {department} team now."

# Pass tools to agent
session = AgentSession(
    vad=silero.VAD.load(),
    stt=deepgram.STT(model="nova-2"),
    llm=openai.LLM(model="gpt-4o"),
    tts=elevenlabs.TTS(voice="Rachel"),
    tools=[lookup_account, transfer_to_human],
)

6. Handling Inbound SIP / PSTN Calls

To accept real phone calls, configure a SIP inbound trunk in LiveKit and create dispatch rules that route incoming calls to your agent workers:

Cloud SIP Carrier Setup

  1. 1.Create LiveKit inbound SIP trunk via API
  2. 2.Add DID numbers (+15551234567)
  3. 3.Point carrier SIP trunk to LiveKit SIP service
  4. 4.Create dispatch rule: DID → room prefix
  5. 5.Deploy agent worker — it auto-joins new rooms

Asterisk PBX Bridge

  1. 1.Create SIP peer in Asterisk pjsip.conf
  2. 2.Define extension routing to LiveKit SIP
  3. 3.Create LiveKit inbound trunk for Asterisk IP
  4. 4.Set dispatch rule for Asterisk DID range
  5. 5.Agent handles call; SIP REFER returns to Asterisk

Production note: Always configure IP allowlisting on your LiveKit SIP trunk to restrict signalling to known carrier/PBX IP addresses. Use SIP digest authentication and enforce TLS for signalling + SRTP for media in production deployments.

7. Self-Hosted Stack for GDPR / HIPAA Compliance

All LiveKit components are open source and self-hostable. For EU data residency or healthcare deployments, CelloIP recommends a fully on-premise AI stack:

LiveKit Server

Self-hosted K8s Helm chart

STT (Deepgram)

faster-whisper or whisper.cpp

LLM (GPT-4o)

Ollama + LLaMA 3 / Mistral

TTS (ElevenLabs)

Piper / Coqui TTS

Frequently Asked Questions

Q:What is the minimum end-to-end latency achievable with a LiveKit voice agent?

With the streaming pipeline (Deepgram Nova-2 STT + GPT-4o streaming + Cartesia Sonic TTS) and a well-optimised deployment close to the caller, first audio byte delivery under 500ms is achievable. The OpenAI Realtime API (speech-to-speech) used via MultimodalAgent can reduce this further to 200–350ms by eliminating the separate STT and TTS stages.

Q:Can LiveKit voice agents answer real phone calls from PSTN?

Yes. LiveKit's SIP service receives inbound calls from any SIP trunk provider. Configure an inbound SIP trunk pointing to your LiveKit SIP service, create a dispatch rule matching your DID(s) to a room prefix, and deploy your voice agent worker. When a call arrives, LiveKit creates a room, the agent joins, and it answers the caller. Works with Twilio Elastic SIP, Telnyx, Vonage, or your own Asterisk/Kamailio SIP infrastructure.

Q:How does LiveKit voice agent turn detection work?

LiveKit Agents 1.x uses semantic turn detection as the default: a small transformer model trained on conversational data that understands prosody and sentence completion, not just silence. It detects utterance endings even when the user pauses mid-sentence (e.g. 'I want to...um... book an appointment'). You can tune sensitivity via the turn_detector parameter, or fall back to simple silence-based VAD for lower latency.

Q:Can I run a LiveKit voice agent on-premise with no cloud AI APIs?

Yes. CelloIP has deployed fully self-hosted LiveKit voice agent stacks: LiveKit server on Kubernetes, Whisper.cpp (STT), Ollama with LLaMA 3 or Mistral (LLM), Piper or Coqui (TTS). The livekit-agents Python SDK supports plugging in any provider that implements the standard STT/LLM/TTS interfaces. This setup satisfies GDPR data residency, HIPAA data isolation, and air-gapped enterprise security requirements.

Q:What is the difference between VoicePipelineAgent and MultimodalAgent in LiveKit?

VoicePipelineAgent chains separate STT → LLM → TTS providers with streaming overlap — maximum flexibility for mixing providers. MultimodalAgent uses a single speech-to-speech model (OpenAI Realtime API or Gemini Live) that processes audio input and outputs audio directly — no transcription step, lower latency, but less provider flexibility. Use VoicePipelineAgent when you need specific STT accuracy, on-premise providers, or self-hosted models. Use MultimodalAgent for ultra-low latency with cloud Realtime APIs.

Q:How do I handle conversation state and memory in LiveKit voice agents?

LiveKit agents maintain conversation history in the LLM context window by default (last N turns). For longer memory, integrate a vector database (Pinecone, pgvector) or use the Mem0 integration for LiveKit agents (documented at docs.mem0.ai/integrations/livekit). For session context (account info, caller history), load it into the agent's system prompt or structured context at call start using a function tool that fires on room_connected.

Need LiveKit Voice Agent Development?

CelloIP builds production LiveKit voice agent systems with SIP integration, Asterisk/FreeSWITCH bridges, and self-hosted GDPR-compliant deployments.