here on agent enter i try to detect voicemail ```...
# ask-ai
b
here on agent enter i try to detect voicemail
Copy code
async def on_enter(self) -> None:
        """Wait for voicemail greeting to finish, then intelligently respond"""
        await asyncio.sleep(3)

        if self.session.user_state == "speaking":
            logger.info("Detected audio on entry")
            while self.session.user_state == "speaking":
                await asyncio.sleep(1)
            logger.info("Audio completed, analyzing for voicemail detection")

            last_user_message = self._get_last_user_message()
            await self.update_instructions(f"""
You just heard audio: '{last_user_message}' Analyze what you heard:
- If it was a voicemail greeting,
Common indicators of voicemail:
* Automated greeting messages: "You have reached the voicemail of..."
* Voicemail system prompts: "Please leave your name and number"
* Generic unavailable messages: "The person you are trying to reach is currently unavailable."

IMMEDIATELY call the detected_answering_machine tool.
- If it was a person saying hello or responding, greet them naturally.
IMPORTANT: DO NOT use the end_call in this context.
Only use detected_answering_machine.""")
        else:
            await self.update_tools(self.tools + [customer_unavailable])
            await self.update_instructions("""
CUSTOMER UNAVAILABLE: If you're told that the person exists but is not available
right now, use the customer_unavailable tool.
            """)
            await self.session.generate_reply()
maybe there is more optimal way?
t
Thanks for reaching out, Aleh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you please share a bit more about which part of the voicemail detection process you'd like to improve? For instance, are you hoping to make the detection more accurate, speed it up, or maybe make the code easier to manage? I'm here to help you find the best solution!
b
i think
Copy code
async def on_enter(self) -> None:
    """Wait for voicemail greeting to finish, then intelligently respond"""
    await asyncio.sleep(3)
sleep to wait for some input from the user is not the best option
t
To help you optimize your voicemail detection logic and move away from using asyncio.sleep, here are some friendly suggestions you might find useful: • Use Real-Time Voice Activity Detection (VAD): Try implementing event-driven approaches like
user_started_speaking
to keep track of when someone starts talking. This way, you can respond instantly without waiting around with artificial delays. • Leverage LLM-Based Voicemail Detection: Consider using semantic analysis to spot voicemail greetings by looking at the transcript content. This method taps into natural language understanding rather than relying on time-based checks. • Combine Silence Monitoring with LLM Context: You can monitor silence dynamically and also analyze transcripts for common voicemail phrases. This combo can really boost your detection accuracy. • Manage Background Tasks Safely: Using
asyncio.create_task
for monitoring is great, just remember to manage these tasks properly by canceling them during shutdown to keep things running smoothly. • Utilize Built-In VAD and STT Plugins: Don’t forget about handy plugins like Silero or Deepgram—they offer real-time speech detection and transcription that can simplify your work. These ideas should help you build a more efficient, scalable, and accurate voicemail detection system without depending on asyncio.sleep. If you'd like, I’m here to walk you through any of these steps or provide examples to get you started! Sources: How to detect and handle silence during calls | Getting Help & Troubleshooting | livekit/livekit_composite | DeepWiki | Agents telephony integration | LiveKit Docs | agent.py | Community & Support | livekit/livekit_composite | DeepWiki
b
provide example for each step
t
Here are some helpful examples for each step to optimize voicemail detection. I hope these make things clearer and easier for you to follow: • *Use Real-Time Voice Activity Detection (VAD):*`import time SILENCE_THRESHOLD = 5 # seconds async def monitor_interaction(): user_last_spoke_time = time.time() @agent.on("user_started_speaking") def on_user_started_speaking(_msg): nonlocal user_last_spoke_time user_last_spoke_time = time.time() while True: if time.time() - user_last_spoke_time > SILENCE_THRESHOLD: logger.info("Silent for too long! Disconnecting.") await ctx.room.disconnect() await asyncio.sleep(1) # Minimal periodic check` • *Leverage LLM-Based Voicemail Detection:*`@function_tool async def detected_answering_machine(): """Call this tool if a voicemail system is detected.""" await self.session.generate_reply( instructions="Leave a voicemail message letting the user know you'll call back later." ) await hangup_call()` • *Combine Silence Monitoring with LLM Context:*`async def analyze_transcript(transcript): if "voicemail" in transcript.lower(): await detected_answering_machine() else: logger.info("Live person detected, continuing conversation.")` • *Manage Background Tasks Safely:*`async def on_shutdown(): logger.info("Shutting down session.") if monitor_task: monitor_task.cancel() ctx.add_shutdown_callback(on_shutdown)` • *Utilize Built-In VAD and STT Plugins:*`session = AgentSession( vad=silero.VAD.load(), stt=deepgram.STT(), turn_detection=EnglishModel(), )` Please feel free to reach out if you'd like me to walk you through any part in more detail or if you need additional examples. I'm here to help!
c
t
Thank you so much for sharing the link! If you have any specific questions or need a hand with the voicemail detection process mentioned in the documentation, please don’t hesitate to reach out. I’m here to help and would love to support you!
b
@cool-camera-83057 i have no problem with detection i can't leave full message
when agent start say() It cuts off at the moment of any sound from the user and does not leave a message
t
To make sure your voicemail message is left completely and clearly, here’s a friendly step-by-step guide you can follow: • Detect Voicemail System: Try using a tool like
detected_answering_machine
that activates right after the voicemail greeting is picked up.
Copy code
@function_tool
async def detected_answering_machine(self):
    """Call this tool after the voicemail greeting is detected"""
• Generate a Complete Message: Use
generate_reply()
to craft a full voicemail message that stands on its own.
Copy code
await self.session.generate_reply(
    instructions="Leave a voicemail letting the user know you'll call back later."
)
• Prevent Interruption: Be sure to set
allow_interruptions=False
so the message plays all the way through without getting cut off.
Copy code
Agent(
    instructions="...",
    allow_interruptions=False  # Prevents early cutoff
)
• Add a Natural Pause: It’s helpful to include a brief pause after the message to give the voicemail system time to capture everything.
await asyncio.sleep(0.5)  # Ensures full message capture
• Hang Up Properly: Finally, make sure to end the call cleanly once the message is complete.
await ctx.api.room.delete_room(room=ctx.room.name)
Following these steps will help your voicemail message come through clearly and completely. If anything feels unclear or you’d like me to walk you through more examples, just let me know—I’m here to help! Sources: Agents telephony integration | LiveKit Docs | Docs::Agents | basics/uninterruptable/README.md | livekit-agents/livekit/agents/voice/agent_activity.py
To help make sure the agent's say() method isn’t interrupted by any user sounds, you can set allow_interruptions=False. This way, your message will be delivered fully without getting cut off. Here’s a quick example:
Copy code
await session.say("This message will not be interrupted.", allow_interruptions=False)
If you’d prefer, you can also set the entire agent to be uninterruptible by default like this:
Copy code
agent = Agent(
    instructions="You are a helpful assistant.",
    stt=deepgram.STT(),
    llm=openai.LLM(model="gpt-4o"),
    tts=openai.TTS(),
    allow_interruptions=False  # Prevents interruptions for all speech
)
This is especially handy for important messages, such as voicemail recordings. If you have any questions or need a hand setting this up, just let me know—I’m here to help! Sources: Turn detection and interruptions | LiveKit Docs | docs/index.yaml | Docs::Agents