In my agent Python, I need to shut down the local ...
# ask-ai
b
In my agent Python, I need to shut down the local participant. Please provide example code for this.
✅ 1
t
Thanks for reaching out, Mat. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’ll show how to shut down the local participant in a LiveKit Python agent and explain the recommended methods. Which part do you want: a short snippet for a JobContext-based agent, an AgentSession example, or both? If you’re not sure which you use, tell me whether your agent code uses `JobContext`/`@server.rtc_session` or an
AgentSession
object. Sources: Job lifecycle | LiveKit Documentation | Build a salary negotiation coach with a LemonSlice avatar | LiveKit, with interactive elements
b
A JobContext example.
t
Thanks — responding with a JobContext example that cleanly shuts down the local participant.
Copy code
from livekit.agents import JobContext

@server.rtc_session
async def my_agent(ctx: JobContext):
    # Connect to the room (usually handled for you by the decorator)
    await ctx.connect()

    # ... agent logic, e.g. handle tracks, send/receive audio, etc. ...

    # Graceful shutdown: request the agent session to end and disconnect the local participant.
    # Use drain=True to allow any in-progress TTS/speech to finish playing.
    ctx.shutdown(reason="Session complete", drain=True)

    # If you need to wait until shutdown/cleanup completes, await aclose()
    await ctx.aclose()
• Use
ctx.shutdown(...)
to request a graceful end (this disconnects the local participant). •
drain=True
waits for any ongoing speech to finish before disconnecting. •
await ctx.aclose()
performs an awaitable cleanup if you need to block until everything is fully closed., with interactive elements