add_shutdown_callback how to correctly use this.
# ask-ai
p
add_shutdown_callback how to correctly use this.
t
Thanks for reaching out, Bryner. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Using
add_shutdown_callback
in LiveKit is pretty straightforward! You just attach an async function to the
JobContext
that runs when the agent is shutting down. It’s super handy for things like cleaning up, saving data, or wrapping up metrics before everything stops. Here’s a simple way to get started: 1. Define an Async Callback Function: Make sure it’s a coroutine (async), and if you want, it can take one string argument that tells you why the shutdown is happening. 2. Attach the Callback: Just call
ctx.add_shutdown_callback(your_function)
right in your agent’s entrypoint. Check out these examples: • Logging Usage Metrics:
Copy code
async def log_usage():
    summary = usage_collector.get_summary()
    logger.info(f"Usage: {summary}")

ctx.add_shutdown_callback(log_usage)
• Saving a Transcript:
Copy code
async def write_transcript():
    current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"/tmp/transcript_{ctx.room.name}_{current_date}.json"
    with open(filename, 'w') as f:
        json.dump(session.history.to_dict(), f, indent=2)
    print(f"Transcript saved to {filename}")

ctx.add_shutdown_callback(write_transcript)
• Flushing Traces:
Copy code
async def flush_trace():
    trace_provider.force_flush()

ctx.add_shutdown_callback(flush_trace)
Just a heads up: It’s best to keep shutdown callbacks quick—they have a default timeout of 60 seconds, but you can tweak that with
shutdown_process_timeout
in
WorkerOptions
. Sources: Inside a session | LiveKit Docs | Session recording and transcripts | LiveKit Docs | examples/other/transcription/multi-user-transcriber.py