Explain these fields in details: "type": "eou_metr...
# ask-ai
a
Explain these fields in details: "type": "eou_metrics" "timestamp": 1759662038.7677453 "end_of_utterance_delay": 3.6059517860412598 "transcription_delay": 3.592564582824707 "on_user_turn_completed_delay": 0.000003814697265625 "last_speaking_time": 1759662035.1615703
t
Thanks for reaching out, Mehul. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to walk you through the fields in "eou_metrics" so you can get a clear understanding: • type: This is a constant string "eou_metrics" that helps identify the type of metric. It’s how we tell EOUMetrics apart from others like "stt_metrics" or "tts_metrics". • timestamp: This marks the Unix timestamp (in seconds) when the end-of-utterance event was recorded. Essentially, it shows when the system wrapped up the user's turn. • end_of_utterance_delay: This measures the time (in seconds) between when the speech ends (detected by VAD) and when the system decides the user’s turn is over. It includes any transcription delays and is influenced by the _min_endpointing_delay_ setting (which defaults to 500ms). • transcription_delay: This tells you how long (in seconds) it takes from the end of the user’s speech until the final transcription is ready from the STT engine. It’s calculated as the maximum of (last_final_transcript_time - last_speaking_time, 0). • on_user_turn_completed_delay: This shows how long (in seconds) it takes to run the _on_user_turn_completed_ callback after the system detects the user’s turn has ended. It includes all the operations inside that callback. • last_speaking_time: This is the timestamp (in seconds) when the user last stopped speaking, based on VAD detection. It helps calculate delays like transcription and end-of-utterance delays. Understanding these metrics can really help you fine-tune your agent’s responsiveness and troubleshoot any latency issues in your voice AI applications. If you have any questions or want to dive deeper into any of these, I’m here to help! Sources: tests/test_agent_session.py | agents/src/voice/audio_recognition.ts | Improving voice AI's turn detection with transformers | Logs, metrics, and telemetry | LiveKit Docs
a
Can you give me a small piece of python code which just runs the audio and gives information about when is VAD getting triggered
t
I'm happy to share a Python code example that gently walks you through detecting when Voice Activity Detection (VAD) is triggered and logging those events:
Copy code
import asyncio
import logging
from livekit import rtc
from livekit.agents.vad import VADEventType
from livekit.plugins import silero

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("vad-example")

async def main():
    # Load the Silero VAD plugin
    vad = silero.VAD.load(
        min_speech_duration=0.2,  # Minimum duration of speech to trigger VAD
        min_silence_duration=0.6  # Minimum silence duration to end speech
    )
    vad_stream = vad.stream()

    async def process_audio():
        # Simulate audio input (replace with actual audio frames in real use)
        for _ in range(100):
            frame = rtc.AudioFrame(data=b"\x00" * 480, sample_rate=48000, num_channels=1)
            vad_stream.push_frame(frame)
            await asyncio.sleep(0.01)  # Simulate real-time audio input

    async def process_vad():
        async for vad_event in vad_stream:
            if vad_event.type == VADEventType.START_OF_SPEECH:
                logger.info("VAD: Start of speech detected")
            elif vad_event.type == VADEventType.END_OF_SPEECH:
                logger.info("VAD: End of speech detected")

    # Run audio processing and VAD detection concurrently
    await asyncio.gather(process_audio(), process_vad())

if __name__ == "__main__":
    asyncio.run(main())
Here are some key things to keep in mind: • VAD Events: This example listens for
START_OF_SPEECH
and
END_OF_SPEECH
events to help you track speech activity. • Plugin: It uses the Silero VAD plugin, which is a reliable tool for detecting speech. • Configuration: You can tweak
min_speech_duration
and
min_silence_duration
to adjust how sensitive the detection should be, depending on your needs. If you have any questions or would like me to guide you through a more advanced example, please don’t hesitate to ask. I’m here to help! Sources: livekit-agents/livekit/agents/voice/audio_recognition.py | Improving voice AI's turn detection with transformers | Silero VAD plugin | LiveKit Docs | metrics/metrics_vad.py
a
i want to setup event handler for speech start and speech end how can i do it?
t
I'm happy to help you set up event handlers for speech start and speech end in LiveKit! You can do this by implementing the
RecognitionHooks
protocol. Here’s a friendly example to guide you through defining and using these handlers:
Copy code
from livekit.agents.vad import VADEvent
from livekit.agents.voice import RecognitionHooks

