in my livekit agent from agent-starter-python, how...
# ask-ai
s
in my livekit agent from agent-starter-python, how can I know when the callee answered the call?
t
Thanks for reaching out, aric. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring how to detect when the callee answers the call in LiveKit using
agent-starter-python
. One helpful way is to keep an eye on the SIP call status through participant attributes. Specifically, you’ll want to listen for changes in the
sip.callStatus
attribute and watch for it to change to
'active'
. This means the call is connected and the callee has answered—great news! Here’s a simple example you can try out:
Copy code
async def async_on_participant_attributes_changed(changed_attributes: dict, participant: rtc.Participant):
    if participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP and 'sip.callStatus' in changed_attributes:
        call_status = changed_attributes['sip.callStatus']
        if call_status == 'active':
            logger.info("Callee has answered the call")
            # Add your logic here (e.g., send a greeting)
This approach works smoothly for both inbound and outbound SIP calls. Plus, if you’re making outbound calls, you might find it handy to use the
wait_until_answered=True
parameter in
create_sip_participant()
. This will pause the process until the call is answered or unfortunately fails, helping you manage the flow better. Sources: telephony/sip_lifecycle.py | agent.py
s
it looks like the process handling my agent during a call is killed when the callee hangs up, leading to my agent not being capable of uploading captured wav frame. How can I make sure my async tasks still lives even when the callee hangsup?
t
I’m glad you reached out! To help your async tasks keep running smoothly even after the callee hangs up, you can separate the task from the
AgentSession
lifecycle and stop the session from closing automatically. Here’s a simple way to do it: 1. Disable Automatic Session Closure: When you create the
AgentSession
, set
close_on_disconnect=False
in
RoomInputOptions
. This way, the session won’t close right away when the callee disconnects:
Copy code
session = AgentSession(
    input_options=RoomInputOptions(close_on_disconnect=False),
    # Other options
)
1. Detach Long-Running Tasks: Use
asyncio.create_task()
to start tasks that run independently from the session lifecycle. For example:
Copy code
@function_tool
async def initiate_background_task(self, query: str):
    task = asyncio.create_task(self._long_running_operation(query))
    self.active_tasks.append(task)
    return "Background task initiated."
1. Manage Session Closure: Make sure to delay closing the session until all your tasks have finished. Here’s a way to do that:
Copy code
async def graceful_shutdown(session: AgentSession, agent: MyAgent):
    await asyncio.gather(*agent.active_background_tasks, return_exceptions=True)
    await session.aclose()
By following these steps, your tasks will keep running and complete their work even after the callee disconnects. If you’d like me to walk you through this further or provide more examples, just let me know—I’m here to help! Sources: examples/voice_agents/README.md | Agents telephony integration | LiveKit Docs
s
but it looks like it's really spawning a new python process for each new call, and it's closing the python process at the end of the call, so my options are pretty limited 😕
t
It looks like the Python process is ending right after each call, which can definitely be a bit limiting. But don’t worry! There are some helpful ways to keep the process running smoothly, and I’m here to guide you through them: 1. Disable Automatic Process Termination: Try to separate the process lifecycle from the call lifecycle. For instance, you can keep the worker active longer by setting a longer drain timeout like this:
Copy code
from livekit.agents import WorkerOptions

worker_opts = WorkerOptions(
    entrypoint_fnc=your_entrypoint,
    drain_timeout=45 * 60  # 45 minutes
)
1. Use Shutdown Callbacks: It’s a great idea to register cleanup functions to make sure everything wraps up nicely before the process ends:
Copy code
async def entrypoint(ctx: JobContext):
    async def cleanup_resources():
        logger.info("Cleaning up resources...")
        # Save state, close connections, etc.

    ctx.add_shutdown_callback(cleanup_resources)
1. Monitor and Manage Process Lifecycle: The framework has built-in features to help prevent the process from stopping too soon. Just make sure your job connects properly to the room and handles shutdown by calling
ctx.connect()
and
ctx.shutdown()
. Following these steps should really help keep your process active so your tasks can finish even after the call ends. If anything’s unclear or you’d like a hand with any of this, please don’t hesitate to reach out—I’m here to help! Sources: Job lifecycle | LiveKit Docs | complex-agents/note-taking-assistant/agent.py | examples/voice_agents/silent_function_call.py | Worker options | LiveKit Docs