refined-hydrogen-81988
10/31/2025, 7:32 PMtall-airline-16756
10/31/2025, 7:32 PMtall-airline-16756
10/31/2025, 7:33 PMrefined-hydrogen-81988
10/31/2025, 8:35 PMtall-airline-16756
10/31/2025, 8:36 PMimport time
class LatencyTracker:
def __init__(self):
self.speech_end_time = None
self.response_start_time = None
def mark_speech_end(self):
self.speech_end_time = time.time()
def mark_response_start(self):
self.response_start_time = time.time()
def calculate_latency(self):
if self.speech_end_time and self.response_start_time:
return (self.response_start_time - self.speech_end_time) * 1000 # in ms
return None
tracker = LatencyTracker()
tracker.mark_speech_end() # Call this when the user finishes speaking
tracker.mark_response_start() # Call this when the agent starts responding
latency = tracker.calculate_latency()
print(f"End-to-end latency: {latency} ms")
You can easily integrate this into your application to keep track of latency for each interaction. If you’d like, I’m here to help with any part of the implementation—just let me know! Sources: Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | livekit-agents/livekit/agents/metrics/utils.py | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | agents/src/metrics/utils.ts | utils/rtpstats.gorefined-hydrogen-81988
10/31/2025, 9:30 PMtall-airline-16756
10/31/2025, 9:31 PM@session.on("agent_state_changed")
def on_agent_state_change(event):
print(f"Agent state changed from {event.old_state} to {event.new_state}")
if event.new_state == "thinking":
log_agent_activity("Agent started processing request")
elif event.new_state == "speaking":
start_audio_visualizer()
elif event.new_state == "listening":
reset_user_interface()
React Frontend Example
const { state } = useAgent();
useEffect(() => {
if (state === 'thinking') {
setShowThinkingIndicator(true);
} else if (state === 'speaking') {
startSpeechAnimation();
} else if (state === 'listening') {
setAgentReady(true);
}
}, [state]);
Agent States
• "initializing": The agent is setting up components.
• "listening": The agent is waiting for user input.
• "thinking": The agent is processing user input.
• "speaking": The agent is generating or playing audio output.
• "idle": The agent is connected but not engaged.
If you have any questions or want me to help you with more examples or implementation tips, just let me know! I’m here to support you.
Sources: packages/react/src/hooks/useAgent.ts | Web and mobile frontends | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | Events and error handling | LiveKit docs | web/src/data/agent.ts