Build a Voice Agent with LiveKit Agents in Python: Inference, MCP Tools and Fallbacks

12 min read

The problem

Most voice agent tutorials stop at "it talks back". A real agent needs more: it has to know when the caller finished speaking, call tools, keep going when a model provider has a bad minute, say something useful when everything fails, and log enough timing data that you can fix it later.

This post builds that agent with LiveKit Agents for Python, one piece at a time. The example is a fictional bike repair shop phone line called Spoke and Chain. Callers ask if their bike is ready, book a service slot, or ask what a tune-up includes. The agent answers using two tools served over MCP (Model Context Protocol, a standard way to expose tools to a language model).

A note on versions. The code here is written against livekit-agents 1.9.0, the latest release on PyPI on 26 Nov 2026, and checked against the docs.livekit.io pages listed in Sources as they read that day, the official agent-starter-python repo, and LiveKit's own MCP example agent. It is example code. It has not been run. LiveKit moves fast, and several APIs from early 2026 tutorials are now deprecated, so check the docs if something doesn't match.

If you are new to how the pieces fit, how voice AI works and part 2 of this series are good starting points.

What you are building

A cascade pipeline, which means three models in a row:

  1. STT (speech to text) turns the caller's audio into text.
  2. LLM (large language model) decides what to say and when to call a tool.
  3. TTS (text to speech) turns the reply into audio.

Around those sit two helpers. VAD (voice activity detection) hears speech versus silence. The turn detector decides whether a pause means the caller is done. Part 3 explains the difference.

In LiveKit, an AgentSession holds the pipeline, and an Agent holds the instructions and tools. An AgentServer receives jobs from LiveKit and starts a session for each room.

flowchart LR
    A[Caller audio] --> V[VAD<br/>Silero]
    V --> S[STT<br/>with Inference fallback]
    S --> D[Turn detector]
    D --> L[LLM<br/>FallbackAdapter]
    L <-->|tools| M[MCPToolset<br/>bike shop server]
    L --> T[TTS<br/>with Inference fallback]
    T --> O[Agent audio]
    L -.-> H[Metrics hook<br/>one row per turn]

Flowchart: the pieces this post wires into one AgentSession for the bike shop line.

Step 1: create the project

The voice AI quickstart has you install the LiveKit CLI (lk), sign in to LiveKit Cloud, and create a project from the Python starter with lk agent init. The quickstart lists the requirements as the uv package manager, Node.js 24 or later, and pnpm 10 or later. The starter includes a working agent, simulation scenarios and an AGENTS.md file for coding agents.

The starter's pyproject.toml pins livekit-agents~=1.8. To get the 1.9 features used below, change that pin to livekit-agents~=1.9 and sync dependencies with uv.

Your LiveKit credentials (LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET) go in .env.local, which the CLI writes when you link the project. Keep that file out of git.

Step 2: Inference or plugins

You have two ways to reach models.

LiveKit Inference. The Inference docs page says it is included with LiveKit Cloud, needs no extra plugins, authenticates with your LiveKit API key and secret, and keeps zero data by default. You name a model with a string like "deepgram/nova-3". You don't need a separate account with each provider.

Plugins. Each provider also has a plugin package that calls the provider directly with your own API key. You would choose this for a model that Inference doesn't offer, or to use a contract you already have with a provider.

This post uses Inference throughout, because it keeps the code short and supports server-side fallback for STT and TTS. Two details from the Inference page are worth knowing:

  • Pinning a model to a specific provider is deprecated and ends on March 1, 2027.
  • Gemma 4 31B is listed as the recommended default LLM.

Pricing changes often, so I've left it out of this post. For a worked cost comparison, see voice AI cost per minute, India vs US.

Step 3: the basic agent

Here is the core of src/agent.py. The model strings, TurnHandlingOptions usage and server setup follow the official starter. The three parts below go in one file, in order.

python
# src/agent.py  (part 1 of 3)
# Written for livekit-agents 1.9.0, following agent-starter-python
# and docs.livekit.io/agents/start/voice-ai/. Not run.
import json
import logging

from dotenv import load_dotenv

from livekit.agents import (
    Agent,
    AgentServer,
    AgentSession,
    ConversationItemAddedEvent,
    ErrorEvent,
    JobContext,
    TurnHandlingOptions,
    cli,
    inference,
    llm,
    mcp,
)

load_dotenv(".env.local")

