How can I make agent to ask question like "sorry, ...
# ask-ai
f
How can I make agent to ask question like "sorry, could you repeat that?" whenever user spoke something (user_state=speaking), but STT didn't output any text?
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 kindly ask, "Sorry, could you repeat that?" when
user_state=speaking
but no text is captured by STT. Here's a friendly step-by-step guide you can follow: 1. Detect User Speaking State: Keep an eye on when the user starts and stops speaking by using the
user_state_changed
event. 2. Monitor for Missing Transcripts: Once the user stops speaking (
user_state
switches to "listening"), check if any transcript was received. If nothing was captured, gently prompt the user to repeat. 3. Use Lifecycle Hooks: You can implement the
on_user_turn_completed()
lifecycle hook, which runs after the user's turn ends and transcript processing is done. Here's a simple example to illustrate this:
Copy code
class RepeatPromptAgent(Agent):
    def __init__(self):
        super().__init__()
        self.last_transcript = ""

    async def on_user_turn_completed(self):
        if not self.last_transcript.strip():
            await self.session.generate_reply("Sorry, I didn't catch that. Could you please repeat?")
        else:
            self.last_transcript = ""

    async def stt_node(self, text_stream):
        async def process_text():
            async for text in text_stream:
                self.last_transcript = text
                yield text
        return process_text()
If you prefer, you can also set up an event listener for
user_state_changed
like this:
Copy code
@session.on("user_state_changed")
async def on_user_state_changed(ev):
    if ev.old_state == "speaking" and ev.new_state == "listening":
        if not session.current_transcript.strip():
            await session.generate_reply("Sorry, I didn't hear anything. Could you repeat that?")
Just a quick tip: make sure you’re capturing transcripts using
on_interim_transcript
and
on_final_transcript
to keep your
current_transcript
up to date. Sources: Agent speech and audio | LiveKit Docs | Events and error handling | LiveKit Docs | examples/src/drive-thru/database.ts | Pipeline nodes and hooks | LiveKit Docs | examples/voice_agents/inactive_user.py
f
According to current stt_node definition, it expects 3 arguments. Therefore, the suggested solution fails with BaseAgent.stt_node() takes 2 positional arguments but 3 were given.
Copy code
stt_node(
        self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings
    ) -> (
        AsyncIterable[stt.SpeechEvent | str]
        | Coroutine[Any, Any, AsyncIterable[stt.SpeechEvent | str]]
        | Coroutine[Any, Any, None]
    )
t
The
stt_node
method in LiveKit requires two arguments:
audio
(an
AsyncIterable[rtc.AudioFrame]
) and
model_settings
(an instance of
ModelSettings
). To override it correctly, please make sure your method signature matches this requirement. Here's an updated implementation that should help you along:
Copy code
class RepeatPromptAgent(Agent):
    def __init__(self):
        super().__init__()
        self.last_transcript = ""

    async def on_user_turn_completed(self):
        if not self.last_transcript.strip():
            await self.session.generate_reply("Sorry, I didn't catch that. Could you please repeat?")
        else:
            self.last_transcript = ""

    async def stt_node(self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings):
        async def process_audio():
            async for frame in audio:
                # Process audio frames if needed
                yield frame

        # Call the default STT node with the processed audio
        return await super().stt_node(process_audio(), model_settings)
This approach ensures your method fits perfectly with what's expected, while still giving you the flexibility to handle audio frames as needed. If anything’s unclear or you’d like me to walk you through it, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/inference/stt.py | docs/index.yaml | Pipeline nodes and hooks | LiveKit Docs
f
How do I use it to make agent ask question like "sorry, could you repeat that?" whenever user spoke something (user_state=speaking), but STT didn't output any text?
t
I understand you'd like your agent to say, "Sorry, could you repeat that?" when
user_state=speaking
but no text is captured by STT. Here are a couple of friendly ways you can achieve this: 1. Override
stt_node
You can customize the
stt_node
method to spot when the transcription is empty and then trigger a response. Here's a simple example to guide you:
Copy code
class MyAgent(Agent):
    async def stt_node(self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings):
        async for event in self.default.stt_node(audio, model_settings):
            if isinstance(event, stt.SpeechEvent):
                if (event.type in [stt.SpeechEventType.FINAL_TRANSCRIPT, stt.SpeechEventType.INTERIM_TRANSCRIPT] and
                    (not event.alternatives or not event.alternatives[0].text.strip())):
                    yield "EMPTY_TRANSCRIPT_DETECTED"
                    continue
            yield event
Then, in your agent’s logic, you can catch this "EMPTY_TRANSCRIPT_DETECTED" signal and respond with something like, "Sorry, could you repeat that?" 2. Use
on_user_turn_completed
Another friendly approach is to check for empty messages right after the user’s turn ends, like this:
Copy code
async def on_user_turn_completed(self, turn_ctx: llm.ChatContext, new_message: llm.ChatMessage):
    if not new_message.content.strip():
        await self.say("Sorry, I didn't catch that. Could you repeat it?")
This way, you don’t need to change the STT pipeline itself, and it keeps the handling nicely at the conversation level. If you’d like, I’m here to help you with any part of the implementation or if you want me to explain anything in more detail! Sources: Pipeline nodes and hooks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
f
Ok, my stt_node actually outputs some text, but it doesn't trigger turn
t
If your
stt_node
outputs text but doesn’t trigger a turn, don’t worry—let’s work through this together. Here are some friendly steps to help you resolve the issue: 1. Check Turn Detection Mode: First, make sure the correct
turn_detection
mode is set up. You have a few options: ◦ `"stt"`: This uses the STT model’s built-in endpointing, like silence detection. ◦ `"vad"`: This relies on Voice Activity Detection to know when the user stops speaking. ◦ Custom turn detector model: This uses a machine learning model specifically for detecting the end of a turn. 1. Configure STT to Avoid Conflicts: If your STT plugin has its own end-of-utterance detection, it’s a good idea to disable it to prevent any conflicts. For example, with Speechmatics, you can set
end_of_utterance_mode=EndOfUtteranceMode.NONE
. 2. Verify Event Flow: Double-check that your
stt_node
is emitting a
FINAL_TRANSCRIPT
event and, if needed, an
END_OF_SPEECH
event. These events are key to triggering turn detection. 3. Adjust Endpointing Delays: You might want to fine-tune
min_endpointing_delay
and
max_endpointing_delay
to get the responsiveness just right. When debugging, keep an eye on your logs for messages like
received user transcript
and
running EOU detection
. These will help confirm that everything is flowing as expected. If you run into any bumps or have questions, please don’t hesitate to reach out—I’m here to help! Sources: Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py | agents/src/voice/audio_recognition.ts | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki