Which event should we treat as authoritative end-o...
# ask-ai
f
Which event should we treat as authoritative end-of-turn when using the LiveKit turn detector: an explicit EOU event,
user_state_changed
transitioning from `speaking`→other, or something exposed right before
on_user_turn_completed
is called? Please point to the recommended Python-side event and provide a sample.
t
Thanks for reaching out, Muthana. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! Just wanted to share that the key event to watch for when using LiveKit's turn detector is the
on_user_turn_completed
event in the Python API. This event pops up when the system figures out you've finished speaking, using a mix of voice activity detection (VAD) and some smart predictions from a transformer-based model. Here's a little example to help you get started:
Copy code
from livekit import rtc
from livekit.agents import Agent, AgentSession
from livekit.plugins.turn_detector.multilingual import MultilingualModel

class CustomTurnDetector:
    def __init__(self):
        self.model = MultilingualModel()

    async def predict_end_of_turn(self, chat_ctx):
        probability = await self.model.predict_end_of_turn(chat_ctx)
        return probability

class MyAgent(Agent):
    def __init__(self, turn_detector):
        super().__init__(
            instructions="You are a helpful assistant.",
            turn_detection=turn_detector
        )

    async def on_user_turn_completed(self, turn_ctx, new_message):
        # Generate a response when the user has finished speaking
        await self.session.generate_reply(f"Response to: {new_message.content}")

# Initialize the turn detector and agent
turn_detector = CustomTurnDetector()
agent = MyAgent(turn_detector)

# Start the agent session
session = AgentSession(
    agent=agent,
    vad=silero.VAD.load(),
    stt=gladia.STT(),
    llm=openai.LLM(),
    tts=openai.TTS(),
    turn_detection=turn_detector
)

await session.start()
This setup makes sure the
on_user_turn_completed
event is your go-to signal for when a user’s turn is done. If you want me to walk you through anything else or have questions, just give me a shout!