Original order: 1. Line 283/316: avatar_session.st...
# ask-ai
e
Original order: 1. Line 283/316: avatar_session.start() — room not connected 2. Line 919: session.start() — room still not connected 3. Line 933: ctx.connect() — room connects last This caused: • Avatar trying to use ctx.room before it was connected • _clear_buffer_task RPC operations failing with "engine is closed" • Race condition where sometimes it worked (if connection happened fast enough)
t
Thanks for reaching out, Guess. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — this diagnosis is correct. Regarding the three lines you listed, the room must be connected before starting sessions that use it. Call order should be: 1. await ctx.connect() — ensure
ctx.room
and the underlying engine are initialized 2. await avatar_session.start(session, room=ctx.room) — start avatar after connection 3. await session.start(room=ctx.room, ...) — then start the agent session If you start
avatar_session
or
session
before
ctx.connect()
, operations that use the room (RPCs,
_clear_buffer_task
, local participant access) can fail with "engine is closed" or race conditions where it only works sometimes. If you'd like, tell me which SDK/language you're using and I can provide a short code snippet showing the correct sequence and a simple readiness check you can add to guard against this. Sources: Job lifecycle | LiveKit docs | Remote method calls | LiveKit docs
e
what is the issue can youe xplain more and whats the proper way
t
You're seeing a race between connecting to the LiveKit room and starting sessions that need that connection. Here's a plain explanation and the correct, safe sequence. What the issue is (simple): •
ctx.connect()
establishes the room connection and initializes the underlying engine (signaling + WebRTC). •
avatar_session.start()
and
session.start()
try to use
ctx.room
and the engine (e.g., register RPCs, access localParticipant, send data). • If you call those starts before
ctx.connect()
finishes, they run against a not-yet-initialized or closed engine, causing errors like "engine is closed" and failing RPC tasks (e.g.,
_clear_buffer_task
). Sometimes it works when the connection completes quickly — that’s the race condition. Why that fails (short tech reason): • Starting sessions triggers actions that require an active signaling channel and peer connection. Without a connected room those actions either no-op or attempt to use closed resources, leading to unpredictable failures. Proper way (order and checks): 1. await ctx.connect() — wait until the room is connected and
ctx.room
is ready. 2. await avatar_session.start(session, room=ctx.room) — avatar uses the connected room. 3. await session.start(room=ctx.room, ...) — start the agent session after the room is ready. Extra safety (optional): • After
ctx.connect()
, check
ctx.room
and
ctx.room.state
or a provided readiness flag before starting sessions. • Add try/catch around session starts and retry once if a transient timing error occurs. If you tell me which SDK/language you’re using, I’ll give a brief example code snippet showing the correct sequence and a simple readiness check.
e
the issue happening is tts is speaking wothout avatar i can see
and i cans ee after some time
t
You're right to suspect this is the same race condition — TTS plays before the avatar is started/connected, so you hear speech while the avatar UI or avatar session isn't ready. What’s happening (short): • TTS playback is triggered by session/avatar actions that assume the room and avatar are ready. • Because
ctx.connect()
completed after `avatar_session.start()`/`session.start()`, the avatar session never fully initialized or the avatar UI wasn't attached, but TTS (which may run locally or via an RPC) still ran. • Result: audio plays but the avatar is not visible or not receiving the events that drive lip sync/animations. What to do next (practical fixes): 1. Ensure connection first: ◦ Call and await
ctx.connect()
before starting avatar/session or triggering TTS. 1. Start avatar only after room is ready: ◦
await ctx.connect()
→
await avatar_session.start(session, room=ctx.room)
→
await session.start(room=ctx.room, ...)
1. Gate TTS on avatar readiness: ◦ Only trigger TTS after the avatar session reports it is started/ready (add an explicit
await avatar_session.ready()
or check
avatar_session.is_started
/
ctx.room
state). 1. Add small retries/timeouts: ◦ If readiness checks are not available, add a short wait + check loop with a retry for up to a few seconds before playing TTS. 1. Add logging: ◦ Log connection state, avatar start success, and TTS triggers to verify ordering and find gaps. What I need to give a concrete snippet: • Which SDK/language are you using (JavaScript, Python, TypeScript, etc.)? • How do you trigger TTS today (local browser API, server-side RPC, LiveKit data messages)? • Any errors or logs when the avatar fails to appear? Tell me those and I’ll provide a minimal code example that ensures avatar is visible before TTS plays.
You're seeing TTS play before the avatar is ready because the avatar session and room connection aren't guaranteed to be established before speech starts. In short: the TTS playback uses audio/output immediately, while the avatar (which depends on the connected room and local participant) is still connecting — a race. What to do (short, actionable): 1. Ensure the room is connected first: ◦ Call and await
ctx.connect()
and confirm
ctx.room
is ready. 1. Start the avatar session only after connection: ◦ Await
avatar_session.start(session, room=ctx.room)
and verify the avatar is initialized/visible. 1. Only then trigger TTS playback: ◦ Delay or enqueue the TTS until the avatar reports ready (visibility or a “ready” event). 1. Add guards and retries: ◦ After starting avatar, poll or listen for a readiness flag (e.g.,
avatar.ready
,
room.state === "connected"
, or a callback/event your SDK exposes). If not ready within a timeout, retry starting the avatar or delay TTS. Example checks to add: • Wait for
ctx.room
and
localParticipant
to exist. • Wait for avatar renderer/display layer to report visible/initialized. • Wrap TTS start in a try/retry with a short backoff if it fails due to connection timing. If you tell me which SDK and language you’re using, I’ll provide a brief code snippet showing the safe sequence and a simple readiness check you can plug in.
e
short code example
t
Below is a short JavaScript/TypeScript example that shows the safe sequence: connect the room, start the avatar session, wait for the avatar to be ready, then trigger TTS. Adapt names to your code if they differ.
Copy code
// async function where you set up and start everything
async function startAndSpeak(ctx, avatarSession, agentSession, ttsSpeak) {
  // 1) connect room
  await ctx.connect();

  // ensure room exists and is connected
  if (!ctx.room || ctx.room.state !== 'connected') {
    throw new Error('Room failed to connect');
  }

  // 2) start avatar session (uses connected room)
  await avatarSession.start(agentSession, { room: ctx.room });

  // 3) wait for avatar to be visible/ready
  // Replace `avatarSession.isReady()` with your SDK's readiness check/event
  const waitForAvatarReady = (timeoutMs = 5000) => {
    return new Promise<void>((resolve, reject) => {
      const timeout = setTimeout(() => reject(new Error('Avatar ready timeout')), timeoutMs);

      const check = () => {
        if (avatarSession.ready === true) { // or avatarSession.isReady()
          clearTimeout(timeout);
          resolve();
        } else {
          setTimeout(check, 100);
        }
      };
      check();
    });
  };

  await waitForAvatarReady();

  // 4) start agent session if needed
  await agentSession.start({ room: ctx.room });

  // 5) trigger TTS only after avatar is ready
  await ttsSpeak('Hello — avatar is ready');
}
If you tell me the exact SDK/language and the avatar readiness API your code exposes (e.g.,
avatarSession.ready
,
on('ready')
, or similar), I can tailor the snippet to match it precisely.
e
i want i python
t
Below is a short Python example showing the correct sequence: connect the room, start the avatar session, wait for avatar readiness, then trigger TTS. Replace readiness checks with your SDK’s actual properties/events.
Copy code
import asyncio

