页面简介
Learn how to build a production-ready Python voice agent using LiveKit Agents. Covers STT, LLM, TTS integration, local testing, and deployment.
正文摘录
Blog/TutorialA Python voice agent connects a speech-to-text model, a large language model, and a text-to-speech model in a streaming pipeline. LiveKit Agents provides the framework and real-time audio transport layer. This tutorial covers setup, implementation, local testing, and deployment. You'll build a working voice agent in the next 30 minutes. By the end of this tutorial, you'll have a voice agent that listens to users, understands their questions, and responds in real-time with natural speech. What you'll create: A voice agent that answers questions in real-time using speech-to-text, an LLM, and text-to-speech. Prerequisites: Basic Python knowledge. You don't need prior experience with audio processing or WebRTC. Note: LiveKit Agents also supports TypeScript. The TypeScript implementation is covered in a separate tutorial. What you'll learn: How the voice agent pipeline works (STT → LLM → TTS) How to connect each component for a real-time conversation How to test, debug, and deploy your agent This guide is written by the LiveKit team, who maintain one of the most widely used open-source real-time communication stacks and power production voice agents across telephony, support, and AI platforms. What is the STT-LLM-TTS pipeline?Link to this section Most voice agents follow the STT-LLM-TTS pipeline: Speech-to-Text (STT) converts the user's audio into text. Large Language Model (LLM) generates an intelligent response. Text-to-Speech (TTS) converts the response back into audio. This modular approach gives you maximum flexibility. Swap providers, fine-tune each component, and debug issues at each stage independently. Note: This pipeline goes by many names. You may see it referred to as: Cascaded pipeline: emphasizes the sequential, chained nature of the components Voice pipeline: generic term used broadly across the industry Conversational AI pipeline: common in enterprise and contact center contexts ASR → LLM → TTS pipeline: uses ASR (Automatic Speech Recognition) instead of STT Listen-Think-Speak pipeline: a more human-readable framing Turn-based voice pipeline: highlights the conversational turn-taking model Classic voice agent architecture: used to distinguish it from newer speech-to-speech models All of these refer to the same fundamental architecture: audio in → text → LLM → text → audio out. Speech-to-speech: the emerging alternativeLink to this section A newer approach skips the text intermediary entirely. Speech-to-speech models (like OpenAI's Realtime API and Google's Gemini Live) process audio in and generate audio out directly. Advantages: Lower latency (fewer processing steps) Preserves paralinguistic cues (tone, emphasis, emotion) More natural conversational dynamics Trade-offs: Less visibility into what the model "heard" or "said" Harder to debug and evaluate Fewer provider options (still early days) Higher cost per minute in most cases For production voice agents today, the cascaded pipeline remains the most practical choice. It's battle-tested, observable, and gives you fine-grained control. But speech-to-speech is maturing fast, and LiveKit Agents supports both approaches. Why real-time mattersLink to this section Traditional HTTP request/response patterns introduce latency at every step. Send audio, wait for transcription, send text, wait for response, send response, wait for audio. Each round trip adds 100–300ms. WebRTC changes this. Instead of request/response, you maintain persistent connections that stream data in both directions simultaneously. Audio flows in while responses flow out. The result: total latency drops from seconds to hundreds of milliseconds. Architecture overview: Each component streams its output to the next. The LLM starts generating before the user finishes speaking. TTS starts synthesizing before the LLM finishes responding. This parallelization is what makes voice agents feel responsive. How do you choose your model stack?Link to this section Your choice of providers affects latency, quality, and cost. LiveKit Inference simplifies this by giving you access to all major providers through a single API key, with no need to manage multiple accounts or credentials. Note: The models below are popular options, not an exhaustive list. LiveKit Agents supports many more providers. Check the documentation for the full list. STT optionsLink to this section ProviderModelLatencyAccuracyCostDeepgramNova-3~250msExcellent$$$DeepgramNova-2~250msGreat$$AssemblyAIUniversal-Streaming~300msGreat$CartesiaInk Whisper~80msGood$ LLM optionsLink to this section ProviderModelLatencyQualityCostOpenAIGPT-4o~200msExcellent$$$OpenAIGPT-4.1 mini~200msGreat$GoogleGemini 2.5 Flash~350msGreat$DeepSeekDeepSeek V3~300msGreat$ TTS optionsLink to this section ProviderModelLatencyVoice QualityCostCartesiaSonic 3~90msExcellent$$DeepgramAura-2~100msGood$$InworldTTS 1.5~200msGood$ Setting up your development environmentLink to this section Let's get your environment ready. Install LiveKit AgentsLink to this section 1uv init --bare2uv add "livekit-agents[silero,turn-detector]~=1.4" python-dotenv Note: When using LiveKit Inference (recommended), you don't need separate plugin packages for STT, LLM, or TTS. LiveKit routes those requests for you. You only need silero for VAD and turn-detector for the multilingual turn detection model. API keysLink to this section With LiveKit Inference, you only need one account: LiveKit Cloud (free tier available) LiveKit Inference provides access to STT, LLM, and TTS models through a single API key. No need to create separate accounts with Deepgram, OpenAI, or Cartesia. LiveKit handles all provider credentials and billing. Environment variablesLink to this section Create a .env.local file: 1LIVEKIT_URL=wss://your-project.livekit.cloud2LIVEKIT_API_KEY=your-api-key3LIVEKIT_API_SECRET=your-api-secret Get your credentials from the LiveKit Cloud dashboard. Building the voice agentLink to this section Time to write code. Create a new file called agent.py in your project directory. The steps below build up this file incrementally. The Complete implementation section at the end shows the finished file. Step 1: initialize the agentLink to this section Start with the agent entry point. Add this to agent.py: 1from dotenv import load_dotenv2from livekit import agents3from livekit.agents import AgentServer, AgentSession, Agent, room_io4from livekit.plugins import silero5from livekit.plugins.turn_detector.multilingual import MultilingualModel6 7load_dotenv(".env.local")8 9class Assistant(Agent):10 def __init__(self):11 super().__init__(12 instructions="You are a helpful voice AI assistant."13 )14 15server = AgentServer()16 17@server.rtc_session(agent_name="my-agent")18async def my_agent(ctx: agents.JobContext):19 pass # We'll add components here20 21if __name__ == "__main__":22 agents.cli.run_app(server) This defines your Assistant class (where agent instructions and personality live) and creates an AgentServer. The @server.rtc_session decorator registers the entry function that runs whenever a new room session starts. The agent_name value is how LiveKit identifies which agent to start when a session is requested. It also switches the agent from automatic dispatch to explicit dispatch, so your agent only starts when explicitly requested rather than joining every new room automatically. This gives you precise control and is the right behavior for both development and production. Step 2: configure speech-to-textLink to this section Update your my_agent function in agent.py to add Deepgram for transcription: 1@server.rtc_session(agent_name="my-agent")2async def my_agent(ctx: agents.JobContext):3 session = AgentSession(4 stt="deepgram/nova-3:multi", # Deepgram Nova-3 via LiveKit Inference5 ) Key options: "deepgram/nova-3:multi" routes to Deepgram Nova-3 via LiveKit Inference with multilingual support. No separate Deepgram API key needed. LiveKit Inference handles provider credentials. Step 3: configure the LLMLink to this section Agent instructions live in the Agent class. Update your Assistant class with a system prompt, then add llm to your AgentSession: 1class Assistant(Agent):2 def __init__(self):3 super().__init__(4 instructions=(5 "You are a helpful voice assistant. Keep responses concise, ideally under 2 sentences. Be conversational and friendly."6 )7 )8 9@server.rtc_session(agent_name="my-agent")10async def my_agent(ctx: agents.JobContext):11 session = AgentSession(12 stt="deepgram/nova-3:multi",13 llm="openai/gpt-4.1-mini", # Great quality at low cost14 ) Prompt tips for voice: Keep responses short. Long responses feel unnatural in conversation. Avoid lists and formatting. They don't translate to speech. Write for the ear, not the eye. Step 4: configure text-to-speechLink to this section Add tts to the AgentSession in my_agent: 1session = AgentSession(2 stt="deepgram/nova-3:multi",3 llm="openai/gpt-4.1-mini",4 tts="cartesia/sonic-3:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc",5) The TTS string uses the format provider/model:voice-id. Cartesia offers many voices. Browse the options and swap the voice UUID in the string. Warning: If no voice UUID is provided, Cartesia will fall back to its default voice. This may produce inconsistent results across sessions and regions, as the default can change without notice. For production agents, always specify an explicit voice UUID to keep your agent's voice consistent. Step 5: add VAD and turn detectionLink to this section Finalize your AgentSession with VAD and turn detection: 1session = AgentSession(2 stt="deepgram/nova-3:multi",3 llm="openai/gpt-4.1-mini",4 tts="cartesia/sonic-3:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc",5 vad=silero.VAD.load(),6 turn_detection=MultilingualModel(),7) The AgentSession handles: Voice Activity Detection (VAD): Silero detects when the user starts and stops speaking. Turn detection: The multilingual model determines when the user has finished their turn. Interruption handling: Stops speaking when the user interrupts. Step 6: