Does a VAD standalone provider exist in 0.x liveki...
# ask-ai
s
Does a VAD standalone provider exist in 0.x livekit SDK? Is there an event that gets emitted when the VAD detects that all participants in a room are done talking?
t
Thanks for reaching out, Wolfgang. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Absolutely! The 0.x LiveKit SDK does include a standalone VAD provider. It offers an abstract
VAD
class that you can implement on its own. For instance, you might want to try the Silero VAD implementation like this:
Copy code
from livekit.plugins import silero

vad = silero.VAD.load(
    min_speech_duration=0.1,
    min_silence_duration=0.5,
)
vad_stream = vad.stream()
As for your second question, the VAD system sends out events such as: •
START_OF_SPEECH
- when someone starts talking •
INFERENCE_DONE
- when the VAD finishes its analysis •
END_OF_SPEECH
- when someone stops talking •
METRICS_COLLECTED
- for gathering performance stats The
END_OF_SPEECH
event tells you when an individual participant or stream has stopped speaking. However, there isn’t a built-in event that signals when all participants in a room have finished talking. You’d need to create some custom logic to keep track of everyone and figure out when the whole group is done. Are you thinking about setting up multi-participant turn detection, or do you have a particular scenario in mind where you want to know when everyone has stopped speaking? I’d be happy to help brainstorm! Sources: agents/src/vad.ts | livekit-agents/livekit/agents/voice/agent_activity.py | Working with plugins | LiveKit Docs | Speech-to-text (STT) integrations | LiveKit Docs
s
give me an example of how i would set up VAD for each participant
t
Hey there! If you want to set up VAD for each participant using the LiveKit SDK, the Silero VAD plugin is a great way to go. Let me walk you through an example in Python: 1. Load VAD in Prewarm Function First off, let's load the VAD model just once in your prewarm function to keep things efficient:
Copy code
def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()
2. Create Individual Sessions for Each Participant For every participant, you'll want to create their own
AgentSession
but use the shared VAD instance like this:
Copy code
async def _start_session(self, participant: rtc.RemoteParticipant) -> AgentSession:
    session = AgentSession(
        vad=self.ctx.proc.userdata["vad"],
    )
    room_io = RoomIO(
        agent_session=session,
        room=self.ctx.room,
        participant=participant,
        input_options=RoomInputOptions(
            text_enabled=False,
        ),
        output_options=RoomOutputOptions(
            transcription_enabled=True,
            audio_enabled=False,
        ),
    )
    await room_io.start()
    await session.start(agent=your_agent)
    return session
3. Handle Participant Events To keep things running smoothly, set up event handlers that create and manage sessions as participants join or leave:
Copy code
def on_participant_connected(self, participant: rtc.RemoteParticipant):
    if participant.identity in self._sessions:
        return

    logger.info(f"starting session for {participant.identity}")
    task = asyncio.create_task(self._start_session(participant))
    self._tasks.add(task)

def on_participant_disconnected(self, participant: rtc.RemoteParticipant):
    if (session := self._sessions.pop(participant.identity)) is None:
        return

    logger.info(f"closing session for {participant.identity}")
    task = asyncio.create_task(self._close_session(session))
    self._tasks.add(task)
4. VAD Configuration Options Feel free to tweak the VAD settings to fit your needs. Here's what you can adjust:
Copy code
vad = silero.VAD.load(
    min_speech_duration=0.05,      # Minimum duration of speech to start a new speech chunk
    min_silence_duration=0.4,      # Wait duration before ending speech
    prefix_padding_duration=0.5,   # Padding at the beginning of each speech chunk
    max_buffered_speech=60.0,      # Maximum duration of speech to keep in buffer
    activation_threshold=0.5,      # Threshold to consider a frame as speech
    sample_rate=16000,             # Sample rate (8000 or 16000)
    force_cpu=True                 # Force CPU usage for inference
)
By following this approach, each participant gets their own VAD session, but they all share the same VAD model. This keeps things efficient and accurate for detecting voice activity across everyone in the room. Hope this helps! Sources: livekit-plugins/livekit-plugins-silero/livekit/plugins/silero/vad.py | examples/src/pipeline_voice_agent.ts | Silero VAD plugin | LiveKit Docs
s
is AgentSession a 1.x framework class? ensure the examples you are giving are using the 0.x version of livekit sdk
t
Just a heads-up: the
AgentSession
class belongs to the 1.x framework and isn’t available in the 0.x LiveKit SDK. If you’re working with the 0.x version, you’d want to use classes like
VoicePipelineAgent
or
MultimodalAgent
instead. Here’s a friendly example of how you can set up VAD for participants using the 0.x framework:
Copy code
from livekit.agents import JobContext, llm
from livekit.agents.pipeline import VoicePipelineAgent
from livekit.plugins import silero, deepgram, google