async def wait_for_avatar_ready(avatar_session, timeout=5.0):
    end = asyncio.get_event_loop().time() + timeout
    while asyncio.get_event_loop().time() < end:
        # replace `.ready` with your SDK's readiness flag or event check
        if getattr(avatar_session, "ready", False):
            return True
        await asyncio.sleep(0.1)
    raise TimeoutError("Avatar ready timeout")

async def start_and_speak(ctx, avatar_session, agent_session, tts_speak):
    # 1) connect room
    await ctx.connect()

    # optional sanity check
    if not getattr(ctx, "room", None) or getattr(ctx.room, "state", None) != "connected":
        raise RuntimeError("Room failed to connect")

    # 2) start avatar session (uses connected room)
    await avatar_session.start(agent_session, room=ctx.room)

    # 3) wait for avatar to be ready/visible
    await wait_for_avatar_ready(avatar_session, timeout=5.0)

    # 4) start agent session if needed
    await agent_session.start(room=ctx.room)

    # 5) trigger TTS only after avatar is ready
    await tts_speak("Hello — avatar is ready")
Tell me the names of the actual readiness property/event your avatar session exposes (for example
avatar_session.ready
or
avatar_session.on_ready(callback)
), and I’ll adapt this snippet precisely.
e
avatar_session.ready
will we get this??
t
Short answer:
avatar_session.ready
is not a guaranteed documented property. Use the fact that
await avatar_session.start(...)
is awaitable — awaiting it ensures the avatar worker has joined the room and is ready. Start TTS only after that await completes. Concise Python example (uses
await avatar.start(...)
as readiness):
Copy code
import asyncio

