how can I suspend a deployed agent
# ask-ai
f
how can I suspend a deployed agent
t
Thanks for reaching out, venu. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! LiveKit doesn’t have a direct command to suspend a deployed agent, but no worries—you can still get the same effect with a couple of handy workarounds: • Delete and Redeploy: You can use
lk agent delete --id <agent-id>
to stop the agent. Just make sure to save your configuration so you can redeploy it whenever you’re ready. • Code-Based Suspension: Another option is to tweak your agent’s code to check for an environment variable (like
AGENT_SUSPENDED=true
). If it’s set, the agent can exit or disable its functions. Deploy this updated version to effectively pause your agent. If you want, I’d be happy to help with a sample implementation or any other questions you have. Just let me know! Sources: Agent deployment CLI reference | LiveKit Docs | cmd/lk/agent.go | Deploying to production | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
f
class Evi(Agent): def __init__(self, _initialUserCtx_: str, _instructions_: str) -> None: super().__init__(instructions=instructions) # Initialize ChatContext self._chat_ctx = ChatContext.empty() # Add initial messages to ChatContext if _initialUserCtx_: chat_ctx = self._chat_ctx.copy() chat_ctx.add_message(role="system", content=instructions) chat_ctx.add_message(role="user", content=initialUserCtx) self.update_chat_ctx(chat_ctx) # Persist changes self.paused: bool = False async def on_enter(self) -> None: if not self.paused: # Use the updated ChatContext for generating a reply await self.session.generate_reply( instructions=INITIAL_USER_FALLBACK_PROMPT ) async def on_exit(self) -> None: return await super().on_exit() how do I pass chat_ctx as instructions in generate reply
t
Hey there! To pass
chat_ctx
as instructions in
generate_reply
, you’ll want to pull out the relevant bits from
chat_ctx
and then pass those explicitly as the
instructions
parameter. Here’s a simple way to do that: • Go through the messages in
chat_ctx
to grab specific content, like system messages or user preferences. • Use what you’ve pulled out to build a string for the
instructions
parameter. Here’s an example to make it clearer:
Copy code
def get_system_instructions_from_ctx(chat_ctx):
    return "\n".join(
        msg.text_content for msg in chat_ctx.messages if msg.role == "system"
    )