async def entrypoint(ctx: JobContext):
    initial_ctx = llm.ChatContext().append(
        role="system",
        text="You are a helpful voice AI assistant.",
    )

    agent = VoicePipelineAgent(
        vad=silero.VAD.load(),
        stt=deepgram.STT(),
        llm=google.LLM(),
        tts=None,  # Add TTS if needed
    )

    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)

    # Wait for the first participant to connect
    participant = await ctx.wait_for_participant()

    # Start the agent for the participant
    await agent.start(ctx.room, participant)

    # Example: Greet the participant
    await agent.say("Hello! How can I assist you today?", allow_interruptions=True)
This example shows how
VoicePipelineAgent
can take care of VAD and other features smoothly. If you want me to walk you through anything else or provide more examples for the 0.x SDK, just let me know—I’m here to help! Sources: Recording agent sessions | LiveKit Docs | Inside a session | LiveKit Docs | OpenAI Realtime API Quickstart | LiveKit Docs | Agents v0.x migration guide | LiveKit Docs | Agents 0.x migration guide | LiveKit Docs
s
I'm not using a VoicePipelineAgent currently. the way we handle audio is in our entrypoint we have a
ctx.room.on("track_subscribed", self.on_track_subscribed)
. here are the following relevant bits of code:
Copy code
def on_track_subscribed(
        self,
        track: rtc.Track,
        publication: rtc.TrackPublication,
        participant: rtc.RemoteParticipant,
    ) -> None:
    
    ...

        if _is_microphone_audio(track, publication):
            if self.audio_task is not None:
                raise RuntimeError("Audio processing task has already been created")
            if self.settings is None:
                raise RuntimeError(
                    "Settings must be initialized before processing audio"
                )
            stt_impl: stt.STT = openai.STT(
                api_key=self.settings.openai_api_key,
                use_realtime=True,  # enable interim transcript events
                turn_detection={
                    # https://platform.openai.com/docs/guides/realtime-vad#semantic-vad
                    "type": "semantic_vad",
                    "eagerness": "low",
                },
            )
            self.audio_task = asyncio.create_task(
                self.transcribe_track(track, stt_impl)
            )

   async def transcribe_track(self, track: rtc.Track, stt_impl: stt.STT) -> None:
        """Send audio to STT."""
        audio_stream = rtc.AudioStream(track)
        self.stt_stream = stt_impl.stream()
        asyncio.create_task(self.forward_transcription())

        async for ev in audio_stream:
            self.stt_stream.push_frame(ev.frame)

        if not self.oko_user_id or not self.session_id or not self.broadcaster:
            raise ValueError("Must have oko_user_id, session_id, and broadcaster")
Would I set up the VAD in on_track_subscribed ? update my
t
Hey there! To add VAD to your existing
on_track_subscribed
method, you can set it up to handle audio streams and detect when someone is speaking. Here’s a friendly example of how you might tweak your code to include VAD:
Copy code
from livekit.plugins import silero

async def transcribe_track(self, track: rtc.Track, stt_impl: stt.STT) -> None:
    """Send audio to STT with VAD."""
    vad = silero.VAD.load(
        min_speech_duration=0.1,    # Minimum duration to start speech chunk
        min_silence_duration=0.5,   # Minimum silence before ending speech
    )
    vad_stream = vad.stream()
    audio_stream = rtc.AudioStream(track)

    self.stt_stream = stt_impl.stream()
    asyncio.create_task(self.forward_transcription())

    async for ev in audio_stream:
        vad_stream.push_frame(ev.frame)

        # Process VAD events
        async for vad_event in vad_stream:
            if vad_event.type == "START_OF_SPEECH":
                print("Speech started")
            elif vad_event.type == "END_OF_SPEECH":
                print("Speech ended")

        self.stt_stream.push_frame(ev.frame)

@ctx.room.on("track_subscribed")
def on_track_subscribed(
    self,
    track: rtc.Track,
    publication: rtc.TrackPublication,
    participant: rtc.RemoteParticipant,
):
    if _is_microphone_audio(track, publication):
        if self.audio_task is not None:
            raise RuntimeError("Audio processing task has already been created")
        if self.settings is None:
            raise RuntimeError("Settings must be initialized before processing audio")

        stt_impl: stt.STT = openai.STT(
            api_key=self.settings.openai_api_key,
            use_realtime=True,
            turn_detection={
                "type": "semantic_vad",
                "eagerness": "low",
            },
        )

        self.audio_task = asyncio.create_task(
            self.transcribe_track(track, stt_impl)
        )
Here’s a quick rundown: • You load and set up the VAD inside the
transcribe_track
method. • Audio frames get pushed to the VAD stream, and you handle VAD events like
START_OF_SPEECH
and
END_OF_SPEECH
. • At the same time, those audio frames are sent off to your STT system for transcription. This way, VAD fits neatly into your current audio processing flow. If anything’s unclear or you want to tweak it further, just give me a shout—I’m happy to help! Sources: main.py | Working with plugins | LiveKit Docs | Working with plugins | LiveKit Docs