how to detect interruption in a tool call in pytho...
# ask-ai
f
how to detect interruption in a tool call in python agents
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 detect interruptions in a tool call using Python agents! You can use the
speech_handle.interrupted
property from the
RunContext
object to help with this. Here’s a friendly walkthrough of the key steps: • For long-running tasks, try using
wait_if_not_interrupted
. Just wrap your task with
asyncio.ensure_future()
and pass it to
run_ctx.speech_handle.wait_if_not_interrupted()
. This way, it patiently waits until your task finishes or an interruption happens. • After waiting, check the
interrupted
flag. If
run_ctx.speech_handle.interrupted
is
True
, it means the tool was interrupted, so it’s a good idea to cancel any related tasks. • If an interruption occurs, remember to cancel ongoing work and return
None
. Don’t worry—when a tool gets interrupted, the return value is simply ignored. And for those important operations that absolutely can’t be interrupted, you can use
run_ctx.disallow_interruptions()
right at the start of your tool call to keep things running smoothly. If you’d like me to share more details or some examples, just let me know—I’m here to help! Sources: Tool definition and use | LiveKit Docs | Docs::Agents | Turn detection and interruptions | LiveKit Docs | Bringing AI avatars to voice agents | livekit-agents/livekit/agents/voice/agent_activity.py