<@U08CKJH7C12> I am facing difficulty with the han...
# agents
b
@refined-appointment-81829 I am facing difficulty with the hangup feature. I am using gemini realtime api and the hangup function given in the docs is leading to a deadlock. condition. I found a work around but it is very buggy. The workaround is my function tool just sets a flag to hangup and the hangup function is implemented when the agent goes into listening and the flag is true. This basically makes sure the agents hangs up after it is done speaking.
r
deadlock
b
yes
do you want my current code for reference?
r
What version of livekit are you running
pip freeze |grep livekit
I've not heard of anyone every having a deadlock on a hangup
You using SIP or WebRTC?
b
we are clickpost asia biggest intelligent logistics provider and we are using livekit for a our voice agents. The voice agents will be used by India's and the Middle East's biggest e-commerce platforms. We are 90% done with the product just having some minors issues ruining the entire experience.
I am using gemini live api
so gemini for tts llm stt all
SIP
outbound trunk from plivo
r
For SIP are you using UDP, TCP, or TLS?
b
I just made an outbound trunk I don't know the protocol being used underneath
wait a sec
r
Can I get a link to the trunk on your dashboard
b
Copy code
async def hangup_call():
    ctx = get_job_context()
    if ctx is None:
        # Not running in a job context
        return
    
    await ctx.api.room.delete_room(
        api.DeleteRoomRequest(
            room=ctx.room.name,
        )
    )
so in this code
r
Can you modify this code to reproduce the issue and give it to me along with steps I need to reproduce it: https://github.com/livekit/agents/blob/main/examples/voice_agents/basic_agent.py
b
the condition if ctx is None is being triggered everytime my agents calls the hangup_call function
r
Also what version of LiveKit are you using?
pip freeze |grep livekit
b
would it be better if I use the hangup_call function in my code and share the logs?
r
I would like to reproduce it
b
yep give me a sec
okay ill give a simplified version of my code. You can reproduce that easily works?
r
yes
b
The issue I am facing after trying to reproduce this is 1. Its is cutting the call while speaking the goodbye message. Basically cutting in between
👀 1
2. Sometimes hanging up the call before even starting to speak the outro
3. It says Hello when the participant picks up the call. But when the participant interrupts its first hello in between by saying hello themselves. It lets the interruption happend and waits for a while to then reply to the interruption. This is causing a very unpleasant begging to the call
The resolution to these problems will provide us the signal to finally deploy this solution for our customers. It will be very helpful if you can help me with this
@refined-appointment-81829 any updates??
r
no, I got the files. I will take a look
b
Thanks a lot
r
Seems to be working for me.
It called my phone I listen for it to say hello and then I ask it to hang up. Seems fine for me
b
Its hanging up the call while its is speaking the goodbye message.
r
But where is the deadlock?
b
the deadlock issue got fixed suprising when I simplified the code to send it to you
r
well I don't see any code to manage a hangup message in your code
b
but I am still facing two big issues. Hanging up in between saying the goodbye message and the starting part. where it says hello and gets interrupted when the participant says hello then waits and continues the convo this is very sketchy.
r
I don't see any good bye message
b
okay am I supposed to add that in my prompt?
Its there in my orignal prompt.
r
how are you expecting a good by message to work if you don't add one hand await the speech handle?
b
I'm sorry I am not aware of this. Can you send some reference.
r
have you looked at the example. Or need one?
b
please share the reference to the example I'll go through it, implement and get back to you with updates. Till then can you also help me with how to handle the starting of the call. I want the agent to start talking but also not get interrupted by the participant;s initial hello.
r
b
Copy code
from __future__ import annotations

import asyncio
import logging
from dotenv import load_dotenv
import json
import os
from typing import Any
from livekit.plugins.openai import realtime
from openai.types.beta.realtime.session import TurnDetection

from livekit import rtc, api
from livekit.agents import (
    AgentSession,
    Agent,
    JobContext,
    function_tool,
    RunContext,
    get_job_context,
    cli,
    WorkerOptions,
    RoomInputOptions,
)
from livekit.plugins import (
    google,
    noise_cancellation,  # noqa: F401
)
from prompt import prompts

load_dotenv()

logger = logging.getLogger("outbound-caller")
logger.setLevel(logging.INFO)

outbound_trunk_id = "ST_DYey6rphZDwX"

