show me the simplest usage of on_user_turn_complet...
# ask-ai
p
show me the simplest usage of on_user_turn_completed with a full code example just write some logger in it to check if it works
t
Thanks for reaching out, Yasser. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Here is a simple example of using
on_user_turn_completed
with a logger to verify its functionality:
Copy code
import logging

from dotenv import load_dotenv

from livekit.agents import (
    Agent,
    AgentSession,
    AutoSubscribe,
    JobContext,
    StopResponse,
    WorkerOptions,
    cli,
    llm,
)
from livekit.plugins import openai, silero

load_dotenv()

logger = logging.getLogger("simple-agent")

class SimpleAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant.",
            stt=openai.STT(),
        )

    async def on_user_turn_completed(self, chat_ctx: llm.ChatContext, new_message: llm.ChatMessage):
        user_transcript = new_message.text_content
        <http://logger.info|logger.info>(f"User said: {user_transcript}")

        # Optional: Stop the agent from generating a reply
        # raise StopResponse()

async def entrypoint(ctx: JobContext):
    <http://logger.info|logger.info>(f"Starting agent in room: {ctx.room.name}")
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)

    session = AgentSession(
        vad=silero.VAD.load(min_silence_duration=0.3),
    )

    await session.start(
        agent=SimpleAgent(),
        room=ctx.room,
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
This example demonstrates: • Setting up a logger to log user input. • Implementing the
on_user_turn_completed
method to log the user’s transcript using
new_message.text_content
. • Optionally raising
StopResponse()
to prevent the agent from generating a reply. The method is triggered when the user’s turn ends, making it ideal for logging, validation, or modifying the chat context. Sources: tests/test_agent_session.py | Voice pipeline nodes | LiveKit Docs
p
yes i want to raise StopResponse however im using an old version of livekit that uses VoicePipelineAgent instead of agent session, would that works also? livekit agent version >=0.12.17<0.13.0
t
Hey there! Just to let you know, raising
StopResponse
in
on_user_turn_completed
works smoothly with
VoicePipelineAgent
in LiveKit agent versions >=0.12.17<0.13.0. It’s a supported and documented way to handle things. When you raise
StopResponse
, the agent simply skips the current turn and doesn’t generate a reply. Here’s a quick example to show you how it works:
Copy code
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage):
    if not new_message.text_content:
        # Raise StopResponse to stop the agent from generating a reply
        raise StopResponse()
This feature is super handy if you want to add conditional response logic, like push-to-talk setups or filtering out inputs you don’t want. If you’d like, I’m happy to help you tailor this for your specific setup—just let me know! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Voice pipeline nodes | LiveKit Docs
p
how to import StopResponse to be used in on_user_turn_completed function
t
Hey there! To bring
StopResponse
into your
on_user_turn_completed
function, you can simply add this import statement:
Copy code
from livekit.agents import StopResponse
That’s the usual way to do it. Once you've got it imported, you can use
StopResponse
to stop the agent from replying. Here’s a quick example:
Copy code
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage):
    if not new_message.text_content:
        # Raise StopResponse to stop the agent from generating a reply
        raise StopResponse()
If you have any questions or want me to walk you through it, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | home_assistant/homeautomation.py | Voice pipeline nodes | LiveKit Docs
p
is it need some decorator so on_user_turn function to be invoked once the user is finished talking? because it didn't being called in my case
t
Hey there! Just to clarify, the
on_user_turn_completed
method doesn’t need a decorator to be triggered when the user finishes talking. It’s a lifecycle hook you override in your custom
Agent
subclass, and the LiveKit framework takes care of calling it automatically right after the user’s turn ends, just before the agent crafts a reply. Here’s a quick example of how you can implement it:
Copy code
async def on_user_turn_completed(self, turn_ctx: llm.ChatContext, new_message: llm.ChatMessage):
    """Called when the user has finished speaking, and the LLM is about to respond."""
    # Your custom logic here
    pass
If you’re not seeing this method get called, here are a few things to double-check: • Make sure you’ve properly overridden the method in your custom agent class. • Confirm that your agent is correctly hooked into the session or pipeline (like
AgentSession
or
VoicePipelineAgent
). • Verify that the framework is detecting when the user’s turn ends (for example, using VAD or other ways). If you’d like, I’m here to help you troubleshoot further—just let me know! Sources: Voice pipeline nodes | LiveKit Docs | examples/voice_agents/preemptive_generation.py
p
in what version exactly does the on_user_turn_completed got released?
t
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!