better-painter-56211
10/23/2025, 7:15 AMtall-airline-16756
10/23/2025, 7:15 AMtall-airline-16756
10/23/2025, 7:16 AMAgentTask from a function tool, you can use the RunContext object that’s available during the tool's execution. Here’s a friendly example in Python that might make things clearer:
from livekit.agents.llm import function_tool
from livekit.agents.voice.events import RunContext
@function_tool
async def update_email_address(email: str, ctx: RunContext) -> str:
"""Update the email address provided by the user.
Args:
email: The email address provided by the user
ctx: The run context containing session and speech handle information
"""
# Access the current speech handle
speech_handle = ctx.speech_handle
# Access session data
session = ctx.session
# Access user data if available
user_data = ctx.userdata
# Wait for current speech to complete before proceeding
await ctx.wait_for_playout()
# Your tool logic here
return f"Email updated to {email}"
This example shows how RunContext helps you tap into session data, manage speech flow smoothly, and keep state across different tool calls. If anything feels unclear or if you'd like me to walk you through more examples, just let me know—I’m here to help!
Sources: examples/voice_agents/realtime_joke_teller.py | Tool definition and use | LiveKit Docs | agents/src/voice/generation.tsbetter-painter-56211
10/23/2025, 7:20 AMclass FileApprovalAgentTask(AgentTask[ApprovalResult]):
"""
Native LiveKit AgentTask for file modification approval.
This task takes control of the voice pipeline to get explicit user approval
or rejection of file modifications. It uses function tools to capture the
user's decision and automatically returns control to the main agent when complete.
The task is launched on-demand when file operations need approval, rather than
running continuously in the background.
"""
def __init__(
self,
chat_ctx: ChatContext,
document_title: str,
operation: str,
) -> None:
super().__init__(
instructions=(
"You are handling file modification approval. "
"Your ONLY job is to get an explicit approval or rejection from the user. "
"The user can say 'approve', 'accept', 'yes', 'confirm' to approve, or "
"'reject', 'deny', 'no', 'cancel' to reject. "
"Call the appropriate tool (approve_change or reject_change) immediately when you understand their intent. "
"Do NOT go off-topic or provide additional commentary. "
"Focus solely on capturing the approval decision."
),
chat_ctx=chat_ctx,
)
self._document_title = document_title
self._operation = operation
self._decision_made = False
async def on_enter(self) -> None:
"""Called when task starts - prompt user for approval."""
logger.info(
f"FileApprovalAgentTask entered for {self._operation} on '{self._document_title}'"
)
await self.session.generate_reply(
instructions=(
f"Tell the user that a file modification requires their approval: "
f"{self._operation} for '{self._document_title}'. "
f"Ask them clearly if they want to approve or reject this change. "
f"Keep it brief and wait for their response."
)
)tall-airline-16756
10/23/2025, 7:21 AMgenerate_reply in an AgentTask can be a bit frustrating. These usually happen because of issues in the task's logic or tool execution. The great news is that LiveKit helps by logging these exceptions and emitting structured events like ErrorEvent or FunctionToolsExecutedEvent, which makes managing errors a lot smoother.
Here are some friendly steps to guide you through handling this:
1. Subscribe to the "error" event: This helps catch any uncaught exceptions so you can log them or offer fallback responses. For example:
@agent.on("error")
def on_error(event: ErrorEvent):
logger.error(f"Error during generate_reply: {event.error}", exc_info=True)
if not event.error.recoverable:
agent.session.say("Sorry, I encountered an issue while responding.")
1. Inspect tool execution results: Keep an eye on the function_tools_executed event to spot any errors in the tool outputs. If a tool fails, it returns isError: true along with a sanitized error message. Here’s how you might handle that:
@agent.on("function_tools_executed")
def on_tool_executed(event: FunctionToolsExecutedEvent):
for output in event.function_call_outputs:
if output.isError:
logger.warning(f"Tool failed: {output.name}")
if output.replyRequired:
agent.session.say("I couldn't retrieve that information right now.")
1. Validate inputs and logic: Double-check that your task’s instructions and tool calls are set up correctly, and try to cover any edge cases to prevent exceptions from popping up.
If you’d like, I’m here to help you debug any specific part of your task or clarify anything further. Just let me know!
Sources: livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent_activity.ts | Events and error handling | LiveKit Docs