custom_instructions = get_system_instructions_from_ctx(custom_chat_ctx)
agent_session.generate_reply(
    instructions=custom_instructions,
    chat_ctx=custom_chat_ctx  # Preserve full history
)
If you want me to walk you through it more or need some extra examples, just let me know—I’m happy to help! Sources: livekit-agents/livekit/agents/llm/realtime.py | Workflows | LiveKit Docs
f
_generate_reply instructions = "\n".join([self._agent.instructions, instructions]) TypeError: sequence item 1: expected str instance, list found async def on_enter(self) -> None: if not self.paused: # Use the updated ChatContext for generating a reply messages=[ {"role": "system", "content": self.instructions}, {"role": "user", "content": self.session_context} ] logger.info("Initial messages for LLM:", messages) await self.session.generate_reply( instructions=messages )
t
Hey there! The error is happening because the
instructions
parameter in
generate_reply
needs to be a string, but it looks like a list was given instead. No worries though—here’s how you can fix it: • Make sure
instructions
is just one string. For example:
Copy code
await self.session.generate_reply(
    instructions="Greet the user warmly and offer assistance."
)
• If you’ve got a few strings you want to combine, you can use
"\n".join()
to put them together into a single string like this:
Copy code
instructions = "\n".join([
    "System: Provide a warm greeting.",
    "User: How can I assist you today?"
])
await self.session.generate_reply(instructions=instructions)
If anything’s unclear or you want a hand with this, just let me know—I’m here to help! Sources: examples/voice_agents/restaurant_agent.py | agent.py | Company directory phone assistant | LiveKit Docs | Workflows | LiveKit Docs | Agent speech and audio | LiveKit Docs
f
the instructions which we pass , what is the role for this when passed to llm ? is it system , user, assistant
t
When you pass the
instructions
parameter to the LLM in
generate_reply
, it’s treated as a system message. Think of it as giving the LLM some helpful guidance or context to shape how it responds. This system message sets the tone, rules, or instructions for the conversation, making sure the LLM stays on track with what you want it to do. Feel free to ask if you want me to explain anything more!
f
_discard_audio_if_uninterruptible_ = True, whose buffered audio is dropped? is it the agents or the users ?
t
When
discard_audio_if_uninterruptible
is set to
True
, any buffered user's audio gets dropped while the agent is speaking and can't be interrupted. This way, we make sure only the user input that comes in after the agent finishes talking is processed—keeping things clear and relevant for you. Sources: livekit-agents/livekit/agents/voice/agent_activity.py
f
_min_endpointing_delay_=0.8, _max_endpointing_delay_=8.0, _min_consecutive_speech_delay_=1.0, what does these do
t
Here’s a quick rundown of what these parameters do in LiveKit: • min_endpointing_delay: This is the shortest time (like 0.8 seconds) the agent waits after it thinks you might be done talking before it actually ends your turn. It helps make sure you don’t get cut off during those little pauses while you’re speaking. • max_endpointing_delay: This is the longest time (like 8.0 seconds) the agent will wait before ending your turn, even if you’re still talking. It’s there to make sure the agent doesn’t wait forever. • min_consecutive_speech_delay: This is the minimum pause (like 1.0 second) between the agent’s speech segments. It keeps the conversation flowing nicely without the agent jumping in too quickly. These settings help keep the conversation smooth and natural. If you want me to explain anything more, just let me know—I’m happy to help! Sources: Turn detection and interruptions | LiveKit Docs | How does end-of-utterance detection work in conversations? | livekit-agents/livekit/agents/voice/audio_recognition.py | LiveKit turn detector plugin | LiveKit Docs
f
this is how I ensure my pause functionality in frontend - if (isPaused != null && room?.localParticipant) { room.localParticipant.setAttributes({ paused: isPaused ? "true" : "false", }); if (isPaused) { room.remoteParticipants.forEach((p) => { if (p.kind == 4) { p.audioTrackPublications.forEach((_p) => { _p.setSubscribed(false); }); } }); } else { room.remoteParticipants.forEach((p) => { if (p.kind == 4) { p.audioTrackPublications.forEach((_p) => { _p.setSubscribed(true); }); } }); } } but when the agent keeps speaking, is there any way to stop the agent from talking
t
If you want to stop the agent from speaking when paused, you can simply use the
session.interrupt()
method. This will immediately stop any speech the agent is doing, no matter what it’s currently saying. Also, if you'd like to control whether the agent can be interrupted while speaking, you can set the
allow_interruptions
parameter to
False
when you use the
say()
method. Just a heads up, though—calling
session.interrupt()
will still work even if interruptions are turned off. Feel free to reach out if you want a hand with setting this up! Sources: VoicePipelineAgent | LiveKit Docs | Agent speech and audio | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | Turn detection and interruptions | LiveKit Docs
f
so after session.interrupt (), can my agent resume from where it was speaking
t
After calling
session.interrupt()
, the agent doesn’t automatically pick up right where it left off. But no worries—you can set up the resumption yourself! Here’s how: • If the interruption turns out to be a "false interruption" (like when there’s no meaningful user input), you can catch this with the
agent_false_interruption
event and then call
session.generate_reply()
to get the agent to continue its previous response. • If the interruption includes a user transcript, the agent will see that as new input and respond fresh, rather than resuming the old response. Feel free to reach out if you want a hand setting this up—I’m here to help! Sources: Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/speech_handle.py | Agent speech and audio | LiveKit Docs
f
can you show a sample code using both session.interrupt and agent_false_interruption
t
Here’s a handy example that shows how you can use
session.interrupt()
and listen for the
agent_false_interruption
event to get your agent back on track with its speech:
Copy code
from livekit.agents import AgentSession

