Is it advised to await an `AgentTask` from inside ...
# ask-ai
l
Is it advised to await an
AgentTask
from inside of an
Agent
function_tool
? If yes, how should this be done? Because when I try it with
livekit-agents==1.3.6
I get the error bellow even tho my code is not explicitly calling the
wait_for_playout
function anywhere
Copy code
RuntimeError: cannot call SpeechHandle.wait_for_playout() from inside the function tool my_awesome_tool that owns this SpeechHandle. This creates a circular wait: the speech handle is waiting for the function tool to complete, while the function tool is simultaneously waiting for the speech handle. To wait for the assistant's spoken response prior to running this tool, use RunContext.wait_for_playout() instead.
t
Thanks for reaching out, vlad. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're right to be concerned — that error means there's a circular wait between the tool and the speech handle. I’m responding to your question about whether to await an
AgentTask
from inside a
function_tool
and how to avoid the RuntimeError. Short answer • Don’t await an
AgentTask
inside a
function_tool
. That can create circular waits when the task or agent triggers speech. • If you need to wait for the agent’s spoken audio to finish inside a tool, use
RunContext.wait_for_playout()
(i.e.,
await context.wait_for_playout()
), not
SpeechHandle.wait_for_playout()
. Why this happens •
function_tool
runs as part of the tool’s execution context. If the agent/task you await produces speech, awaiting the task can indirectly cause a
SpeechHandle
that the tool also tries to wait on — producing the circular wait shown in your error. What to do instead • If you only need to wait for speech to finish inside the tool: ◦ Use
await context.wait_for_playout()
inside the
function_tool
. • If you’re trying to run an
AgentTask
and wait for its result: ◦ Run the
AgentTask
from the agent-level context (e.g., agent
on_enter
or other agent code) and await it there, not from the tool. • If the task must be initiated from the tool, refactor so the tool signals the agent to create/run the task, then the agent awaits it (tool → signal → agent runs/awaits task). If you’d like, share the minimal snippet showing how you create/await the task and any `say`/speech calls; I can point out the exact lines causing the circular wait and suggest a concrete refactor. Sources: Tasks and task groups | LiveKit docs | Agent speech and audio | LiveKit docs