I have built a self-hosted voice agent in python, ...
# ask-ai
d
I have built a self-hosted voice agent in python, now I want to track the number of input/output credits used by the LLM during the call by logging them. Give me the code to do this
t
Thanks for reaching out, Harsha. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to keep an eye on how many input/output credits (tokens) your LLM uses during a call in your self-hosted voice agent, LiveKit has a handy built-in metrics system to help with that. Let me walk you through how to set it up: 1. Subscribe to Metrics Events: After each completion request, the LLM component sends out a
metrics_collected
event. You can listen for this event to get the token usage details.
Copy code
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.
Copy code
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.
Copy code
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