async def start_and_speak(ctx, avatar_session, agent_session, tts_speak):
    # 1) connect room
    await ctx.connect()

    # 2) start avatar session and await join (this is the readiness)
    await avatar_session.start(agent_session, room=ctx.room)

    # 3) start agent session (audio sent to avatar)
    await agent_session.start(room=ctx.room, room_output_options=RoomOutputOptions(audio_enabled=False))

    # 4) now safe to trigger TTS
    await tts_speak("Hello — avatar is ready")
If your SDK actually provides a
ready
flag or an
on_ready
event, you can use that after
start()
for extra confirmation; otherwise relying on the awaitable
start()
is correct. Would you like me to adapt this to your exact session/class names? Sources: Agents v0.x migration guide - Node.js | LiveKit Docs | Virtual avatar plugins | LiveKit Docs | Beyond Presence virtual avatar integration guide | LiveKit Docs | Hedra Realtime Avatar integration guide | LiveKit docs | Tavus virtual avatar integration guide | LiveKit docs
e
avatar_session.ready - this property will we get from sdk directly or do we need to add anything in sdk
t
Short answer: the SDK does not guarantee an
avatar_session.ready
property. Awaiting
avatar_session.start(...)
is the built-in readiness signal —
start()
completes after the avatar worker has joined the room. If you want an explicit
ready
flag or event, add it in your app (no SDK change required). Two simple options: • Wrapper flag
Copy code
avatar_session._ready = False
await avatar_session.start(session, room=ctx.room)
avatar_session._ready = True
• Event/callback
Copy code
# set up a future or callback the app resolves when start() finishes
avatar_ready = asyncio.Event()
async def start_avatar():
    await avatar_session.start(session, room=ctx.room)
    avatar_ready.set()
asyncio.create_task(start_avatar())
await avatar_ready.wait()
Want me to adapt one of these patterns to your exact classes/names?
e
do o need toa dd of fe sdk or bE
t
You do not need to change the SDK or the frontend. Awaiting
avatar_session.start(...)
is the built-in readiness signal — once that await completes the avatar worker has joined the room. If you want an explicit flag/event in your app, add it in your code (no SDK modification required). Two minimal options: • Simple flag
Copy code
avatar_session._ready = False
await avatar_session.start(session, room=ctx.room)
avatar_session._ready = True
# later: if avatar_session._ready: trigger TTS
• asyncio.Event (recommended for async flows)
Copy code
avatar_ready = asyncio.Event()

async def start_avatar():
    await avatar_session.start(session, room=ctx.room)
    avatar_ready.set()

