I have followed the voice ai agent quickstart guid...
# ask-ai
e
I have followed the voice ai agent quickstart guide. This works OK in a purely self-host approach. I need to add events register logic in order to identify when a sip participant joins and trigger function tool (API) to retrieve customer profile information based on participant_identity. I added logic for events but seems to be skipped see the entrypoint code .. Any suggestion ?
Copy code
async def entrypoint(ctx: agents.JobContext):
    await ctx.connect()
    agent = Assistant()
    session = AgentSession(llm=openai.realtime.RealtimeModel(voice="coral"))

    await session.start(
        room=ctx.room,
        agent=agent,
        room_input_options=RoomInputOptions()
    )

    # Handler SIN async, dispara la lógica asíncrona:
    def on_participant_connected(p):
        participant_identity = getattr(p, "participant", None)
        logger.debug(f"ON_PARTICIPANT_JOINED: participant_identity= {participant_identity}").  # This is NOT shown at log
        print(f"ON_PARTICIPANT_JOINED: participant_identity= {participant_identity}")   # This is NOT shown at log
        asyncio.create_task(handle_real_join(participant_identity, p))

    ctx.room.on("participant_connected", on_participant_connected)
    logger.debug(f"AFTER participant_connected| CTX.room attributes: {dir(ctx.room)}")     # This is shown at log

    async def handle_real_join(participant_identity, participant_obj):
        # 1. Perfil y update
        profile = get_customer_profile(participant_identity)
        logger.debug(f"HANDLE_REAL_JOIN: participant_identity= {participant_identity} | profile= {profile}")  # This is NOT shown at log
        print(f"HANDLE_REAL_JOIN: participant_identity= {participant_identity} | profile= {profile}")    # This is NOT shown at log
        agent.update_profile(profile)

        bienvenida = (
            f"¡Hola, {profile.get('apellido')}! "
            f"Su saldo actual es de {profile.get('saldo')}. "
            f"Tipo de cliente: {get_priority_label(profile.get('priority'))}. "
            "¿En qué puedo ayudarle hoy?"
        )
        participant = next(iter(ctx.room.remote_participants.values()))
        identity = participant.identity if participant else "unknown"
        msg = await agent.transfer_call(identity, ctx.room.name)
        await session.generate_reply(instructions=msg)
t
Thanks for reaching out, Juan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm here to help you smoothly handle the
participant_connected
event and get your custom logic working just right. Let's walk through a few friendly tips together: • First, double-check that your
on_participant_connected
handler is properly registered using
ctx.room.on("participant_connected", on_participant_connected)
. It’s important to have this set up before any participants join the room. • Take a moment to see if there’s any filtering happening based on participant kind or attributes. Sometimes the event might be skipped if certain conditions aren’t met. • You're on the right track using
asyncio.create_task
for asynchronous logic inside the event handler. This helps keep things running smoothly without blocking the main event loop. • Adding some logging can be really helpful! Try logging when you register the event and also inside the handler to confirm it’s being triggered and see participant details. • Make sure your
handle_real_join
function is properly defined and accessible where the event handler can use it. If things still feel tricky, adding error handling and extra logging can catch any hidden exceptions or missed steps. Please don’t hesitate to reach out if you’d like me to walk you through specific examples or troubleshoot further—I’m here to support you every step of the way! Sources: telephony/sip_lifecycle.py | livekit-agents/livekit/agents/voice/room_io/room_io.py | ivr-nagivator/README.mdoc | Building an Automated IVR Menu Caller | LiveKit Docs
e
You advise "First, double-check that your
on_participant_connected
handler is properly registered using
ctx.room.on("participant_connected", on_participant_connected)
. It’s important to have this set up before any participants join the room." How I double check this ? You advise "Try logging when you register the event and also inside the handler to confirm it’s being triggered and see participant details." How I do log my register to event ?
t
Let's make sure your
on_participant_connected
handler is all set up correctly and that we can track its registration smoothly. Here's a simple way to do that: 1. Right after you register the event, add a log statement to confirm everything went through nicely. For example:
Copy code
ctx.room.on("participant_connected", on_participant_connected)
logger.debug("Registered participant_connected event handler")
1. Then, inside your
on_participant_connected
handler, include a log statement to check that it’s actually being triggered and to capture some details about the participant. Like this:
Copy code
def on_participant_connected(participant):
    logger.debug(f"Handler triggered for participant: {participant.identity}")
    # Your existing logic here
