narrow-hairdresser-82835
11/25/2025, 3:56 PMtall-airline-16756
11/25/2025, 3:56 PMtall-airline-16756
11/25/2025, 3:56 PMend_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
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 docsnarrow-hairdresser-82835
11/25/2025, 3:58 PMtall-airline-16756
11/25/2025, 3:59 PMimport 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)
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 docsnarrow-hairdresser-82835
11/25/2025, 4:00 PMtall-airline-16756
11/25/2025, 4:00 PMend_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:
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.