class MyAgent:
    def __init__(self, session: AgentSession):
        self.session = session
        self.last_instructions = None

        # Listen out for any false interruptions
        self.session.on("agent_false_interruption", self.handle_false_interruption)

    async def start_speaking(self, instructions):
        # Keep these instructions handy in case we need to pick up again
        self.last_instructions = instructions

        # Let the agent start talking
        await self.session.generate_reply(instructions=instructions)

    async def interrupt_speaking(self):
        # Pause the agent’s current speech
        await self.session.interrupt()

    async def handle_false_interruption(self, event):
        # If the interruption was a false alarm, resume speaking
        if self.last_instructions:
            await self.session.generate_reply(instructions=self.last_instructions)

# Here’s how you might use it
async def main():
    session = AgentSession()
    agent = MyAgent(session)

    # Start the conversation
    await agent.start_speaking("Hello, how can I assist you today?")

    # Interrupt the agent if needed
    await agent.interrupt_speaking()

    # If that interruption turns out to be false, the agent will jump right back in

# To run the example
# asyncio.run(main())
This setup makes sure your agent can smoothly pick up where it left off if it gets interrupted by mistake. If you want me to walk you through it more or tweak anything, just let me know—I’m here to help!
f
how is the handle_false_interruption being called
t
Hey! Just to explain, the
handle_false_interruption
method gets called automatically whenever the
agent_false_interruption
event pops up during the session. This usually happens if the agent’s speech gets cut off (like when
session.interrupt()
is used) but no meaningful user input (such as a transcript) comes through within the set timeout period (like
agent_false_interruption_timeout
). In the example code, you’ll see the event listener is set up like this:
Copy code
self.session.on("agent_false_interruption", self.handle_false_interruption)
This way, whenever the
agent_false_interruption
event happens, the session framework automatically calls the
handle_false_interruption
method for you. If anything’s unclear or you want me to walk you through it more, just let me know—I’m happy to help!
f
the handle_false_interruptions is currently called after a specified time, I want that to be called when we change value of certain variable
t
To trigger
handle_false_interruption
whenever a variable changes, instead of waiting for a timeout, you can simply call the method right when the variable updates. Here’s a quick example to show you how:
Copy code
class MyAgent:
    def __init__(self, session: AgentSession):
        self.session = session
        self.last_instructions = None
        self.is_paused = False  # Variable to track state

    async def start_speaking(self, instructions):
        self.last_instructions = instructions
        await self.session.generate_reply(instructions=instructions)

    async def interrupt_speaking(self):
        await self.session.interrupt()

    async def handle_false_interruption(self):
        if self.last_instructions:
            await self.session.generate_reply(instructions=self.last_instructions)

    def set_paused(self, paused):
        self.is_paused = paused
        if not paused:
            # Trigger handle_false_interruption when unpaused
            asyncio.create_task(self.handle_false_interruption())

# Example usage
async def main():
    session = AgentSession()
    agent = MyAgent(session)

    # Start speaking
    await agent.start_speaking("Hello, how can I assist you today?")

    # Interrupt the agent
    await agent.interrupt_speaking()

    # Change the variable to trigger resumption
    agent.set_paused(False)

# Run the example
# asyncio.run(main())
So, in this example, the
set_paused
method updates the variable and immediately calls
handle_false_interruption
if the agent is no longer paused. Feel free to reach out if you want me to walk you through it or if you have any other questions!
f
how to stop publishing from local participant audio track
t
If you want to stop publishing an audio track from the local participant in LiveKit, you can use the
unpublishTrack
method. Here’s a friendly guide on how to do it in different SDKs: • Swift SDK:
Copy code
let localAudioTrack: LocalAudioTrack = // reference to your audio track
if let publication = localParticipant.getPublication(for: localAudioTrack) {
    try await localParticipant.unpublish(publication: publication)
}
• Android SDK:
Copy code
val track: LocalAudioTrack = // reference to your audio track
localParticipant.unpublishTrack(track)
• Flutter SDK:
Copy code
final publication = localParticipant.trackPublications[trackSid];
if (publication != null) {
  await localParticipant.removePublishedTrack(publication.sid);
}
Unpublishing means the track won’t be sent to the server or other participants anymore. If you just want to pause sending audio for a bit without fully unpublishing, using
mute()
might be a better fit. Feel free to reach out if you have any questions or need a hand with this! Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/participant/Local... | Sources/LiveKit/TrackPublications/LocalTrackPublication.swift | lib/src/participant/remote.dart | Swift & iOS SDK | livekit/livekit_composite | DeepWiki
f
react native
t
Hey there! If you want to stop publishing an audio track from a local participant in LiveKit using React Native, you can simply use the
unpublishTrack
method. Here’s a quick example for you:
Copy code
import { useLocalParticipant } from '@livekit/react-native';

