Is there a way to choose which shutdown callback o...
# ask-ai
w
Is there a way to choose which shutdown callback occurs based on how the shutdown occured?
t
Thanks for reaching out, Arthur. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Absolutely! You can decide which shutdown callback to run based on why the shutdown happened by using the shutdown reason parameter. When you add a shutdown callback with
add_shutdown_callback()
, the callback can optionally take a single string parameter that tells you the reason for the shutdown. Here’s a simple example to show you how it works:
Copy code
async def entrypoint(ctx: JobContext):
    async def shutdown_handler(reason: str):
        if reason == "room disconnected":
            # Handle unexpected disconnection
            logger.warning("Room disconnected unexpectedly")
            # Maybe try to reconnect or save your state here
        elif reason == "Session ended":
            # Handle graceful shutdown
            logger.info("Session ended gracefully")
            # Do your usual cleanup
        else:
            # Handle other shutdown reasons
            logger.info(f"Shutdown with reason: {reason}")
    
    ctx.add_shutdown_callback(shutdown_handler)
Some common shutdown reasons you might see include: •
"room disconnected"
- When the room connection drops unexpectedly • Reasons you provide yourself when calling
ctx.shutdown(reason="your reason")
• Various system-generated reasons depending on how the shutdown happens This way, you can easily tailor what happens during different shutdown situations—whether it’s a smooth exit, an unexpected disconnect, or something else. Sources: examples/voice_agents/realtime_joke_teller.py