faint-arm-51818
09/05/2025, 11:24 AMtall-airline-16756
09/05/2025, 11:24 AMtall-airline-16756
09/05/2025, 11:24 AMsession.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.pyfaint-arm-51818
09/05/2025, 11:25 AMtall-airline-16756
09/05/2025, 11:25 AMsession.on listeners with an AgentSession instance:
# 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.pyfaint-arm-51818
09/05/2025, 11:26 AMtall-airline-16756
09/05/2025, 11:26 AM