can I use session.on listeners inside Agent class?
# ask-ai
f
can I use session.on listeners inside Agent class?
t
Thanks for reaching out, Taras. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Absolutely! You can use
session.on
listeners right inside an Agent class in LiveKit. These listeners—like
"user_state_changed"
,
"agent_state_changed"
,
"metrics_collected"
,
"conversation_item_added"
, and `"close"`—can be attached directly to the
session
object, whether that’s inside your agent or at the session level. They’re super handy for keeping an eye on the conversation flow, logging important metrics, or kicking off actions when certain states change. For instance, you might use
session.on("metrics_collected")
to track metrics while the session is ongoing, or
session.on("close")
to save the chat history once the session wraps up. These event listeners are part of the
AgentSession
API and you can access them anywhere the
session
object is available—including inside your agent classes. Sources: Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py
f
create example
t
Here’s a friendly example of how you can use
session.on
listeners with an
AgentSession
instance:
Copy code
# Create an AgentSession instance
session = AgentSession()

# Listen for conversation events
session.on("conversation_item_added", lambda event: print("Conversation item added:", event))

# Listen for agent state changes
session.on("agent_state_changed", lambda event: print("Agent state changed:", event))

# Listen for user input transcription
session.on("user_input_transcribed", lambda event: print("User input transcribed:", event))

# Listen for metrics collection
session.on("metrics_collected", lambda event: print("Metrics collected:", event))
In this example, we’ve set up event listeners on the
AgentSession
instance to catch things like conversation updates, agent state changes, and metrics collection. Feel free to swap out those simple lambda functions with your own custom methods if you want to handle the events in a more detailed way. Sources: examples/other/text_only.py
f
inside Agent class
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!