When I entering the room and before the video is s...
# ask-ai
a
When I entering the room and before the video is shown, the agent already speaking, and after I can see the video the first introduction is already over await session.say( "Hi there!")
t
Thanks for reaching out, pui. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I understand you’re seeing the agent start speaking before the video appears and you want the TTS from
session.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:
Copy code
@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
):
Copy code
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 Docs
a
where should i place this code at ? it seems like inside the entrypoint it does not getting called @room.local_participant.register_rpc_method
t
You're right to ask — if the RPC method isn't being called, it's typically a placement or lifecycle issue. A few quick points and a couple of questions so I can give an exact snippet. Where to place the RPC registration (general guidance) • Register the RPC on the server-side after you have the
room
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.
a
i am using python, should i place it at the last line of entrypoint ?
t
You should register the RPC after the server has created/joined the room and the
local_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)
Copy code
# 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.
a
here is the entrypoint
Copy code
async 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,
    # )
t
Thanks — looking at your entrypoint, two issues explain why the RPC isn't called: you register on
room
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:
Copy code
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.
a
is there anyway to refresh all the conversation and restart the conversation like after disconnect and reconnect ?
t
You're already close — the conversation resets automatically when the AgentSession closes on disconnect. To refresh/restart the conversation after a disconnect/reconnect, create a brand-new AgentSession and call
start()
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:
Copy code
@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 Docs
a
is it the only way to do it ? can i somehow reset all the conversation and state ?
t
You can do more than just recreate the session — recreating is the simplest and most reliable way to fully clear everything, but you can also programmatically reset parts of an active session if you need an in-place restart. Short summary of options (choose one based on your need): • Recreate the session (recommended for full reset) ◦ Create a new
AgentSession
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:
Copy code
from livekit.agents import ChatContext
    await session.agent.update_chat_ctx(ChatContext())
• Reset custom session state:
Copy code
session.userdata = {}  # or a fresh object
• Update instructions/tools:
Copy code
await session.update_instructions("New instructions")
    await session.update_tools([])  # clear tools if applicable
• Interrupt ongoing processing:
Copy code
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 docs
a
for simli what is the longest time i can talk ? it disconnected after few minutes
t
Short answer: there’s no documented hard limit for continuous talk time in the Simli avatar integration. Disconnections after a few minutes are usually caused by network/room timeouts, agent process termination, or service-side idle limits — not a published Simli “max talk” value. What you can check next: • Share the disconnection reason from your LiveKit logs (e.g., DISCONNECTED, ICE_FAILED, ROOM_CLOSED). • Confirm the agent process stayed running and didn’t crash or restart. • Check for network/ICE interruptions on the client side (browser/mobile) during the call. • If you set a Simli config like
max_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 AWS
a
Copy code
agent-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"}
t
Thanks — the logs are helpful. They show two things: • The agent session closed because the participant disconnected: "closing agent session due to participant disconnect (disable via
RoomInputOptions.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):
Copy code
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:
Copy code
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:
Copy code
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?
a
It seems like when i am using openai realtime model, after I disconnect and leave the room which reset it, and i connect second time, it starts with english then sometimes will speak the previous user language like malay why does this happen ?
t
You're seeing residual language because the realtime model can retain internal conversational context unless you fully reset it. This explains why, after reconnecting, it sometimes falls back to a previous user's language (Malay) even though you expect English. What you can do (pick one): • Full reset (recommended) ◦ Recreate the
AgentSession
and
Agent
on reconnect so the model and chat history are fresh:
Copy code
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:
Copy code
from livekit.agents import ChatContext
    await session.agent.update_chat_ctx(ChatContext())
