are these the correct livekit events and methods t...
# ask-ai
p
are these the correct livekit events and methods to get trnascripts manually? @session.on("user_speech_committed") def _on_user_speech(msg): if participant_identity and msg.text: call_tracker.add_transcript( participant_identity=participant_identity, speaker="user", text=msg.text ) print(f"📝 [TRANSCRIPT] User: {msg.text}") # Hook into LLM to capture agent responses and token usage @session.on("agent_speech_committed") def _on_agent_speech(msg): if participant_identity and msg.text: call_tracker.add_transcript( participant_identity=participant_identity, speaker="agent", text=msg.text ) print(f"📝 [TRANSCRIPT] Agent: {msg.text}") # Hook into LLM completion to track tokens @session.on("agent_speech_created") def _on_llm_completion(msg): # Try to extract token usage from LLM response if participant_identity and hasattr(msg, 'usage'): usage = msg.usage if hasattr(usage, 'prompt_tokens') and hasattr(usage, 'completion_tokens'): call_tracker.add_llm_tokens( participant_identity=participant_identity, prompt_tokens=usage.prompt_tokens, completion_tokens=usage.completion_tokens ) print(f"🔢 [TOKENS] Prompt: {usage.prompt_tokens}, Completion: {usage.completion_tokens}")
t
Thanks for reaching out, Vaneeza. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
The events you mentioned for obtaining transcripts in LiveKit aren’t quite right, but no worries—I’m here to help clarify! Here are the correct events and methods you can use: •
user_input_transcribed
: This event gives you real-time transcripts of what the user is saying. Here’s a simple example to show how it works:
Copy code
@session.on("user_input_transcribed")
def on_user_transcript(ev):
    print(f"User said: {ev.transcript}")
•
conversation_item_added
: This one triggers whenever a message—whether from the user or the agent—is added to the chat history, providing finalized transcripts. •
speech_created
: This event fires when agent speech is generated, but keep in mind, to get the transcript you’ll want to pull it from the related message or TTS output. •
session.history
: This lets you programmatically access the full conversation history, including messages from both users and agents. Just a heads-up, the events
user_speech_committed
,
agent_speech_committed
, and
agent_speech_created
aren’t valid LiveKit events. If you’d like, I’m happy to walk you through implementing these correctly or answer any other questions you have—just let me know! Sources: Events and error handling | LiveKit Docs | Session recording and transcripts | LiveKit Docs | livekit-agents/livekit/agents/stt/stt.py | pipeline-stt/transcriber/transcriber.py | Understanding Transcript Timing in Voice Conversations
p
is this the correct parameter to pass for sip calls? when starting sessions async def entrypoint(ctx: agents.JobContext): # Connect to the room and set up room-level hooks await ctx.connect(auto_subscribe=agents.AutoSubscribe.AUDIO_ONLY) room = ctx.room # Store participant identity for transcript tracking participant_identity = None @room.on("participant_connected") def _on_participant_connected(participant): nonlocal participant_identity participant_identity = participant.identity print(f"[ROOM] Participant connected: {participant.identity}") # Extract SIP information from participant metadata sip_call_id = None from_number = None to_number = None # Start the session with the configurable booking bot try: await session.start( room=room, agent=GenericBookingBot(config_loader, participant_identity or "unknown"), room_input_options=room_options,
t
To get you started with SIP calls in LiveKit, here are the key parameters you'll want to include when starting your sessions: •
sip_trunk_id
: This is the ID of the SIP trunk you'll use for your outbound call. •
sip_call_to
: The phone number you want to dial. •
room_name
: The LiveKit room where the SIP participant will join. •
participant_identity
: A unique ID for the SIP participant within the room. There are also some optional parameters that can be really helpful: •
sip_number
: This sets the Caller ID (the From number) that the receiving party will see. •
dtmf
: If you need to send DTMF digits after the call connects, this is where you specify them. •
play_dialtone
: Choose whether to play a dialtone in the room for other participants. •
headers
: You can add custom SIP headers to include in the INVITE message. •
wait_until_answered
: This makes the system wait until the call is answered before moving forward. Make sure these are set up correctly in your session, and please don’t hesitate to reach out if you want me to walk you through any part of this or if you have any other questions. I’m here to help! Sources: livekit-protocol/src/livekit.rs | protobufs/livekit_sip.proto | Preserving Caller ID During SIP Transfers in LiveKit Agents | livekit-protocol/livekit/protocol/sip.pyi
p
how can i get the number of tokens used by the agent?
t
To get the number of tokens used by the agent in LiveKit, you can use the
UsageCollector
class. Here's a simple way to do it: 1. *Initialize the UsageCollector:*`usage_collector = UsageCollector()` 2. Collect Metrics: Just use the
collect()
method to gather token usage from different metrics like LLM or real-time models. For example:
Copy code
# Collect LLM metrics
usage_collector.collect(llm_metrics_instance)
3. Retrieve the Summary: Then, call
get_summary()
to see the total token usage:
Copy code
summary = usage_collector.get_summary()
print("Prompt Tokens:", summary.llm_prompt_tokens)
print("Completion Tokens:", summary.llm_completion_tokens)
This method helps you keep track of tokens for LLM, TTS, and real-time models easily. If you’d like, I’m here to help with more details or examples—just let me know! Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | agents/src/metrics/base.ts
p
usage collector is available on free plan too?
t
The UsageCollector class is available on the free plan in LiveKit, and it’s part of the open-source LiveKit Agents SDK. It’s a handy tool to help you keep track of important metrics like LLM, TTS, and STT usage. That said, I want to gently remind you that while the UsageCollector itself is free, the AI and Agent services it keeps an eye on might have some limits or quotas on the free plan. For instance, there are hard limits on metered resources, and going over those might cause some requests to fail. Please feel free to reach out if you’d like more details about these plan-specific limits or if you want some tips on how to make the most of the UsageCollector—I’m here to help! Sources: agents/src/metrics/index.ts | Logs, metrics, and telemetry | LiveKit Docs | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | LiveKit | Quotas and limits | LiveKit Docs
p
there's no such thing as usage collector Traceback (most recent call last): File "<string>", line 2, in <module> File "/home/runner/work/livekit-callbot-agents/livekit-callbot-agents/main.py", line 10, in <module> from livekit.agents import AgentSession, Agent, RoomInputOptions, UsageCollector ImportError: cannot import name 'UsageCollector' from 'livekit.agents' (/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/livekit/agents/__init__.py)
t
I’m happy to help you with this! The
UsageCollector
class isn’t found in the root
livekit.agents
module, but rather in the
livekit.agents.metrics
submodule. To fix the ImportError, you can update your import statement like this:
Copy code
from livekit.agents.metrics import UsageCollector

