is ctx.connect() necessary? What is it's use?
# ask-ai
c
is ctx.connect() necessary? What is it's use?
t
Thanks for reaching out, Subham. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
The
ctx.connect()
method in LiveKit is your friendly gateway to connecting an agent (that's the server-side participant) with a LiveKit room. Once connected, the agent can: • Access the room object (
ctx.room
), which lets you do things like publish tracks, subscribe to media, or exchange data with other participants. • Enjoy real-time interactions with everyone else in the room, making the experience lively and engaging. • Take advantage of cool features like speech-to-text (STT), text-to-speech (TTS), or even AI-driven interactions to enhance communication. This connection step usually kicks off an agent's entrypoint function and is essential for smooth and effective interaction within the room. If you'd like, I’m here to help with more details or examples on how to use it—just let me know! Sources: examples/src/basic_eou.ts | examples/warm-transfer/warm_transfer.py | OpenAI and LiveKit partner to turn Advanced Voice into an API
c
what if I don't write ctx.connect() in the entry_point()?
t
I understand how important it is for your agent to connect smoothly! If
ctx.connect()
isn’t called in the
entry_point()
, the agent won’t be able to join the room, and a few issues might come up: • The agent won’t be able to subscribe to tracks, publish media, or exchange data with participants, which means it won’t function properly during the session. • You might see a warning after 10 seconds saying: "The job task completed without establishing a connection or performing a proper shutdown." • Session management won’t recognize the agent’s presence, which could affect workflows that rely on the agent being active. • The job process will keep running until it times out or is manually stopped, using resources without actually contributing to the session. • Shutdown callbacks and cleanup routines won’t run, which might cause incomplete cleanup or state issues. So, calling
ctx.connect()
is really key to making sure your agent works as expected and interacts with the room properly. If you’d like, I’m here to help with any questions or next steps! Sources: examples/voice_agents/silent_function_call.py | Job lifecycle | LiveKit Docs | Worker lifecycle | LiveKit Docs
c
Copy code
async def entrypoint(ctx: JobContext):
    # Logging setup
    # Add any other context you want in all log entries here
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    # Set up a voice AI pipeline using OpenAI, Cartesia, Deepgram, and the LiveKit turn detector
    session = AgentSession(
    #     # A Large Language Model (LLM) is your agent's brain, processing user input and generating a response
    #     # See all providers at https://docs.livekit.io/agents/integrations/llm/
    #     # llm=openai.LLM(model="gpt-4o-mini"),
        llm=google.LLM(model="gemini-2.5-flash-lite"),
    #     # Speech-to-text (STT) is your agent's ears, turning the user's speech into text that the LLM can understand
    #     # See all providers at https://docs.livekit.io/agents/integrations/stt/
        stt=elevenlabs.STT(),
    #     # Text-to-speech (TTS) is your agent's voice, turning the LLM's text into speech that the user can hear
    #     # See all providers at https://docs.livekit.io/agents/integrations/tts/
        tts=elevenlabs.TTS(
                model="eleven_flash_v2_5", 
                voice_id="H8bdWZHK2OgZwTN7ponr",
                voice_settings=elevenlabs.VoiceSettings(
                    stability=0.5,
                    similarity_boost=0.7,
                    speed=1.12,
                ),
                streaming_latency=4
                ),
    #     # VAD and turn detection are used to determine when the user is speaking and when the agent should respond
    #     # See more at https://docs.livekit.io/agents/build/turns
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
    #     # allow the LLM to generate a response while waiting for the end of turn
    #     # See more at https://docs.livekit.io/agents/build/audio/#preemptive-generation
        preemptive_generation=True,
    )

    # session = AgentSession(
    #     llm=openai.realtime.RealtimeModel(
    #         model="gpt-4o-realtime-preview",
    #         # modalities=["audio, 'text"],
    #         voice="marin",
    #         temperature=0.8,
    #         speed=1.10
    #     ),
    # )

    # sometimes background noise could interrupt the agent session, these are considered false positive interruptions
    # when it's detected, you may resume the agent's speech
    # @session.on("agent_false_interruption")
    # def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
    #     logger.info("false positive interruption, resuming")
    #     session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)

    # Metrics collection, to measure pipeline performance
    # For more information, see https://docs.livekit.io/agents/build/metrics/
    usage_collector = metrics.UsageCollector()

    @session.on("metrics_collected")
    def _on_metrics_collected(ev: MetricsCollectedEvent):
        metrics.log_metrics(ev.metrics)
        usage_collector.collect(ev.metrics)

    @session.on("close")
    def _on_close(ev: CloseEvent):
        logger.info(f"Session closed")
        ctx.delete_room()


    # # Add a virtual avatar to the session, if desired
    # # For other providers, see https://docs.livekit.io/agents/integrations/avatar/
    # avatar = hedra.AvatarSession(
    #   avatar_id="...",  # See https://docs.livekit.io/agents/integrations/avatar/hedra
    # )
    # # Start the avatar and wait for it to join
    # await avatar.start(session, room=ctx.room)

    # Start the session, which initializes the voice pipeline and warms up the models
    await session.start(
        agent=Assistant(),
        room=ctx.room,
        room_input_options=RoomInputOptions(
            # LiveKit Cloud enhanced noise cancellation
            # - If self-hosting, omit this parameter
            # - For telephony applications, use `BVCTelephony` for best results
            noise_cancellation=noise_cancellation.BVC(),
        ),
    )