const { localParticipant } = useLocalParticipant();

// Assuming you have a reference to the audio track you want to unpublish
const stopPublishingAudio = async (track) => {
  try {
    await localParticipant.unpublishTrack(track);
    console.log('Audio track unpublished successfully');
  } catch (error) {
    console.error('Failed to unpublish audio track', error);
  }
};
This will take the track out of the session and stop it from being sent to others. If you're just looking to pause the audio temporarily, you might want to try
muteTrack()
instead. Feel free to reach out if you want me to walk you through it or if you have any other questions! Sources: src/room/participant/LocalParticipant.ts | Stream music over WebRTC using React and WebAudio
f
puase the audio temporarily
t
Hey there! If you want to temporarily pause an audio track from a local participant in LiveKit using React Native, you can use the
pauseUpstream()
method on the track's publication. Here’s a quick example to help you out:
Copy code
import { LocalParticipant, Track } from 'livekit-client';

// Assuming you have access to the local participant object
const localParticipant: LocalParticipant = room.localParticipant;

// Get the microphone track publication
const microphonePublication = localParticipant.getTrackPublication(Track.Source.Microphone);

if (microphonePublication) {
  // Pause audio upstream (stop sending to server)
  await microphonePublication.pauseUpstream();

  // Later, resume audio upstream
  await microphonePublication.resumeUpstream();
}
Just a heads up:
pauseUpstream()
will stop the audio from being sent to the server but keeps your local track active. When you're ready, just call
resumeUpstream()
to pick things back up. If you have any questions or need a hand, feel free to ask—I’m here to help! Sources: src/room/participant/LocalParticipant.ts
f
async def handle_false_interruption(self): last_instructions = self.session.history.to_dict() logger.debug(_f_"Handling false interruption, resuming with instructions: {last_instructions}") await self.session.generate_reply(instructions=last_instructions) here the history is being passed by I want the agent to resume from that part where it was paused
t
If you want the agent to pick up right where it left off after a false interruption, you can use the
AgentFalseInterruptionEvent
. This event gives you the
extra_instructions
field, which holds the original instructions passed to
generate_reply()
, and sometimes the
message
field, which has the partial assistant message up to the interruption. Here’s a quick example to show how it works:
Copy code
@session.on("agent_false_interruption")
def handle_false_interruption(ev: AgentFalseInterruptionEvent):
    logger.info("Resuming agent from interruption", extra={"instructions": ev.extra_instructions})
    session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)
Just make sure you’ve set
agent_false_interruption_timeout
in your
AgentSession
to decide how long to wait before calling an interruption false. This way, the agent can smoothly and accurately continue from where it stopped. Feel free to reach out if you want me to walk you through anything else! Sources: livekit-agents/livekit/agents/voice/agent_activity.py
f
class Evi(Agent): def __init__(self, _session_AgentSession, initialUserCtx str, _instructions_: str) -> None: super().__init__(instructions=instructions) self.session_context= initialUserCtx self.paused: bool = False async def on_enter(self) -> None: if not self.paused: messages="\n".join([ self.instructions, self.session_context ]) logger.info("Initial messages for LLM:", messages) await self.session.generate_reply( instructions=messages ) async def handle_false_interruption(self): last_instructions = self.session.history.to_dict() logger.debug(_f_"Handling false interruption, resuming with instructions: {last_instructions}") await self.session.generate_reply(instructions=last_instructions) async def on_pause(self,_is_paused_) -> None: self.paused = _is_paused_ if not self.paused: asyncio.create_task(self.handle_false_interruption()) async def on_exit(self) -> None: return await super().on_exit() async def handle_pause_state_change(_session_: AgentSession, _agent_:Evi, _is_paused_: bool) -> None: if _is_paused_: session.interrupt() else: await agent.on_pause(_is_paused_=False) can you tell me how to use it this way
t
Here’s how you can use the implementation to handle pause and resume functionality step-by-step: 1. Initialize the Agent: Start by creating an instance of the
Evi
class, making sure to pass in the necessary parameters like
session
,
initialUserCtx
, and
instructions
. 2. Handle Pause State Changes: Use the
handle_pause_state_change
function to manage when the agent should pause or resume. If
is_paused
is
True
, it will interrupt the session. When
is_paused
is
False
, it resumes the agent by calling
on_pause
. 3. Trigger Pause/Resume: Simply call
handle_pause_state_change
with the right
is_paused
value to pause or resume the agent as needed. Here’s a quick example to show you how it works:
Copy code
# Initialize the session and agent
session = AgentSession()
agent = Evi(session=session, initialUserCtx="Hello!", instructions="Assist the user.")