• Update instructions to force English:
Copy code
await session.update_instructions("Speak only in English.")
• Interrupt any ongoing processing:
Copy code
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.
a
I have code like this where should i add so that it wont keep track the old history from liveapi
Copy code
async 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))
t
You're close — to avoid carrying old LiveAPI/realtime-model history, clear the agent's chat context or recreate the AgentSession before you call
generate_reply
. Put the reset right after
await session.start(...)
and before any generation. Two options (pick one): 1) Clear chat context in-place (quick)
Copy code
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)
Copy code
# 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?
a
is it because i am connecting my same api key, so even i think i am creating a new session the openai still have the same connection or session in the cloud ?
t
Good question — using the same API key does NOT by itself force OpenAI to reuse prior conversation state. The realtime model can retain internal context across calls if the same model/process is reused, but that persistence is at the model/session instance level (your running AgentSession / RealtimeModel), not the API key. What causes the behavior you saw • Realtime models may keep internal context while your AgentSession or the RealtimeModel instance remains active. If you reuse the same session or model instance, language cues from a previous conversation can carry over. • Recreating the AgentSession (and the RealtimeModel instance) ensures the model has no leftover internal state. • Simply using the same API key is normal and expected — API keys authenticate you but don’t force cross-session memory. How to guarantee a fresh conversation • Recommended (full isolation): create a new AgentSession and new RealtimeModel instance on each reconnect:
Copy code
session = 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:
Copy code
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?
a
in my code am i not creating a new agent ? async 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))
t
You are creating a new
AgentSession
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:
Copy code
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):
Copy code
# 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?
a
I have tried to clear it with code below, but seems like it sometimes still will speak previous communication language session._chat_ctx = ChatContext.empty()
t
You're on the right track — assigning to
session._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):
Copy code
# 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(...)
.
Copy code
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:
Copy code
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.
a
AgentSession' object has no attribute 'update_instructions
t
You're correct —
AgentSession
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(...)
):
Copy code
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:
Copy code
# 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:
Copy code
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 Docs
a
OpenAI Realtime API returned an error", "error": "RealtimeError(message='Audio content of 2550ms is already shorter than 8599ms', type='invalid_request_error', code='invalid_value', event_id=None, param=None
t
That error means the Realtime API was asked to process audio of a longer duration than the audio you actually sent — e.g., you requested/announced ~8599ms but the audio payload contained only 2550ms. Common causes and fixes: • Cause: chunking/timestamps mismatch ◦ Your code is sending audio frames in chunks but the metadata or the RealtimeModel expects a larger duration for that chunk. Verify your chunk-duration calculation and headers you send with each audio packet. • Fix: ensure payload duration >= requested duration ◦ Calculate each audio chunk's actual duration from sample rate and frame count and only call the Realtime send/commit when that duration meets the expected window. ◦ Add a guard to drop or buffer too-short chunks until you have enough samples. • Fix: align encoding/sample-rate ◦ Confirm the sample rate, channels and encoding you declare match the actual audio you send. Mismatched rates change computed durations. • Robustness: catch and recover ◦ Wrap realtime send calls in try/except for RealtimeError; on this error either: ▪︎ buffer more audio and retry the send, or ▪︎ discard the partial chunk and continue, or ▪︎ recreate the RealtimeModel instance if errors persist. • Logging to debug ◦ Log chunk sample count, sample rate, computed duration (ms), and any declared duration you send to the API to find mismatches. If you share the snippet that packages/sends audio to OpenAI (how you compute chunk length, sample rate, and the exact send call), I’ll point out the precise line to fix and provide a patched example. Which code block should I look at?
a
session = AgentSession( llm=openai.realtime.RealtimeModel(voice="sage"), )
t
Thanks — that OpenAI Realtime error means the Realtime API expected more audio than you actually sent for a given chunk (you declared ~8599ms but the payload contained ~2550ms). This is usually caused by buffering/chunking mismatches or leftover audio in the input pipeline, not the single line
session = 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.
Copy code
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:
Copy code
await session.aclose()
• Also unpublish any leftover tracks:
Copy code
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:
Copy code
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:
Copy code
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 docs
a
why when i use the hook from your library useVoiceAssistant the voice agent will never go into thinking state ?
t
You're asking why the voice agent never shows the "thinking" state when using
useVoiceAssistant
. 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 docs
a
2025-11-27 145335,970 - ERROR livekit.agents - Error in _aclose_impl Traceback (most recent call last): File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\agent_session.py", line 743, in _aclose_impl await self._room_io.aclose() File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\room_io\room_io.py", line 289, in aclose await self._tr_synchronizer.aclose() File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\transcription\synchronizer.py", line 441, in aclose await self.barrier() File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\transcription\synchronizer.py", line 495, in barrier await self._rotate_segment_atask RuntimeError: Task <Task pending name='job_shutdown_callback' coro=<JobContext.add_shutdown_callback.<locals>.wrapper() running at C\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site packages\livekit\agents\job.py238> cb=[gather.<locals>._done_callback() at C\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py764]> got Future <Task pending name='Task-264' coro=<TranscriptSynchronizer._rotate_segment_task() running at C\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site packages\livekit\agents\voice\transcription\synchronizer.py472> wait_for=<Future finished result=None>> attached to a different loop 2025-11-27 145336,006 - ERROR livekit.agents - error while shutting down the job Traceback (most recent call last): File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\ipc\job_proc_lazy_main.py", line 298, in _run_job_task await asyncio.gather(*shutdown_tasks) File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\job.py", line 238, in wrapper await callback() # type: ignore ^^^^^^^^^^^^^^^^ File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\agent_session.py", line 743, in _aclose_impl await self._room_io.aclose() File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\room_io\room_io.py", line 289, in aclose await self._tr_synchronizer.aclose() File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\transcription\synchronizer.py", line 441, in aclose await self.barrier() File "C:\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site-packages\livekit\agents\voice\transcription\synchronizer.py", line 495, in barrier await self._rotate_segment_atask RuntimeError: Task <Task pending name='job_shutdown_callback' coro=<JobContext.add_shutdown_callback.<locals>.wrapper() running at C\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site packages\livekit\agents\job.py238> cb=[gather.<locals>._done_callback() at C\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py764]> got Future <Task pending name='Task-264' coro=<TranscriptSynchronizer._rotate_segment_task() running at C\Users\Desktop\AppData\Local\Programs\Python\Python311\Lib\site packages\livekit\agents\voice\transcription\synchronizer.py472> wait_for=<Future finished result=None>> attached to a different loop
t
You're hitting an asyncio loop-mismatch during shutdown: a task the job shutdown callback is awaiting has an inner Task/Future that was created on a different event loop, so awaiting it raises "got Future ... attached to a different loop." This happens when async work is spawned on a loop that isn't the JobContext's loop (common causes: creating a new loop via asyncio.new_event_loop/asyncio.run, running blocking threads that create tasks on other loops, or scheduling background tasks outside the job's loop). What to check and fix (concrete): 1) Ensure all async tasks use the same loop • Do not call
asyncio.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:
Copy code
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
Copy code
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.
a
is there anyway to allow interruption but before the ai have the answer it will keep continue talking first, then switch to new message once ready ? is this a good way
t
You can do this — it’s a common UX pattern — and there are two main ways to implement it. I’ll explain the behavior, trade-offs, and a concise implementation approach you can use with LiveKit agents. Behavior you want • Allow the user to interrupt (their audio/stt is captured and processed). • Let the agent finish the current utterance immediately. • Once a new reply is ready, stop the current playback (if still playing) and switch to the new reply. Is it a good idea? • Pros: feels responsive (user intent is captured immediately) while keeping speech coherent (agent doesn’t cut mid-sentence unless needed). • Cons: complexity (coordination between playback and generation), possible awkwardness if the agent’s finished sentence contradicts the new intent. Requires careful UX tuning (timers, thresholds). How to implement (recommended pattern) 1. Always permit interruptions at the STT/agent level so user input is captured immediately. 2. When user speech arrives, queue the new generation request instead of aborting current playback immediately. 3. Let the TTS/playout continue until either: ◦ the agent finishes speaking naturally, then play the queued reply; OR ◦ the new reply is ready and you decide to cut in — stop current TTS and play the new reply. 1. Provide a small crossfade or very short silence to avoid jarring cuts. Implementation sketch (server-side logic) • Maintain per-session state:
current_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)
Copy code
# 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?
a
i am using livekit with ai avatar from simli and live chatgpt ai model sometimes the respond seems slow after 4 seconds only start to speak although i checked the logs seems like ok for the ttft 2025-11-27 145947,787 - INFO livekit.agents - RealtimeModel metrics {"model_name": "gpt-realtime", "model_provider": "api.openai.com", "ttft": 0.64, "input_tokens": 3746, "cached_input_tokens": 3584, "output_tokens": 104, "total_tokens": 3850, "tokens_per_second": 59.0} 2025-11-27 145951,021 - INFO livekit.agents - playback finished event received {"caller_identity": "simli-avatar-agent"} 2025-11-27 145956,612 - INFO livekit.agents - RealtimeModel metrics {"model_name": "gpt-realtime", "model_provider": "api.openai.com", "ttft": -1.0, "input_tokens": 0, "cached_input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "tokens_per_second": 0.0} 2025-11-27 145956,612 - DEBUG livekit.plugins.openai - OpenAI Realtime API response done but not complete with status: cancelled {"event_id": "resp_CgQGwzhuF2YJCHOV734OK", "event_response_status": "cancelled"} 2025-11-27 150002,648 - INFO livekit.agents - RealtimeModel metrics {"model_name": "gpt-realtime", "model_provider": "api.openai.com", "ttft": 0.49, "input_tokens": 3841, "cached_input_tokens": 3648, "output_tokens": 161, "total_tokens": 4002, "tokens_per_second": 93.51} 2025-11-27 150007,978 - INFO livekit.agents - playback finished event received {"caller_identity": "simli-avatar-agent"} 2025-11-27 150014,287 - INFO livekit.agents - RealtimeModel metrics {"model_name": "gpt-realtime", "model_provider": "api.openai.com", "ttft": 0.65, "input_tokens": 3942, "cached_input_tokens": 3712, "output_tokens": 106, "total_tokens": 4048, "tokens_per_second": 72.66}
t
You're seeing delays between model readiness and actual playback start. Logs show low TTFT (0.49–0.65s) but playback events and a "cancelled" realtime response in between — that points to orchestration/hand-off delays rather than model latency. Concrete things to check and try: 1) Confirm playback pipeline timing • Ensure the TTS/Simli playout starts immediately when the model finishes. Check where you wait for the model response, then where you call the Simli/TTS play API; add logging timestamps at both points. 2) Investigate the "cancelled" response • The log "OpenAI Realtime API response done but not complete with status: cancelled" means a generation was cancelled mid-stream. Cancels can delay the next successful response if the system waits for cleanup. Look for places that call
interrupt()
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.
a
how do I even check each of this ?
t
Good — here's a focused, actionable checklist with small code snippets you can add to pinpoint where the 3–4s gap happens (model → TTS → Simli play). Add these logs and checks in your server and frontend; they’ll show exactly which stage is slow. 1) Add timestamps around model generation • Log when you start/finish generation and include TTFT from metrics.
Copy code
import 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.
Copy code
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.
Copy code
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.
Copy code
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.
Copy code
# 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.
Copy code
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.
a
any metrics can be collected for virtual avatars I am using the plugins Simli
t
Yes — you can collect useful metrics for Simli avatars via the LiveKit Agents observability hooks and standard metrics events. Below are the most relevant metrics to capture, how to enable collection, and short code snippets to log and aggregate them. What to collect (high value) • TTS metrics ◦
TTSMetrics.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
Copy code
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
Copy code
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