How to detect an interruption from within a tool c...
# ask-ai
f
How to detect an interruption from within a tool call with livekit agents python. E.g. to stop a running action.
t
Thanks for reaching out, Amjad. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring how to handle interruptions within a tool call in LiveKit Agents using Python! To gracefully stop a running action when needed, you can use the
RunContext
parameter in your tool function. This helps you keep an eye out for interruptions during those longer tasks. Here's a friendly pattern you might find useful:
Copy code
@function_tool
async def search_web(self, query: str, run_ctx: RunContext) -> str | None:
    logger.info(f"Searching the web for {query}")

    # Start the long-running task
    wait_for_result = asyncio.ensure_future(self._a_long_running_task(query))
    
    # Wait for either task completion or interruption
    await run_ctx.speech_handle.wait_if_not_interrupted([wait_for_result])

    if run_ctx.speech_handle.interrupted:
        logger.info(f"Interrupted searching the web for {query}")
        wait_for_result.cancel()  # Cancel the background task
        return None  # Skip sending result to LLM

    output = wait_for_result.result()
    logger.info(f"Done searching the web for {query}, result: {output}")
    return output
This way, your background tasks get canceled properly if an interruption happens, which helps avoid extra work and outdated responses. It's good to know that tools are interruptible by default when the user speaks, and any interrupted tool results are simply ignored. If you have operations that really shouldn’t be interrupted—like irreversible actions—you can easily prevent interruptions by calling
run_ctx.disallow_interruptions()
at the start of your tool. This makes sure the current tool runs without being cut off by user speech. Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Tool definition and use | LiveKit docs | Turn detection and interruptions | LiveKit Docs