dry-rainbow-66344
08/30/2025, 3:08 PMtall-airline-16756
08/30/2025, 3:08 PMtall-airline-16756
08/30/2025, 3:08 PMdry-rainbow-66344
08/30/2025, 3:13 PMtall-airline-16756
08/30/2025, 3:14 PMLLMMetrics event after each LLM inference call, which includes:
• completion_tokens: Tokens generated in the LLM's response
• prompt_tokens: Tokens in the input prompt
• total_tokens: The total of prompt and completion tokens
To get these metrics, just listen for the metrics_collected event in the LiveKit Agents SDK. Here’s a quick example in Python:
def sync_wrapper(metrics: LLMMetrics):
asyncio.create_task(on_metrics_collected(metrics))
self.llm.on("metrics_collected", sync_wrapper)
async def on_metrics_collected(self, metrics: LLMMetrics):
print(f"Prompt tokens: {metrics.prompt_tokens}")
print(f"Completion tokens: {metrics.completion_tokens}")
print(f"Total tokens: {metrics.total_tokens}")
If you want to keep track of tokens across multiple calls, you can use the UsageCollector utility to add up the token counts. Feel free to reach out if you’d like a hand with setting this up—I’m here to help!
Sources: Logs, metrics, and telemetry | LiveKit Docs | livekit-agents/livekit/agents/metrics/base.py | agents/src/llm/llm.ts | metrics/metrics_llm.pydry-rainbow-66344
08/30/2025, 3:14 PMtall-airline-16756
08/30/2025, 3:15 PMLLMMetrics) and you’ll want to capture them programmatically using the LiveKit Agents SDK. From there, you can process and show these metrics in your own app or monitoring tools.
If you’d like a hand setting up the SDK to grab these metrics, just give me a shout—I’m happy to help!dry-rainbow-66344
08/30/2025, 3:16 PMtall-airline-16756
08/30/2025, 3:16 PMmetrics_collected event and grab those token details:
from livekit.agents import LLMMetrics
def sync_wrapper(metrics: LLMMetrics):
asyncio.create_task(on_metrics_collected(metrics))
# Just attach this event listener to your LLM instance
self.llm.on("metrics_collected", sync_wrapper)
# Here’s the callback where you can handle the metrics
async def on_metrics_collected(metrics: LLMMetrics):
print(f"Prompt tokens: {metrics.prompt_tokens}")
print(f"Completion tokens: {metrics.completion_tokens}")
print(f"Total tokens: {metrics.total_tokens}")
Here’s how to get started:
1. First, make sure the LiveKit Agents SDK is installed.
2. Then, attach the metrics_collected event listener to your LLM instance before you start any inference calls.
3. Finally, use the callback function to log or display the token usage however you like.
If you want me to walk you through any part of this or if you have any specific questions, just let me know—I’m happy to help!dry-rainbow-66344
08/30/2025, 3:26 PM5.279 File "/app/src/agent.py", line 21, in <module>
5.279 from livekit.agents import LLMMetrics
5.279 ImportError: cannot import name 'LLMMetrics' from 'livekit.agents' (/app/.venv/lib/python3.11/site-packages/livekit/agents/__init__.py)tall-airline-16756
08/30/2025, 3:26 PMLLMMetrics isn’t exported directly from livekit.agents. No worries though—you just need to import it from the livekit.agents.metrics submodule instead. Try updating your import statement like this:
from livekit.agents.metrics import LLMMetrics
That should do the trick! If you run into any other issues, feel free to reach out—I’m here to help.
Sources: livekit-agents/livekit/agents/resources/__init__.py | metrics/send-metrics-to-3p/send_metrics_to_3p.pydry-rainbow-66344
08/30/2025, 3:39 PMclass Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""You are a helpful voice AI assistant.
You eagerly assist users with their questions by providing information from your extensive knowledge.
Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols.
You are curious, friendly, and have a sense of humor.""",
)
# all functions annotated with @function_tool will be passed to the LLM when this
# agent is active
@function_tool
async def lookup_weather(self, context: RunContext, location: str):
"""Use this tool to look up current weather information in the given location.
If the location is not supported by the weather service, the tool will indicate this. You must tell the user the location's weather is unavailable.
Args:
location: The location to look up weather information for (e.g. city name)
"""
logger.info(f"Looking up weather for {location}")
return "sunny with a temperature of 70 degrees."
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
async def entrypoint(ctx: JobContext):
# Logging setup
# Add any other context you want in all log entries here
ctx.log_context_fields = {
"room": ctx.room.name,
}
# Set up a voice AI pipeline using OpenAI, Cartesia, Deepgram, and the LiveKit turn detector
session = AgentSession(
# A Large Language Model (LLM) is your agent's brain, processing user input and generating a response
# See all providers at https://docs.livekit.io/agents/integrations/llm/
llm=openai.LLM(model="gpt-4o-mini"),
# Speech-to-text (STT) is your agent's ears, turning the user's speech into text that the LLM can understand
# See all providers at https://docs.livekit.io/agents/integrations/stt/
#stt=deepgram.STT(model="nova-3", language="multi"),
stt=sarvam.STT(language="kn-IN", model="saarika:v2.5", api_key=SARVAM_API_KEY),
# Text-to-speech (TTS) is your agent's voice, turning the LLM's text into speech that the user can hear
# See all providers at https://docs.livekit.io/agents/integrations/tts/
#tts=cartesia.TTS(voice="6f84f4b8-58a2-430c-8c79-688dad597532"),
tts=sarvam.TTS(target_language_code="kn-IN", speaker="anushka", api_key=SARVAM_API_KEY),
# VAD and turn detection are used to determine when the user is speaking and when the agent should respond
# See more at https://docs.livekit.io/agents/build/turns
turn_detection=MultilingualModel(),
vad=ctx.proc.userdata["vad"],
# allow the LLM to generate a response while waiting for the end of turn
# See more at https://docs.livekit.io/agents/build/audio/#preemptive-generation
preemptive_generation=True,
)
# To use a realtime model instead of a voice pipeline, use the following session setup instead:
# session = AgentSession(
# # See all providers at https://docs.livekit.io/agents/integrations/realtime/
# llm=openai.realtime.RealtimeModel(voice="marin")
# )
# sometimes background noise could interrupt the agent session, these are considered false positive interruptions
# when it's detected, you may resume the agent's speech
@session.on("agent_false_interruption")
def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
logger.info("false positive interruption, resuming")
session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)
# Metrics collection, to measure pipeline performance
# For more information, see https://docs.livekit.io/agents/build/metrics/
usage_collector = metrics.UsageCollector()
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
metrics.log_metrics(ev.metrics)
usage_collector.collect(ev.metrics)
async def log_usage():
summary = usage_collector.get_summary()
logger.info(f"Usage: {summary}")
ctx.add_shutdown_callback(log_usage)
# # Add a virtual avatar to the session, if desired
# # For other providers, see https://docs.livekit.io/agents/integrations/avatar/
# avatar = hedra.AvatarSession(
# avatar_id="...", # See https://docs.livekit.io/agents/integrations/avatar/hedra
# )
# # Start the avatar and wait for it to join
# await avatar.start(session, room=ctx.room)
# Start the session, which initializes the voice pipeline and warms up the models
await session.start(
agent=Assistant(),
room=ctx.room,
room_input_options=RoomInputOptions(
# LiveKit Cloud enhanced noise cancellation
# - If self-hosting, omit this parameter
# - For telephony applications, use `BVCTelephony` for best results
noise_cancellation=noise_cancellation.BVC(),
),
)
# Join the room and connect to the user
await ctx.connect()
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))tall-airline-16756
08/30/2025, 3:39 PMmetrics_collected event along with the UsageCollector utility. Here’s a friendly walkthrough on how to tweak your code:
from livekit.agents.metrics import LLMMetrics, UsageCollector\n\nclass Assistant(Agent):\n def __init__(self) -> None:\n super().__init__(\n instructions=\"\"\"You are a helpful voice AI assistant.\n You eagerly assist users with their questions by providing information from your extensive knowledge.\n Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols.\n You are curious, friendly, and have a sense of humor.\"\"\"\n )\n\nasync def entrypoint(ctx: JobContext):\n usage_collector = UsageCollector()\n\n @session.on(\"metrics_collected\")\n def _on_metrics_collected(ev: MetricsCollectedEvent):\n usage_collector.collect(ev.metrics)\n logger.info(f\"Prompt tokens: {ev.metrics.prompt_tokens}\")\n logger.info(f\"Completion tokens: {ev.metrics.completion_tokens}\")\n logger.info(f\"Total tokens: {ev.metrics.total_tokens}\")\n\n async def log_usage():\n summary = usage_collector.get_summary()\n logger.info(f\"Cumulative Usage: {summary}\")\n\n ctx.add_shutdown_callback(log_usage)\n\n # Start the session\n await session.start(\n agent=Assistant(),\n room=ctx.room,\n room_input_options=RoomInputOptions(\n noise_cancellation=noise_cancellation.BVC(),\n ),\n )\n\n await ctx.connect()
This change will help you see token usage for every LLM call and give you a handy cumulative summary when the session wraps up. If you want me to walk you through anything else or have questions, just let me know—I’m here to help!