I am using livekit for handling calls(both inbound...
# ask-ai
b
I am using livekit for handling calls(both inbound and outbound), currently i am using azure realtime model, during calls, there is one issue, due to background noises or user interrupting, the agent stops, and it starts repeating itself, like the last sentence which it spoke, i want to handle the interruption via events, and want it to be more natural, so wanted to update the ctx object to store where agent was interrupted, what it was going to speak and what the user said to produce the new output
t
Thanks for reaching out, Siddharth. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I completely understand how important it is to smoothly handle interruptions during calls and keep your context updated. LiveKit has some great built-in features to help with this: • When an interruption happens, LiveKit automatically stops the agent's speech playback and updates the context object with the text that was actually spoken before the interruption. This way, your conversation history stays accurate and meaningful. • If you want to trigger interruptions yourself, you can use the
interrupt()
method. Here’s a quick example:
Copy code
# Interrupt current and queued speeches
future = activity.interrupt(force=False)
await future  # Wait for interruption to complete
• The
force
parameter lets you decide whether to interrupt regardless of the
allow_interruptions
setting. • And if there are moments where you want to prevent interruptions, simply set
allow_interruptions=False
when calling
say()
or
generate_reply()
. For instance:
Copy code
session.say("Sorry, can I pause you there?", allow_interruptions=False)
await session.generate_reply(allow_interruptions=False)
• For those tricky false interruptions, LiveKit smartly pauses the audio instead of stopping it right away. If no new user speech comes in shortly, the audio just picks back up, keeping things feeling natural. These tools really help you manage interruptions gracefully and keep your conversations flowing smoothly. If you’d like, I’m here to help walk you through the implementation or answer any questions you have! Sources: Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/events.py | agents/src/voice/speech_handle.ts | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | pipeline-llm/interrupt_user.py
b
i am not using seperate stt/tts pipeline, i am using realtime model, so this session.say is not present, and idts livekit keeps track of what was already spoken by the agent before interruption, i think it erases that completely and continues from last complete sentence and what user spoke
t
When using Azure's real-time model with LiveKit, interruptions are handled a bit differently since the
session.say
method isn’t used here. Let me walk you through how you can manage interruptions and keep your context updated smoothly: • First, you can use the
interrupt()
method to programmatically stop speech. Here’s a simple example:
Copy code
# Interrupt current and queued speeches
future = activity.interrupt(force=False)
await future  # Wait for interruption to complete
• To update the context properly, you’ll want to use the
truncate()
method to reflect where the playback actually stopped before the interruption. Here’s how that looks:
Copy code
def truncate(
    self,
    *,
    message_id: str,
    modalities: list[Literal["text", "audio"]],
    audio_end_ms: int,
    audio_transcript: NotGivenOr[str] = NOT_GIVEN,
):
    if "audio" in modalities:
        self.send_event(
            ConversationItemTruncateEvent(
                type="conversation.item.truncate",
                content_index=0,
                item_id=message_id,
                audio_end_ms=audio_end_ms,
            )
        )
• For handling false interruptions, LiveKit actually pauses the audio output instead of stopping it right away. If it doesn’t detect any more user speech within a certain time, it will resume the audio automatically. • It’s important to keep chat context updates synchronized between your client and server to ensure everything stays in harmony. • If you’re using your own custom interruption logic, make sure to disable server-side turn detection, as it might interfere with how LiveKit manages interruptions. Following these steps will help you manage interruptions gracefully and keep your conversations feeling natural. If anything’s unclear or you’d like me to explain further, just let me know—I’m here to help! Sources: pipeline-llm/interrupt_user.py | Turn detection and interruptions | LiveKit Docs | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | Bringing AI avatars to voice agents | plugins/openai/src/realtime/realtime_model.ts
b
I was thinking of creating a listener, which listens when the user_state_changed from listening to speaking and agent state was speaking, at that time the interrupt happened, so in this callback i could give my custom logic to update the ctx
t
It’s wonderful that you’re setting up listeners for
user_state_changed
and
agent_state_changed
to manage interruptions and add your own custom logic. Here’s a friendly guide on how you can bring this to life: • First, set up your event listeners for
user_state_changed
and
agent_state_changed
like this:
Copy code
session.on("user_state_changed", handle_user_state_change)
session.on("agent_state_changed", handle_agent_state_change)
• Next, define the event handlers to catch those interruptions:
Copy code
def handle_user_state_change(event):
    if event.new_state == "speaking" and session.agent_state == "speaking":
        print("🚨 User interrupting agent!")
        # Here’s where you can add your custom logic to update the context

def handle_agent_state_change(event):
    if event.old_state == "speaking" and event.new_state == "listening":
        print("🔄 Agent was interrupted while speaking")
        # Feel free to add your logic to handle this interruption
• If you want to trigger an interruption programmatically, you can simply call:
Copy code
session.interrupt()
• And to keep your context up to date, you might want to modify the chat context or use the
truncate()
method, so everything reflects the interruption properly. This setup should help you smoothly detect when the user interrupts the agent and apply your custom logic accordingly. If you’d like, I’m here to assist you further with any part of the implementation—just let me know! Sources: agents/src/voice/agent_session.ts | livekit-agents/livekit/agents/voice/room_io/room_io.py
b
• And to keep your context up to date, you might want to modify the chat context or use the
truncate()
method, so everything reflects the interruption properly. This setup should help you smoothly detect when the user interrupts the agent and apply your custom logic accordingly. If you’d like, I’m here to assist you further with any part of the implementation—just let me know! can u give me the logic on how to update the ctx, in the listeners
t
When it comes to updating the context (
ctx
) in your listeners during interruptions, a great way to handle this is by using the
agent.update_chat_ctx()
method. Let me walk you through how you can do this: • First, when you detect an interruption, you’ll want to create a new
ChatMessage
object that captures the user’s input along with the interrupted state. For example:
Copy code
from livekit.agents.llm import ChatContext, ChatMessage

# Create a new ChatMessage for the interruption
interruption_message = ChatMessage(
    type="message",
    role="user",
    content="User interrupted the agent and said: '...'")
• Next, update the chat context with this new message:
Copy code
# Update the chat context
chat_ctx = ChatContext([interruption_message])
await agent.update_chat_ctx(chat_ctx)
• Make sure to update the context before you generate a new reply:
Copy code
# Generate a reply after updating the context
await session.generate_reply()
• For RealtimeModels, the
update_chat_ctx()
method helps keep the local context in sync with the server by sending only the new messages. This way, your context stays accurate without repeating any history. • Also, it’s a good idea to handle any exceptions like
llm.RealtimeError
in case the update takes too long. This method helps ensure your context truly reflects the interruption, allowing the agent to respond just right. If anything feels unclear or you want a hand with the implementation, please don’t hesitate to ask—I’m here to help! Sources: Agents v0.x migration guide - Node.js | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | pipeline-llm/interrupt_user.py
b
where i have to add this callback listener?? in the agent class, or in the entrypoint?? # Start the session await session.start(agent=assistant, room=ctx.room) logger.info("🎙️ Agent session started.") # Send the initial "Hello" to kick off the conversation await session.generate_reply(user_input="Hello") here is the code where i started the agent conversation, further convo is handled via agent session itself, now where should i add the callback to handle interrupts
t
It’s a great idea to add the callback listeners for handling interruptions right in the same entrypoint where you initialize and start the agent session. I’d recommend setting up the listeners before you call
session.start()
. This way, the listeners are ready and active as soon as your session kicks off. Here’s a friendly example of how you can weave the listeners into your code:
Copy code
# Set up the session
session = AgentSession(...)

# Add the callback listeners
session.on("user_state_changed", handle_user_state_change)
session.on("agent_state_changed", handle_agent_state_change)

# Start the session
await session.start(agent=assistant, room=ctx.room)
logger.info("🎙️  Agent session started.")

# Send the initial "Hello" to kick off the conversation
await session.generate_reply(user_input="Hello")
By placing the listeners before
session.start()
, you make sure that any interruptions or changes in state are caught right from the start of the session. If you’d like me to walk you through this or if there’s anything else you want to explore, just let me know—I’m here to help!
b
can u walk me through how a call would proceed after these changes, like walking me through the flow after session.start
t
Let me walk you through how a call would proceed after making these changes and starting the session. I hope this helps clarify things! 1. Session Initialization: We begin by initializing the session with the agent and room details. The callback listeners for
user_state_changed
and
agent_state_changed
are already set up before calling
session.start()
. 2. Session Start: Once
session.start()
is called, the agent sends an initial message (like "Hello") using
session.generate_reply()
. This is what kicks off the conversation. 3. Listening for User Input: The session then listens for user input. When the user starts speaking, the
user_state_changed
event triggers, and the corresponding callback runs. If the user interrupts the agent while it’s speaking, the callback detects this and manages the interruption. 4. Handling Interruption: Inside the
user_state_changed
callback, if the user interrupts the agent (meaning the user state changes to "speaking" while the agent is also "speaking"), this interruption is recognized. The callback updates the context (
ctx
) using
agent.update_chat_ctx()
to reflect both the interruption and the user’s input. 5. Generating a Response: After updating the context, the agent creates a new response with
session.generate_reply()
. This way, the response is based on the latest context, including the interruption details. 6. Continuing the Conversation: The session keeps handling the conversation smoothly, with listeners actively watching for any further interruptions or state changes. Every time an interruption happens, the context updates, and the agent replies accordingly. 7. Session End: Finally, when the conversation wraps up, the session is closed and any necessary cleanup is done. This flow is designed to handle interruptions smoothly, keep the context accurate, and allow the conversation to flow naturally. If you’d like me to explain any part in more detail or need help with something specific, please don’t hesitate to ask—I’m here to help!
b
context (
ctx
) using
agent.update_chat_ctx()
to reflect both the interruption and the user’s input. since the callback will be triggered while user is still speaking, how would i know what the user said??
t
I understand how important it is to capture the user’s input accurately, even while they’re still speaking. When the callback is triggered during this time, you can actually grab the user’s input through the interim and final transcripts created by the Speech-to-Text (STT) system. Here’s a friendly breakdown of how this works: • As the user talks, the STT system provides interim transcripts in real-time. These keep updating until the user finishes speaking, and then a final transcript is created. • You can tap into these interim transcripts in the callback to handle interruptions smoothly. For instance, you might add the interim transcript to a buffer and then process it once the user pauses or completes a sentence. • When the final transcript is ready, you can use it to update the context (
ctx
) and craft a thoughtful response. If you’d like, I’d be happy to share a code example to show you how to manage interim transcripts and update the context on the fly. Just let me know if that sounds helpful—I’m here to support you! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | agents/src/voice/agent_activity.ts | docs/index.yaml | Agent speech and audio | LiveKit Docs
b
I am using azure realtime so no seperate stt is present
t
I’m glad you asked about how Azure’s real-time model handles user input during interruptions! It’s designed to make things smooth and effortless for you. Here’s a quick overview: • As the user speaks, the Azure real-time model creates transcripts instantly. These transcripts are directly processed by the LiveKit framework, so you don’t have to worry about setting up a separate STT pipeline. • If an interruption happens, the system gently pauses the agent’s speech and captures the user’s input. This transcript is then passed along to the agent for the next steps. • You can easily listen for user input events like
UserInputTranscribedEvent
to grab the transcript dynamically. For example:
Copy code
self._session._user_input_transcribed(
    UserInputTranscribedEvent(
        language=ev.alternatives[0].language,
        transcript=ev.alternatives[0].text,
        is_final=False,
        speaker_id=ev.alternatives[0].speaker_id,
    ),
)
• Once the user finishes speaking, the final transcript is ready to update the context (
ctx
) and help generate a thoughtful response. This setup makes sure user input is captured smoothly during interruptions, without any extra STT setup on your end. If you’d like, I’m here to help with any part of the implementation or answer any questions you have! Sources: livekit-agents/livekit/agents/voice/events.py | Turn detection and interruptions | LiveKit Docs | docs/index.yaml | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki
b
class InterruptionTracker: def __init__(self, session: AgentSession): self.interrupted_text: str = "" self.is_interrupted: bool = False self.pending_speech: str = "" self.session = session tracker = InterruptionTracker(session) async def on_user_state_changed(event: UserStateChangedEvent): nonlocal tracker if (event.new_state == "speaking" and session.agent_state == "speaking" and not tracker.is_interrupted): logger.info("👤 User started speaking over agent (interruption detected)") tracker.is_interrupted = True # Store what the agent was about to say if hasattr(session, '_current_speech'): tracker.pending_speech = getattr(session, '_current_speech', '') async def on_agent_state_changed(event: AgentStateChangedEvent): nonlocal tracker if event.new_state == "listening" and tracker.is_interrupted: logger.info("🤖 Agent stopped speaking due to interruption") # The agent will now wait for user input async def on_user_input_transcribed(event: UserInputTranscribedEvent): nonlocal tracker if event.is_final and tracker.is_interrupted: logger.info(f"🎤 User said: {event.transcript}") tracker.interrupted_text = event.transcript # Reset the interruption state tracker.is_interrupted = False tracker.pending_speech = "" # Now create the tracker and register the handlers session.on("user_state_changed", on_user_state_changed) session.on("agent_state_changed", on_agent_state_changed) session.on("user_input_transcribed", on_user_input_transcribed) i have started doing some chanegs can u guide me how i can use this to update the chat history(ctx) for llm to handle interruptions better
t
Your implementation of the
InterruptionTracker
and the event handlers for
user_state_changed
,
agent_state_changed
, and
user_input_transcribed
looks well-structured. I’d love to walk you through how this flow works to make sure everything is clear and working as you expect: 1. Tracking Interruption: The
on_user_state_changed
handler notices when the user starts speaking while the agent is still talking. It sets the
is_interrupted
flag and keeps track of the agent’s pending speech (if there is any). 2. Handling Agent State: The
on_agent_state_changed
handler catches when the agent stops speaking because of the interruption. This helps ensure the agent is ready to listen and process what the user says next. 3. Processing User Input: The
on_user_input_transcribed
handler takes the user’s final transcript once their input is complete. It then resets the interruption state and clears any saved pending speech. 4. Event Registration: All these handlers are registered with the session, so they trigger at just the right moments during the interaction. This setup really helps interruptions flow smoothly, keeps the agent’s speech intact, and accurately captures the user’s input. If you’d like, I’m here to help with any questions or if you want to explore any enhancements to this implementation!
b
class InterruptionTracker: def __init__(self, session: AgentSession): self.interrupted_text: str = "" self.is_interrupted: bool = False self.pending_speech: str = "" self.session = session tracker = InterruptionTracker(session) async def on_user_state_changed(event: UserStateChangedEvent): nonlocal tracker if (event.new_state == "speaking" and session.agent_state == "speaking" and not tracker.is_interrupted): logger.info("👤 User started speaking over agent (interruption detected)") tracker.is_interrupted = True # Store what the agent was about to say if hasattr(session, '_current_speech'): tracker.pending_speech = getattr(session, '_current_speech', '') async def on_agent_state_changed(event: AgentStateChangedEvent): nonlocal tracker if event.new_state == "listening" and tracker.is_interrupted: logger.info("🤖 Agent stopped speaking due to interruption") # The agent will now wait for user input async def on_user_input_transcribed(event: UserInputTranscribedEvent): nonlocal tracker if event.is_final and tracker.is_interrupted: logger.info(f"🎤 User said: {event.transcript}") tracker.interrupted_text = event.transcript # Reset the interruption state tracker.is_interrupted = False tracker.pending_speech = "" # Now create the tracker and register the handlers session.on("user_state_changed", on_user_state_changed) session.on("agent_state_changed", on_agent_state_changed) session.on("user_input_transcribed", on_user_input_transcribed) i have started doing some chanegs can u guide me how i can use this to update the chat history(ctx) for llm to handle interruptions better
t
To help you use your
InterruptionTracker
for updating the chat history (
ctx
) and improve how the LLM handles interruptions, here’s a friendly step-by-step guide: 1. Capture Interruption Details: In the
on_user_input_transcribed
handler, once the user’s final transcript is ready, create a new
ChatMessage
object to capture the interruption and the user’s input like this:
Copy code
from livekit.agents.llm import ChatContext, ChatMessage

# Create a new ChatMessage for the interruption
interruption_message = ChatMessage(
    type="message",
    role="user",
    content=f"User interrupted and said: {tracker.interrupted_text}"
)
1. Update the Chat Context: Next, use the
agent.update_chat_ctx()
method to add this new message to the context:
Copy code
# Update the chat context
chat_ctx = ChatContext([interruption_message])
await tracker.session.agent.update_chat_ctx(chat_ctx)
1. Handle Pending Speech: If the agent was in the middle of speaking when interrupted, it’s helpful to include that too. Here’s how you can do it:
Copy code
# Add the agent's pending speech to the context
if tracker.pending_speech:
    pending_message = ChatMessage(
        type="message",
        role="assistant",
        content=f"Agent was interrupted while saying: {tracker.pending_speech}"
    )
    chat_ctx.items.append(pending_message)

# Update the context again
await tracker.session.agent.update_chat_ctx(chat_ctx)
1. Generate a Response: Finally, after updating the context, generate a fresh response based on this updated history:
Copy code
# Generate a response
await tracker.session.generate_reply()
This way, the LLM gets the full picture of the interruption—what the agent was saying and what the user added—so it can respond thoughtfully. If anything feels unclear or you’d like me to walk you through any part, just let me know! I’m here to help.
b
can u give me the full updated code
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!
b
can u tell how can i fetch the current speech of the agent to update when the state changes so that i can update my tracker