usage_collector = UsageCollector()
If you’re still running into trouble, it’s a good idea to double-check that the
livekit-agents
package is installed and up to date. You can do that by running:
Copy code
pip install --upgrade livekit-agents
Please feel free to reach out if you have any more questions or need a hand with anything else! Sources: examples/voice_agents/speedup_output_audio.py | Logs, metrics, and telemetry | LiveKit Docs | chain-of-thought-tts/agent.py
p
whats the content tructure in livekit? to accurately get transcripts. currently i have this async def write_transcript(): """Save conversation history when session ends""" if participant_identity and hasattr(entrypoint, '_session'): session = entrypoint._session # Get conversation history from session history_dict = session.history.to_dict() # Save to call tracker if history_dict and 'items' in history_dict: for item in history_dict['items']: role = item.get('role') content = item.get('content', []) # Handle different content formats text = '' if isinstance(content, list) and len(content) > 0: # Content is a list of items first_item = content[0] if isinstance(first_item, dict): text = first_item.get('text', '') elif isinstance(first_item, str): text = first_item elif isinstance(content, str): # Content is directly a string text = content elif isinstance(content, dict): # Content is a dict with text field text = content.get('text', '') speaker = 'user' if role == 'user' else 'agent' if text: call_tracker.add_transcript( participant_identity=participant_identity, speaker=speaker, text=text ) print(f"📝 [TRANSCRIPT] Saved conversation history for {participant_identity}") ctx.add_shutdown_callback(write_transcript) # Connect to the room and set up room-level hooks await ctx.connect(auto_subscribe=agents.AutoSubscribe.AUDIO_ONLY) room = ctx.room which gives errors {"message": "process exiting", "level": "INFO", "name": "livekit.agents", "reason": "", "pid": 709, "job_id": "AJ_f6M9fnAhZcFj", "timestamp": "2025-10-16T152008.216449+00:00"} 2025-10-16T152008.219 app[1857440a629918] iad [info] {"message": "livekit:rtc engine453livekit:rtc_engine - received session close: \"signal client closed: \\\"stream closed\\\"\" UnknownReason Resume", "level": "WARNING", "name": "livekit", "pid": 709, "job_id": "AJ_f6M9fnAhZcFj", "timestamp": "2025-10-16T152008.216516+00:00"} 2025-10-16T152008.227 app[1857440a629918] iad [info] {"message": "error while shutting down the job\nTraceback (most recent call last):\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/ipc/job_proc_lazy_main.py\", line 298, in _run_job_task\n await asyncio.gather(*shutdown_tasks)\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/job.py\", line 238, in wrapper\n await callback() # type: ignore\n ^^^^^^^^^^^^^^^^\n File \"/home/appuser/main.py\", line 675, in write_transcript\n text = content[0].get('text', '')\n ^^^^^^^^^^^^^^\nAttributeError: 'str' object has no attribute 'get'", "level": "ERROR", "name": "livekit.agents", "pid": 709, "job_id": "AJ_f6M9fnAhZcFj", "timestamp": "2025-10-16T152008.221758+00:00"}
t
The content structure of session.history in LiveKit is made up of ChatMessage objects, which include: •
id
: A unique identifier for each message •
timestamp
: The time when the message was created •
edit_timestamp
: An optional timestamp for when the message was edited •
message
: The actual content of the message •
deleted
: A boolean indicating if the message has been deleted •
generated
: A boolean showing if the message was AI-generated To help you accurately parse transcripts, here are some friendly tips: 1. Use
conversation_item_added
or
user_input_transcribed
events for processing messages in real-time. 2. For batch processing, you can access session.history once the session has ended. 3. Always check the
message
field for content, and be prepared to handle different formats like strings, lists, or dictionaries. 4. Use the
timestamp
field to keep messages in chronological order, and make sure to skip any messages marked as deleted by checking the
deleted
field. I noticed your current implementation might run into trouble if the
content
field is a string since strings don’t have a
get
method. Here’s a little update for your code to handle that smoothly:
Copy code
if isinstance(content, str):
    text = content
elif isinstance(content, list) and len(content) > 0:
    first_item = content[0]
    if isinstance(first_item, dict):
        text = first_item.get('text', '')
    elif isinstance(first_item, str):
        text = first_item
elif isinstance(content, dict):
    text = content.get('text', '')
Please feel free to reach out if you’d like me to clarify anything further or if you need a hand with anything else! I’m here to help. Sources: Session recording and transcripts | LiveKit Docs | lib/livekit/proto/livekit_models_pb.rb | hooks/useDataStreamTranscriptions.ts