INSTRUCTIONS = """You answer the phone for Spoke and Chain, a bike repair shop.
Keep replies to one or two short sentences. Speak plainly, no lists.
Use the tools to check repair status and book service slots.
Never guess a price or a date. If a tool fails, say so and offer a callback."""


class BikeShopAgent(Agent):
    def __init__(self) -> None:
        super().__init__(instructions=INSTRUCTIONS)

    async def on_enter(self) -> None:
        self.session.generate_reply(
            instructions="Greet the caller as Spoke and Chain and ask how you can help."
        )

on_enter runs when the agent takes over the session. The greeting call matches the pattern in LiveKit's MCP example.

Step 4: the session, with turn detection

python
# src/agent.py  (part 2 of 3)
def build_session() -> AgentSession:
    return AgentSession(
        stt=inference.STT(
            model="assemblyai/assemblyai-stt-3-7-realtime-agent",
            fallback=["deepgram/nova-3"],
        ),
        llm=llm.FallbackAdapter(
            [
                inference.LLM(model="google/gemma-4-31b-it"),
                inference.LLM(model="openai/gpt-4.1-mini"),
            ],
            attempt_timeout=5.0,
        ),
        tts=inference.TTS(
            model="fishaudio/s2.1-pro",
            voice="fa4c9eb3dccc4806b382b40d61c6b10a",
            fallback=[{"model": "cartesia/sonic-3", "voice": ""}],
        ),
        turn_handling=TurnHandlingOptions(
            turn_detection=inference.TurnDetector(),
            preemptive_generation={"enabled": True},
        ),
        tools=[
            mcp.MCPToolset(
                id="bikeshop_tools",
                mcp_server=mcp.MCPServerHTTP(
                    url="http://localhost:8000/mcp",
                    allowed_tools=["get_repair_status", "book_service_slot"],
                    client_session_timeout_seconds=10,
                ),
            )
        ],
    )

What each part does:

VAD. There is no vad= line. In 1.9.0, if you leave VAD out, the session uses the bundled Silero model through inference.VAD(model="silero"). Older tutorials load Silero in a prewarm function. You can still pass one explicitly if you want to tune it.

Turn detector. inference.TurnDetector() is LiveKit's turn detection model. According to the turn detector page, it reads the agent's last message plus the caller's audio and predicts whether they are done. It is built in since livekit-agents 1.8.12. It has two versions: v1, which runs on Inference at no extra cost on Cloud, and v1-mini, which runs locally on CPU. The page says the default is v1 on Cloud and in dev mode, and v1-mini when you self-host with start. If the model gives no prediction within about a second, the turn is committed anyway. The page also says that if you leave turn_detection out entirely, the turn detector is the default. I set it explicitly so it is obvious.

Turn handling options. The turn handling options reference groups everything about turns into one object: turn_detection, endpointing (how long to wait after speech ends, with min_delay and max_delay), interruption, and preemptive_generation. That last one starts generating a reply before the turn is fully confirmed. The tuning page says it doesn't always reduce latency, so measure it (see part 8). The older top-level arguments such as min_endpointing_delay, allow_interruptions and turn_detection on AgentSession are deprecated in 1.9.0. If you copy code from an older tutorial, move those settings into turn_handling.

STT and TTS fallback. The fallback= lists are LiveKit Inference's server-side fallback. For TTS, each entry needs a model and a voice; the 1.9.0 source says an empty voice string picks the model's default voice. The fallback strategies page points out one catch: an Inference TTS fallback replays the whole turn, so the caller might hear the beginning twice. Each turn is billed once.

LLM fallback. llm.FallbackAdapter runs in your process and tries each LLM in order. The 1.9.0 signature is FallbackAdapter(llm, *, attempt_timeout=5.0, max_retry_per_llm=0, retry_interval=0.5, retry_on_chunk_sent=False, sticky=False). The fallback page explains the important default: if the first model has already streamed text when it fails, the adapter raises instead of switching, unless you set retry_on_chunk_sent=True. Switching halfway through a sentence would make the agent say half of one answer and then a different answer. sticky=True (Python only, per the docs) keeps using the backup once it has switched. The adapter also emits llm_availability_changed events you can log.

There are also stt.FallbackAdapter and tts.FallbackAdapter for in-process fallback across plugins. You'd use those if you mix providers outside Inference.

Step 5: tools over MCP

