How can I execute a hook when the agent gets inter...
# ask-ai
m
How can I execute a hook when the agent gets interrupted? Realtime agent to be specific. Python sdk
t
I'm happy to help you with executing a hook when a real-time agent gets interrupted using the Python SDK! Here are some approaches you can try: • False Interruption Events: You can register for the
agent_false_interruption
event to handle cases where interruptions turn out to be false alarms. For example:
Copy code
async def on_false_interruption(event):
    print(f"False interruption detected, resumed: {event.resumed}")
    # Your custom hook logic here

# Register the event handler
session.on("agent_false_interruption", on_false_interruption)
• Tool Execution Interruption Hooks: Another way is to monitor interruptions during tool execution by checking
run_ctx.speech_handle.interrupted
and then defining what you'd like to happen next:
Copy code
async def my_tool(self, run_ctx):
    try:
        await some_async_operation()
        if run_ctx.speech_handle.interrupted:
            await self.handle_tool_interruption()
    except asyncio.CancelledError:
        if run_ctx.speech_handle.interrupted:
            await self.cleanup_after_interruption()
• Programmatic Interruption Hooks: You can also create hooks that respond to programmatic interruptions like this:
Copy code
# Trigger interruption and execute custom logic
handle = session.say("Hello world")
await self.before_interruption_hook()
handle.interrupt()
await self.after_interruption_hook()
If you have any questions or want to dive deeper into any of these methods, just let me know. I'm here to support you every step of the way! Sources: Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/events.py | Tool definition and use | LiveKit docs
m
I want to execute code on actual interruptions that are intentional (so, not false) AND initiated by the user (not programmatically) If it's not possible, then let me know so I can contribute to the project.
t
I'm glad you're exploring how to handle intentional interruptions initiated by the user (not programmatically). A great way to do this is by using the
user_input_transcribed
event in the Python SDK. This event triggers whenever the system detects and transcribes user speech, making it your go-to tool for identifying and responding to those interruptions. Method 1: Using
user_input_transcribed
Event
This event fires for both interim (partial) and final (complete) transcriptions. By listening to interim transcripts, you can respond as soon as the user starts speaking, which is really helpful:
Copy code
async def handle_interruption():
    session.say("Sorry, can I pause you there?", allow_interruptions=False)
    await session.generate_reply(allow_interruptions=False)

@session.on("user_input_transcribed")
def on_transcript(transcript):
    if not transcript.is_final:  # Process interim speech
        if "specific condition met":
            asyncio.create_task(handle_interruption())
Method 2: Overriding
stt_node
If you want more fine-grained control, you can override the
stt_node
method in a custom agent class. This gives you direct access to the transcription pipeline, letting you handle user input in real-time:
Copy code
async def stt_node(self, text: AsyncIterable[str], model_settings=None):
    async for event in parent_stream:
        if hasattr(event, 'type') and str(event.type) == "SpeechEventType.FINAL_TRANSCRIPT":
            # Custom logic for user interruptions
            await self.session.say("Let me stop you there.")
At the moment, there isn't a dedicated
on_user_interruption
event, but if this is something important for your project, contributing to the development could be a wonderful way to help improve it. Please don’t hesitate to reach out if you’d like any more guidance or support—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | basics/uninterruptable.py | Turn detection and interruptions | LiveKit Docs
m
But realtime models don't use STT and thus, have no audio to transcribe. Am I missing something here?
t
I’m glad you asked about handling interruptions with real-time models that don’t use STT! These models use built-in Voice Activity Detection (VAD) and barge-in detection to manage interruptions smoothly. Let me walk you through how you can handle intentional user interruptions: 1. Built-in Interruption Handling: • Real-time models like AWS Nova Sonic are designed to automatically recognize when a user starts speaking and interrupt the agent’s speech. This happens behind the scenes, so you don’t need to worry about explicit STT or transcription. • For instance, Nova Sonic sends an event with
{ "interrupted": true }
whenever it detects a user interruption. 2. Programmatic Interruption: If you want to control interruptions yourself, you can use the
session.interrupt()
method to programmatically interrupt the agent’s speech:
Copy code
# Interrupt the agent
session.interrupt()
3. Configuration Options: • Make sure to set
allow_interruptions=True
in your session configuration to enable this feature. • You can also tweak
min_interruption_duration
to specify the minimum speech length needed to trigger an interruption. 4. Handling Interruptions in Tools: For tools that run longer, you can check the
run_ctx.speech_handle.interrupted
flag to detect interruptions and run any custom cleanup logic you might need. If anything feels unclear or you’d like a hand implementing these strategies, please don’t hesitate to ask—I’m here to help! Sources: Turn detection and interruptions | LiveKit Docs | livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | Tool definition and use | LiveKit docs
m
I want to know when a user interrupted the (realtime) model so I can log a custom metric and know when it happened. That is my use case