How to stop the forcefully stop running agent or t...
# ask-ai
l
How to stop the forcefully stop running agent or task or fuction_calll and update new agent to the session using session.update_agent()
t
Thanks for reaching out, Rajadurai. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you're asking how to forcibly stop a running agent/task/function call and then replace it in the session with a new agent via
session.update_agent()
. I’ll walk through the typical steps and ask one quick question so I can tailor the answer to your code. Short question before specifics: • Are you using Python async agents (asyncio tasks) or another runtime? If Python asyncio, the steps below apply directly. Steps to stop a running function/task/agent and update the session 1. Stop the running function call or asyncio task • If the function is running as an asyncio Task, cancel the task:
Copy code
task.cancel()
• After calling
cancel()
, ensure you handle
asyncio.CancelledError
in the function to stop cleanup properly. 1. Interrupt the agent (session-level) • If the agent is mid-generation, call:
Copy code
session.interrupt()
This interrupts the agent’s current activity and helps ensure the session is not waiting on the old agent. 1. Complete or cancel AgentTask objects • If you are using
AgentTask
instances, call
complete()
when you want to mark them finished. If the AgentTask is actively running as a background asyncio task, cancel that underlying task as well. 1. Update the session with the new agent • Once the running work is stopped/interrupted, replace the agent:
Copy code
session.update_agent(NewAgent())
• Call this only after interruption/cancellation so the session switches cleanly to the new agent. Important notes and best practices • Always cancel the actual asyncio Task that is executing the function/agent logic; calling
session.interrupt()
helps but doesn’t replace cancelling the task itself. • Ensure your agent code catches
asyncio.CancelledError
and performs any needed cleanup (closing resources, releasing locks). • If you need to guarantee no stray tasks remain, track tasks you spawn (keep references) so you can cancel them explicitly. If you share a short code snippet showing how your agent/task is started (for example, how you create the asyncio Task or how
AgentTask
is used), I can give exact code to cancel it and then call
session.update_agent()
without race conditions. Sources: Agent session | LiveKit Documentation | Agents and handoffs | LiveKit Documentation
l
livekit.agents Error in _update_activity_task Traceback (most recent call last): File "/home/azureuser/dasboard-agent/.venv/lib/python3.12/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/azureuser/dasboard-agent/.venv/lib/python3.12/site-packages/livekit/agents/voice/agent_session.py", line 1094, in _update_activity_task await self._update_activity(agent) File "/home/azureuser/dasboard-agent/.venv/lib/python3.12/site-packages/livekit/agents/voice/agent_session.py", line 1039, in _update_activity raise RuntimeError("cannot start agent: an activity is already running") RuntimeError: cannot start agent: an activity is already running {"room": "voice_assistant_room_2095", "pid": 255157, "job_id": "AJ_fAFU9PEKRH6X", "room_id": "RM_4YqzdtcN8xCt"} Traceback (most recent call last): File "/home/azureuser/dasboard-agent/.venv/lib/python3.12/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/azureuser/dasboard-agent/.venv/lib/python3.12/site-packages/livekit/agents/voice/agent_session.py", line 1094, in _update_activity_task await self._update_activity(agent) File "/home/azureuser/dasboard-agent/.venv/lib/python3.12/site-packages/livekit/agents/voice/agent_session.py", line 1039, in _update_activity raise RuntimeError("cannot start agent: an activity is already running") RuntimeError: cannot start agent: an activity is already running
t
Thanks — I can see the RuntimeError: "cannot start agent: an activity is already running" from your logs. That error happens when you try to start or update an agent while an existing agent activity (speech, function call, or AgentTask) is still active. Below are practical steps, code patterns, and best practices to stop the running activity cleanly and then call
session.update_agent()
. Short checklist (what to do) • Interrupt the session’s current activity with
session.interrupt()
so the session stops current/queued speech and generation. • Cancel any underlying asyncio Task you created for the agent/function call (call
task.cancel()
and handle
asyncio.CancelledError
in the coroutine). • If using
AgentTask
objects, call
complete()
or otherwise mark them finished, and cancel any background tasks they spawned. • After interruption and cancellation are confirmed, call
session.update_agent(new_agent)
. Example flow (Python asyncio) 1. Interrupt session-level activity:
Copy code
# stop current speech/generation in the session
session.interrupt()
1. Cancel any explicit asyncio tasks you started:
Copy code
# assume you stored the task when starting the agent work
if agent_task is not None and not agent_task.done():
    agent_task.cancel()
    try:
        await agent_task
    except asyncio.CancelledError:
        # expected — task was cancelled
        pass
1. Ensure AgentTask is finalized (if used):
Copy code
# if using AgentTask API
if my_agent_task and not my_agent_task.completed:
    await my_agent_task.complete()  # or otherwise mark it finished
1. Safely update the session agent:
Copy code
# now replace the agent
session.update_agent(NewAgent())
Key details and best practices • session.interrupt() is designed to stop speaking/generation and to clear queued speech — call it before attempting update to avoid races. • Cancel the actual asyncio Task(s).
session.interrupt()
may not cancel tasks you spawned directly; keep references to those tasks so you can cancel them explicitly. • Make agent code robust: catch
asyncio.CancelledError
to clean up resources (audio handles, streams, locks). • Use short waits/polling or task.await to confirm cancellation before calling
update_agent()
to avoid a race where the session still thinks an activity is active. • If your code restarts agents frequently, centralize task tracking (e.g., a single list/dict of active tasks per session) so you can cancel them reliably. If you want, share: • A short snippet showing how you start the agent activity / create the asyncio task, and whether you use
AgentTask
or raw asyncio. • Whether the activity is speech synthesis, function call, or long-running background work. With that snippet I’ll provide an exact code patch to cancel the task, call
session.interrupt()
safely, and then call
session.update_agent()
without triggering the RuntimeError. Sources: examples/voice_agents | livekit/livekit_composite | DeepWiki