The bike shop's tools live in a separate MCP server: one tool looks up repair status by ticket number, the other books a service slot. The agent doesn't need to know how they work. Part 7 covers MCP in depth. Here is what changed recently in LiveKit, per the MCP docs page:

  • Wrap each server in mcp.MCPToolset and put it in tools. The older mcp_servers= argument is deprecated because its tool IDs were not stable.
  • Transport is detected from the URL. A URL ending in /mcp uses streamable HTTP; anything else uses SSE (server-sent events). You can override this with transport_type.
  • allowed_tools limits which tools the model sees. That matters for a phone line: if the MCP server also exposes an admin tool, the model can't call it.
  • headers lets you pass an auth header to the MCP server.
  • If you configure several servers, they initialize in parallel, and one failing does not stop the agent.
  • The docs recommend session-level toolsets, which is what the code above does.

The 1.9.0 constructor is MCPServerHTTP(url, transport_type=None, allowed_tools=None, headers=None, timeout=5, sse_read_timeout=300, client_session_timeout_seconds=5, *, tool_result_resolver=None). The default session timeout is 5 seconds. A booking system can be slower than that, so the example raises it to 10. LiveKit's own MCP example uses 120.

MCPToolset also takes tool_options, keyed by tool name. LiveKit's MCP example uses it to mark a booking tool as cancellable, ask for confirmation on duplicate calls, and report progress:

python
# Per-tool options, following examples/voice_agents/mcp/mcp-agent.py
# in the livekit/agents repo. Not run.
from livekit.agents.llm import ToolFlag

booking_options = {
    "book_service_slot": {
        "flags": ToolFlag.CANCELLABLE,
        "on_duplicate": "confirm",
        "report_progress": True,
    }
}
# mcp.MCPToolset(id="bikeshop_tools", mcp_server=..., tool_options=booking_options)

on_duplicate accepts allow, reject, replace or confirm, according to the MCP docs page. For a booking tool, confirm is the safe choice: double-booking a service slot because the caller repeated themselves is a real problem.

Step 6: error speech and a metrics hook

When every provider fails, a voice agent that goes silent is the worst outcome. The caller doesn't know whether to wait or hang up. The fallback strategies page says a successful fallback raises no error event, and an error event fires only when no provider can serve. In 1.9.0 the event's error field carries a recoverable flag for LLM, STT and TTS errors.

For metrics, use the per-turn ChatMessage.metrics described on the data hooks page. The session-level metrics_collected event and UsageCollector are deprecated there, even though many tutorials still use them.

python
# src/agent.py  (part 3 of 3)
logger = logging.getLogger("bikeshop")

ERROR_SPEECH = (
    "Sorry, I'm having trouble on my end. "
    "Please call the shop back in a few minutes."
)


def attach_hooks(session: AgentSession) -> None:
    last_user: dict = {}

    @session.on("conversation_item_added")
    def _on_item(ev: ConversationItemAddedEvent) -> None:
        nonlocal last_user
        item = ev.item
        if item.type != "message":
            return
        m = item.metrics or {}
        if item.role == "user":
            last_user = {
                "end_of_turn_delay": m.get("end_of_turn_delay"),
                "transcription_delay": m.get("transcription_delay"),
            }
        elif item.role == "assistant":
            row = {
                **last_user,
                "llm_node_ttft": m.get("llm_node_ttft"),
                "tts_node_ttfb": m.get("tts_node_ttfb"),
                "e2e_latency": m.get("e2e_latency"),
                "interrupted": item.interrupted,
            }
            logger.info("turn_latency %s", json.dumps(row))
            last_user = {}

    @session.on("error")
    def _on_error(ev: ErrorEvent) -> None:
        if getattr(ev.error, "recoverable", True):
            return
        logger.error("unrecoverable error from %s", type(ev.source).__name__)
        session.say(ERROR_SPEECH, allow_interruptions=True, add_to_chat_ctx=False)


async def on_session_end(ctx: JobContext) -> None:
    report = ctx.make_session_report()
    logger.info("session_report %s", json.dumps(report.to_dict(include_chat_history=False)))


server = AgentServer()


@server.rtc_session(agent_name="bikeshop-agent", on_session_end=on_session_end)
async def entrypoint(ctx: JobContext) -> None:
    session = build_session()
    attach_hooks(session)
    await session.start(agent=BikeShopAgent(), room=ctx.room)
    await ctx.connect()


if __name__ == "__main__":
    cli.run_app(server)

