Overview
Agent Simulations evaluate your agent against an LLM-driven simulated user that follows a scenario from start to finish, then judge whether the agent met your expectations. Unlike unit tests, which assert on individual turns, simulations evaluate the conversation as a whole. The simulated user pursues a goal, your agent responds with its real logic and tools, and the result includes a pass or fail verdict and the full transcript.
Agent Simulations run in two modes. In text mode the simulated user exchanges text with your agent, testing your LLM, tools, and conversation logic. In audio mode it speaks and listens over a real audio track, testing the whole STT-LLM-TTS pipeline and measuring how the call sounds.
Run a few scenarios while you iterate, or a larger batch to catch regressions before you ship. Agent Simulations execute in parallel on LiveKit Cloud, subject to two separate concurrency limits. A per-run limit controls how many simulations in a run execute at once, 15 by default. A per-project limit of 30 running simulations applies across all runs.
Run text simulations on every commit, and save audio runs for a nightly or pre-release pass. To learn more, see Run simulations in CI.
Requirements
Before you begin, make sure you have the following:
- LiveKit CLI
v2.19.0or later. To install or update it, see Install the CLI. - LiveKit Agents
1.6.6or later (Python), or@livekit/agents1.6.0or later (Node.js). - A LiveKit Cloud project. Agent Simulations run on LiveKit Cloud, so the CLI must be signed in to your project with user authentication or API key authentication. User authentication requires LiveKit CLI
v2.19.4or later.
Key terms
Agent Simulations use the following terms:
- Scenario. A script for one simulated caller: the
instructionsthe simulated user follows and theagent_expectationsthe judge grades against. To learn more, see Write a scenario. - Scenario file. A YAML file with an ID, a name, and a list of scenarios, usually named
scenarios.yaml. LiveKit Cloud tracks each scenario file as a scenario group, named after the top-levelnamein the file. To learn more, see Build a scenario group. - Simulation. One conversation between the simulated user and your agent for one scenario, graded with a pass or fail verdict.
- Sample. One of several simulations of the same scenario in a run that uses
--samples. - Run. Everything one
lk agent simulatecommand executes: a simulation for each scenario or sample, their verdicts, and a summary of the run. Each run has its own ID and its own page in the dashboard.
How it works
A simulation run has three components:
- The simulated user. An LLM follows the scenario's
instructions(a persona and a goal for the simulated user) and chats with your agent until the conversation reaches a natural end. - Your agent. By default, the CLI starts your real agent as a local worker and dispatches jobs for the simulated rooms to it. Your entrypoint, tools, and conversation logic all run unchanged. To run against an agent that's already running, use
--agent-name, or call its phone number with--to. - The judge. When the conversation ends, the simulator judges the transcript against the scenario's
agent_expectationsand records a verdict. You can layer your own check on top to grade against real end state. To learn more, see Grade on final state.
By default, the simulated user interacts over text, so a run exercises your LLM, tools, and logic without the STT and TTS pipeline. To learn more, see Text mode.
Every simulation spends tokens on the simulated user, on your agent, and on the judge. That spend is what lets a simulation catch behavior the other checks in the testing lifecycle can't reach.
Use the Agent Console to try behavior yourself while you build it, and unit tests for turn-level assertions on every commit. Use simulations when the question is whether a whole conversation reaches the right outcome. Text runs are cost effective enough to run on every commit; save audio runs for a nightly or pre-release pass.
After release, agent insights shows what real sessions do, and a session that goes wrong can become a scenario. To learn more, see Derive a scenario from a session.
Run a simulation
Run simulations from your agent's project directory with the LiveKit CLI. Each mode and action has its own subcommand, and text runs a simulation in the default text mode:
lk agent simulate text -n 10
With user authentication, add --user-auth to each lk agent simulate command:
lk agent simulate text -n 10 --user-auth
With no scenario file, the CLI generates scenarios from your agent source. Because this uploads your code to LiveKit Cloud for the generator to read, the CLI asks you to confirm first. After you confirm, it starts your agent, dispatches the generated scenarios, and reports results live, with a link to the run in the dashboard. To learn more, see Review simulation runs in LiveKit Cloud.
The upload skips files that the .gitignore and .dockerignore files in your project root exclude, as well as environment files such as .env.local and virtual environment directories. If those rules exclude your agent code, the run fails with no source files found.
The CLI runs your agent as a local worker by default. It registers the worker under a temporary name, dispatches jobs for the simulated rooms to it, and stops it when the run finishes. Your entrypoint, tools, and conversation logic run unchanged.
Run against a live agent
To grade an agent that's already running instead of one spawned from your working directory, pass --agent-name with the registered name for the agent:
lk agent simulate text --agent-name my-agent --scenarios scenarios.yaml
To target the default agent for the project, the one that auto-joins every room, pass an empty string "". Running against a live agent requires a scenario file, passed with --scenarios, since there's no local source to generate scenarios from.
A live agent runs its production deployment by default. To test a change before it reaches production callers or production data, deploy it to a non-production deployment, such as staging, and pass --deployment with its name:
lk agent simulate text --agent-name my-agent --deployment staging --scenarios scenarios.yaml
When the run passes, promote that build to production.
For every subcommand and option, see lk agent simulate in the CLI reference.
Work with scenarios.yaml
Generating from source bootstraps a set of scenarios, but the workflow is iterative. Capture the scenarios you care about in a scenarios.yaml file, run them, refine the ones that surface bugs, and run them again. A checked-in scenario file is reproducible, reviewable, and runnable from automation.
Run every scenario in the file with a single command:
lk agent simulate text --scenarios scenarios.yaml
The file carries an ID, a name, and a list of scenarios. Each scenario holds the instructions the simulated user follows and the expectations the judge grades against. To learn more about the format and the fields, see Write a scenario. To decide which scenarios the file needs, see Build a scenario group. To run it automatically, see Run simulations in CI.
Run each scenario more than once
Because the simulated user and the judge are both LLMs, the same scenario can pass on one run and fail on the next. A single run can't distinguish a flaky scenario from one your agent can't handle. To find out which, use the --samples flag to run every scenario in the file several times within one run:
lk agent simulate text --scenarios scenarios.yaml --samples 3
You can run 3 samples per scenario. Sampling requires a scenario file since generated scenarios run only once.
Set the pass rate
In a sampled run, each scenario passes or fails as a whole. The --pass-rate flag sets the share of samples that must pass for a scenario to pass, and defaults to 0.75.
A failed sample doesn't fail the run by itself. The run fails only when a scenario finishes below the pass rate. Without sampling, every scenario runs once and must pass. To learn how this changes a CI job, see Handle scenarios that pass inconsistently.
Read pass@k and pass^k
A sampled run also reports pass@k, the share of scenarios that passed at least one of k samples, and pass^k, the share that passed every sample. A gap between the two indicates scenarios that pass inconsistently. Neither figure affects whether the run passes.
Both the CLI run view and the dashboard list each scenario once. The CLI shows its pass count, such as 2/3, and nests the samples under it. The dashboard shows each sample on its own tab. To learn more, see Repeated scenarios.
Work with the simulation context
Use the userdata field of a scenario to give your agent deterministic, per-scenario state. In your entrypoint, call ctx.simulation_context() (Python) or ctx.simulationContext() (Node.js) to detect a simulated run. It returns a SimulationContext object in a simulation, and None in Python or undefined in Node.js outside one. Your agent receives the userdata value as decoded JSON, with the keys exactly as written in your scenarios.yaml file. For example, read room_type rather than roomType.
You can read the simulation context as soon as your entrypoint runs. The following example reads it right after calling ctx.connect():
from livekit.agents import AgentServer, JobContext, mock_toolsserver = AgentServer()@server.rtc_session(on_simulation_end=on_simulation_end)async def entrypoint(ctx: JobContext) -> None:await ctx.connect()tool_mocks = {}if sim := ctx.simulation_context():# Seed deterministic state from the scenario's userdata.inventory = build_fake_inventory(sim.userdata()["available_rooms"])tool_mocks = build_tool_mocks(inventory)else:inventory = production_inventory()session = AgentSession(userdata=Userdata(inventory=inventory), ...)# Mock the agent's tools in a simulation so runs are reproducible. The LLM# still sees the real tool schemas; only execution is intercepted.mock_tools(MyAgent, tool_mocks, session=session)await session.start(agent=MyAgent(), room=ctx.room)
Passing session to mock_tools keeps mocks active for the session's lifetime. To learn more, see Mock tools for a running session.
Node.js has no session-scoped tool-mocking helper. Instead, seed per-scenario state from userdata() and have your tools read it directly: define each tool inside your entrypoint so its execute function references that state, as shown in the following example. The voice.testing.withMockTools helper only scopes mocks to a using block for tests and isn't designed for a long-running simulation session.
import { type JobContext, defineAgent, inference, tool, voice } from '@livekit/agents';import { z } from 'zod';export default defineAgent({entry: async (ctx: JobContext) => {await ctx.connect();// In a simulation, seed deterministic state from the scenario's userdata;// otherwise use your real backend. The tool below reads `inventory`, so the// LLM sees the same tool schemas either way. Only the data changes.// Userdata values are typed `unknown`, so `buildFakeInventory(rooms: unknown)` validates.const sim = ctx.simulationContext();const inventory = sim? buildFakeInventory(sim.userdata()['available_rooms']): productionInventory();const agent = voice.Agent.create({instructions: 'You are a hotel booking assistant.',tools: [tool({name: 'getAvailability',description: 'List room types available on a date.',parameters: z.object({ date: z.string() }),execute: async ({ date }) => inventory.roomsFor(date),}),],});const session = new voice.AgentSession({llm: new inference.LLM({ model: 'openai/gpt-4.1-mini' }),// Plus your usual stt, tts, and turn detection.// A text simulation drops them automatically.});await session.start({ agent, room: ctx.room });},});
Outside a simulation, the simulation context is absent and your agent uses its production backends. In a simulation, the front-desk example (Python) seeds a deterministic calendar, and the hotel receptionist example (Python) seeds a SQLite database. Both examples show the simulation check in a complete agent.
Context the simulator doesn't set
The simulation context includes the scenario label, instructions, expectations, tags, userdata, and the run ID, job ID, and mode. It doesn't include the per-session context your app normally sets at dispatch, because the simulator dispatches the job instead of your app. If your agent relies on that context to initialize, it starts without those values or fails:
- Job metadata is empty. Job metadata is a common way to pass per-session values when you dispatch an agent, such as the number an outbound calling agent dials or the ID of a signed-in user. If your entrypoint parses job metadata as JSON without a fallback, parsing the empty string throws an error and the job fails before the session starts. When that happens before the agent connects, the run reports that no agent joined the room.
- Room metadata is empty. The simulator creates the room with a name and an agent dispatch, and nothing else.
- The simulated user has no app attributes. The simulated user joins with the identity
simulation-<job-id>and a single attribute,lk.simulator, set totrue. An agent that loads a profile from participant attributes finds nothing to load. - No SIP participant joins. The simulated user is a standard participant, so SIP attributes such as the caller number are absent.
Add the values your agent needs at startup to userdata, and read them from the simulation context.
Read context in one function
Read context in a single function that checks for a simulation. Production behavior stays the same, and a simulation can't crash on empty metadata:
import jsonfrom livekit.agents import JobContextdef resolve_dial_info(ctx: JobContext) -> dict:# In a simulation the scenario supplies the context; in production the job does.if sim := ctx.simulation_context():return sim.userdata().get("dial_info", {})return json.loads(ctx.job.metadata or "{}")
import { type JobContext } from '@livekit/agents';function resolveDialInfo(ctx: JobContext): DialInfo {// In a simulation the scenario supplies the context; in production the job does.// Userdata values are typed `unknown`, so `parseDialInfo(value: unknown)` validates.const sim = ctx.simulationContext();return sim? parseDialInfo(sim.userdata()['dial_info']): parseDialInfo(JSON.parse(ctx.job.metadata || '{}'));}
Give the scenario the matching userdata:
scenarios:- label: Confirm a delivery windowinstructions: >You are Jordan Reyes. You answer the phone expecting a deliveryconfirmation call and want the window moved to the afternoon.agent_expectations: Delivery window moved to the afternoon and confirmed backuserdata:dial_info:phone_number: "+15105550142"customer_id: cus_8812
Simulate an outbound agent
An outbound agent dials the person it talks to: the entrypoint gets the number to call, creates a SIP participant, and waits for the callee to answer. A simulation reverses this flow. The simulated user is already in the room as the callee, so the agent doesn't need to place an outbound call. If your app passes the number in job metadata, as in the outbound calls example, that number is also absent. The simulation context doesn't include job metadata.
Place the call only when no simulation is running:
from livekit.agents import room_io@server.rtc_session(agent_name="my-telephony-agent")async def my_agent(ctx: JobContext) -> None:await ctx.connect()sim = ctx.simulation_context()phone_number = resolve_dial_info(ctx).get("phone_number")if sim is None and phone_number is not None:# Production only: place the call and wait for the callee to pick up.await ctx.api.sip.create_sip_participant(...)participant = await ctx.wait_for_participant(identity=phone_number)else:# The simulated user is already in the room, playing the callee.participant = await ctx.wait_for_participant()session = AgentSession(...)await session.start(agent=Assistant(),room=ctx.room,room_options=room_io.RoomOptions(participant_identity=participant.identity),)
import { LiveKitAPI } from 'livekit-server-sdk';const outboundTrunkId = '<outbound-trunk-id>';export default defineAgent({entry: async (ctx: JobContext) => {await ctx.connect();const sim = ctx.simulationContext();const phoneNumber = resolveDialInfo(ctx).phoneNumber;let participant;if (!sim && phoneNumber) {// Production only: place the call and wait for the callee to pick up.// Reads LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET from the environment.const api = new LiveKitAPI();await api.sip.createSipParticipant(outboundTrunkId, phoneNumber, ctx.room.name!, {participantIdentity: phoneNumber,waitUntilAnswered: true,});participant = await ctx.waitForParticipant(phoneNumber);} else {// The simulated user is already in the room, playing the callee.participant = await ctx.waitForParticipant();}const session = new voice.AgentSession({ /* ... configure your session ... */ });await session.start({agent,room: ctx.room,inputOptions: { participantIdentity: participant.identity },});},});
An entrypoint that calls create_sip_participant during a simulation dials a real number over your SIP trunk and bills the call. A scenario file in CI then places one call per scenario, on every push.
The following details also differ from an inbound run:
- Don't filter for the callee by identity. The simulated user joins as
simulation-<job-id>, so a wait for a participant whose identity is the phone number never matches. Your session never starts, and the run fails with a reason that says your agent wasnot ready within 10s. Wait without an identity filter in a simulation, as shown in the previous example. - Let the simulated user speak first. The outbound calls topic has your agent wait for the callee to speak first, and that works in a simulation. If your agent stays silent, the simulated user opens the conversation: after about 2 seconds in text mode, and after about 10 seconds of silence in audio mode.
- Write the persona as the person who answered. Write the scenario instructions from the point of view of someone who picked up a call they didn't place.
Grade on the final state
The simulator's verdict is an LLM evaluation of the conversation. That isn't always sufficient, for example, a polished conversation can still book the wrong room. Register an on_simulation_end (Python) or onSimulationEnd (Node.js) callback to validate your agent's final state and fail the simulation if it doesn't match the expected result:
from livekit.agents import SimulationContextasync def on_simulation_end(ctx: SimulationContext) -> None:expected = ctx.userdata().get("expected_state")if not expected:return # grade on the conversation alonesession = ctx.job_context.primary_sessionif not booking_matches(session.userdata.db, expected):ctx.fail(reason="final DB state diverged from the expected booking")
Add onSimulationEnd as a sibling of entry on the same defineAgent object, not nested inside entry. It runs only when a simulation finishes, and never fires for a normal session.
import { type JobContext, type SimulationContext, defineAgent } from '@livekit/agents';// Node.js has no equivalent of Python's `ctx.job_context.primary_session`, so// keep a handle to the state you want to grade, keyed by the job.const gradedState = new WeakMap<JobContext, Db>();export default defineAgent({entry: async (ctx: JobContext) => {const sim = ctx.simulationContext();const db = sim ? seedDb(sim.userdata()) : productionDb();if (sim) gradedState.set(ctx, db);// Start the session as usual; the agent's tools read and write `db`.},onSimulationEnd: (ctx: SimulationContext) => {const expected = ctx.userdata()['expected_state'];if (!expected) return; // grade on the conversation aloneconst db = gradedState.get(ctx.jobContext);if (db && !bookingMatches(db, expected)) {ctx.fail('final DB state diverged from the expected booking');}},});
Key points:
- Your check can only fail a simulation. It can't override a failed simulator verdict. The final result is the logical AND of the simulator's verdict and your check. Calling
ctx.fail()fails a simulation the simulator passed, but it can't pass one the simulator failed. If you don't callctx.fail(), the simulator's verdict stands. - Use
ctx.simulator_verdict(Python) orctx.simulatorVerdict(Node.js) to inspect the simulator's decision, including its success flag and reason. It's only available inside the callback. - Access the final agent state to compare it against the expected state defined in the scenario user data. In Python, read
ctx.job_context.primary_sessionfor the room, session, and user data your agent accumulated. Node.js has no equivalent accessor, so keep a reference to the state you want to grade, such as the backend you seeded fromuserdata(), and read it in the callback as shown in the preceding example.
This pattern turns simulation into an evaluation by checking both the conversation and the state your agent ended in. A simulation passes only if both are correct.
Text mode
Agent Simulations run in text mode by default. The simulated user exchanges text with your agent, so the run tests your LLM, tools, and conversation logic without the STT and TTS pipeline. Text mode is faster, more cost effective, and more deterministic. Use it for CI runs and for any scenario that doesn't exercise speech.
Under a text simulation, the framework automatically disables STT, TTS, VAD, and audio input and output, so your agent runs its LLM and tools unchanged without any audio setup.
To check which mode a simulation is running in, read sim.simulation_mode (Python) or sim.simulationMode (Node.js) from the SimulationContext. It returns a SimulationMode enum value. Compare it against SimulationMode.SIMULATION_MODE_TEXT (Python) or SimulationMode.TEXT (Node.js). An unspecified mode resolves to text.
Audio mode runs the same scenarios through your agent's full media pipeline and scores the call itself. To learn more, see Audio simulations.
Audio simulations
In audio mode, the simulated user speaks your scenario aloud, listens to your agent, and interrupts it where your scenario scripts an interruption. Your agent runs its full STT-LLM-TTS pipeline against that audio, and the run scores the aspects that only speech exposes:
- Turn-taking. Whether the agent starts speaking before the caller finishes, or leaves a caller who has finished waiting.
- Interruption handling. Whether the agent yields when the caller interrupts it and correctly distinguishes a brief acknowledgment from a turn.
- Transcription. Numbers, spelled-out names, addresses, and confirmation codes, in both directions.
- Perceived speed and speech quality. The latency the caller hears, and whether names and amounts are pronounced correctly.
Run a scenario file in audio mode with the audio subcommand:
lk agent simulate audio --scenarios scenarios.yaml
An audio run executes in real time rather than as fast as the LLM responds, calls your STT and TTS providers on every turn, and meters audio turns at a higher rate than text turns.
How an audio simulation runs
Scenarios, the judge, and the pass or fail verdict work the same way in both text and audio modes. Audio mode adds the following behavior:
- The simulated user joins the room as a participant. It publishes an audio track and subscribes to your agent's, so your agent sees a caller rather than a text stream.
- Your configured audio models run. STT, TTS, and VAD use the models configured for your agent, and their providers are billed accordingly. If your agent uses a realtime model, audio mode exercises it end to end. The realtime model hears the simulated user directly, and any STT or TTS you pair with it also runs.
- The run executes in real time at normal inference priority. This means measured response times match production. Text runs are dispatched to LiveKit Inference as low-priority batch load because nothing is waiting on the results.
- Usage is metered in audio turns. Audio turns are tracked separately from text turns.
- The simulated user interrupts only where the scenario scripts an interruption. While your agent speaks, the simulated user says brief acknowledgments such as "mm-hmm." To learn more, see Script an interruption.
- The simulated user listens in the language the agent answers in. Its speech recognition uses the agent language your scenario states, or the caller's language if the scenario states none. To learn more, see State the languages.
- The simulated user can press keys. When your agent asks the caller to press or enter something, the simulated user presses keys on its phone keypad: the digits 0–9,
*, and#. Your agent receives them as DTMF, the same as from a phone. To learn more, see Script key presses.
In audio mode, the simulated user waits for your agent to open the conversation. If the line stays quiet for about 10 seconds, the simulated user speaks first, so an agent that waits for the user still runs, but the call starts with a pause. To start without the pause, have your agent greet the user when the session starts, for example by calling generate_reply() in on_enter. To learn more, see Initiating speech. In text mode, the simulated user sends the first message after about 2 seconds.
An agent the CLI spawns locally would otherwise fall back to the local turn detector model and VAD-based interruption, measuring turn-taking that doesn't reflect production. The CLI uses the same turn detection and adaptive interruption defaults as a deployed agent, so audio runs reflect production behavior.
Supported languages
The simulated user speaks and listens in the language of the scenario. By default, that's the language you write the scenario in. To test a user who speaks a different language, describe them in the scenario, for example as "a native Spanish speaker who doesn't speak English." Mixed speech, such as Hindi mixed with English, runs in the non-English language. To learn how to state the caller's and the agent's languages, see State the languages.
The simulated user transcribes your agent using its own STT model, regardless of the STT model your agent uses. An audio simulation supports the following languages, and runs a regional variety as its base language:
| Arabic | Belarusian | Bengali | Bulgarian | Catalan | Chinese |
| Croatian | Czech | Danish | Dutch | English | Estonian |
| Farsi | Finnish | French | German | Greek | Hebrew |
| Hindi | Hungarian | Indonesian | Italian | Japanese | Kannada |
| Korean | Latvian | Lithuanian | Macedonian | Malay | Marathi |
| Norwegian | Polish | Portuguese | Romanian | Russian | Serbian |
| Slovak | Slovenian | Spanish | Swedish | Tagalog | Tamil |
| Telugu | Turkish | Ukrainian | Urdu | Vietnamese |
If the language of a scenario isn't in this list, the audio run fails before the first turn, and the failure reason names the unsupported language. Text simulations don't use speech recognition, so this list doesn't apply to them. To test the scenario, run it in text mode or write it in a supported language.
What an audio run measures
Alongside the verdict, an audio run measures call quality per turn and aggregated over the run, so you can track real-world quality over time rather than correctness alone. These metrics appear in the dashboard and in the exported JSON.
Responsiveness. The primary metric is the end-to-end latency the caller heard, reported at p50, p95, and p99. A positive value indicates a gap before the agent responded, while a negative value means the agent talked over the caller. Track this separately from the latency the agent reports. The agent measures when it started producing audio, while the caller measures when they heard it. The difference between the two is what the user perceives. The run also breaks the pipeline down stage by stage, reporting STT and endpointing delay, LLM time-to-first-token and time-to-first-sentence, tokens per second, and TTS time-to-first-byte. This helps identify the stage responsible for slow responses.
Turn-taking. A turn-taking score with the specific failures behind it: end-of-turn mispredictions where the agent started speaking before the caller finished, false interruptions where the agent stopped when there was no interruption, the share of overlapping speech, unfilled silences after a natural pause, and caller turns that the agent never answered.
Speech accuracy. Word and character error rates in both directions: what the agent heard compared with what the caller said, and what the caller heard compared with what the agent said. Key entities, such as names, IDs, confirmation codes, and amounts, are scored separately, with recall distinguishing between an entity the agent never recognized and one it recognized but later lost.
Conversation quality. The overall score, conciseness, and whole-call issue flags such as unnecessary tool calls, information loss, redundant statements, and poor question quality. These combine into a conversation-progression score. Because these measures are judged from the dialog, they're reported for both modes.
Metrics the agent reports about itself, such as the pipeline latency breakdown, error rates, and false interruptions, require the agent's own session data and are absent for waveform-only captures. Judged metrics such as conciseness and entity scoring require the text judge to have run.
Simulate a degraded connection
Real callers connect from noisy environments and unreliable networks. These flags degrade the simulated user's audio so you can test how your agent responds:
| Flag | Description |
|---|---|
--background-noise | Mix ambient noise into the simulated user's audio. Surfaces endpointing that triggers on noise and ineffective noise cancellation. |
--low-quality-microphone | Publish the simulated user's audio as a low-quality microphone would capture it. Surfaces transcription errors on names, numbers, and codes. |
--packet-loss | Drop packets from the simulated user's audio track. Surfaces how the agent handles clipped or partially lost speech, including whether it asks the user to repeat. |
Combine them to model a worst-case caller:
lk agent simulate audio --background-noise --packet-loss
Every option on text also applies to audio. For example, run a degraded audio pass against an already-running agent:
lk agent simulate audio --agent-name my-agent --scenarios scenarios.yaml --low-quality-microphone
Test an agent by phone
To test an agent through your telephony setup, provide a phone number for the simulation to call. Each simulation calls the number and tests the agent through the same production telephony pipeline as a real inbound call. This lets you verify your phone configuration and agent behavior before real callers reach it.
Testing by phone requires LiveKit CLI v2.19.3 or later.
Pass the number to call, an outbound trunk to call through, and a caller ID on that trunk:
lk agent simulate audio --scenarios scenarios.yaml --to +14155550100 --from +14155550199 --trunk ST_xxxx
Testing by phone differs from other audio simulations in these ways:
- Inbound calls only. The simulated user is always the caller. Simulations don't currently support agents that place calls.
- No simulation context. Your agent runs as it does in production. Scenario
userdata, mocked tools, and theon_simulation_endhandler don't apply, and tools act on real systems. - Caller-side metrics only. The run sees only the call audio. Metrics the agent reports about itself, such as the pipeline latency breakdown, error rates, and false interruptions, aren't available. Tool calls aren't evaluated.
- SIP minutes. Each call uses SIP minutes in addition to audio turns.
- Failed calls aren't retried. A call that's busy, rejected, or unanswered after 30 seconds fails the simulation.
Export a run
To analyze a finished run outside the CLI, export it as JSON. The export includes the run, its summary, and the exact per-job chat contexts, which is useful for archiving results as a build artifact or comparing behavior between runs:
lk agent simulate export <run-id> > run.json
For a run from a scenario file, each job in the export carries the scenario_id of the scenario it ran and its sample number. Use these fields to group samples by scenario and track a scenario across runs. A sampled run also carries its sampling settings, which hold the number of samples and the pass rate.
To reopen a previous run in the terminal, pass its ID to view:
lk agent simulate view <run-id>
To find a run ID, list the most recent runs for the project:
lk agent simulate list
Limitations
Agent Simulations don't support the following features:
- Per-session context at dispatch. The simulator doesn't set job metadata, room metadata, or participant attributes. Add those values to the
userdatafield in your scenario instead. To learn more, see Context the simulator doesn't set. - Control over who speaks first. The simulated user waits for your agent to open the conversation, and speaks first only if your agent stays silent: after about 2 seconds in text mode, and after about 10 seconds of silence in audio mode. You can't have it answer right away, as a real callee does.
- Voicemail and phone trees. The simulated user answers as a person. It doesn't play a voicemail greeting or a phone menu for your agent to navigate, but it can press keys to navigate a menu your agent plays.
- Warm transfers and human escalation. A scenario runs between one simulated user and one agent, so a transfer to another agent or to a person isn't simulated.
Example agents and scenarios
These open source agents run simulations as part of their own test setup. Read them to see complete scenario files alongside the agent code they grade.
Front desk example (Python)
Test how the front desk agent behaves with simulations. See the scenarios.yaml and simulation.py files.
Hotel receptionist example (Python)
Run simulations with the hotel receptionist agent. To learn more, see scenarios_guardrails_and_faq.yaml .
Tool accuracy testing (Python)
A scenarios file that grades the tool flows of the hotel receptionist agent against a deterministic final database state.
Additional resources
These topics cover writing scenarios, choosing which ones to commit, and running them.
Write a scenario
Persona scripting, outcome-shaped expectations, and the speech patterns that break a live call.
Build a scenario group
Decide which scenarios your scenario group needs.
Derive a scenario from a session
Turn a recorded session into a scenario.
Run simulations in CI
Automate your scenarios, and choose how often to run each mode.
Review simulation runs in LiveKit Cloud
Read scores, detected issues, metrics, and transcripts for each run.
Unit tests
Assert on individual turns, tool calls, and agent state with the unit-testing helpers.