polite-furniture-24847
08/23/2025, 8:47 AMtall-airline-16756
08/23/2025, 8:47 AMtall-airline-16756
08/23/2025, 8:48 AMadd_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:
async def log_usage():
summary = usage_collector.get_summary()
logger.info(f"Usage: {summary}")
ctx.add_shutdown_callback(log_usage)
• Saving a Transcript:
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:
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