Notes on this part:

  • Event handlers registered with session.on are plain functions. Keep them quick.
  • add_to_chat_ctx=False keeps the apology out of the conversation history, so the model doesn't treat it as something it said.
  • The metrics hook pairs each user message with the next assistant message. In 1.9.0, e2e_latency is the agent's start of speech minus the user's stop of speech, measured on the server. It doesn't include network delivery or playback on the caller's device. Part 8 explains how to turn these rows into p50 and p95 and how to measure from the caller's side.
  • The data hooks page says on_session_end gets up to 5 minutes by default to finish. That is the right place to write a full session report.
  • cli.run_app(server) is what the starter uses. In 1.9.0 the old Python-based command line it starts is marked as being replaced by the lk agent commands, which is why the steps below use lk agent.

Step 7: run it in the terminal

The lk agent CLI reference lists lk agent console. It runs your agent in a simulated room using your computer's microphone and speakers, and doesn't connect to LiveKit Cloud. Useful flags from that page:

  • --text: type instead of speaking, handy for testing tool calls.
  • --no-aec: turn off echo cancellation.
  • --record: save the session.
  • --list-devices: pick a microphone.

The CLI finds agent.py or src/agent.py on its own.

One caveat. Console mode doesn't connect to LiveKit Cloud, and the Inference models above authenticate against your LiveKit project. The CLI page doesn't say how console mode treats Inference calls, so if model calls fail in console, move on to dev mode.

You will also need the MCP server running at http://localhost:8000/mcp before the agent starts. If it isn't, the MCP docs say the agent keeps running without those tools, and the model will tell callers it can't check their bike.

Step 8: dev mode, then LiveKit Cloud

lk agent dev runs the agent locally but connected to your LiveKit Cloud project, with auto-reload when you edit files. The CLI reference says it uses a random dev- deployment name (CLI v2.19.0 and later). The quickstart says lk agent dev prints a link to the Agent Console, where you click Start a session and speak. The console's panes show events, tool calls and model timing for each turn. That gives you a quick view of the same numbers your metrics hook logs.

sequenceDiagram
    participant B as Browser, Agent Console
    participant R as LiveKit Cloud room
    participant W as Your AgentServer
    participant M as Bike shop MCP server
    W->>R: lk agent dev connects to the project
    B->>R: Start a session, joins a room
    R->>W: dispatches a job for that room
    W->>W: entrypoint runs build_session and attach_hooks
    W->>R: session.start with BikeShopAgent, then ctx.connect
    W->>M: MCPToolset connects to localhost 8000 /mcp
    W-->>B: on_enter greeting as Spoke and Chain
    B->>R: caller audio
    R->>W: audio to VAD, turn detector and STT
    W-->>B: agent reply audio
    Note over B,W: phone callers reach the room over SIP instead, see the SIP setup post

Sequence: what happens when you click Start a session in dev mode, from the room join to the agent's greeting.

The starter's README also mentions lk agent simulate text --scenarios scenarios.yaml for scripted conversations, and an agent debugger. Both are worth running before real callers arrive. For example, you could write scenarios for "caller gives a wrong ticket number" and "caller asks to book on a closed day".

To deploy, the quickstart's Deploy section has you run a CLI command from the project directory. It asks which region to use, registers the agent with your Cloud project, builds it and deploys it. Later changes go out with lk agent deploy. After that, the project's Agents dashboard can launch the Agent Console against the deployed agent.

Two deployment details from the turn detector page:

  • The default turn detector version differs between Cloud (v1) and self-hosted start (v1-mini, which runs on your CPU and uses about 310 to 340 MB for its weights).
  • If you self-host, the page recommends compute-optimized instances.

To put the shop's real phone number on this agent, you need SIP, the protocol phone networks use to set up calls. That is a separate setup covered in LiveKit SIP trunk voice agent setup and how a phone call reaches an AI voice agent.

Before real callers

A short list of what this example does and doesn't cover:

  • Covered: turn detection, MCP tools with an allow-list, STT/TTS/LLM fallback, spoken error message, per-turn latency logging, session report.
  • Not covered: a filler line while a slow tool runs (see part 7), interruption tuning (see part 4), load testing (part 8 covers lk perf agent-load-test), and noise cancellation, which the official starter adds through room_options on session.start.
  • Check yourself: model availability on Inference changes, so confirm each model string on the Inference page before deploying.

If you want to compare this cascade approach with speech-to-speech models, read part 5 and part 6 on open real-time speech models.

New to a term used here? The series glossary defines VAD, endpointing, barge-in, full-duplex, MCP, p95 and the rest in plain language.

Sources