agents icon indicating copy to clipboard operation
agents copied to clipboard

Participant Events not triggering

Open JuanAn-72 opened this issue 1 year ago • 4 comments

Bug Description

I am trying to trigger a simple SIP REFER, searching in the documentation I was able to create a prototype. However I am unable to set properly the participant_identity. Looks at the moment to create the agent no available, then I move to session.start and not good either. So lastly I thought using Events but looks like never triggered. Let me explain:

I can see in my logs transfer_sip_participant is at least tried but rejected due to participant_identity mismatch. The function tool code

   @function_tool()
    async def transfer_call(self, participant_identity: str, room_name: str) -> str:
        logger.debug("function_tool: transfer_call invoked")
        priority = self.customer_metadata.get("priority")
        if priority == 1:
            async with api.LiveKitAPI() as livekit_api:
                transfer_to = 'tel:+888'
                transfer_request = TransferSIPParticipantRequest(
                    participant_identity=participant_identity,
                    room_name=room_name,
                    transfer_to=transfer_to,
                    play_dialtone=False
                )
                logger.info(f"Transfer request: {transfer_request}")
                await livekit_api.sip.transfer_sip_participant(transfer_request)
                logger.debug(f"Successfully transferred participant {participant_identity} to {transfer_to}")
                return "Su llamada está siendo transferida a Servicio a Clientes. Por favor, espere en la línea."
        else:
            logger.debug(f"Transferencia no permitida para cliente prepago ({participant_identity})")
            return "Lo sentimos, solamente los clientes postpago pueden ser transferidos a Servicio a Clientes. ¿Hay algo más en lo que pueda ayudarle?"

The Error logs showing the situation .. as u can see before Transfer I can see my participant_identity (sip_1500) and I am able to interact with agent but transfer fails 2025-11-13 18:23:35,101 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx {"pid": 75824, "job_id": "AJ_GGa66ZVBPo9p"} 2025-11-13 18:23:36,205 - DEBUG livekit.agents - using audio io: RoomIO -> AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 75824, "job_id": "AJ_GGa66ZVBPo9p"} 2025-11-13 18:23:36,205 - DEBUG livekit.agents - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 75824, "job_id": "AJ_GGa66ZVBPo9p"} 2025-11-13 18:23:36,214 - DEBUG livekit.agents - start reading stream {"participant": "sip_1500", "source": "SOURCE_MICROPHONE", "pid": 75824, "job_id": "AJ_GGa66ZVBPo9p"} 2025-11-13 18:23:55,271 - DEBUG livekit.plugins.openai - OpenAI Realtime API response done but not complete with status: cancelled {"event_id": "resp_CbVIJZBDh2BZOi3XnPXEr", "event_response_status": "cancelled", "pid": 75824, "job_id": "AJ_GGa66ZVBPo9p"} 2025-11-13 18:24:00,236 - DEBUG livekit.agents - executing tool {"function": "transfer_call", "arguments": "{ \n "room_name": "soporte_técnico", \n *"participant_identity": "usuario*" \n} \n", "speech_id": "speech_9351db72edd7", "pid": 75824, "job_id": "AJ_GGa66ZVBPo9p"} 2025-

The Code for Event that never get triggered altough I can see in logs there is indeed a participant

    def on_participant_joined(p):
        # En este evento ya está `identity` disponible
        participant_identity = getattr(p, "identity", None)
        asyncio.create_task(handle_real_join(participant_identity, p))

    # Registra el evento para que sólo se ejecute CUANDO el participante SIP real esté disponible
    ctx.room.on("ParticipantConnected", on_participant_joined)
``

### Expected Behavior

ParticipantConnected Event triggered. 

### Reproduction Steps

