How can I run code when the Worker is connected to...
# ask-ai
r
How can I run code when the Worker is connected to LiveKit
t
Thanks for reaching out, Trevor. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
When a Worker connects to LiveKit, you can run code in the
entrypoint
function. This function is executed when a job is created and your agent connects to a room. Below is an example implementation:
Copy code
import logging
from livekit.agents import AutoSubscribe, JobContext, WorkerOptions, WorkerType, cli

logger = logging.getLogger("my-worker")
logger.setLevel(<http://logging.INFO|logging.INFO>)

async def entrypoint(ctx: JobContext):
    <http://logger.info|logger.info>("starting entrypoint")
    
    # This code runs when the worker connects to LiveKit
    await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL)
    
    <http://logger.info|logger.info>("connected to the room")
    # Add your agent logic here!

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, worker_type=WorkerType.ROOM))
The
ctx.connect()
method establishes the connection to LiveKit, and any code after this line will run once the connection is established. Let me know if you need further assistance! Sources: Tree View: | dse-workbench
r
Can I run code before entrypoint? I want to trigger dispatch to a new room immediately, once the cli has started
t
Yes, you can run code before the
entrypoint
function in LiveKit by using the
prewarm
function. The
prewarm
function is part of the
WorkerOptions
class and is designed to initialize resources or perform actions before a job is assigned to a worker process. This is particularly useful for tasks like dispatching to a new room immediately after the CLI starts. Here is an example implementation:
Copy code
def prewarm_fnc(proc: JobProcess):
    # Perform actions or load resources before entrypoint
    proc.userdata["dispatch"] = "Your dispatch logic here"

async def entrypoint(ctx: JobContext):
    # Access pre-initialized resources or logic
    dispatch_logic = ctx.proc.userdata["dispatch"]
    # Your entrypoint code...

# Set up worker options with the prewarm function
opts = WorkerOptions(
    entrypoint_fnc=entrypoint,
    prewarm_fnc=prewarm_fnc,
    # other options...
)

# Start the worker
cli.run_app(opts)
Using the
prewarm
function ensures that your dispatch logic or other initialization tasks are executed before the
entrypoint
function is called. Let me know if you need further clarification or assistance! Sources: Anatomy of an Agent | LiveKit Docs | Anatomy of an Agent | LiveKit Docs