dry-rainbow-66344
09/01/2025, 5:26 AMtall-airline-16756
09/01/2025, 5:26 AMtall-airline-16756
09/01/2025, 5:27 AMmetrics_collected event. You can listen for this event to get the token usage details.
def sync_wrapper(metrics: LLMMetrics):
asyncio.create_task(self.on_metrics_collected(metrics))
self.llm.on("metrics_collected", sync_wrapper)
2. Process Metrics in a Callback: Create a function that handles these metrics and logs the token usage so you can see what's going on.
async def on_metrics_collected(self, metrics: LLMMetrics):
print(f"Input tokens (prompt): {metrics.prompt_tokens}")
print(f"Output tokens (completion): {metrics.completion_tokens}")
print(f"Total tokens: {metrics.total_tokens}")
print(f"Time to first token (TTFT): {metrics.ttft}s")
print(f"Tokens per second: {metrics.tokens_per_second:.2f}")
3. Aggregate Metrics Across a Session: To get a full picture over the whole session, use the UsageCollector to gather all the token usage.
from livekit.agents.metrics import UsageCollector
usage_collector = UsageCollector()
@agent.on("metrics_collected")
def on_metrics(metrics: AgentMetrics):
usage_collector.collect(metrics)
# At session end
summary = usage_collector.get_summary()
print(f"Total prompt tokens: {summary.llm_prompt_tokens}")
print(f"Total completion tokens: {summary.llm_completion_tokens}")
This setup works smoothly with all supported LLM integrations, like OpenAI and Anthropic. Plus, you can easily log these metrics or send them off to external monitoring tools if you want to dive deeper. Hope this helps you keep track effortlessly!
Sources: livekit-agents/livekit/agents/voice/agent_session.py | metrics/send-metrics-to-3p/send_metrics_to_3p.py | Example Applications | livekit/livekit_composite | DeepWiki | Capturing metrics | LiveKit Docs | LLM Integrations | livekit/livekit_composite | DeepWiki