# Pause the agent
await handle_pause_state_change(session=session, agent=agent, is_paused=True)

# Resume the agent
await handle_pause_state_change(session=session, agent=agent, is_paused=False)
When you pause, the session will interrupt the agent’s speech. And when you resume, the agent picks up right where it left off by calling
handle_false_interruption
. If anything’s unclear or you want to dive deeper, just let me know—I’m here to help!
f
how to get that extra_instructions value here
t
Hey there! To get the
extra_instructions
value in your setup, you can grab it straight from the
AgentFalseInterruptionEvent
when you're handling the
agent_false_interruption
event. Here’s a quick example:
Copy code
@session.on("agent_false_interruption")
def handle_false_interruption(ev: AgentFalseInterruptionEvent):
    # Grab the extra_instructions from the event
    instructions = ev.extra_instructions
    logger.info("Resuming agent", extra={"instructions": instructions})
    # Use those instructions to pick up where the agent left off after the interruption
    session.generate_reply(instructions=instructions or NOT_GIVEN)
The
extra_instructions
field holds the original instructions you passed to
generate_reply
, so it’s perfect for helping the agent continue its response smoothly after a false interruption. If anything’s unclear or you want to dive deeper, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_session.py
f
how to manually trigger false interruption and resume from from false interruption manually. and if I do not write @seesion.on("agent_false_interruption") will the extra_instructions var still be there
t
Here’s a quick guide to help you with your questions: • Manually Triggering a False Interruption: False interruptions can’t be triggered directly. They happen automatically when user audio is detected but no transcript comes through within the
agent_false_interruption_timeout
. To simulate this, you can interrupt the agent (like with
session.interrupt()
) and just make sure no transcript is sent from the user side. • Resuming from a False Interruption: You can use the
agent_false_interruption
event to get the agent back on track. Here’s a quick example:
Copy code
@session.on("agent_false_interruption")
def handle_false_interruption(ev: AgentFalseInterruptionEvent):
    session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)
• Accessing
extra_instructions
Without the Event:
Just a heads up—the
extra_instructions
field is only available inside the
agent_false_interruption
event handler. So if you’re not using
@session.on("agent_false_interruption")
, you won’t be able to access
extra_instructions
. If anything’s unclear or you want to dive deeper, just let me know—I’m here to help! Sources: examples/voice_agents/README.md
f
so I am able to pause the agent by session.interrupt() but not resume from where the agent left talking. How can I achieve this? All this has to be manually triggered . Also can we create custom events on session
t
Hey there! If you want to manually resume an agent after calling
session.interrupt()
, you can simply use the
session.generate_reply()
method. This will pick up the agent’s response right where it left off, based on the current conversation state. Here’s a quick example:
Copy code
# Resume the agent manually\nsession.generate_reply(instructions=\"Resume from where you left off.\")
Now, if the interruption was actually a false alarm, you can have it resume automatically by using the
agent_false_interruption
event like this:
Copy code
@session.on(\"agent_false_interruption\")\ndef handle_false_interruption(ev: AgentFalseInterruptionEvent):\n    session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)
Custom Events: Just a heads up, LiveKit doesn’t support creating custom events on
AgentSession
. But no worries—you can still use built-in events like
agent_state_changed
or
conversation_item_added
to run your own custom logic. If you have any questions or want me to walk you through anything else, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_session.py | agents/src/voice/agent_session.ts