enough-dentist-75383
12/10/2025, 11:02 AMtall-airline-16756
12/10/2025, 11:02 AMtall-airline-16756
12/10/2025, 11:03 AMctx.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 docsenough-dentist-75383
12/10/2025, 11:04 AMtall-airline-16756
12/10/2025, 11:04 AMctx.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.enough-dentist-75383
12/11/2025, 4:01 AMenough-dentist-75383
12/11/2025, 4:02 AMtall-airline-16756
12/11/2025, 4:02 AMctx.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.tall-airline-16756
12/11/2025, 4:02 AMctx.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.enough-dentist-75383
12/11/2025, 4:03 AMtall-airline-16756
12/11/2025, 4:03 AM// 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.enough-dentist-75383
12/11/2025, 4:04 AMtall-airline-16756
12/11/2025, 4:04 AMimport 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.enough-dentist-75383
12/11/2025, 4:15 AMavatar_session.ready will we get this??tall-airline-16756
12/11/2025, 4:16 AMavatar_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):
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 docsenough-dentist-75383
12/11/2025, 4:21 AMtall-airline-16756
12/11/2025, 4:21 AMavatar_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
avatar_session._ready = False
await avatar_session.start(session, room=ctx.room)
avatar_session._ready = True
• Event/callback
# 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?enough-dentist-75383
12/11/2025, 4:24 AMtall-airline-16756
12/11/2025, 4:24 AMavatar_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
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)
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?enough-dentist-75383
12/11/2025, 7:38 AMtall-airline-16756
12/11/2025, 7:39 AMavatar_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 docsenough-dentist-75383
12/11/2025, 7:53 AMtall-airline-16756
12/11/2025, 7:54 AMif 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)
# 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.enough-dentist-75383
12/11/2025, 8:01 AMtall-airline-16756
12/11/2025, 8:01 AMavatar_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():
# 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)
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
# 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.