async def *session_end_timer*(_session_: AgentSess...
# ask-ai
b
async def *session_end_timer*(_session_: AgentSession, _max_duration_: int) -> None: """End the session when the timer triggers.""" await asyncio.sleep(_max_duration_) logger.info(f"Session end timer triggered at: {get_current_strftime()}") await session.say( text="Time is up. The feedback will be available shortly.", _allow_interruptions_=False, ) await remove_participant(session) how to make sure this session.say is run only after the user finishes speaking?
t
Thanks for reaching out, mateuszkasprowicz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to ensure
session.say
runs only after the user finishes speaking — the simplest, reliable approach is to wait for the user to transition to the "listening" state and only then call
session.say
. Also wait for any agent playout to finish so you don't interrupt an ongoing agent utterance. Suggested pattern:
Copy code
async def session_end_timer(session: AgentSession, max_duration: int) -> None:
    await asyncio.sleep(max_duration)
    logger.info(f"Session end timer triggered at: {get_current_strftime()}")

    # Ensure any agent audio currently playing finishes
    await session.wait_for_playout()

    async def on_user_state_changed(ev: UserStateChangedEvent):
        if ev.new_state == "listening":
            # User finished speaking — safe to speak now
            await session.say(
                text="Time is up. The feedback will be available shortly.",
                allow_interruptions=False,
            )
            await remove_participant(session)
            session.off("user_state_changed", on_user_state_changed)

    # Subscribe to user state changes
    session.on("user_state_changed", on_user_state_changed)

    # If user is already silent, speak immediately
    if session.current_state.user_state == "listening":
        await session.say(
            text="Time is up. The feedback will be available shortly.",
            allow_interruptions=False,
        )
        await remove_participant(session)
        session.off("user_state_changed", on_user_state_changed)
Key points: • Use
user_state_changed
to detect transition to
"listening"
(user finished speaking). • Use
await session.wait_for_playout()
so the agent doesn't interrupt its own audio. • Unsubscribe the event handler after it runs to avoid duplicate calls. Would you like this adjusted to handle short silences (e.g., a debounce) or to support multiple participants? Sources: Events and error handling | LiveKit docs | Agent speech and audio | LiveKit docs | Turn detection and interruptions | LiveKit Docs
b
are there alternativc solutions to this?
t
Yes — besides
user_state_changed
+
wait_for_playout()
, you can use any of these alternatives depending on your UX and control needs: • on_user_turn_completed Put the
session.say
call in
on_user_turn_completed
in your Agent. This hook runs after the user turn is finished, so it’s the most semantically appropriate place for post-turn messages. • user_input_transcribed (final transcript) Listen for
user_input_transcribed
with
is_final == True
. When you receive the final transcript, wait for any current playout (if needed) and then call
session.say
. • generate_reply() Use
generate_reply()
to produce the agent response tied to the user input; it respects turn boundaries and avoids interrupting the user. • Manual / push-to-talk flow Disable automatic audio commit, detect the user’s explicit end-of-turn (button or silence detection), call
session.commit_user_turn()
, then run
session.say
. This gives you full control over timing. • Debounce short silences If you want tolerance for brief pauses, implement a short debounce timer that waits e.g. 300–800 ms of continuous silence (or until
user_state
= "listening" for that duration) before speaking. Which of these fits your use case best — automatic turn-based agents, transcription-based flows, or a manual/push-to-talk UX? I can provide a focused code example for the option you pick. Sources: Pipeline nodes and hooks | LiveKit docs | Events and error handling | LiveKit docs | Turn detection and interruptions | LiveKit Docs
b
how about getting user participant speech handle and adding callback?
t
Yes — you can use the user's speech handle and attach a callback to run
session.say
once that speech handle completes. That lets you react precisely when the participant's current utterance finishes. Suggested pattern:
Copy code
# assume `participant` is the user participant object
speech_handle = participant.current_speech  # or however you access the participant's speech handle

if speech_handle:
    # schedule a callback when the user's speech completes
    async def on_user_speech_done():
        await session.say(
            text="Time is up. The feedback will be available shortly.",
            allow_interruptions=False,
        )
        await remove_participant(session)

    # wait for the handle to finish, then run callback
    # speech_handle may be an awaitable or provide a finished event
    await speech_handle  # if it's awaitable
    await on_user_speech_done()
else:
    # no active speech — safe to speak immediately
    await session.say(
        text="Time is up. The feedback will be available shortly.",
        allow_interruptions=False,
    )
    await remove_participant(session)
Alternatives depending on the handle API: • If
current_speech
is an awaitable (future/task) —
await
it, then call
session.say
. • If it emits an event or has
.on("finished", cb)
— register a callback that performs
session.say
and then unregisters itself. • Combine with a short debounce (300–800 ms) if you want to tolerate brief pauses before declaring the user finished. If you tell me which exact object/method you have access to for the participant speech handle (e.g.,
participant.current_speech
is an awaitable vs an event emitter), I’ll give a precise callback implementation.
b
session.current_speech is only returning speech handle for agent speech or also user?
t
Good question —
session.current_speech
only returns a speech handle for the agent's speech
, not the user's. It represents the agent's currently active/generated audio (or None if the agent isn't speaking). To run
session.say
only after the user finishes speaking, use one of these instead: • Listen for the
user_state_changed
event and trigger when
ev.new_state == "listening"
. • Use the
on_user_turn_completed
lifecycle hook to run post-turn logic. • Listen for
user_input_transcribed
with
is_final == True
if you prefer transcript finality. If you prefer using a participant-level handle, get the user's completion via their turn events or final transcript rather than
session.current_speech
. Want a short code example for any of these approaches? Sources: Agent speech and audio | LiveKit docs | Turn detection and interruptions | LiveKit Docs | External data and RAG | LiveKit Docs