```bash
1. Create a new project using template for: livekit-voice-agent-0.1.0
2. Change Code as below shown. 
- Sample code snippet, or a GitHub Gist link -
from __future__ import annotations
from dotenv import load_dotenv
import logging
import os
import asyncio
from livekit import agents, api
from livekit.agents import AgentSession, Agent, RoomInputOptions
from livekit.agents.llm import function_tool
from livekit.protocol.sip import TransferSIPParticipantRequest
from livekit.plugins import openai

load_dotenv(".env.local")

logger = logging.getLogger("agent-tools")
logger.setLevel(logging.DEBUG)

def get_customer_profile(participant_identity):
    # Simula llamada a un API externo
    mocked_response = {
        "participant_identity": participant_identity,
        "apellido": "Celaya",
        "saldo": 25.50,
        "priority": 1  # Puedes probar con 3 para clientes prepago
    }
    return mocked_response

def get_priority_label(priority: int) -> str:
    if priority == 1:
        return "postpago"
    elif priority == 3:
        return "prepago"
    return f"desconocida [{priority}]"

class Assistant(Agent):
    def __init__(self, customer_metadata: dict = None) -> None:
        self.customer_metadata = customer_metadata or {}
        instructions = self.build_instructions()
        super().__init__(instructions=instructions)

    def build_instructions(self):
        if not self.customer_metadata or not self.customer_metadata.get("priority"):
            return (
                "Un momento por favor, estamos identificando a su usuario y recuperando información de la cuenta."
            )
        base_instructions = (
            "You are a friendly assistant providing support for Customer Balance inquiries. "
        )
        if self.customer_metadata["priority"] == 1:
            extra_instructions = (
                "This is a POSTPAGO customer. You can transfer the call to Customer Service Technical Support if the user requests it."
            )
        else:
            extra_instructions = (
                "This is a PREPAGO customer. Inform the user that transfer to Customer Service is not available for this type of customer if they request it."
            )
        return (
            f"{base_instructions}"
            f"Customer Profile: Apellido={self.customer_metadata.get('apellido', '-')}, "
            f"Saldo={self.customer_metadata.get('saldo', '-')}, "
            f"Priority={get_priority_label(self.customer_metadata.get('priority', 3))}. "
            f"{extra_instructions}"
        )

    def update_profile(self, new_profile: dict):
        logger.info(f"[PROFILE] Actualizando perfil: {new_profile}")
        self.customer_metadata = new_profile
        self.instructions = self.build_instructions()

    @function_tool()
    async def transfer_call(self, participant_identity: str, room_name: str) -> str:
        logger.debug("function_tool: transfer_call invoked")
        priority = self.customer_metadata.get("priority")
        if priority == 1:
            async with api.LiveKitAPI() as livekit_api:
                transfer_to = 'tel:+888'
                transfer_request = TransferSIPParticipantRequest(
                    participant_identity=participant_identity,
                    room_name=room_name,
                    transfer_to=transfer_to,
                    play_dialtone=False
                )
                logger.info(f"Transfer request: {transfer_request}")
                await livekit_api.sip.transfer_sip_participant(transfer_request)
                logger.debug(f"Successfully transferred participant {participant_identity} to {transfer_to}")
                return "Su llamada está siendo transferida a Servicio a Clientes. Por favor, espere en la línea."
        else:
            logger.debug(f"Transferencia no permitida para cliente prepago ({participant_identity})")
            return "Lo sentimos, solamente los clientes postpago pueden ser transferidos a Servicio a Clientes. ¿Hay algo más en lo que pueda ayudarle?"

async def entrypoint(ctx: agents.JobContext):
    # Fase 1: Inicializa el agente SIN perfil aún
    agent = Assistant()  # Sin perfil, instrucciones genéricas
    session = AgentSession(llm=openai.realtime.RealtimeModel(voice="coral"))

    profile_cargado = asyncio.Event()  # Para controlar que la bienvenida sólo se realice una vez cargado el perfil

    async def handle_real_join(participant_identity, p):
        logger.info(f"[JOIN] Participant with identity: {participant_identity}")
        
        # 1. Obtén el perfil ANTES de hablar
        profile = get_customer_profile(participant_identity)
        agent.update_profile(profile)  # Ahora el agente tiene todas las instrucciones personalizadas

        # 2. Primera interacción VERBAL personalizada (ya tienes el perfil)
        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?"
        )
        await session.generate_reply(instructions=bienvenida)

        # 3. (opcional) Aquí ya puedes manejar transferencias, dudas, etc basándote en el perfil.
        profile_cargado.set()

    def on_participant_joined(p):
        # En este evento ya está `identity` disponible
        participant_identity = getattr(p, "identity", None)
        asyncio.create_task(handle_real_join(participant_identity, p))

    # Registra el evento para que sólo se ejecute CUANDO el participante SIP real esté disponible
    ctx.room.on("ParticipantConnected", on_participant_joined)

    # Arranca la sesión así: el agente inicia con instrucciones genéricas
    await session.start(
        room=ctx.room,
        agent=agent,
        room_input_options=RoomInputOptions()
    )

    # Mensaje inicial que sólo oye el usuario si el perfil no se cargó a tiempo (opcional; a veces puede obviarse)
    await session.generate_reply(
        instructions="Un momento por favor. En breve le atenderemos. Estoy esperando la información de su perfil…"
    )

    # Bloquea aquí hasta que se haya saludado al cliente con el perfil correcto.
    await profile_cargado.wait()

if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))

Operating System

macOS

Models Used

OpenAI

Package Versions

livekit= 0.0.1
livekit-voice-agent version = "0.1.0"

Session/Room/Call IDs

N/A My setup is Local, entirely but OPENAI requests.

Proposed Solution


Additional Context

No response

Screenshots and Recordings

No response

JuanAn-72 avatar Nov 13 '25 18:11 JuanAn-72

Hi, to listen to the ParticipantConnected events on Python, you would need to listen on "participant_connected". You can also use a decorator. It can look something like this:

    @ctx.room.on("participant_connected")
    def on_participant_joined(p):
        # En este evento ya está `identity` disponible
        participant_identity = getattr(p, "identity", None)
        asyncio.create_task(handle_real_join(participant_identity, p))

You can view all available events here. Let me know if that fixes your problem!

tinalenguyen avatar Nov 13 '25 19:11 tinalenguyen

Hola @tinalenguyen , thanks for the tip... not working, with or without decorator code related to events publish seems to be ignored. In the run time what I see is logger is only shown when I ask the AGENT to be transferred and the function tool is triggered, I set a logger within that fucntion tool and I can see participant_identity is set to "usuario" but there is nothing in my code for this.

Log follows: 2025-11-14 12:34:56,735 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx {"pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:34:56,737 - DEBUG livekit.agents - using audio io: RoomIO -> AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:34:56,737 - DEBUG livekit.agents - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 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"} 2025-11-14 12:34:56,740 - DEBUG livekit.agents - start reading stream {"participant": "sip_1500", "source": "SOURCE_MICROPHONE", "pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:35:08,495 - DEBUG livekit.agents - executing tool {"function": "transfer_call", "arguments": "{ \n "room_name": "soporte_técnico", \n "participant_identity": "usuario" \n} \n", "speech_id": "speech_5873e7667793", "pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:35:08,496 - DEBUG agent-tools - FUNCTION_TOOL: transfer_call invoked | priority= None | usuario {"pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:35:08,496 - DEBUG livekit.agents - tools execution completed {"speech_id": "speech_5873e7667793", "pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:35:12,200 - DEBUG livekit.agents - stream closed {"participant": "sip_1500", "source": "SOURCE_MICROPHONE", "pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:35:12,201 - INFO livekit.agents - closing agent session due to participant disconnect (disable via RoomInputOptions.close_on_disconnect=False) {"participant": "sip_1500", "reason": "CLIENT_INITIATED", "pid": 95838, "job_id": "AJ_6oAYB3JupJop"} 2025-11-14 12:35:12,201 - DEBUG livekit.agents - input stream detached {"participant": "sip_1500", "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 95838, "job_id": "AJ_6oAYB3JupJop"}

The fragment I am using follows

==========================================

Punto de entrada del agente

===========================================

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}")
    print(f"ON_PARTICIPANT_JOINED: participant_identity= {participant_identity}")
    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 in Logs but previous Loggers don´t

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}")
    print(f"HANDLE_REAL_JOIN: participant_identity= {participant_identity} | profile= {profile}")
    agent.update_profile(profile)
    # 2. Saludo
    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?"
    )
    #await session.generate_reply(instructions=bienvenida)
    #profile = get_customer_profile('participant_identity')
    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)

while True:
    await asyncio.sleep(10)

if name == "main": agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))

JuanAn-72 avatar Nov 14 '25 11:11 JuanAn-72

We can close the issue, I finally came across I needed to use await ctx.wait_for_participant()

   # If no participants yet, wait  
    if not ctx.room.remote_participants:  
        logger.info("=== WAITING FOR PARTICIPANT ===")  
        participant = await ctx.wait_for_participant()  
        logger.info(f"=== PARTICIPANT JOINED: {participant.identity} ===")  
    else:  
        participant = next(iter(ctx.room.remote_participants.values()))  
        logger.info(f"=== FOUND EXISTING PARTICIPANT: {participant.identity} ===")  

Logs: 025-11-14 15:56:31,404 - INFO agent-tools - === ENTRYPOINT STARTED === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,507 - INFO agent-tools - === CONNECTED TO ROOM === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,507 - INFO agent-tools - Room name: call-_1500_Li46wU89NrnJ {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,507 - INFO agent-tools - Local participant: agent-AJ_DezbkJHc9TGR {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,507 - INFO agent-tools - Remote participants: ['sip_1500'] {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,507 - INFO agent-tools - === FOUND EXISTING PARTICIPANT: sip_1500 === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,508 - INFO agent-tools - === PROFILE FETCHED: {'apellido': 'Celaya', 'saldo': 25.5, 'priority': 1} === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,508 - INFO agent-tools - === USERDATA CREATED === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,508 - INFO agent-tools - === AGENT CREATED WITH INSTRUCTIONS === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,508 - INFO agent-tools - Instructions preview: You are a friendly assistant providing support for Customer Balance inquiries. Customer Profile: Apellido=Celaya, Saldo=25.5, Priority=postpago. This is a POSTPAGO customer. If the user asks to be tra... {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,508 - INFO agent-tools - === SESSION CREATED === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,513 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,531 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,533 - DEBUG livekit.agents - using audio io: RoomIO -> AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,533 - DEBUG livekit.agents - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,533 - INFO agent-tools - === SESSION STARTED === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,533 - INFO agent-tools - === GENERATING GREETING: ¡Hola, Celaya! Su saldo actual es de 25.5. Tipo de cliente: postpago. ¿En qué puedo ayudarle hoy? === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:32,553 - DEBUG livekit.agents - start reading stream {"participant": "sip_1500", "source": "SOURCE_MICROPHONE", "pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:39,801 - INFO livekit.agents - process exiting {"reason": "", "pid": 76079, "job_id": "AJ_6YwTkfZSE4Ps"} 2025-11-14 15:56:39,801 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false, "pid": 76079, "job_id": "AJ_6YwTkfZSE4Ps"} 2025-11-14 15:56:39,801 - DEBUG livekit.agents - http_session(): closing the httpclient ctx {"pid": 76079, "job_id": "AJ_6YwTkfZSE4Ps"} 2025-11-14 15:56:46,325 - INFO agent-tools - === GREETING SENT === {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:53,530 - DEBUG livekit.agents - executing tool {"function": "transfer_call", "arguments": "{ }", "speech_id": "speech_6c3a9044f287", "pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:53,530 - DEBUG agent-tools - function_tool: transfer_call invoked | priority=1 {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:53,550 - INFO agent-tools - Successfully transferred sip_1500 to sip:[email protected]:5060 {"pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-11-14 15:56:53,551 - DEBUG livekit.agents - tools execution completed {"speech_id": "speech_6c3a9044f287", "pid": 76202, "job_id": "AJ_DezbkJHc9TGR"} 2025-1

JuanAn-72 avatar Nov 14 '25 15:11 JuanAn-72

Thanks for the support I leave the solution just in case for someone else.

JuanAn-72 avatar Nov 14 '25 15:11 JuanAn-72