Why does this error happen when the documentation ...
# ask-ai
h
Why does this error happen when the documentation shows it should work? https://docs.livekit.io/agents/start/telephony/#voicemail-detection
Copy code
ERROR (2970): Cannot call 'SpeechHandle.waitForPlayout()' from inside the function tool 'voicemail-detect'. 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, tri.nguyen. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand this can be a bit tricky! The error happens because calling
SpeechHandle.waitForPlayout()
inside the
voicemail-detect
function tool creates a circular wait. Essentially, the speech handle is waiting for the tool to finish, while the tool is also waiting for the speech handle, which leads to a deadlock. To smoothly get around this, I recommend using
RunContext.waitForPlayout()
instead. This method patiently waits for the assistant's spoken response to complete before running the tool, so it avoids that circular waiting problem. Here's a friendly example in Python to illustrate:
Copy code
from livekit.agents.voice import RunContext

@function_tool
async def voicemail_detected(context: RunContext):
    # Wait for the assistant's spoken response to finish
    await context.wait_for_playout()
    
    # Perform voicemail handling logic
    return "Voicemail detected and handled"
If you’d like, I’m here to help with more examples or to walk you through this in another language. Just let me know! Sources: agents/src/voice/generation.ts | examples/warm-transfer/warm_transfer.py | How to detect and handle silence during calls
h
Copy code
llm.tool({
    description: VOICEMAIL_DETECT_TOOL_PROMPT,
    execute: async (_, { ctx }: llm.ToolOptions) => {
      console.log('➿ Voicemail detected, tool executing...');

      ctx.session.generateReply({
        instructions:
          "Leave a brief voicemail message for the user telling them you are sorry you missed them, but you will call back later. You don't need to mention you're going to leave a voicemail, just say the message.",
      });

      await ctx.waitForPlayout();

      // Wait 500ms before hanging up the call
      await new Promise((resolve) => setTimeout(resolve, 500));

      await hangUpCall(roomName, ctx);
    },
  })
