is there any state that I can get from livekit tha...
# ask-ai
c
is there any state that I can get from livekit that shows that its listening the users speech?
t
Thanks for reaching out, Babken. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring LiveKit! It has a helpful state called
listening
that shows when it's tuned in to the user's speech. This state comes through the
user_state_changed
event, which is triggered by the Voice Activity Detection (VAD) module as it processes the user's audio input. To give you a clearer picture, here are the possible states you might see: • speaking: This means the VAD has detected that the user has started speaking. • listening: This indicates the VAD has noticed the user has stopped speaking. • away: This shows the user hasn't responded for a while. To keep track of these changes, you can listen for the
user_state_changed
event in your application. If you have any questions or want to chat more about this, I'm here to help! Sources: Events and error handling | LiveKit docs | livekit-agents/livekit/agents/voice/agent_session.py | Agents v0.x migration guide - Python | LiveKit docs
c
so agent can listening user, but user can don't make speech, so I want to catch only the event when agent catch user's speech
t
To help you detect when LiveKit specifically catches user speech, a great way is to keep an eye on the
user_state_changed
event and watch for changes to the
speaking
state. This happens when the Voice Activity Detection (VAD) module notices that the user has started talking. Here's a simple example to guide you:
Copy code
from livekit.agents.voice.events import UserStateChangedEvent, UserState

@session.on("user_state_changed")
def on_user_state_changed(event: UserStateChangedEvent):
    if event.new_state == "speaking":
        # This is fired when LiveKit's VAD detects the user has started speaking
        print("User has started speaking!")
    elif event.new_state == "listening":
        print("User has stopped speaking.")
    elif event.new_state == "away":
        print("User is away (no response for a while).")
This approach makes sure you catch events only when the user is actively speaking, as detected by the VAD. If you have any questions or need further help, feel free to ask! Sources: Events and error handling | LiveKit docs | livekit-agents/livekit/agents/voice/events.py
c
which is the best way use this states on frontend side? how is better way to pass it and handle?
?
t
To effectively manage user states like
speaking
and
listening
on the frontend, here are some friendly best practices you might find helpful: 1. Use Events to Monitor State Changes It’s great to listen for the
user_state_changed
event and handle transitions to the
speaking
or
listening
states. For example:
Copy code
room.on("user_state_changed", (event) => {
  if (event.new_state === "speaking") {
    console.log("User started speaking");
  } else if (event.new_state === "listening") {
    console.log("User stopped speaking");
  }
});
2. Optimize State Handling • Try debouncing rapid state changes to keep things smooth and avoid too many re-renders. • Batch updates for active speakers to help boost performance. 3. Provide Visual Feedback Adding visual indicators like animations or color changes can really enhance the user experience by clearly showing the current state. 4. Synchronize States It’s important to keep the frontend in sync with the real-time user and agent states, maybe by syncing participant attributes or using handy hooks like
useAgent
in React. If you’d like, I’d be happy to share more detailed examples or walk you through how to implement these practices step-by-step. Just let me know!
c
useEffect(() => { if (!room) return room.on(RoomEvent.TranscriptionReceived, updateRawSegments) room.registerTextStreamHandler('lk.transcription', handleCustomTranscriptionsAgent) room.registerTextStreamHandler('lk.transcription.user', handleCustomTranscriptionsUser) room.on(RoomEvent.DataReceived, handleCustomState) room.on("user_state_changed", handleUserSpeakingState) return () => { room.off(RoomEvent.TranscriptionReceived, updateRawSegments) room.off(RoomEvent.DataReceived, handleCustomState) room.unregisterTextStreamHandler('lk.transcription.user') room.unregisterTextStreamHandler('lk.transcription') room.off("user_state_changed", handleUserSpeakingState) } }, [ room, updateRawSegments, handleCustomState, handleCustomTranscriptionsAgent, handleCustomTranscriptionsUser, handleUserSpeakingState ]) nothin works
t
Thanks for reaching out! It looks like the
user_state_changed
event isn’t available in the frontend SDK because it’s designed specifically for LiveKit’s AI Agents system and isn’t supported in the participant-facing frontend code. I know that can be a bit confusing, but don’t worry—we have a good alternative for you. You can use the
RoomEvent.ActiveSpeakersChanged
event to detect when users are actively speaking. Here’s a simple example to help you get started:
Copy code
room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
  console.log('Active speakers:', speakers.map(p => p.identity));
});
Regarding the
RoomEvent.TranscriptionReceived
event, here are a few key things to keep in mind to make sure it works smoothly: • Attach the event listener after the room has connected, like this:
Copy code
await room.connect(url, token);
room.on(RoomEvent.TranscriptionReceived, (segments, participant) => {
  console.log('Transcription received:', segments);
});
• Make sure transcription is enabled on the server side (for example, through an AI Agent or transcription gateway). • Check that audio tracks are being published and participants are actually speaking. • Don’t forget to clean up event listeners properly in your
useEffect
to avoid any unexpected behavior:
Copy code
useEffect(() => {
  const handler = (segments) => { /* handle transcription */ };
  room?.on(RoomEvent.TranscriptionReceived, handler);
  return () => {
    room?.off(RoomEvent.TranscriptionReceived, handler);
  };
}, [room]);
I’m here to help! Would you like me to walk you through debugging these events or assist with setting them up? Sources: complex-agents/teleprompter/teleprompter-frontend/hooks/use-transcriber.ts | Agents v0.x migration guide - Node.js | LiveKit Docs | livekit-rtc/livekit/rtc/room.py | Events and error handling | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs
c
а почему нет ивента как для user_state_changed, он у меня на агенте работает
t
Понимаю, что у вас возник вопрос по событию
user_state_changed
. Оно действительно работает на стороне агента, поскольку предназначено для системы AI Agents LiveKit. В то же время, это событие не доступно в клиентских SDK для фронтенда, так как связано с обработкой состояния пользователя именно на уровне агента. Для фронтенда я рекомендую использовать событие
RoomEvent.ActiveSpeakersChanged
. Оно отлично показывает, кто сейчас активно говорит в комнате. Вот небольшой пример, как это можно использовать:
Copy code
room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
  console.log('Активные участники:', speakers.map(p => p.identity));
});
Если хотите, я с радостью помогу вам разобраться, как настроить похожую функциональность на фронтенде — просто дайте знать!