flaky-hospital-13625
10/31/2025, 12:41 PMtall-airline-16756
10/31/2025, 12:41 PMtall-airline-16756
10/31/2025, 12:41 PMRunContext 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:
@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