async def hangup_call():
    ctx = get_job_context()
    if ctx is None:
        # Not running in a job context
        return
    
    await ctx.api.room.delete_room(
        api.DeleteRoomRequest(
            room=ctx.room.name,
        )
    )


class OutboundCaller(Agent):
    def __init__(
        self,
    ):
        super().__init__(instructions="You are Parth a customer support voice agent investigating Failed Deliveries")
        # keep reference to the participant for transfers
        self.participant: rtc.RemoteParticipant | None = None

    def set_participant(self, participant: rtc.RemoteParticipant):
        self.participant = participant
    
    @function_tool()
    async def end_call(self, ctx: RunContext):
        """Called when the user wants to end the call"""
        await ctx.wait_for_playout() # let the agent finish speaking

        await hangup_call()

async def entrypoint(ctx: JobContext):
    logger.info(f"connecting to room {ctx.room.name}")
    print(1)
        # when dispatching the agent, we'll pass it the approriate info to dial the user
    # dial_info is a dict with the following keys:
    # - phone_number: the phone number to dial
    # - transfer_to: the phone number to transfer the call to when requested
    dial_info = json.loads(ctx.job.metadata)
    participant_identity = phone_number = dial_info["phone_number"]

    await ctx.connect()
    instruction = """You are Parth a customer support agent who assists with failed deliveries. You are access to a function end_call use it to hangup the call once the conversation is over."""
    # look up the user's phone number and appointment details
    agent = OutboundCaller()

    session_google_india = AgentSession(
    llm=google.beta.realtime.RealtimeModel(
        voice="Orus",
        temperature=0.3,
        instructions=instruction,
        language="en-IN"
        ),
    )

    session = session_google_india
    # start the session first before dialing, to ensure that when the user picks up
    # the agent does not miss anything the user says
    session_started = asyncio.create_task(
        session.start(
            agent=agent,
            room=ctx.room,
            room_input_options=RoomInputOptions(
                # enable Krisp background voice and noise removal
                # noise_cancellation=noise_cancellation.BVCTelephony(),
            ),
        )
    )

    # `create_sip_participant` starts dialing the user
    try:
        await ctx.api.sip.create_sip_participant(
            api.CreateSIPParticipantRequest(
                room_name=ctx.room.name,
                sip_trunk_id=outbound_trunk_id,
                sip_call_to=phone_number,
                participant_identity=participant_identity,
                # function blocks until user answers the call, or if the call fails
                wait_until_answered=True,
            )
        )

        # wait for the agent session start and participant join
        await session_started
        participant = await ctx.wait_for_participant(identity=participant_identity)
        logger.info(f"participant joined: {participant.identity}")

        agent.set_participant(participant)

        await session.generate_reply(
        instructions=instruction + """Say the world "Hello" nothing else"""
        )

    except api.TwirpError as e:
        logger.error(
            f"error creating SIP participant: {e.message}, "
            f"SIP status: {e.metadata.get('sip_status_code')} "
            f"{e.metadata.get('sip_status')}"
        )
        ctx.shutdown()
    print(session.history.to_dict())


if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            agent_name="outbound-caller",
        )
    )
Encountering this error with this code.
Copy code
Traceback (most recent call last):
  File "/Users/dhruvnagill/coding/ndr-ai-agent-sarvam/agent_simplified.py", line 64, in end_call
    await ctx.wait_for_playout() # let the agent finish speaking
AttributeError: 'RunContext' object has no attribute 'wait_for_playout' {"function": "end_call", "speech_id": "speech_f49e64044e9c", "pid": 75051, "job_id": "AJ_A4PLQoTJYuor"}
my livekit version @refined-appointment-81829
Copy code
livekit==1.0.11
livekit-agents==1.1.5
livekit-api==1.0.3
livekit-plugins-cartesia==1.1.5
livekit-plugins-deepgram==1.1.5
livekit-plugins-google==1.1.5
livekit-plugins-noise-cancellation==0.2.5
livekit-plugins-openai==1.1.5
livekit-plugins-sarvam==1.1.5
livekit-plugins-silero==1.1.5
livekit-plugins-turn-detector==1.1.5
livekit-protocol==1.0.4
Can you please help me with this @refined-appointment-81829 it would mean alot
@refined-appointment-81829 can you please help me out on this.