My agent can't speak while a tool call is running....
# ask-ai
e
My agent can't speak while a tool call is running. I'm using the wait_if_not_interrupted method and I need the agent to answer other questions while a tool is running. I'm using python. How can I solve this?
t
Thanks for reaching out, Lucas. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help your agent answer questions even while a tool call is running, you can use the
wait_if_not_interrupted
method. This handy method lets the agent keep an eye out for any user interruptions during tool execution and jump right in to respond if needed. Here’s a friendly example in Python to guide you:
Copy code
from livekit.agents import Agent, RunContext
from livekit.agents.llm import function_tool
import asyncio

class MyAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a voice agent.")

    @function_tool
    async def search_web(self, query: str, run_ctx: RunContext) -> str | None:
        print(f"Searching the web for {query}")
        run_ctx.session.say("I'm searching for that now...")

        # Start the long-running task
        wait_for_result = asyncio.ensure_future(self._a_long_running_task(query))

        # Wait for completion or interruption
        await run_ctx.speech_handle.wait_if_not_interrupted([wait_for_result])

        if run_ctx.speech_handle.interrupted:
            print(f"User interrupted search for {query}")
            wait_for_result.cancel()
            return None

        output = wait_for_result.result()
        print(f"Search completed: {output}")
        return output

    async def _a_long_running_task(self, query: str) -> str:
        await asyncio.sleep(5)
        return f"Results for {query}"
Here are some key points to keep in mind: • Users can interrupt the tool execution anytime to ask new questions. • If interrupted, the tool execution cancels gracefully, so the agent can quickly respond to new input. • It’s great to provide immediate feedback to users with
session.say()
to keep them in the loop. If you have any questions or want me to walk you through anything else, just let me know—I’m here to help! Sources: tests/test_agent_session.py | Tool definition and use | LiveKit docs
e
The agent is being completely blocked. It won't even say the status if I set function for that
t
I understand it might feel like the agent is blocked because the
wait_if_not_interrupted
method waits quietly for tasks to finish without giving any updates along the way. This can sometimes make it seem like nothing is happening, even though the operation is running in the background. To help with this, you can add manual status updates. For instance, you could set up a background task to let users know if the operation is taking a bit longer than expected:
Copy code
import asyncio
from livekit.agents import function_tool, RunContext

class MyAgent:
    @function_tool
    async def search_web(self, query: str, run_ctx: RunContext) -> str | None:
        # Start the long-running task
        long_task = asyncio.ensure_future(self._a_long_running_task(query))

        # Background task for status updates
        async def provide_status_update():
            await asyncio.sleep(2)  # Wait 2 seconds before updating
            if not long_task.done():
                run_ctx.session.say("Still working on your request, please hold on.")

        status_task = asyncio.create_task(provide_status_update())

        # Wait for the main task or interruption
        await run_ctx.speech_handle.wait_if_not_interrupted([long_task])

        # Clean up
        status_task.cancel()
        if run_ctx.speech_handle.interrupted:
            long_task.cancel()
            return None

        return long_task.result()

    async def _a_long_running_task(self, query: str) -> str:
        await asyncio.sleep(5)
        return f"Results for {query}"
Here’s what’s happening in this example: • A background task gives a quick status update after 2 seconds if the main task is still running. • The agent uses
session.say()
to kindly inform the user about the progress. • The status update task is canceled once the main task finishes or if it gets interrupted. This way, the agent stays responsive and keeps the user in the loop during longer operations. If you have any questions or need a hand implementing this, just let me know—I’m here to help! Sources: How to detect when an agent has finished speaking | Tool definition and use | LiveKit docs | livekit-agents/livekit/agents/worker.py | External data and RAG | LiveKit docs