busy-breakfast-32623
09/18/2025, 5:19 AMtall-airline-16756
09/18/2025, 5:19 AMtall-airline-16756
09/18/2025, 5:20 AMUsageCollector class from livekit.agents.metrics. Let me walk you through the steps:
1. Start by initializing a UsageCollector instance at the beginning of your session. This will help you gather all the important metrics.
2. Next, subscribe to the metrics_collected event of the AgentSession. Every time you get new AgentMetrics, just pass them to your collector using usage_collector.collect().
3. Finally, to make sure you see the complete usage summary, log it at the end of the session using ctx.add_shutdown_callback(). This way, the total token usage will be printed right when your session wraps up.
Here’s a simple example to illustrate this:
from livekit.agents.metrics import UsageCollector
from livekit.agents import MetricsCollectedEvent
# Initialize UsageCollector
usage_collector = UsageCollector()
# Subscribe to metrics_collected event
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
usage_collector.collect(ev.metrics)
# Log usage summary at session end
async def log_usage_summary():
summary = usage_collector.get_summary()
print(f"Total LLM Tokens: {summary.llm_prompt_tokens + summary.llm_completion_tokens}")
print(f"Total TTS Characters: {summary.tts_characters_count}")
print(f"Total STT Audio Duration: {summary.stt_audio_duration:.2f}s")
ctx.add_shutdown_callback(log_usage_summary)
By following these steps, you'll have a clear view of the total token consumption and other key metrics at the end of each session. If you have any questions or need further assistance, feel free to ask—I’m here to help!
Sources: Logs, metrics, and telemetry | LiveKit Docs | Capturing metrics | LiveKit Docs | Capturing metrics | LiveKit Docs | examples/voice_agents/basic_agent.py | metrics/metrics_tts.py