This works without the ctx.connect()
t
I understand that your code might work without explicitly calling
ctx.connect()
, and that's because the
AgentSession
class has a handy automatic connection feature when
start()
is called. However, to keep things smooth and reliable, especially in production, it's better not to rely on this automatic behavior. By explicitly calling
ctx.connect()
, you make sure that: • The room is properly connected and set up before the session begins. • All the room properties are ready and available for you to interact with. • You avoid any unexpected issues, especially in custom or less typical setups. So, for the best experience, I recommend always using
await ctx.connect()
before
session.start()
. If you'd like me to explain anything further or help you with your setup, just let me know—I'm here to help! Sources: Job lifecycle | LiveKit Docs | README.md | livekit-agents/livekit/agents/job.py
c
Copy code
async def entrypoint(ctx: JobContext):
    """Entrypoint for the agent"""
    # Logging setup
    # Add any other context you want in all log entries here
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }
    logger.info(f"connecting to room {ctx.room.name}")
    await ctx.connect()
    room_id = await ctx.room.sid
    logger.info(f"connected to room {ctx.room.name}, room_id: {room_id}")

    dial_info = json.loads(ctx.job.metadata)
    bridge_id = dial_info.get("bridge_id")
    trunk_id = dial_info.get("trunk_id")
    participant_identity = dial_info.get("phone_number")
    phone_number = dial_info.get("phone_number")
    clean_phone_number = phone_number.replace("+91", "")
    logger.info(f"sip_trunk_id : {trunk_id}")
    logger.info(f"Phone number: {phone_number}")
    s3_file_name_hash = hashlib.sha256(ctx.room.name.encode('utf-8')).hexdigest()
    recording_file_name=f"call_recording_{s3_file_name_hash}.mp4"

    # Prepare egress request, but start only after audio is present
    req = api.RoomCompositeEgressRequest(
        room_name=ctx.room.name,
        layout="grid",
        audio_only=True,
        file_outputs=[
            api.EncodedFileOutput(
                file_type=api.EncodedFileType.MP4,
                filepath=recording_file_name,
                s3=api.S3Upload(
                    access_key=os.getenv("AWS_ACCESS_KEY_ID"),
                    secret=os.getenv("AWS_SECRET_ACCESS_KEY"),
                    bucket=os.getenv("S3_RECORDING_BUCKET"),
                    region=os.getenv("S3_RECORDING_REGION"),   # pick your S3 bucket region
                ),
            ),
        ],
    )



    # Set up a voice AI pipeline using OpenAI, Cartesia, Deepgram, and the LiveKit turn detector
    session = AgentSession(
        vad=ctx.proc.userdata["vad"],
        false_interruption_timeout=1.0,  # Wait 1 second before resuming
        resume_false_interruption=True,   # Enable auto-resume
        preemptive_generation=True,
        # allow_interruptions=True,
        # min_interruption_duration=0.5,
        # min_interruption_words=2
    )

    # sometimes background noise could interrupt the agent session, these are considered false positive interruptions
    # when it's detected, you may resume the agent's speech
    @session.on("agent_false_interruption")
    def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
        logger.info("false positive interruption, resuming")
        session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN, allow_interruptions=True)

    # Metrics collection, to measure pipeline performance
    # For more information, see https://docs.livekit.io/agents/build/metrics/
    usage_collector = metrics.UsageCollector()

    @session.on("metrics_collected")
    def _on_metrics_collected(ev: MetricsCollectedEvent):
        metrics.log_metrics(ev.metrics)
        usage_collector.collect(ev.metrics)

    lkapi = api.LiveKitAPI()
    egress_id: str | None = None

    agent = LivspaceInboundAgent(dial_info=dial_info, user_project_details=user_project_details)
    # agent = LivspaceInboundAgent(dial_info=dial_info)

    # Start the session, which initializes the voice pipeline and warms up the models
    session_started = asyncio.create_task(
        session.start(
            agent=agent,
            room=ctx.room,
            room_input_options=RoomInputOptions(
                # LiveKit Cloud enhanced noise cancellation
                # - If self-hosting, omit this parameter
                # - For telephony applications, use `BVCTelephony` for best results
                noise_cancellation=noise_cancellation.BVCTelephony(),
            ),
        )
    )
    try:
        await ctx.api.sip.create_sip_participant(
            api.CreateSIPParticipantRequest(
                room_name=ctx.room.name,
                sip_trunk_id=trunk_id,
                sip_call_to=phone_number,
                participant_identity=participant_identity,
                wait_until_answered=True,
            )
        )

        await session_started
        participant = await ctx.wait_for_participant(identity=participant_identity)
        logger.info(f"participant joined: {participant.identity}")

        agent.set_participant(participant)

        try:
            res = await lkapi.egress.start_room_composite_egress(req)
            egress_id = getattr(res, "egress_id", None)
            logger.info(f"Started egress: {egress_id}")
        except Exception as e:
            logger.error(f"Failed to start egress: {e}")

        # Watchdog to ensure egress is stopped if the session ends but egress hangs
        async def _egress_watchdog():
            try:
                # Fixed timeout watchdog: wait 5 minutes then attempt a best-effort stop
                await asyncio.sleep(600)
                if egress_id:
                    try:
                        await lkapi.egress.stop_egress(api.StopEgressRequest(egress_id=egress_id))
                        logger.info(f"Watchdog stop issued for egress after timeout: {egress_id}")
                    except Exception as stop_err:
                        logger.warning(f"Watchdog stop failed: {stop_err}")
            except Exception as err:
                logger.warning(f"Egress watchdog error: {err}")

        asyncio.create_task(_egress_watchdog())

        async def _stop_egress_on_close():
            if egress_id:
                try:
                    await lkapi.egress.stop_egress(api.StopEgressRequest(egress_id=egress_id))
                    logger.info(f"Stopped egress on close: {egress_id}")
                except Exception as e:
                    logger.warning(f"Failed to stop egress on close: {e}")

        ctx.add_shutdown_callback(_stop_egress_on_close)
        await lkapi.aclose()
        
    except Exception as e:
        call_status = identify_call_status(e)
        
        # Log the call status and SIP details
        logger.error(f"Failed to create SIP participant: {e}")
        logger.error(f"Call Status: {call_status}")

        url = f"https://qualif.revspot.ai/livekit/webhook_listener/{bridge_id}"
        logger.info(f"Sending webhook to {url}")

        status_mapping = {
            "in-progress": "processing",
            "completed": "ended",
            "failed": "dial_failed",
            "cancelled": "dial_failed",
            "busy": "dial_busy",
            "no-answer": "dial_no_answer",
            "ringing": "processing",
            "initiated": "processing",
            "error": "error",
        }
        data = {
            "event": "failed_to_create_sip_participant",
            "conversation_id": ctx.room.name,
            "status": status_mapping.get(call_status, "error"),
            "room_id": room_id,
            "call_status": call_status,
            "error": str(e),
        }
        
        # You can now use call_status to decide your action:
        # - "busy": User is busy, you might want to retry later
        # - "no_answer": No answer, you might want to retry or mark as no answer
        # - "other": Other error, check logs for details
        # - "unknown": Could not determine, check raw error
        
        # logger.error(f"Raw error details: {sip_info.get('raw_error', str(e))}")
        
        ctx.shutdown()
        await lkapi.aclose()
        return
do i need to add ctx.connect here too? If yes, where ?
t
Thanks for sharing your code! I see that you’ve already included
await ctx.connect()
early on in the
entrypoint
function, right after logging the room name. That’s actually the perfect spot to make sure the room is connected before moving forward with any operations that rely on the connection, like accessing
ctx.room
or starting the
AgentSession
. Since
ctx.connect()
is already there and in the right place, you don’t need to add it again elsewhere. But if you have any more questions or want me to walk through anything else, just let me know—I’m here to help!