Adding these logs will help us confirm that your event handler is both registered and firing as expected when someone connects. If anything’s unclear or you’d like a hand with the next steps, just let me know—I’m here to help!
e
If you check my original code you will find this statement:
Copy code
ctx.room.on("participant_connected", on_participant_connected)
logger.debug(f"AFTER participant_connected| CTX.room attributes: {dir(ctx.room)}")
In the logs I can see this logger is executed and this is output
Copy code
2025-11-14 12:34:56,737 - DEBUG agent-tools - AFTER participant_connected| CTX.room attributes: ['__class__', '__class_getitem__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__orig_bases__', '__parameters__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_byte_stream_handlers', '_byte_stream_readers', '_connection_state', '_create_remote_participant', '_data_stream_tasks', '_drain_data_stream_tasks', '_drain_rpc_invocation_tasks', '_e2ee_manager', '_events', '_ffi_handle', '_ffi_queue', '_first_sid_future', '_handle_stream_chunk', '_handle_stream_header', '_handle_stream_trailer', '_info', '_listen_task', '_local_participant', '_loop', '_on_room_event', '_on_rpc_method_invocation', '_remote_participants', '_retrieve_participant', '_retrieve_remote_participant', '_room_queue', '_rpc_invocation_tasks', '_task', '_text_stream_handlers', '_text_stream_readers', 'connect', 'connection_state', 'creation_time', 'departure_timeout', 'disconnect', 'e2ee_manager', 'emit', 'empty_timeout', 'get_rtc_stats', 'is_recording', 'isconnected', 'local_participant', 'metadata', 'name', 'num_participants', 'num_publishers', 'off', 'on', 'once', 'register_byte_stream_handler', 'register_text_stream_handler', 'remote_participants', 'sid', 'unregister_byte_stream_handler', 'unregister_text_stream_handler'] {"pid": 95838, "job_id": "AJ_6oAYB3JupJop"}
t
Thank you for sharing your logs! It looks like the
participant_connected
event handler is being registered just right, which is great news. Sometimes, though, the handler might not trigger because of some specific conditions. Let’s walk through a few steps together to help you debug and get this working smoothly: 1. Log All Participant Connections: Try adding a listener that logs every participant connection. This way, we can check if the event is firing and take a closer look at the participant details:
Copy code
@ctx.room.on("participant_connected")
def on_participant_connected(participant):
    logger.info(f"Participant connected: {participant.identity}, kind: {participant.kind}, attributes: {participant.attributes}")
1. Check Participant Identity: Double-check that the participant’s identity matches what you expect. If you’re aiming to catch any SIP participant, it’s best not to use a strict identity filter. 2. Verify Participant Kind: Make sure the participant’s kind (like
SIP
or
STANDARD
) is among the accepted kinds. Logging the kind as shown above can really help here. 3. Agent Initialization Sequence: It’s important to have the agent connect to the room and register the event listener before any participants join. This helps ensure no events slip through unnoticed. 4. Inspect Participant Attributes: Take a look at the participant’s attributes by logging them. This will confirm if they include the metadata you expect, such as
sip.callStatus
or
task
. I hope these steps make things clearer and bring you closer to a solution! Please feel free to reach out if you want me to explain anything further or if you need any more help—I’m here for you. Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | agents/src/voice/room_io/room_io.ts | ivr-nagivator/README.mdoc | telephony/sip_lifecycle.py
e
You said include this "@ctx.room.on("participant_connected")
Copy code
def on_participant_connected(participant):
    logger.info(f"Participant connected: {participant.identity}, kind: {participant.kind}, attributes: {participant.attributes}")"
However, I reaches agent and nothing at log is shown. Are u sure there is nothing else I might missed ..lets´s say a libray, import or whatever that need to be declared, imported in order the code for events to work ?
t
To help you get the
participant_connected
event handler working smoothly, let’s make sure all the necessary libraries and imports are properly included in your project. Here’s a friendly checklist for you: 1. Install Required Packages: Make sure you have these packages installed:
Copy code
pip install livekit-agents livekit python-dotenv
1. Core Imports: Don’t forget to add these essential imports to your code:
Copy code
from livekit.agents import JobContext, WorkerOptions, cli
from livekit import rtc, api
1. Additional Imports for Voice AI Agents: If you’re working with advanced features, include these too:
Copy code
from livekit.agents import AutoSubscribe, llm
from livekit.plugins import openai, silero, deepgram
1. Environment Configuration: Be sure to load your environment variables like this:
Copy code
from dotenv import load_dotenv
from pathlib import Path

load_dotenv(dotenv_path=Path(__file__).parent / '.env')
Once you have these set up, your project should be in great shape! If you run into any questions or need a hand with anything else, just let me know — I’m here to help! Sources: ivr-nagivator/README.mdoc | requirements.txt | telephony/sip_lifecycle.py | livekit-agents/livekit/agents/voice/room_io/room_io.py
e
Not working
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
e
Thanks a lot. Your suggestion about DeepWiki solved my issue, I learned about this participant = await ctx.wait_for_participant() and other errors. We can close this thread, do u want the final code ?