How to declare and use async callbacks in entrypoi...
# ask-ai
d
How to declare and use async callbacks in entrypoint ?
t
Thanks for reaching out, W. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You can declare and use async callbacks in the entrypoint of a LiveKit application in several ways: 1. Participant Entrypoint Callbacks • Declare async functions with the signature
(ctx: JobContext, p: rtc.RemoteParticipant)
. • Add them using
ctx.add_participant_entrypoint(entrypoint_fnc=...)
before calling
ctx.connect()
. • Each callback runs in parallel for every participant that joins.
Copy code
async def entrypoint(ctx: JobContext):
    async def participant_task(ctx: JobContext, p: rtc.RemoteParticipant):
        # Your async logic here
        await asyncio.sleep(10)
    ctx.add_participant_entrypoint(entrypoint_fnc=participant_task)
    await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL)
2. Shutdown Callbacks • Declare an async function for cleanup or finalization. • Add it using
ctx.add_shutdown_callback(...)
.
Copy code
async def entrypoint(ctx: JobContext):
    async def my_shutdown_hook():
        # Cleanup logic
        ...
    ctx.add_shutdown_callback(my_shutdown_hook)
3. Other Async Callbacks • You can also declare async callbacks for agent events, such as metrics collection.
Copy code
@agent.on("metrics_collected")
def _on_metrics_collected(mtrcs: metrics.AgentMetrics):
    # Handle metrics
    ...
Key requirements: • All callbacks must be declared as
async
functions. • Participant entrypoint callbacks must be added before
ctx.connect()
. • Shutdown callbacks should complete quickly (default timeout is 60 seconds). • Each callback type has specific signature requirements. This approach allows you to run async logic for participants, cleanup, and other agent events in your entrypoint function. Sources: livekit-agents/livekit/agents/ipc/job_proc_lazy_main.py | Inside a session | LiveKit Docs | chain-of-thought-tts/agent.py