How do I make my agent to wait up to 5 sec at the ...
# ask-ai
f
How do I make my agent to wait up to 5 sec at the beginning of conversation and start speaking firsts if no input from user?
t
Thanks for reaching out, Taras. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you set up your agent to wait up to 5 seconds at the start of a conversation and then speak first if the user hasn't said anything. You can achieve this by using the
session.say()
method inside the agent's
on_enter()
lifecycle event. Here's a simple example to guide you:
Copy code
import asyncio
from livekit.agents import Agent

class WelcomeAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant.")
        self._welcome_task = None
        self._user_has_spoken = False

    async def on_enter(self):
        # Start a background task to wait 5 seconds
        self._welcome_task = asyncio.create_task(self._delayed_welcome())
        
        # Set up event listener for user activity
        self.session.on("user_state_changed", self._on_user_state_changed)

    async def _delayed_welcome(self):
        """Wait 5 seconds, then speak if user hasn't spoken yet"""
        try:
            await asyncio.sleep(5.0)
            if not self._user_has_spoken:
                await self.session.say("Hello! How can I help you today?")
        except asyncio.CancelledError:
            # Task was cancelled because user spoke first
            pass

    def _on_user_state_changed(self, event):
        """Cancel welcome message if user starts speaking"""
        if event.new_state == "speaking" and not self._user_has_spoken:
            self._user_has_spoken = True
            if self._welcome_task and not self._welcome_task.done():
                self._welcome_task.cancel()
This approach makes sure your agent patiently waits for the user to say something for 5 seconds and only steps in if there's no response. If you'd like me to walk you through any part of this or help customize it further, just let me know—I'm here to help! Sources: Agent speech and audio | LiveKit Docs | agent_extensions/README.md | Events and error handling | LiveKit Docs
✅ 1