end_call tool is not getting invoked. Give me an e...
# ask-ai
n
end_call tool is not getting invoked. Give me an example in python
t
Thanks for reaching out, Hari. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking for a Python example showing how to ensure the
end_call
tool is invoked. Below is a complete minimal example that: • Registers
end_call
as a function tool on an Agent • Waits for any TTS playout before hanging up • Deletes the room via the LiveKit API to end the call
Copy code
import asyncio
from livekit.agents import Agent, function_tool, get_job_context, RunContext
from livekit import api

async def hangup_call():
    """Ends the call for all participants by deleting the room."""
    ctx = get_job_context()
    if ctx is None:
        print("No job context available")
        return
    try:
        await ctx.api.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))
        print("Room deleted — call ended.")
    except Exception as e:
        print(f"Error ending call: {e}")

class MyAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant. If the user wants to end the call, use the end_call tool.")

    @function_tool()
    async def end_call(self, ctx: RunContext):
        """Called when the user wants to end the call."""
        # Ensure any TTS finishes before hanging up
        await ctx.wait_for_playout()
        await hangup_call()
        return None  # No additional LLM reply after hangup

    async def on_enter(self):
        await self.session.generate_reply(instructions="Hello — say 'end the call' or 'goodbye' to hang up.")

# Example entrypoint to start the agent session in a job context
async def entrypoint(ctx):
    await ctx.connect()  # Connect to the room
    # Create AgentSession with configured llm/stt/tts (replace with your instances)
    session = AgentSession(llm=llm_instance, stt=stt_instance, tts=tts_instance)
    await session.start(agent=MyAgent(), room=ctx.room)

# Run (example)
if __name__ == "__main__":
    asyncio.run(entrypoint(job_context_instance))
Quick checks if
end_call
still isn't invoked: • Ensure the LLM has the tool metadata (the agent created with
@function_tool()
exposes the tool to the model). • Make the tool's description/instructions mention ending the call (the LLM decides to call it on user intent like "end the call" or "goodbye"). • Add logging/prints inside
end_call
and
hangup_call
to confirm invocation. • Confirm
ctx.wait_for_playout()
completes if you use TTS (otherwise the hangup may be delayed). Would you like me to tailor this to your existing agent code (paste your agent file) so I can spot why it's not firing? Sources: Agents telephony integration | LiveKit Docs | Agent speech and audio | LiveKit docs
n
can we log the LLM responses
t
Regarding logging LLM responses — yes, you can. Below are two concise Python options depending on whether you want raw incremental model output or the final text sent to TTS. 1) Log incremental LLM chunks (streamed output)
Copy code
import logging
from livekit.agents import Agent, llm, ModelSettings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class MyAgent(Agent):
    async def llm_node(
        self,
        chat_ctx: llm.ChatContext,
        tools: list[llm.FunctionTool],
        model_settings: ModelSettings,
    ) -> AsyncIterable[llm.ChatChunk]:
        async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
            if hasattr(chunk, "delta") and getattr(chunk.delta, "content", None):
                logger.info(f"LLM chunk: {chunk.delta.content}")
            yield chunk
2) Log final text before TTS (post-processed text)
Copy code
import logging
from livekit.agents import Agent, ModelSettings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class MyAgent(Agent):
    async def transcription_node(self, text: AsyncIterable[str], model_settings: ModelSettings) -> AsyncIterable[str]:
        async for delta in text:
            logger.info(f"Final TTS input: {delta}")
            yield delta
Which do you want to capture (raw streamed chunks or final TTS text)? If you share which logging framework or where you want logs stored (stdout, file, external system), I can give the exact wiring. Sources: Pipeline nodes and hooks | LiveKit docs
n
class Assistant(Agent): def __init__(self) -> None: super().__init__( instructions=SYSTEM_INSTRUCTION, ) @function_tool async def end_call(self, context: RunContext[None]) -> str: """End the current interview call/session. Use this when the user explicitly asks to end the call or when the interview should be concluded.""" try: logger.info("End call tool invoked by agent") room = get_job_context().room # Send one-way data message to frontend via LiveKit data channel end_call_data = {"type": "end_call_tool", "timestamp": time.time()} data_packet = json.dumps(end_call_data).encode("utf-8") await room.local_participant.publish_data(data_packet) return "Call ended successfully" except Exception as e: logger.error(f"Error in end_call tool: {e}") raise ToolError(f"Unable to end call: {e!s}") from e def prewarm(proc: JobProcess) -> None: proc.userdata["vad"] = silero.VAD.load() async def entrypoint(ctx: JobContext) -> None: await ctx.connect() print(f"ctx.job.metadata: {ctx.job.metadata}") ctx.log_context_fields = { "room": ctx.room.name, } # Create assistant assistant = Assistant() await session.start( agent=assistant, room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), close_on_disconnect=False, ), ) this is my code. End_call is not working
t
Thanks — I looked at your code sample for
end_call
. A few targeted checks and fixes to confirm so I can pinpoint why it isn't invoked: 1. Confirm the tool is registered to the LLM • Are you instantiating the Agent so the model sees the
@function_tool
metadata? The LLM must be started with your agent session so it knows the available tools. 1. Check logs for LLM tool decisions • Do you see any logs where the model chooses a function/tool or where
end_call
prints "End call tool invoked by agent"? If not, the LLM may not be choosing the function (intent/description mismatch). 1. Make the tool description explicit • Ensure
end_call
docstring clearly matches user language (e.g., "end the call", "hang up", "goodbye"). The LLM triggers tools from matching intent. 1. Verify get_job_context() exists at runtime • Instead of calling
get_job_context().room
inline, store ctx = get_job_context(); if ctx is None you'll avoid attribute errors. Add logging right after to confirm ctx and ctx.room are present. 1. Confirm data publish works • Publishing data is one-way; ensure the frontend listens on the data channel. Add a print/log right after
publish_data
to confirm the await succeeded. 1. Ensure exceptions/logging surface • Your except re-raises ToolError. Add logging before raising and check agent logs for that error. 1. Minimal debug changes to add now • Add these prints/logs and small guards:
Copy code
ctx = get_job_context()
logger.info(f"get_job_context(): {ctx}")
if ctx is None or not getattr(ctx, "room", None):
    logger.error("No job context or room")
    raise ToolError("No job context/room")
logger.info("End call tool invoked by agent")
await ctx.room.local_participant.publish_data(data_packet)
logger.info("publish_data completed")
Questions to narrow this down: • Do you see the "End call tool invoked by agent" log at all? • Is your frontend receiving the data channel message when you manually publish elsewhere? • Which LLM/model are you using and how do users trigger ending the call (exact user phrases)? Tell me the answers or paste the additional logs and I’ll suggest the next precise fix.