average-leather-27589
11/24/2025, 9:02 AMtall-airline-16756
11/24/2025, 9:02 AMtall-airline-16756
11/24/2025, 9:03 AMsession.say() to wait until the video is playing.
You can fix this by coordinating speech from the frontend when the video is actually ready. Two recommended approaches:
Option A — Event-driven RPC (recommended)
1. In your agent/room code, expose an RPC the frontend can call:
@room.local_participant.register_rpc_method("video_started")
async def on_video_started(data):
await session.say("Hi there!")
1. In the frontend, call that RPC when the video fires a readiness event (onloadeddata or onplay):
videoEl.onplay = () => {
room.localParticipant.call("video_started", {});
};
Option B — Data messages
1. Have the frontend publish a data message like { type: "video_started" } when the video begins.
2. Have the agent listen for that message and call session.say() on receipt.
Quick alternative: a small fixed delay before session.say() can help during testing, but it’s less reliable than using `onplay`/`onloadeddata`.
Which platform are you using for the frontend (web, mobile) and how do you currently trigger the agent speech? Share a short code snippet and I’ll give the exact RPC/data message example you need.
Sources: Pipeline nodes and hooks | LiveKit docs | Agent speech and audio | LiveKit docs | Bringing AI avatars to voice agents | Turn detection and interruptions | LiveKit Docsaverage-leather-27589
11/24/2025, 9:09 AMtall-airline-16756
11/24/2025, 9:10 AMroom object and its local_participant available, and before you expect the client to call it. That means not inside a transient handler that exits before the participant is ready.
• Common placements:
◦ In your room setup code that runs once when the room is created/initialized.
◦ In a handler that runs when your server-side participant successfully joins the room (so local_participant is guaranteed).
• Ensure the server process that registers the RPC stays running and keeps the room object alive.
Common reasons the RPC isn't invoked
• The RPC was registered too early (before local_participant exists) or too late (after the client call).
• The client is calling a different method name or using the wrong participant (check localParticipant.call vs otherParticipant.call).
• Network/permission constraints or the room instance on server vs client are different processes.
Quick checklist to verify
• Is the code that registers @room.local_participant.register_rpc_method("video_started") executed after the server joins the room as the local participant?
• Are you using the exact same method name on the client (case-sensitive)?
• Is the server process still running when the client calls the RPC?
• Do you see any logs/errors on the server when the client attempts the call?
Please tell me:
1. Which SDK/language are you using on the server (Python, Node, Go)?
2. A short snippet (5–10 lines) showing where you create/join the room and where you placed the decorator — I’ll point out the exact spot to move it to and provide a corrected example.average-leather-27589
11/24/2025, 9:12 AMtall-airline-16756
11/24/2025, 9:12 AMlocal_participant is available — not necessarily the very last line, but before your process begins waiting for client events. Placing it at the end of your entrypoint can work if by that time the room and local_participant exist and the process continues running to receive RPC calls.
Key points
• Register once, after join/room creation.
• Keep the process alive (event loop) so the handler stays registered.
• Use the exact RPC name the client calls.
Example pattern (Python)
# create/join the room and get `room`
room = await server.join_room(...)
# now register the RPC on the local participant
@room.local_participant.register_rpc_method("video_started")
async def on_video_started(data):
await session.say("Hi there!")
# keep the server running / handle incoming events
await room.wait() # or your app's run loop
If your entrypoint exits or the room object goes out of scope, the RPC won't be callable. Paste your current entrypoint (5–10 lines around room creation/join) and I’ll point exactly where to move the decorator.average-leather-27589
11/24/2025, 9:14 AMasync def entrypoint(ctx: JobContext):
await ctx.connect()
session = AgentSession(preemptive_generation=True)
try:
avatar = simli.AvatarSession(
simli_config=simli.SimliConfig(
api_key=os.environ.get("SIMLI_API_KEY"),
face_id=os.environ.get("SIMLI_FACE_ID"),
max_idle_time=60,
# max_session_length=300,
),
)
await avatar.start(session, room=ctx.room)
except Exception as e:
print(f"Avatar setup error: {e}")
await session.start(agent=LocalAgent(), room=ctx.room)
session.user_data = {"room": ctx.room}
@room.local_participant.register_rpc_method("coffee_menu")
async def on_video_started(data):
print("Participant joined, sending greeting...")
await session.say("Hi there! How can I assist you")
# await session.say(
# "Hi there!",
# allow_interruptions=True,
# )tall-airline-16756
11/24/2025, 9:14 AMroom which isn't defined in that scope, and the RPC must be registered after the server has the local_participant (i.e., after join/start) while the process remains running.
Move the RPC registration to use ctx.room (or the room variable you have) immediately after await session.start(...) and before any await that would exit the function. Example:
await session.start(agent=LocalAgent(), room=ctx.room)
session.user_data = {"room": ctx.room}
@ctx.room.local_participant.register_rpc_method("video_started")
async def on_video_started(data):
print("video_started RPC received")
await session.say("Hi there! How can I assist you")
# keep the entrypoint running so the RPC stays registered
await ctx.room.wait() # or your app's run loop
Notes:
• Use ctx.room (the same room instance) when registering.
• Ensure the entrypoint does not exit (keep the event loop alive) so the handler stays registered.
• Confirm the client calls the exact RPC name "video_started" (case-sensitive) on the server participant.
If you share a short snippet of the client call (how you invoke the RPC from frontend), I’ll verify that part too.average-leather-27589
11/24/2025, 4:08 PMtall-airline-16756
11/24/2025, 4:08 PMstart() again when the user returns.
Key actions:
• Ensure you do not set close_on_disconnect=False (leave default so the session closes on disconnect).
• On reconnect, reinitialize the session and agent, then call await session.start(room=ctx.room, agent=agent).
Example pattern in your entrypoint:
@server.rtc_session()
async def my_agent(ctx: agents.JobContext):
# wait for participant to join/reconnect
participant = await ctx.wait_for_participant()
# create fresh session + agent each time this job runs
session = AgentSession(preemptive_generation=True)
agent = MyInitialAgent()
await session.start(room=ctx.room, agent=agent)
# keep running to handle RPCs / events
await ctx.room.wait()
If you want to preserve some external state (e.g., user prefs), load that from your database before creating the new session. Do you want an example that preserves specific state across reconnects or the exact reconnection flow for your frontend?
Sources: How We Built a Globally Distributed WebRTC Mesh Network | Agent session | LiveKit docs | External data and RAG | LiveKit Docs | Building an Automated IVR Menu Caller | LiveKit Docsaverage-leather-27589
11/24/2025, 4:09 PMtall-airline-16756
11/24/2025, 4:10 PMAgentSession and Agent and call await session.start(...). This guarantees chat history, agent context, and any internal model state are fresh.
• Partial reset in-place (advanced)
◦ Clear conversation history: create a fresh ChatContext and update the agent with it:
from livekit.agents import ChatContext
await session.agent.update_chat_ctx(ChatContext())
• Reset custom session state:
session.userdata = {} # or a fresh object
• Update instructions/tools:
await session.update_instructions("New instructions")
await session.update_tools([]) # clear tools if applicable
• Interrupt ongoing processing:
await session.agent.interrupt()
Note: in-place resets may not clear internal state held by realtime LLMs — for full isolation you may still need to recreate the session.
Which approach fits you best?
• If you want a full guaranteed reset (like after disconnect), recreate the AgentSession.
• If you want a user-facing “Reset” button without disconnecting, use the partial reset calls above.
Tell me which scenario you need (reconnect flow vs. in-app reset button) and whether you use any realtime LLMs; I’ll give the exact code snippet to implement it.
Sources: Agent Session Management & Turn Detection | livekit/livekit_composite | Dee... | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | Connecting to LiveKit | LiveKit docsaverage-leather-27589
11/25/2025, 9:18 AMtall-airline-16756
11/25/2025, 9:18 AMmax_idle_time, try increasing it.
• If using realtime LLMs or heavy CPU, monitor server CPU/memory — resource issues can drop sessions.
If you want, send:
• The exact disconnection log line(s) and any error codes,
• Your Simli settings (e.g., max_idle_time) and where the agent runs (host/env).
I’ll use those to suggest targeted fixes (keep-alive, increase idle time, or reproduce the disconnect).
Sources: Simli virtual avatar integration guide | LiveKit Docs | Quotas and limits | LiveKit docs | Connecting to LiveKit | LiveKit docs | Agent session | LiveKit docs | Troubleshooting Latency and Timeout Errors with Turn Detection on AWSaverage-leather-27589
11/25/2025, 9:21 AMagent-1 | {"level": "INFO", "name": "livekit.agents", "message": "closing agent session due to participant disconnect (disable via `RoomInputOptions.close_on_disconnect=False`)", "participant": "identity-2vh1", "reason": "CLIENT_INITIATED", "pid": 101, "job_id": "AJ_WxP8pUBzmFQ6", "room_id": "RM_zwTJkAeWnq4n", "timestamp": "2025-11-25T09:15:37.212899+00:00"}
agent-1 | {"level": "ERROR", "name": "livekit.agents", "message": "failed to perform clear buffer rpc\nTraceback (most recent call last):\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/avatar/_datastream_io.py\", line 174, in _clear_buffer_task\n await self._room.local_participant.perform_rpc(\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/rtc/participant.py\", line 328, in perform_rpc\n raise RpcError._from_proto(cb.perform_rpc.error)\nlivekit.rtc.rpc.RpcError: Connection timeout", "pid": 101, "job_id": "AJ_WxP8pUBzmFQ6", "room_id": "RM_zwTJkAeWnq4n", "timestamp": "2025-11-25T09:15:44.213901+00:00"}
agent-1 | {"level": "WARNING", "name": "livekit.agents", "message": "didn't receive playback finished event after clear buffer, marking playout as done arbitrarily", "pid": 101, "job_id": "AJ_WxP8pUBzmFQ6", "room_id": "RM_zwTJkAeWnq4n", "timestamp": "2025-11-25T09:15:44.214777+00:00"}
agent-1 | {"level": "INFO", "name": "livekit.agents", "message": "process exiting", "reason": "", "pid": 101, "job_id": "AJ_WxP8pUBzmFQ6", "room_id": "RM_zwTJkAeWnq4n", "timestamp": "2025-11-25T09:15:58.727239+00:00"}tall-airline-16756
11/25/2025, 9:21 AMRoomInputOptions.close_on_disconnect=False)", reason "CLIENT_INITIATED".
• The server tried to call an RPC to the participant but timed out: RpcError: Connection timeout when performing the clear-buffer RPC, then it proceeded to exit.
What to do next (concrete steps)
1) If you want the agent to keep running when the participant disconnects
• Start the room/AvatarSession with close_on_disconnect=False so the AgentSession is not automatically closed on client disconnect.
Example placement (where you create/join the room / start avatar):
from livekit.agents import RoomInputOptions
await avatar.start(
session,
room=ctx.room,
room_input_options=RoomInputOptions(close_on_disconnect=False),
)
• Keep a run loop (e.g., await ctx.room.wait()) so the server stays alive to handle future reconnects.
2) Prevent RPC timeouts and handle playback-clear RPCs robustly
• The RPC timeout happened because the participant was already disconnected or not responding when the server attempted perform_rpc. Only call participant-directed RPCs while the participant is connected.
• Before performing RPCs, check participant connection state or wrap calls with try/except and fallback behavior:
try:
await ctx.room.local_participant.perform_rpc("clear_buffer", {})
except RpcError:
# handle timeout: skip, retry, or mark playback done
• Use client-side events (e.g., onplay, onloadeddata) to acknowledge playback finished so server-side clears are coordinated and unnecessary retries are avoided.
3) Simli-specific timeout hints
• If Simli disconnects after a few minutes, also increase Simli config max_idle_time when creating the AvatarSession:
simli.SimliConfig(max_idle_time=300) # seconds
• Monitor agent process health (no crashes or restarts) and network/ICE on the client.
4) Debug info to collect if it still happens
• Participant connection state and reason at disconnect (you already have CLIENT_INITIATED).
• Client-side console logs around disconnect and RPC calls.
• Any Simli API errors or logs and the max_idle_time value you used.
If you want, I can:
• Provide a full example entrypoint that keeps the agent alive across disconnects and retries RPCs safely.
• Help tune max_idle_time and show where to place RPC checks in your existing code. Which would you prefer?average-leather-27589
11/25/2025, 10:23 AMtall-airline-16756
11/25/2025, 10:23 AMAgentSession and Agent on reconnect so the model and chat history are fresh:
session = AgentSession(...)
await session.start(room=ctx.room, agent=MyAgent())
• This guarantees no leftover LLM state.
• In-place reset (partial)
◦ Clear the chat context so the agent loses prior language cues:
from livekit.agents import ChatContext
await session.agent.update_chat_ctx(ChatContext())
• Update instructions to force English:
await session.update_instructions("Speak only in English.")
• Interrupt any ongoing processing:
await session.agent.interrupt()
• Note: realtime LLMs may still keep some internal state; in-place resets are less reliable than full recreation.
• Safer language enforcement
◦ Always send an explicit system instruction at session start (or immediately after reconnect) that enforces the language, e.g., "System: Use only English for all responses."
◦ Optionally run a quick probe prompt (like "Please reply in English: OK") and verify language before proceeding.
Questions to narrow it down
• Do you recreate the AgentSession on reconnect or reuse the same session instance?
• Are you using any persisted ChatContext, instructions, or userdata across reconnects?
• Do you want a code example for full recreation or for clearing context in-place?
Tell me which approach you prefer and I’ll give the exact snippet to add to your reconnect flow.average-leather-27589
11/25/2025, 10:36 AMasync def entrypoint(ctx: JobContext):
await ctx.connect()
session = AgentSession(
llm=openai.realtime.RealtimeModel(voice="sage"),
)
try:
avatar = simli.AvatarSession(
simli_config=simli.SimliConfig(
api_key=os.environ.get("SIMLI_API_KEY"),
face_id=os.environ.get("SIMLI_FACE_ID"),
max_idle_time=90,
max_session_length=900,
),
)
await avatar.start(session, room=ctx.room)
except Exception as e:
print(f"Avatar setup error: {e}")
await session.start(agent=LocalAgent(), room=ctx.room)
session.user_data = {"room": ctx.room}
await session.generate_reply(
instructions=SESSION_INSTRUCTION,
allow_interruptions=True,
)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, job_memory_warn_mb=1500))tall-airline-16756
11/25/2025, 10:36 AMgenerate_reply. Put the reset right after await session.start(...) and before any generation.
Two options (pick one):
1) Clear chat context in-place (quick)
await session.start(agent=LocalAgent(), room=ctx.room)
# clear previous conversation so realtime model won't reuse prior history
from livekit.agents import ChatContext
await session.agent.update_chat_ctx(ChatContext())
# enforce English immediately
await session.update_instructions("Speak only in English.")
await session.generate_reply(
instructions=SESSION_INSTRUCTION,
allow_interruptions=True,
)
2) Recreate session (recommended for full isolation)
# create a fresh session and agent each time
session = AgentSession(llm=openai.realtime.RealtimeModel(voice="sage"))
await session.start(agent=LocalAgent(), room=ctx.room)
# then generate
await session.generate_reply(...)
Notes:
• For realtime LLMs, in-place clears may be less reliable than full recreation; recreation guarantees no leftover model state.
• If you want the session to persist when a participant disconnects, set RoomInputOptions(close_on_disconnect=False) when starting your avatar — otherwise reconnects start a fresh job by default.
Would you like the full entrypoint example updated with one of these approaches? Which option do you prefer?average-leather-27589
11/25/2025, 10:39 AMtall-airline-16756
11/25/2025, 10:39 AMsession = AgentSession(llm=openai.realtime.RealtimeModel(voice="sage"))
await session.start(agent=LocalAgent(), room=ctx.room)
• Alternative (partial reset): clear chat context and force instructions after start:
from livekit.agents import ChatContext
await session.start(agent=LocalAgent(), room=ctx.room)
await session.agent.update_chat_ctx(ChatContext()) # clear history
await session.update_instructions("Speak only in English.") # enforce language
await session.agent.interrupt() # stop ongoing activity
Notes
• For realtime LLMs, the full recreation approach is the most reliable because internal model state may not be fully flushed by updating chat context alone.
• Keeping the same API key is fine — you don’t need separate keys per session.
If you want, I can:
• Provide a full entrypoint example that recreates the session on each connect, or
• Show how to detect reconnects and recreate the session automatically. Which would you prefer?average-leather-27589
11/25/2025, 10:42 AMtall-airline-16756
11/25/2025, 10:42 AMAgentSession in that entrypoint, but that doesn't guarantee the realtime model's internal state is fresh across reconnects if the same job/process stays alive. Two cases explain the behavior:
1. Job/process ends on participant disconnect (default): a new job runs on reconnect and your entrypoint creates a new AgentSession and RealtimeModel — this gives full isolation.
2. Job/process stays alive (e.g., you set close_on_disconnect=False or the server keeps the job running): your entrypoint may run once and reuse the same `AgentSession`/`RealtimeModel` instance on reconnect — that can preserve internal model context (language preferences) even if you call generate_reply again.
What to do
• If you want guaranteed fresh model state on each reconnect: ensure the job ends on disconnect (leave close_on_disconnect default) so the entrypoint runs anew and creates a fresh AgentSession + RealtimeModel.
• If you must keep the job alive and still reset state: immediately after await session.start(...) clear the model/context or recreate the model instance:
Option A — clear context in-place:
from livekit.agents import ChatContext
await session.start(agent=LocalAgent(), room=ctx.room)
await session.agent.update_chat_ctx(ChatContext()) # clear history
await session.update_instructions("Speak only in English.") # enforce language
await session.agent.interrupt()
Option B — recreate the RealtimeModel in the same job (stronger):
# create fresh llm instance to avoid reused internal state
session.llm = openai.realtime.RealtimeModel(voice="sage")
await session.start(agent=LocalAgent(), room=ctx.room)
Pick recreation for full reliability with realtime LLMs. Do you want a full entrypoint example that forces a fresh RealtimeModel on each connect?average-leather-27589
11/25/2025, 12:15 PMtall-airline-16756
11/25/2025, 12:15 PMsession._chat_ctx is not reliable. That private attribute may not propagate into the runtime state used by the realtime LLM, so the model can still retain internal context (like language cues). To reliably clear history and prevent language carryover, use one of these approaches.
Recommended (full, reliable)
• Recreate the AgentSession and the RealtimeModel instance on each new connection so the model has no prior internal state.
Example (replace your current session creation in entrypoint):
# create fresh session + llm per connection
session = AgentSession(
llm=openai.realtime.RealtimeModel(voice="sage"),
)
await session.start(agent=LocalAgent(), room=ctx.room)
await session.generate_reply(instructions=SESSION_INSTRUCTION, allow_interruptions=True)
In-process reset (less reliable for realtime models)
• Use the public APIs to clear chat context and enforce language; handle interrupts. Do this after await session.start(...).
from livekit.agents import ChatContext
# clear conversation context
await session.agent.update_chat_ctx(ChatContext())
# enforce English (or any language) immediately
await session.update_instructions("System: Respond only in English.")
# cancel any ongoing processing
await session.agent.interrupt()
If you must keep the job alive across disconnects
• Ensure you either recreate the RealtimeModel instance inside the same job:
session.llm = openai.realtime.RealtimeModel(voice="sage")
then call await session.agent.update_chat_ctx(ChatContext()) and await session.update_instructions(...).
And consider leaving close_on_disconnect as default (so jobs restart on reconnect) unless you have a reason to keep the job alive.
Which would you prefer — I can give a full entrypoint example that (A) recreates the session per connect, or (B) reinitializes the realtime model and clears context inside a persistent job.average-leather-27589
11/27/2025, 3:41 AMtall-airline-16756
11/27/2025, 3:41 AMAgentSession doesn't have update_instructions. That method belongs on the agent instance (or you must recreate the session/model). To stop the realtime model from inheriting previous language/state, do one of the following (with exact placement in your entrypoint):
Option A — Recommended: create a fresh session + model per connect
• Replace the existing session creation inside entrypoint so a new AgentSession and new RealtimeModel are constructed each time the entrypoint runs (guarantees no leftover internal model state).
Example placement (inside your entrypoint, before await session.start(...)):
session = AgentSession(
llm=openai.realtime.RealtimeModel(voice="sage"),
)
await session.start(agent=LocalAgent(), room=ctx.room)
await session.generate_reply(instructions=SESSION_INSTRUCTION, allow_interruptions=True)
Option B — Persistent job but reinitialize model & agent (same job, avoid reuse)
• If your job persists across disconnects (e.g., close_on_disconnect=False), recreate the realtime model and agent instance inside the same job before calling generate_reply so internal state is fresh:
# reassign a fresh realtime model and new agent instance
session.llm = openai.realtime.RealtimeModel(voice="sage")
await session.start(agent=LocalAgent(), room=ctx.room)
Option C — Partial in-place reset (less reliable for realtime models)
• Use public agent APIs after start to clear chat context and enforce language, but this may not flush internal realtime-model state:
from livekit.agents import ChatContext
await session.start(agent=LocalAgent(), room=ctx.room)
await session.agent.update_chat_ctx(ChatContext()) # clear history
await session.agent.update_instructions("Respond only in English.") # on agent, not session
await session.agent.interrupt()
await session.generate_reply(instructions=SESSION_INSTRUCTION, allow_interruptions=True)
Notes:
• Do not assign private attributes like session._chat_ctx — that does not reliably reset runtime state.
• Using the same API key does not force shared conversation memory. The model/process instance is what retains state.
• For full reliability with OpenAI realtime models, Option A (fresh session + model) is the safest.
If you want, I can:
• Provide a full, corrected entrypoint example that recreates the session per connection, or
• Show the minimal changes to your current entrypoint to reinitialize the RealtimeModel inside a persistent job.
Which would you like?
Sources: Building an Automated IVR Menu Caller | LiveKit Docs | Agent session | LiveKit docs | Azure OpenAI Realtime API and LiveKit | LiveKit Docsaverage-leather-27589
11/27/2025, 4:48 AMtall-airline-16756
11/27/2025, 4:49 AMaverage-leather-27589
11/27/2025, 4:49 AMtall-airline-16756
11/27/2025, 4:50 AMsession = AgentSession(...) itself.
Concrete steps to troubleshoot and fix:
1. Recreate session/model per connect
• Ensure you create a fresh AgentSession and new RealtimeModel for each connection/reconnect. Realtime models can keep internal state and buffers if you reuse the same instance.
session = AgentSession(llm=openai.realtime.RealtimeModel(voice="sage"))
await session.start(agent=LocalAgent(), room=ctx.room)
1. Cleanly close previous session and buffers
• Before recreating, close the old session so internal buffers are flushed:
await session.aclose()
• Also unpublish any leftover tracks:
await ctx.room.local_participant.unpublish_all_tracks()
1. Verify audio chunking/duration math
• Log sample count, sample rate, and computed ms per chunk before sending to the Realtime API.
• Only flush/send when chunk_duration_ms >= declared duration. Buffer short chunks until you have enough samples.
• Ensure declared sample rate/encoding matches actual audio.
1. Catch and recover from RealtimeError
• Wrap send/commit calls and on this error either buffer more audio and retry or discard the partial chunk and continue. Example:
try:
# send/commit audio
except RealtimeError:
# buffer or retry logic
1. If you keep jobs persistent (close_on_disconnect=False)
• Reinitialize the RealtimeModel in-process to avoid stale buffers:
session.llm = openai.realtime.RealtimeModel(voice="sage")
1. Debugging logs to gather
• Chunk sample counts, sample rate, computed duration (ms) and declared duration sent to OpenAI.
• Whether the error is consistent or intermittent and the timeline relative to connects/disconnects.
If you share the code that packages/sends audio frames to the Realtime API (how you compute chunk length and the send/commit calls), I’ll point to the exact line to change and provide a patched snippet. Would you like to share that audio-send code?
Sources: Agent session | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs | Turn detection and interruptions | LiveKit Docs | Agents (Python) | livekit/livekit_composite | DeepWiki | OpenAI Realtime API plugin guide | LiveKit docsaverage-leather-27589
11/27/2025, 5:56 AMtall-airline-16756
11/27/2025, 5:57 AMuseVoiceAssistant. A few likely causes and quick checks:
• Realtime models or pipelined audio: OpenAI Realtime (and similar) can minimize intermediate states, so thinking may be brief or skipped.
• Fast generation: If the agent replies almost immediately, the transition is too fast to observe.
• Agent not emitting state changes: lk.agent.state is set by the backend AgentSession; if that session isn't running or not updating state, the hook won't see thinking.
• Frontend subscription issue: The hook reads participant attributes — verify you receive participant updates.
Troubleshooting steps (fast):
1. Confirm backend uses LLM/STT/TTS and AgentSession is active.
2. Inspect agent logs for state transitions (look for events moving to thinking).
3. On the frontend, log participant attributes and check lk.agent.state changes.
4. If using a realtime LLM, try forcing a small delay before responding (or add an explicit system step) to see if thinking appears.
5. If you want, share:
◦ Backend snippet showing AgentSession and agent loop,
◦ Frontend snippet where you call/use useVoiceAssistant,
◦ Any agent logs around a request — I’ll point to the exact cause. Sources: Web and mobile frontends | LiveKit docs | Events and error handling | LiveKit docsaverage-leather-27589
11/27/2025, 6:54 AMtall-airline-16756
11/27/2025, 6:54 AMasyncio.run() or create a new event loop inside your job or any code the job imports.
• Any background tasks must be created with the JobContext loop (the one running your entrypoint). Use ctx.loop.create_task(...) or asyncio.create_task(...) from inside the currently running coroutine.
2) Clean shutdown ordering
• Await await session.aclose() from the same loop before exiting the job. That ensures synchronizer tasks are cancelled/finished on the correct loop.
• If you register shutdown callbacks via ctx.add_shutdown_callback, ensure they run on the job loop and do not spawn tasks on other loops.
3) Avoid creating threads that spawn asyncio tasks
• If you must use threads, use thread-safe APIs to submit coroutine execution to the job loop:
fut = asyncio.run_coroutine_threadsafe(coro(), loop=job_loop)
and wait on that Future instead of creating tasks in the thread.
4) Inspect any third-party code that starts its own loop
• The trace shows the transcription synchronizer _rotate_segment_task as the pending task. Ensure any audio/transcription helpers are started from your entrypoint coroutine (so they use the job loop) rather than in a different loop.
5) Example pattern for entrypoint shutdown-safe tasks
async def entrypoint(ctx: JobContext):
await ctx.connect()
session = AgentSession(...)
await session.start(agent=LocalAgent(), room=ctx.room)
async def shutdown():
# run on same loop
await session.aclose()
ctx.add_shutdown_callback(shutdown)
await ctx.room.wait()
6) SDK/version
• If you’re on an older livekit.agents release, upgrade to the latest — some loop-handling fixes have been made. (If you cannot upgrade, follow steps above.)
If you'd like, share:
• Any places in your code where you call asyncio.run(), create new loops, spawn threads, or start background tasks.
• How you register shutdown callbacks.
I can then point to the exact lines to change and provide a patched entrypoint that guarantees all tasks run on the same loop and cleanly close without that RuntimeError.average-leather-27589
11/27/2025, 7:02 AMtall-airline-16756
11/27/2025, 7:02 AMcurrent_playout_task, pending_request.
• On user-turn detected:
◦ Start generation async and store its Future in pending_request.
◦ Do NOT immediately interrupt playback.
• When generation finishes:
◦ If current_playout_task is still playing, cancel/stop it and immediately start the new TTS.
◦ If not playing, just play the new TTS.
• Use allow_interruptions=True for generation if you want the new reply itself to be interruptible later.
Example flow (pseudo-Python)
# on user speech detected:
pending = asyncio.create_task(session.generate_reply(...))
# playout handling
if current_playout_task and not current_playout_task.done():
# keep playing until pending completes OR decide to cut in
done, _ = await asyncio.wait({pending, current_playout_task}, return_when=asyncio.FIRST_COMPLETED)
if pending in done:
# new reply ready — stop current playout and play new reply
await stop_current_playout()
await play_reply_from(pending.result())
else:
# current finished first — then play pending result when ready
await pending # wait and then play
else:
await pending
await play_reply_from(pending.result())
Frontend coordination
• Use a lightweight RPC/data message to:
◦ Notify client to stop current audio and start new TTS immediately when server decides to cut in.
◦ Notify client when agent is still “finishing” so UI shows appropriate state.
Tuning tips
• Thresholds: only cut in if new reply is ready within X seconds (e.g., 1–2s) to avoid frequent abrupt cuts.
• Silence window: when cutting, insert 50–150ms silence to reduce jarring transitions.
• UX indicators: show “listening” or “processing” states so users know their interruption was heard.
Trade-offs specific to realtime LLMs / TTS
• With realtime LLMs, partial generation/streaming may allow you to start playing the new reply faster; but model internal buffering can complicate precise timing.
• Cancelling TTS mid-utterance is supported but may produce clipped audio; a quick ramp-down or crossfade helps.
If you want, I can:
• Provide a complete code example for your entrypoint/session (server-side) that implements this exact queuing + cut-in behavior, or
• Suggest exact RPC/data messages and client-side handlers for your frontend to coordinate stop/play actions.
Which would you like?average-leather-27589
11/27/2025, 7:31 AMtall-airline-16756
11/27/2025, 7:31 AMinterrupt() or cancel generation when playback finishes.
3) Ensure you don't wait for a redundant "playback finished" before starting the next utterance
• If server waits for a client-side playback-finished ack before starting new speech, network/jitter can add seconds. Consider:
◦ Start playing immediately when generation is ready.
◦ Use a short timeout for waiting for playback-finished events (e.g., 500–1000ms) and proceed if not received.
4) Avoid unnecessary serialization between model -> TTS -> play
• If you have steps like "generate -> wait for full audio file -> upload -> wait for client ack -> play", try streaming or early handoff:
◦ Start TTS streaming as tokens arrive (if supported) or
◦ Upload/play immediately after TTS finished generation without extra RPCs.
5) Check Simli playout latency
• Measure time between your server issuing the Simli play command and receiving "playback started" on the client. If Simli playback startup is slow, you may need to pre-warm voices or reduce clip processing.
6) Concurrency and cancellation handling
• Make sure you don't cancel the model response because of an unrelated playback event. Use clear state: current_generation_task, current_playout_task, pending_generation_task and only cancel when intended.
7) Add diagnostic logging
• Log timestamps for:
◦ model generation start and finish (TTFT)
◦ server-side TTS/send-to-Simli call
◦ Simli playback start and playback finished events
This will show where the gap is.
8) Quick mitigations
• If cancellations are common, avoid cancelling in-flight generations unless a user explicitly interrupts.
• Use short client-side timeouts for playback ACK and proceed after timeout.
• If using realtime LLM, recreate session per connection to avoid hidden buffering issues.
If you want, share:
• The code path that handles model result -> TTS -> play (server-side),
• The log lines with timestamps for generation finish and when you call Simli play.
I’ll point to the exact spot to reduce the 3–4s gap.average-leather-27589
11/27/2025, 7:32 AMtall-airline-16756
11/27/2025, 7:33 AMimport time, logging
logging.info("gen:start %s", time.time())
resp = await session.generate_reply(...) # or await model call
logging.info("gen:done %s ttft=%s", time.time(), resp.metrics.get("ttft"))
2) Log when you convert/generate TTS and when you hand off to Simli
• Immediately before and after any TTS call or audio upload.
logging.info("tts:start %s", time.time())
# call TTS or send audio to Simli
logging.info("tts:done %s", time.time())
3) Log the exact time you call Simli play and when you receive Simli playback-start/finished events
• On server: log when issuing the play RPC/command.
logging.info("simli:play_cmd_sent %s", time.time())
await room.local_participant.perform_rpc("play_clip", {"id": clip_id})
• On frontend (or server if Simli sends play events): log onplay and onended with timestamps.
4) Capture and log cancellation events from the realtime model
• Where you detect a cancelled response, log it with time and context.
logging.warning("model:cancelled %s resp_id=%s", time.time(), event_id)
5) Measure client-network latency for RPCs (round-trip)
• Send a ping RPC from server to client and back; measure RTT.
# server
t0 = time.time()
await room.local_participant.perform_rpc("ping", {"ts": t0})
# client replies immediately; server logs reply time and RTT
6) Inspect playback-finished wait logic
• If server waits for a playback-finished ack before starting next TTS, add a timeout and log wait duration.
start_wait = time.time()
try:
await wait_for_playback_finished(timeout=0.8)
except TimeoutError:
logging.warning("playback ack timeout %s", time.time()-start_wait)
7) Add coarse end-to-end timing on frontend
• When user finishes speaking, mark t_user_end. When audio starts playing from agent, log t_play_start. That shows total end-to-start delay:
◦ t_play_start - t_user_end = perceived latency.
8) Check for cancellations or double-generation logic
• Search code paths for interrupt(), cancel(), or places you call .cancel() on generation/stream tasks. Log when you invoke them and why.
9) Verify Simli playout overhead
• Measure time between server issuing play and client onplay. If large, issue may be Simli or network.
• If Simli requires preparing audio, log TTS upload / processing time.
10) Run one recorded test and inspect logs
• Perform a single interaction and collect logs:
◦ model start/finish times
◦ tts start/finish times
◦ simli play command time
◦ client onplay time
◦ any "cancelled" events
• Create a timeline from those timestamps to see the slow stage.
If you share a short snippet of the code that handles: model result → TTS generation/upload → Simli play command (server), plus where you handle playback-finished acks (server or client), I’ll mark exactly where to add these logs and interpret the results for you.average-leather-27589
11/27/2025, 9:09 AMtall-airline-16756
11/27/2025, 9:10 AMTTSMetrics.ttfb (time to first byte) — predicts when avatar starts speaking
◦ TTSMetrics.audio_duration — expected animation length
• LLM metrics
◦ LLMMetrics.ttft (time to first token)
◦ token counts, tokens/sec — model performance and cost indicators
• EO U / speech timing
◦ EOUMetrics.end_of_utterance_delay — how long after user stops before processing
• Playback / avatar events
◦ playback started / finished timestamps from Simli (to measure playout latency and sync)
• Session traces & state
◦ agent_state_changed (listening → thinking → speaking)
◦ conversation turn timestamps
• Usage/cost
◦ aggregate input/output tokens and durations for billing/optimization
How to enable observability
• Enable Agent Observability in LiveKit Cloud (project settings → Data and privacy → Agent observability).
• In your entrypoint, set recording/observability options (record=True) so metrics/traces are emitted.
Example: capture metrics via the session event hook
from livekit.agents import metrics, MetricsCollectedEvent
@session.on("metrics_collected")
def on_metrics(ev: MetricsCollectedEvent):
m = ev.metrics
if isinstance(m, metrics.TTSMetrics):
logger.info("tts ttfb=%s audio_ms=%s", m.ttfb, m.audio_duration)
elif isinstance(m, metrics.LLMMetrics):
logger.info("llm ttft=%s tokens=%s tps=%s", m.ttft, m.total_tokens, m.tokens_per_second)
elif isinstance(m, metrics.EOUMetrics):
logger.info("eou delay=%s", m.end_of_utterance_delay)
Aggregate usage and build summaries
from livekit.agents.metrics import UsageCollector
uc = UsageCollector()
@session.on("metrics_collected")
def collect(ev: MetricsCollectedEvent):
uc.collect(ev.metrics)
# at session end
summary = uc.get_summary()
logger.info("usage summary: %s", summary)
Instrument playback and avatar timings
• Log when you call Simli play and when you receive playback start/finished events (server or client) to measure handoff latency.
• Correlate TTSMetrics.ttfb with Simli playback start to spot gaps between TTS completion and avatar play.
Practical tips
• Add timestamps at these points: model generation start/finish, TTS start/finish, Simli play command, Simli onplay. This gives an end-to-end timeline.
• Watch for LLMMetrics with ttft = -1 or event_response_status = "cancelled" — these indicate cancelled/incomplete responses that can delay subsequent play.
• Use short server-side timeouts for playback-finished waits so lost ACKs don’t stall the next turn.
• If you need cost tracking, aggregate token counts and TTS audio durations per session with UsageCollector.
If you want, I can:
• Provide a full instrumented entrypoint example that wires these hooks and emits structured logs (JSON) for ingestion into your monitoring system, or
• Suggest specific dashboards/queries (Prometheus/Grafana/ELK) for the metrics above.
Which would you like me to provide?
Sources: Observability data hooks | LiveKit docs