class MySpeechHandler(RecognitionHooks):
    def on_start_of_speech(self, ev: VADEvent | None) -> None:
        print("Speech started")
        if ev:
            print(f"Detected at {ev.timestamp}, speech duration: {ev.speech_duration}s")

    def on_end_of_speech(self, ev: VADEvent | None) -> None:
        print("Speech ended")
        if ev:
            print(f"Ended at {ev.timestamp}, silence duration: {ev.silence_duration}s")

# Example integration with a VoicePipelineAgent
from livekit.agents.pipeline import VoicePipelineAgent
from livekit.plugins import silero, deepgram, openai

vad_instance = silero.VAD.load()
stt_instance = deepgram.STT()
llm_instance = openai.LLM()
tts_instance = openai.TTS()

speech_handler = MySpeechHandler()

agent = VoicePipelineAgent(
    vad=vad_instance,
    stt=stt_instance,
    llm=llm_instance,
    tts=tts_instance,
    hooks=speech_handler  # Register your custom hooks here
)

# Start the agent (example context setup required)
# await agent.start(ctx.room, participant)
Here are some key things to keep in mind: • on_start_of_speech: This triggers right when speech begins, giving you useful info like timestamp and how long the speech has lasted. • on_end_of_speech: This kicks in when speech ends, letting you know the timestamp and the duration of silence afterward. • By integrating your handler into a
VoicePipelineAgent
, you ensure these VAD events are routed smoothly to your custom methods. If you have any questions or want help customizing this further, please don’t hesitate to ask—I’m here to support you! Sources: Events and error handling | LiveKit Docs | livekit-agents/livekit/agents/voice/audio_recognition.py | Improving voice AI's turn detection with transformers | Improving voice AI's turn detection with transformers
a
Let;s say llm or speech starts playing how do i clear the llm call, the tts or anything which is playing, if the user speech starts again?
t
Thanks for reaching out! Just to make sure I understand correctly, are you hoping to pause the ongoing LLM processing, stop the TTS playback, or both when the user starts speaking again? Also, could you let me know if you're using a particular LiveKit agent or plugin for these features? I'm here to help you through this!
a
no i am using openai, elevenlabs
t
Hey there! I wanted to share how LiveKit Agents thoughtfully manage interruptions when a user starts speaking during OpenAI LLM processing or TTS playback. Here’s a friendly breakdown: • For TTS Playback: If the TTS engine supports pausing (like OpenAI TTS), playback gently pauses as soon as user speech is detected. If pausing isn’t available, the system stops the current speech and signals the session to interrupt playback. • For LLM Processing: The ongoing LLM call is gracefully interrupted, stopping any further response generation. If you ever want to manually trigger an interruption, here’s a simple way to do it:
Copy code
# Force interruption even if allow_interruptions=False
session.interrupt()
Here are some key parameters to keep in mind: • allow_interruptions: This controls whether user speech can interrupt the agent’s speech. • min_interruption_duration: The minimum length of user speech needed before an interruption happens. • false_interruption_timeout: How long to wait before resuming playback if there’s a brief pause without more speech. If you’re working with ElevenLabs TTS, just double-check that your integration supports pausing and matches LiveKit’s interruption approach. And please feel free to reach out if you’d like a hand verifying or customizing your ElevenLabs setup—I’m here to help! Sources: Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
a
i want to specifically handle the state where agent hasnt started speaking it's yet passing data to llm and generating the audio, and user starts speaking during that duration.
t
Hey there! I totally understand how important it is to smoothly handle interruptions when the agent is generating audio but hasn’t started speaking yet. LiveKit has some great built-in features to help with this, by detecting user speech and canceling ongoing tasks. Let me walk you through how you can manage this: • Interruption Detection: When the system detects user speech through VAD or STT during audio generation, it automatically cancels the current speech generation task and stops playback from starting. • Configuration: You have control over interruption behavior with these handy parameters: ◦ allow_interruptions: Turn interruptions on or off globally (default is True). ◦ min_interruption_duration: Set the minimum length of speech to count as an interruption (default is 0.5 seconds). ◦ min_interruption_words: Define the minimum word count for STT-based interruption detection. Here’s an example configuration to get you started:
Copy code
session = AgentSession(
    allow_interruptions=True,
    min_interruption_duration=0.5,
    min_interruption_words=1
)
Manual Interruption: And if you ever need to force an interruption right away, you can do so with:
Copy code
# Force interruption regardless of allow_interruptions setting
await session.interrupt()
Monitoring Speech State: To keep an eye on whether a speech task is active, just check the
current_speech
property like this:
Copy code
current_speech = session.current_speech
if current_speech:
    print(f"Current speech ID: {current_speech.id}")
    print(f"Allow interruptions: {current_speech.allow_interruptions}")
