A working voice demo is one milestone. A deployable service also needs reliable routing, useful failure evidence, and clear operating ownership. Build a Python LiveKit voice agent with a read-only tool, run a browser session, and carry the same application into deployment with those boundaries explicit.
The session you are building
A LiveKit voice agent is a program that joins a room as a participant. It receives user audio, runs conversational logic, and publishes a spoken response. This implementation uses LiveKit Cloud for media transport and inference, with your Python agent running locally first and on Cloud after deployment.
The initial goal is deliberately narrow: an assistant that reads two local troubleshooting runbooks. It cannot inspect infrastructure or change a deployment. That gives you an observable tool call without connecting a production system.
Four components have separate jobs:
| Component | Responsibility |
|---|---|
| LiveKit room | Carries audio and data between participants. |
Agent | Defines instructions, tools, and agent-specific model configuration. |
AgentSession | Coordinates input, model processing, turn handling, and output. |
AgentServer | Registers your application and handles incoming session jobs. |
The starter uses speech-to-text (STT), a large language model (LLM), and text-to-speech (TTS). A speech-to-speech model is another architecture, with different configuration and observability. Keep one pipeline intact until the first session works.
1. Create the Python project
You need Git, the uv Python package manager, the LiveKit command-line interface (CLI), a LiveKit Cloud project, and a microphone. Headphones prevent your speaker output from feeding back into the microphone.
Install the CLI for your operating system from the official CLI installation instructions. Then link a development project:
lk cloud auth lk project list lk project set-default "<development-project>" lk agent init runbook-agent --template agent-starter-python cd runbook-agent
Replace <development-project> with the linked project's name. Accept dependency installation during initialization. The generated project includes the agent, dependency configuration, and supporting development files. A coding assistant is optional.
This follows the starter-based Voice AI quickstart. The inference path uses LiveKit credentials rather than separate credentials for each model provider. It still makes real network and model requests.
Keep LIVEKIT_API_KEY and LIVEKIT_API_SECRET on the server side. Any .env.local file containing them stays outside version control. LIVEKIT_URL identifies the media service; a browser client receives a scoped access token, never your API secret.
Preserve the generated dependency configuration and commit the resolved uv.lock with your application. A deployment should identify a source revision and dependency set, rather than silently installing a different software development kit (SDK) for each release.
2. Add a read-only tool
Open src/agent.py. Add this import alongside the existing imports:
from livekit.agents import RunContext, function_tool
Replace only the Assistant class with the following. Leave the generated imports, AgentServer, session configuration, connection code, and application entry point in place.
class Assistant(Agent): def __init__(self) -> None: super().__init__( llm=inference.LLM(model="google/gemma-4-31b-it"), instructions=( "You are a read-only voice runbook assistant. " "Use lookup_runbook for audio or dispatch questions. " "Ask which topic the user needs when it is unclear. " "For unsupported topics, say no runbook is available. " "Never claim to inspect services or change anything. " "Speak briefly in plain text, without Markdown." ), ) @function_tool async def lookup_runbook(self, context: RunContext, topic: str) -> str: """Read a local runbook. Supported topics are audio and dispatch.""" runbooks = { "audio": ( "Microphone capture and remote audio playback are separate " "paths. Participant and audio-track events help locate " "which path is missing." ), "dispatch": ( "A room can exist without an agent. Named agents need " "explicit dispatch to the matching agent name and deployment." ), } return runbooks.get(topic.strip().lower(), "No runbook is available.")
The LLM setting remains in the class because the Python starter supplies it there. The generated AgentSession retains its STT, TTS, turn detector, and audio configuration. Replacing the whole file with an older snippet can lose those connections.
The decorator exposes the function to the model. Its typed argument and description explain the tool's interface. The dictionary is local application data, so this tool needs no additional credentials and has no external side effects.
Instructions guide conversation behavior. Authorization belongs in application code. When a real backend replaces this dictionary, its handler must enforce tenant scope, allowed operations, timeouts, and retry rules independently of anything the caller says.
3. Run a browser voice session
From the project directory, start development mode:
lk agent dev
Open the Agent Console URL printed in the terminal, allow microphone access, and select Start a session. Use that printed URL: it targets the local development deployment rather than an unrelated production agent.
Ask, “What does the dispatch runbook say?” A completed session has three observable results: your speech appears as input, a lookup_runbook call contains the dispatch topic, and an audible answer summarizes the local runbook.
Then ask about an unsupported topic, such as billing. The expected behavior is an unavailable-runbook response without an invented operational answer. During a longer response, an interruption should return control to the user. An early pause inside a sentence should not be treated as permission to answer every time.
These are separate acceptance conditions. A transcript proves neither that the speaker played audio nor that interruption handling behaved correctly.
The generated agent_name is a routing identifier. Dispatch means assigning that named agent to a room. A user can join a healthy room while no agent joins it. The agent dispatch contract distinguishes this name from the participant's display name and routes production sessions separately from development deployments.
For a terminal conversation instead, use:
lk agent console
Console mode isolates the conversation from browser media transport. It still uses inference credentials and network requests. A successful terminal exchange does not establish that the browser audio path works.
4. Deploy the same application
Deployment creates running infrastructure and can incur usage. Use a development Cloud project for the first deployment, with only the intended credentials and downstream permissions.
From the agent directory, create its first Cloud deployment:
lk agent create lk agent status lk agent logs
The create command registers the agent, writes deployment configuration to livekit.toml, uploads the application, builds its container image, and deploys it. The CLI can generate a Dockerfile when one is absent. Preserve the generated files with the application.
The Cloud deployment quickstart separates this initial creation from later updates. For a subsequent application revision, use:
lk agent deploy
Use deployment secrets for any backend or provider credentials added later. An environment variable on your laptop is not evidence that the deployed container has the same value. Secrets must also stay out of container layers and build logs.
Open the deployed agent through the project's Agents dashboard and launch its Agent Console. The release record should tie that session to the deployment, source revision, dependency lock, agent name, and model configuration. A green build establishes that an image was built. A registered agent establishes that a worker is available. Neither establishes a completed conversation.
LiveKit Cloud manages agent hosting and scaling within your plan's limits. Your team still sets capacity requirements, provider quotas, downstream connection limits, and release acceptance criteria. Include a known rollback target in each release record.
Self-hosting changes more than the container destination
Running your agent process yourself and running the LiveKit media servers yourself are different choices. The first adds worker scheduling, health, capacity, shutdown, and deployment ownership. The second also adds media infrastructure and its network configuration.
A container runs its configured application entry point. Development-mode commands and reload behavior do not belong in its production startup path.
5. Connect your users explicitly
Agent Console is a development interface. A product frontend also needs an authenticated server route that issues room-scoped tokens and dispatches the intended agent. Derive tenant and permission information from the authenticated user, rather than trusting a browser-supplied tenant ID.
Keep the room, agent name, and deployment aligned. Otherwise the browser may connect successfully while the conversation never starts.
Phone access is another integration milestone. For a LiveKit Phone Number, inbound routing needs the number and a dispatch rule. A third-party Session Initiation Protocol (SIP) provider also needs an inbound trunk. These are separate setup paths; the browser session does not provision either one.
An inbound rule places the caller into a room, and agent dispatch brings the agent into that room. Plan call termination, transfer behavior, and failure handling separately from the initial greeting.
Room names also deserve privacy review. An individual SIP dispatch rule can include the caller's phone number in the room name, and room names can appear in logs and traces. Built-in redaction does not remove those names. Use the privacy controls described in the SIP dispatch rules before adopting room names as supposedly anonymous correlation labels.
6. Make telemetry explain a failed conversation
Enable project observability before collecting sessions intended for diagnosis. Built-in Agent insights requires LiveKit Cloud media servers. It supports self-hosted agent processes connected to Cloud, but does not cover an entirely self-hosted media deployment.
Agent insights brings transcripts, traces, logs, metrics, and audio into a session timeline. Audio and transcripts upload after the session ends, while traces and logs can stream during it. An absent recording during an active session is not sufficient evidence of a recording failure. The observability overview explains these collection boundaries.
Keep conversation evidence and service-health evidence separate:
| Failure question | Evidence to retain |
|---|---|
| Did the agent join? | Dispatch target, deployment, participant join, and session identifiers. |
| Where did the response stall? | Turn timing, model stages, tool duration, errors, and response playback timing. |
| Did the tool act correctly? | Tool name, validated argument category, result status, and downstream request ID. |
| Did the service fail before a session existed? | Startup errors, process exits, build logs, and deployment-level runtime logs. |
The LLM's time to first token and TTS time to first byte measure different boundaries. Neither equals the caller's wait. User-perceived response latency spans the end of their speech to audible response playback, including turn detection, transport, and buffering. Streaming stages can overlap, so adding stage averages can misrepresent the total.
For a backend you operate, SDK data hooks provide session reports and metrics, and OpenTelemetry exports traces. ctx.make_session_report() in the session-end callback can produce a structured post-session artifact. Export selected fields deliberately: a full report can contain conversation content. Deployment logs or log drains remain necessary for failures outside a session.
Decide recording access, retention, redaction, and deletion before production collection. Keep secrets and unnecessary personal data out of application logs. An opaque correlation ID is useful only if the fields attached to it are also controlled.
7. Assign the operating responsibilities
The production boundary includes the application, models, media transport, and business systems. Managed hosting removes some infrastructure work; it does not transfer every product responsibility.
| Area | Your team's responsibility |
|---|---|
| Conversation behavior | Instructions, tool permissions, unsupported requests, interruptions, and escalation policy. |
| Release control | Source and dependency versions, acceptance cases, deployment targets, and rollback decisions. |
| Capacity | Expected concurrent sessions, model quotas, backend limits, and saturation alerts. |
| Incident response | An on-call owner, usable session correlation, service logs, and recovery procedures. |
| Data handling | Recording policy, access, retention, tenant boundaries, and downstream storage. |
Keep release acceptance cases small and specific: the supported runbook, an unsupported topic, an interruption, a delayed or failed tool, and a disconnected participant. Model-based simulations and live audio exercises consume real inference. They belong in a controlled development environment with explicit usage limits.
This is a good fit for teams that want to own their voice application and its operating model. When the larger question is which layer to own, our voice API guide separates frameworks from managed platforms.
At Dasha, we help technical teams build and run production voice AI agents through a managed runtime, APIs, and a web application, with telephony, integrations, testing, and monitoring. That is a separate implementation choice, not a plug-in added by the code above. Your business rules, downstream permissions, and acceptance criteria still need owners.
For a managed runtime and operations path, start with Dasha.