It appears the agent doesn't wait and speak the reply, it just hangs up
t
I understand the issue arises because
ctx.waitForPlayout()
only waits for the assistant's spoken response before the tool runs, but not for any speech that happens afterward. To make sure the agent finishes speaking the voicemail message completely before hanging up, you'll want to wait for the entire speech playout using the active
SpeechHandle
. Here’s a friendly way to fix it:
Copy code
execute: async (_, { ctx }: llm.ToolOptions) => {
  console.log('➿ Voicemail detected, tool executing...');

  // Wait for pre-tool speech
  await ctx.waitForPlayout();

  // Generate and play the voicemail message
  await ctx.session.generateReply({
    instructions: "Leave a brief voicemail message for the user telling them you are sorry you missed them, but you will call back later."
  });

  // Wait for the full voicemail message to finish playing
  if (ctx.session.current_speech) {
    await ctx.session.current_speech.waitForPlayout();
  }

  // Wait 500ms before hanging up the call
  await new Promise((resolve) => setTimeout(resolve, 500));

  await hangUpCall(roomName, ctx);
},
This way, the voicemail message will be fully played before the call disconnects. If anything is unclear or you’d like me to walk you through it further, just let me know—I’m here to help! Sources: examples/warm-transfer/warm_transfer.py | Agent speech and audio | LiveKit docs | Agents telephony integration | LiveKit Docs | How to detect and handle silence during calls | agents/src/voice/agent_activity.ts
h
ctx.session.current_speech doesn't exist
t
If
ctx.session.current_speech
isn’t available, a helpful way to handle this is by explicitly keeping the
SpeechHandle
when it’s created. For instance, both
ctx.session.say()
and
ctx.session.generateReply()
return a
SpeechHandle
, which you can store and use later to wait for playout. Here’s a friendly example of how you might adjust your implementation:
Copy code
execute: async (_, { ctx }: llm.ToolOptions) => {
  console.log('➿ Voicemail detected, tool executing...');

  // Wait for pre-tool speech
  await ctx.waitForPlayout();

  // Generate and play the voicemail message
  const speechHandle = await ctx.session.generateReply({
    instructions: "Leave a brief voicemail message for the user telling them you are sorry you missed them, but you will call back later."
  });

  // Wait for the voicemail message to finish playing
  if (speechHandle) {
    await speechHandle.waitForPlayout();
  }

  // Wait 500ms before hanging up the call
  await new Promise((resolve) => setTimeout(resolve, 500));

  await hangUpCall(roomName, ctx);
},
This way, you’ll have direct access to the
SpeechHandle
and can be sure the voicemail message finishes playing before the call ends. If anything feels unclear or you’d like me to walk you through it step-by-step, just let me know—I’m here to help! Sources: Agent speech and audio | LiveKit docs | livekit-agents/livekit/agents/voice/agent_activity.py | Tool definition and use | LiveKit docs
h
This circles back to the initial error:
Copy code
ERROR (2970): Cannot call 'SpeechHandle.waitForPlayout()' from inside the function tool 'voicemail-detect'. 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
I understand that the circular wait error can be a bit tricky! It happens because
SpeechHandle.waitForPlayout()
can't be called from within the same function tool that owns the speech handle. To work around this, a great approach is to use
RunContext.waitForPlayout()
inside your tool. This way, you wait for the assistant's spoken response before the tool runs, which helps everything flow smoothly. Here’s a safe implementation pattern you might find helpful:
Copy code
execute: async (_, { ctx }: llm.ToolOptions) => {
  console.log('➿ Voicemail detected, tool executing...');

  // Wait for pre-tool speech
  await ctx.waitForPlayout();

  // Generate and play the voicemail message
  await ctx.session.generateReply({
    instructions: "Leave a brief voicemail message for the user telling them you are sorry you missed them, but you will call back later."
  });

  // Use silence detection or a timeout to ensure the message completes before hanging up
  await new Promise((resolve) => setTimeout(resolve, 5000));

  await hangUpCall(roomName, ctx);
},
This method helps you avoid the circular wait by making sure the tool doesn’t block on the speech handle it owns. If anything isn’t clear or you’d like me to walk you through it step-by-step, just let me know—I’m here to help! Sources: Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | livekit-agents/livekit/agents/voice/agent_activity.py | Community & Support | livekit/livekit_composite | DeepWiki | Agent Testing & CI/CD | livekit/livekit_composite | DeepWiki | agents/src/voice/speech_handle.ts
h
ctx.session.generateReply is not a promise so you can't await it
t
ctx.session.generateReply
isn’t a promise, so it shouldn’t be awaited directly. Instead, it immediately gives you a
SpeechHandle
, which you can use to wait until the speech finishes. Here’s how you can use it properly:
Copy code
const handle = ctx.session.generateReply({
  instructions: "Leave a brief voicemail message for the user telling them you are sorry you missed them, but you will call back later."
});

// Wait for the speech to finish playing
await handle.waitForPlayout();
This way, you make sure the voicemail message plays completely before moving on. If you have any questions or want me to walk you through it, just let me know—I’m here to help! Sources: agents/src/voice/agent_activity.ts | livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/...
a
@happy-diamond-58115 Were you able to fix that issue? I am facing the same issue.
t
It seems like you’re referring to a similar issue. Could you clarify which specific problem you’re encountering? For example: • Are you facing the circular wait error when using
SpeechHandle.waitForPlayout()
? • Are you having trouble ensuring the voicemail message is fully played before hanging up? • Or is there another issue related to
ctx.session.generateReply
? Let me know so I can assist you further!
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
h
@able-pillow-22864 No, I didn't use a tool to detect voicemail as the documentation suggests. Instead, I checked the call recipient's first greeting message using an external AI model like OpenAI to determine if the response was from a voicemail or a human. Janky but it works
🙌 1