asyncio.create_task(start_avatar())
await avatar_ready.wait()
# now trigger TTS
Would you like this wired into your exact function names and flow?
e
From the logs: the avatar readiness check is timing out. The warning appears, but we don't see the "⏳ Waiting for avatar..." log, which suggests the wait logic may not be running or the ready property isn't working as expected.
t
You're correct to flag the timeout — here's what's happening and what I need to diagnose it. What’s happening • The SDK does not guarantee an
avatar_session.ready
property. Awaiting
await avatar_session.start(...)
is the built‑in readiness signal — when that await completes the avatar worker has joined the room. • Your "⏳ Waiting for avatar..." log not appearing suggests the wait code path either isn't being executed or
avatar_session.start()
returned (or raised) before the wait logic ran, so your timeout triggers later. • Common causes: the wait logic is placed in the wrong spot (before/after start), the wait uses a property that doesn't exist or never becomes true, exceptions from
start()
are swallowed, or your log statement is behind a branch that isn't reached. What to check / quick fixes 1. Ensure ordering: ◦
await ctx.connect()
◦
await avatar_session.start(agent_session, room=ctx.room)
<-- this is the readiness gate ◦ then any explicit wait/log and
await agent_session.start(...)
1. If you implement a wait after
start()
, use an asyncio.Event or set a flag immediately after
await avatar_session.start(...)
(no SDK change required). 2. Make sure exceptions from
avatar_session.start()
are surfaced (don’t catch and ignore them). 3. Add a short immediate log right after
await avatar_session.start(...)
to confirm it completed: ◦ "avatar.start() completed" then "⏳ Waiting for avatar..." if you still need an extra check. What I need from you to help further • Paste the small code snippet around where you call
ctx.connect()
,
avatar_session.start(...)
, your wait logic, and the logs. I’ll point out exactly why the "Waiting…" log isn’t running and propose a minimal fix. Sources: bitHuman virtual avatar integration guide | LiveKit Docs | Tavus virtual avatar integration guide | LiveKit docs | Hedra Realtime Avatar integration guide | LiveKit docs | LiveAvatar virtual avatar integration guide | LiveKit docs | Simli virtual avatar integration guide | LiveKit docs
e
Code snippets 1. Room connection (Lines 1378-1385) # ✅ CRITICAL FIX: Connect to room FIRST before starting session logger.info("🔌 Connecting to room BEFORE starting session to ensure event handlers are active") await ctx.connect() # ← Line 1384: Room connects logger.info("✅ Room connected - event handlers are now active and listening") 2. Session start (Lines 1393-1402) # Start the session with the interview agent await session.start( # ← Line 1394: Session starts agent=interview_agent, room=ctx.room, _room_input_options_=RoomInputOptions( _noise_cancellation_=noise_cancellation.BVC(), _close_on_disconnect_=False, ), ) 3. Avatar initialization (Lines 1404-1468) # ✅ CRITICAL: Initialize avatar AFTER room is connected and session is started if avatar_enabled and avatar_id: logger.info(f"🎭 Starting avatar session (room connected, session started)") # ... provider selection ... avatar_session = anam.AvatarSession(...) # ← Line 1457: Avatar created # Start the avatar and wait for it to join await avatar_session.start(session, room=ctx.room) # ← Line 1466: Avatar starts logger.info(f"✅ Anam avatar started - ready={getattr(avatar_session, 'ready', 'N/A')}") 4. Greeting wait logic (Lines 668-712) @ctx.room.on("participant_connected") def on_participant_connected(_participant_: rtc.RemoteParticipant): # ... participant handling ... if not is_bot and not greet_sent: greet_sent = True async def _send_greeting(): nonlocal avatar_session # ✅ FIXED: Access outer scope _try_: # Debug log logger.info(f"🔍 Greeting check: avatar_enabled={avatar_enabled}, avatar_id={avatar_id}, avatar_session={avatar_session is not None}") if avatar_enabled and avatar_id: # ← Line 676: Condition check max_wait = 15 wait_interval = 0.1 waited = 0 logger.info("⏳ Waiting for avatar to be ready before greeting...") # ← Line 680: THIS LOG IS MISSING! _# Step 1: Wait for avatar_session creation_ while avatar_session is None and waited < max_wait: await asyncio.sleep(wait_interval) waited += wait_interval # Step 2: Wait for avatar ready if avatar_session is not None: while not getattr(avatar_session, "ready", False) and waited < max_wait: await asyncio.sleep(wait_interval) waited += wait_interval if getattr(avatar_session, "ready", False): logger.info(f"✅ Avatar ready after {waited:.1f}s") _else_: logger.warning(f"⚠️ Avatar not ready after {max_wait}s - proceeding anyway") # ← This appears in logs! _else_: logger.info(f"ℹ️ Avatar not enabled or no avatar_id - skipping wait") # Send greeting logger.info("📤 Calling generate_reply for greeting...") await session.generate_reply(...) Why "Waiting..." log isn't appearing From your logs: 070637 [WARNING] ⚠️ Avatar not ready after 15s - proceeding anyway ← Line 702 executed 070637 [INFO] 📤 Calling generate_reply for greeting ← Line 711 executed The warning at line 702 appears, but the "⏳ Waiting..." log at line 680 does not. This suggests: 1. The condition if avatar_enabled and avatar_id: is False, so the wait block is skipped. 2. The debug log at line 674 should show this. What to check The debug log at line 674 should appear: 🔍 Greeting check: avatar_enabled=..., avatar_id=..., avatar_session=... If that log is missing, _send_greeting() may not be running. If it appears and shows avatar_enabled=False or avatar_id=None, that explains why the wait block is skipped. Expected flow 1. Participant connects → on_participant_connected() fires 2. greet_sent = True 3. _send_greeting() task created 4. 🔍 Greeting check log (line 674) ← Should appear 5. If avatar_enabled and avatar_id: → ⏳ Waiting... log (line 680) ← Missing in your logs! → Wait loops → ⚠️ Avatar not ready after 15s (line 702) ← This appears! 6. 📤 Calling generate_reply (line 711) ← This appears! The missing "⏳ Waiting..." log suggests the condition at line 676 is False. Check the debug log at line 674 to confirm.
t
Thanks — this is very helpful detail. Quick diagnosis and concrete next steps. Why the "⏳ Waiting for avatar..." log is missing • That log is inside the branch guarded by
if avatar_enabled and avatar_id:
. The missing log plus the warning ("Avatar not ready after 15s") strongly suggests that either: a. The
_send_greeting()
coroutine never ran (so none of those logs ran), or b.
_send_greeting()
ran but
avatar_enabled and avatar_id
evaluated to False, so the wait block was skipped and you hit the fallback warning later. What to check right now (small, targeted checks) 1. Confirm
_send_greeting()
runs: ◦ Add an immediate log at the start of
_send_greeting()
(before the debug line) to prove the coroutine executes. 1. Inspect the debug log you already have: ◦ Verify the "🔍 Greeting check: avatar_enabled=..., avatar_id=..., avatar_session=..." log appears and copy its values. 1. If that debug log is missing, ensure the participant-connected handler actually schedules
_send_greeting()
(no swallowing of exceptions, and task created via
asyncio.create_task
or awaited). 2. If the debug log shows
avatar_enabled=True
and a non-empty
avatar_id
but you still don't see "⏳ Waiting...", then confirm the code path ordering — ensure that code runs after
avatar_session
creation/assignment. Short, safe fixes (pick one) • Prefer relying on
await avatar_session.start(...)
as the readiness gate (no
ready
property needed). Move greeting logic to execute only after
avatar_session.start()
completes. • Or make your wait visible and reliable by: a. Setting a flag immediately after avatar start:
avatar_session._ready = True
b. Using an asyncio.Event that you set after start and await in
_send_greeting()
. Minimal example using await (recommended)
Copy code
# after ctx.connect() and session.start(...)
await avatar_session.start(session, room=ctx.room)
logger.info("avatar.start() completed")