If you have any questions or want a hand setting this up or tweaking the interruption logic to fit your needs, I’m here to help! Just let me know. Sources: Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | Agent speech and audio | LiveKit Docs | Bringing AI avatars to voice agents
a
agent_session._vad.on( "start_of_speech", lambda ev: on_start_of_speech(ev), ) agent_session._vad.on( "end_of_speech", lambda ev: on_end_of_speech(ev), ) is this right?
t
It's great that you're using
agent_session._vad.on
to handle
start_of_speech
and
end_of_speech
events! The VAD system in LiveKit does emit these events and supports attaching listeners with the
.on()
method. Just a small note—the underscore prefix (
_vad
) usually means it might be an internal API. To keep things smooth and future-proof, I’d suggest using the public
agent_session.vad
property instead, or you might find it helpful to process VAD events using the VAD stream pattern like this:
Copy code
async def process_vad():
    async for vad_event in agent_session.vad.stream():
        if vad_event.type == VADEventType.START_OF_SPEECH:
            on_start_of_speech(vad_event)
        elif vad_event.type == VADEventType.END_OF_SPEECH:
            on_end_of_speech(vad_event)
This way aligns nicely with LiveKit’s recommended usage and helps keep everything compatible with future updates. If you have any questions or want me to walk you through it, just let me know—I’m here to help! Sources: basics/echo_transcriber_agent.py | livekit-agents/livekit/agents/voice/agent_session.py
a
is there a way to tap into these events using session?
t
I'm glad to help you tap into the
start_of_speech
and
end_of_speech
events using the session by implementing the
RecognitionHooks
protocol. These hooks work hand-in-hand with session state management, so they automatically update the user state whenever speech starts or ends—making things much smoother for you. Here’s a friendly example of how you can implement it:
Copy code
class MyRecognitionHooks:
    def on_start_of_speech(self, ev):
        print("User started speaking")
        if ev:
            print(f"Speech started at {ev.timestamp}")

    def on_end_of_speech(self, ev):
        print("User finished speaking")
        if ev:
            print(f"Speech duration: {ev.speech_duration}s")

    # Other required methods for RecognitionHooks
    def retrieve_chat_ctx(self):
        pass

    def on_end_of_turn(self, info):
        return True

    def on_interim_transcript(self, ev, speaking):
        pass

    def on_final_transcript(self, ev):
        pass
Once you pass these hooks to an
AgentSession
, the framework will: • Automatically connect VAD or STT streams to your hook methods. • Update the session state to "speaking" or "listening" based on these events. • Coordinate agent responses in a seamless way. If you'd like, I’m here to walk you through integrating this into your session or help customize it to fit your needs perfectly. Just let me know! Sources: plugins/deepgram/src/stt.ts | livekit-agents/livekit/agents/inference/stt.py | Agent Session & Activity Management | livekit/livekit_composite | DeepWiki
a
give me full example and sample
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
a
Give me a full example for the vad events capturing using session