# now start greeting (safe — avatar joined)
await send_greeting()  # or create_task if you want concurrency
If you prefer the existing participant-connected flow, add this minimal instrumentation so we can see what’s happening: • At start of `_send_greeting()`: logger.info("ENTER _send_greeting()") • Right after your existing debug: logger.info(f"avatar_enabled={avatar_enabled} avatar_id={avatar_id} avatar_session={avatar_session is not None}") • After entering the wait block: logger.info("⏳ Waiting for avatar to be ready before greeting...") Send me the outputs of those added logs (the three lines above). If you paste them, I’ll point out the exact line that’s failing and give the smallest code change to fix it.
e
The avatar_session.ready property may not be working as expected. Checking for an alternative way to detect avatar readiness:
t
You're right to look for alternatives —
avatar_session.ready
isn't guaranteed. Here are reliable options to detect avatar readiness and a minimal Python pattern you can plug into your flow. Recommended approaches (choose one) • Await start() (best, simplest) ◦
await avatar_session.start(session, room=ctx.room)
completes after the avatar worker joins the room. Treat that as readiness. • Listen for the avatar participant in the room ◦ Use the room participant events and check for the avatar worker participant (identify via
lk.publish_on_behalf
or a known participant identity). Wait until that participant appears and publishes an audio/video track. • Application-level flag / asyncio.Event ◦ Set a flag or
asyncio.Event
immediately after
await avatar_session.start(...)
and await that in other tasks (preferred if your flow creates tasks earlier). Minimal patterns 1) Rely on await avatar.start():
Copy code
# after ctx.connect() and session.start(...)
await avatar_session.start(session, room=ctx.room)
logger.info("avatar.start() completed — avatar is ready")
await tts_speak("Hello — avatar is ready")
2) Use asyncio.Event (non-blocking tasks)
Copy code
avatar_ready = asyncio.Event()

async def start_avatar():
    await avatar_session.start(session, room=ctx.room)
    avatar_ready.set()

asyncio.create_task(start_avatar())

# elsewhere, before TTS
await avatar_ready.wait()
await tts_speak("Hello — avatar is ready")
3) Wait for avatar participant + published tracks
Copy code
# called after ctx.connect()
def is_avatar_participant(p):
    return getattr(p, "lk", {}).get("publish_on_behalf") == "avatar" or p.identity == EXPECTED_ID

async def wait_for_avatar_participant(room, timeout=15.0):
    end = asyncio.get_event_loop().time() + timeout
    while asyncio.get_event_loop().time() < end:
        for p in room.participants.values():
            if is_avatar_participant(p) and any(t.kind == "audio" for t in p.tracks):
                return True
        await asyncio.sleep(0.1)
    return False

ready = await wait_for_avatar_participant(ctx.room)
if ready:
    await tts_speak("Hello — avatar is visible")
else:
    logger.warning("Avatar participant/tracks not found — proceeding anyway")
Debug tips (given your logs) • Log immediately after
avatar_session.start()
completes to prove readiness. • Log at the top of
_send_greeting()
to confirm it runs. • If using the participant-check approach, log participant identities and track kinds when participants connect. If you tell me which approach you prefer, I’ll adapt one of the snippets to your exact function names and the participant identity check you can use to detect the avatar.