Defining a task Extend the `AgentTask` class and s...
# ask-ai
b
Defining a task Extend the
AgentTask
class and specify a result type using generics . Use the
on_enter
method to begin the task's interaction with the user, and call the
complete
method with a result when complete. The task has full support for tools, similar to an agent.
Copy code
from livekit.agents import AgentTask, function_tool

class CollectConsent(AgentTask[bool]):
    def __init__(self, chat_ctx=None):
        super().__init__(
            instructions="""
            Ask for recording consent and get a clear yes or no answer.
            Be polite and professional.
            """,
            chat_ctx=chat_ctx,
        )

    async def on_enter(self) -> None:
        await self.session.generate_reply(
            instructions="""
            Briefly introduce yourself, then ask for permission to record the call for quality assurance and training purposes.
            Make it clear that they can decline.
            """
        )

    @function_tool
    async def consent_given(self) -> None:
        """Use this when the user gives consent to record."""
        self.complete(True)

    @function_tool
    async def consent_denied(self) -> None:
        """Use this when the user denies consent to record."""
        self.complete(False)
Running a task The task runs automatically upon creation. It must be created within the context of an existing
Agent
which is active within an
AgentSession
. The task takes control of the session until it returns a result. Await the task to receive its result.
Copy code
from livekit.agents import Agent, function_tool, get_job_context

class CustomerServiceAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a friendly customer service representative.")

    async def on_enter(self) -> None:
        if await CollectConsent(chat_ctx=self.chat_ctx):
            await self.session.generate_reply(instructions="Offer your assistance to the user.")
        else:
            await self.session.generate_reply(instructions="Inform the user that you are unable to proceed and will end the call.")
            job_ctx = get_job_context()
            await job_ctx.api.room.delete_room(api.DeleteRoomRequest(room=job_ctx
in this case do I need to explicitly handoff back to the CustomerServiceAgent?
t
Thanks for reaching out, mateuszkasprowicz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Just so you know, when you're working with tasks in LiveKit, you don't need to worry about explicitly handing things back to the parent
Agent
. Once a task is completed, the framework kindly takes care of restoring the session to the parent agent's context for you, so everything continues smoothly. This is all built into how the session management works, and you usually won’t need to add any extra code—unless you want to customize the behavior with your own specific logic. If you have any questions or want to explore that, I’m here to help! Sources: livekit-agents/livekit/agents/voice/run_result.py | Tool definition and use | LiveKit docs
b
so in my unit test why am I not seeing the handoff back? class QuestionAnsweredComprehensively(AgentTask[bool]): """Task to check if the question was answered comprehensively.""" def *__init__*( self, _chat_ctx_: ChatContext | None = None, _evaluation_criteria_: str | None = None, _expected_duration_: int | None = None, ): instructions = get_evaluation_criteria(_evaluation_criteria_, _expected_duration_) voice_stack = build_default_voice_stack(_llm_kwargs_={"tool_choice": "required"}) super().__init__(_chat_ctx_=_chat_ctx_, instructions=instructions, **voice_stack) async def *on_enter*(self): """Initialize the agent and start the timer (in seconds).""" self.session.input.set_audio_enabled(False) speech = self.session.say(text=self.session.userdata.question_prompt) speech.add_done_callback(lambda ___: self.session.input.set_audio_enabled(True)) @function_tool() async def *confirm_comprehensive_answer*(self) -> None: """Mark that the current question has been answered comprehensively. Use this tool when, based on the evaluation_criteria and expected_duration provided in the context, the candidate's answer is complete, correct, clear, relevant, and sufficiently detailed. It also applies when very little time remains and the answer is as strong as can be reasonably expected. Calling this tool finalizes the task with a positive result. """ self.complete(True) @function_tool async def *decline_comprehensive_answer*(self) -> None: """Mark that the current question has not yet been answered comprehensively. Use this tool when there are significant gaps, errors, lack of clarity, or insufficient depth in the candidate's answer. It also applies when the content is off-topic and further detail or clarification would be helpful. Calling this tool finalizes the task with a negative result. """ self.complete(False) class Interviewer(Agent): def *__init__*(self, *_args_, **_kwargs_) -> None: super().__init__(*_args_, **_kwargs_) async def *on_enter*(self): """Initialize the agent and start the timer (in seconds).""" self.session.userdata.start_time = time.time() if await QuestionAnsweredComprehensively( _chat_ctx_=self.chat_ctx, _evaluation_criteria_=self.session.userdata.evaluation_criteria, _expected_duration_=self.session.userdata.expected_duration, ): logger.info("Question answered comprehensively") await self.session.say( text="Thank you for your answer. You'll see the feedback shortly.", _allow_interruptions_=False, ) await remove_participant(self.session) _else_: logger.info("Question not answered comprehensively") await self.session.generate_reply( instructions="Ask a relevant follow-up question.", _allow_interruptions_=False, )
t
Thanks for sharing your question! The absence of a visible handoff back to the parent
Agent
in your unit test is actually expected behavior. When an
AgentTask
completes, it quietly resolves its result and merges its chat context back into the parent agent's context. This process doesn’t trigger a handoff event because handoffs are specifically for explicit agent transitions, like when a new agent instance is returned from a tool function. To make sure everything is working as it should in your test, try checking for function call outputs or messages from the parent agent after the task finishes, instead of looking for a handoff event. If anything feels unclear or you’d like a hand with your test setup, please don’t hesitate to reach out—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent.py | Testing and evaluation | LiveKit Docs | Workflows | LiveKit docs | agents/src/voice/agent_activity.ts
b
but no reply is generated from parent Agent on_enter...
t
It looks like the parent `Agent`'s
on_enter
method might not be generating a reply after an
AgentTask
completes because it doesn’t explicitly call
session.generate_reply()
or
session.say()
. Since
on_enter
is empty by default unless you override it, no reply will happen unless you add that part yourself. To fix this, you’ll want to make sure the parent agent’s
on_enter
method includes the steps to generate a reply once the task is done. If you’d like, I’m here to help guide you through how to implement that! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Workflows | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | home_assistant/homeautomation.py
b
async def *on_enter*(self): """Initialize the agent and start the timer (in seconds).""" self.session.userdata.start_time = time.time() if await QuestionAnsweredComprehensively( _chat_ctx_=self.chat_ctx, _evaluation_criteria_=self.session.userdata.evaluation_criteria, _expected_duration_=self.session.userdata.expected_duration, ): logger.info("Question answered comprehensively") await self.session.say( text="Thank you for your answer. You'll see the feedback shortly.", _allow_interruptions_=False, ) await remove_participant(self.session) _else_: logger.info("Question not answered comprehensively") await self.session.generate_reply( instructions="Ask a relevant follow-up question.", _allow_interruptions_=False, ) but I have session say and generate reply for both cases
t
Hi there! I understand it can be a bit tricky when
session.say
or
session.generate_reply
don’t seem to run in your
on_enter
method after an
AgentTask
finishes. Let’s walk through some common reasons together: • Session State: It’s important to check that your
AgentSession
is active when you call these methods. If the session is closing or hasn’t fully started, these calls might not work as expected. • Activity Interruption: Sometimes, if the session state changes or a handoff happens right when the task completes, it can interrupt these method executions. • Await Usage: Make sure you’re properly using
await
with
session.generate_reply()
or
session.say()
so they have time to finish before moving on. • TTS Configuration: Remember,
session.say
needs a TTS plugin set up. Without it, speech won’t be generated. • Task Completion Handling: After the task finishes, the switch back to the parent agent might not handle speech generation unless it’s explicitly coded to do so. To get this sorted, I recommend double-checking the session state, ensuring you’re awaiting those methods properly, and confirming your TTS plugin is configured. If you’re still stuck after that, please don’t hesitate to reach out—I’m here to help you dig deeper and find a solution! Sources: pipeline-tts/short_replies_only.py | Events and error handling | LiveKit docs | livekit-agents/livekit/agents/voice/agent.py | Agent speech and audio | LiveKit docs | Workflows | LiveKit docs
b
should STT be present during testing?
t
Thanks for reaching out! Just to help you better, STT (Speech-to-Text) is needed during testing only if your agent or task works with user speech input. So, if your test is about checking transcription or handling audio input, having STT is important. But if your focus is more on TTS (Text-to-Speech) or other parts that don’t involve audio input, then STT might not be required. Could you please share a bit more about whether your test involves processing user speech or if it’s centered on other features? I’m here to help you through this! Sources: examples/src/basic_agent.ts
b
question = "What's your biggest weakness?" async with ( build_default_voice_stack().get("llm") as llm, AgentSession[UserSessionInfo]( userdata=UserSessionInfo(_question_prompt_=question), llm=llm, stt=None, ) as session, ): initial_result = await session.start( Interviewer(instructions=_llm_instructions_, _chat_ctx_=_initial_context_), _capture_run_=True, ) initial_result.expect.next_event().is_agent_handoff(_new_agent_type_=Interviewer) initial_result.expect.next_event().is_agent_handoff(_new_agent_type_=QuestionAnsweredComprehensively) initial_result.expect.next_event().is_message(role="assistant") result = await session.run( _user_input_="I think my biggest weakness is that I'm too shy.", ) result.expect.next_event().is_function_call() result.expect.next_event().is_function_call_output() await session.run(_user_input_="I don't know.") @pytest.mark.asyncio @pytest.mark.usefixtures("job_process") async def test_interviewer_full_turn( initial_context: ChatContext, llm_instructions: str ) -> None: question = "What's your biggest weakness?" async with ( build_default_voice_stack().get("llm") as llm, AgentSession[UserSessionInfo]( userdata=UserSessionInfo(question_prompt=question), llm=llm, stt=None, ) as session, ): initial_result = await session.start( Interviewer(instructions=llm_instructions, chat_ctx=initial_context), capture_run=True, ) initial_result.expect.next_event().is_agent_handoff(new_agent_type=Interviewer) initial_result.expect.next_event().is_agent_handoff(new_agent_type=QuestionAnsweredComprehensively) initial_result.expect.next_event().is_message(role="assistant") result = await session.run( user_input="I think my biggest weakness is that I'm too shy.", ) result.expect.next_event().is_function_call() result.expect.next_event().is_function_call_output()
await session.run(user_input="I don't know.")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tests/voice/test_experimental_interviewer.py171 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.12/site-packages/livekit/agents/voice/agent_session.py421 in run self.generate_reply(user_input=user_input) .venv/lib/python3.12/site-packages/livekit/agents/voice/agent_session.py838 in generate_reply handle = self._next_activity._generate_reply( .venv/lib/python3.12/site-packages/livekit/agents/voice/agent_activity.py851 in _generate_reply self._schedule_speech(handle, SpeechHandle.SPEECH_PRIORITY_NORMAL) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <livekit.agents.voice.agent_activity.AgentActivity object at 0x783e2cec9700>, speech = <livekit.agents.voice.speech_handle.SpeechHandle object at 0x783e3c2c2c30>, priority = 5 force = False def _schedule_speech(self, speech: SpeechHandle, priority: int, force: bool = False) -> None: # when force=True, we still allow to schedule a new speech even if #
pause_speech_scheduling
is waiting for the schedule_task to drain. # This allows for tool responses to be generated before the AgentActivity is finalized. if self._scheduling_paused and not force:
raise RuntimeError(
"cannot schedule new speech, the speech scheduling is draining/pausing" ) E RuntimeError: cannot schedule new speech, the speech scheduling is draining/pausing what could be the root cause of this issue?
t
I'm here to help you understand the error "cannot schedule new speech, the speech scheduling is draining/pausing." This message appears when the agent's speech scheduling system is in a draining or pausing state, which usually happens during lifecycle transitions like when the agent is shutting down or paused. This is designed to make sure ongoing tasks are handled smoothly. While in this state, scheduling new speech is generally blocked unless it's explicitly forced, such as for tool responses. To get around this, please check that the agent isn’t in a draining or pausing state when you try to schedule speech. If this seems unexpected, it might be helpful to review any lifecycle transitions or pauses in your test setup that could be causing this. I'm here if you need any further guidance! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent_activity.ts | Agent Session Management & Turn Detection | livekit/livekit_composite | Dee...
b
async def *on_enter*(self): """Initialize the agent and start the timer (in seconds).""" self.session.userdata.start_time = time.time() if await QuestionAnsweredComprehensively( _chat_ctx_=self.chat_ctx, _evaluation_criteria_=self.session.userdata.evaluation_criteria, _expected_duration_=self.session.userdata.expected_duration, ): logger.info("Question answered comprehensively") self.session.say( text="Thank you for your answer. You'll see the feedback shortly.", _allow_interruptions_=False, ) await remove_participant(self.session) _else_: logger.info("Question not answered comprehensively") self.session.generate_reply( instructions="Ask a relevant follow-up question.", _allow_interruptions_=False, ) class QuestionAnsweredComprehensively(AgentMixin, AgentTask[bool]): """Task to check if the question was answered comprehensively.""" def *__init__*( self, _chat_ctx_: ChatContext | None = None, _evaluation_criteria_: str | None = None, _expected_duration_: int | None = None, ): instructions = get_evaluation_criteria(_evaluation_criteria_, _expected_duration_) voice_stack = build_default_voice_stack(_llm_kwargs_={"tool_choice": "required"}) super().__init__(_chat_ctx_=_chat_ctx_, instructions=instructions, **voice_stack) async def *on_enter*(self): """Initialize the agent and ask the question.""" self.session.say( text=self.session.userdata.question_prompt, _allow_interruptions_=False ) @function_tool() async def *confirm_comprehensive_answer*(self, _ctx_: RunContext) -> None: """Mark that the current question has been answered comprehensively. Use this tool when, based on the evaluation_criteria and expected_duration provided in the context, the candidate's answer is complete, correct, clear, relevant, and sufficiently detailed. It also applies when very little time remains and the answer is as strong as can be reasonably expected. Calling this tool finalizes the task with a positive result. """ self.complete(True) @function_tool async def *decline_comprehensive_answer*(self) -> None: """Mark that the current question has not yet been answered comprehensively. Use this tool when there are significant gaps, errors, lack of clarity, or insufficient depth in the candidate's answer. It also applies when the content is off-topic and further detail or clarification would be helpful. Calling this tool finalizes the task with a negative result. """ self.complete(False) we're basically in the state after task is completed and for some reason it doesn't generate reply
t
I'm here to help you understand why a reply might not be generated after an
AgentTask
completes. There are a few common reasons this could happen: • LLM Not Configured: Please double-check that your session has a valid LLM instance assigned, since
generate_reply
depends on it. • Session State: Make sure the session is active and not in a closing or draining state when you call
generate_reply
. • Tool Execution Logic: If the tool used in the task doesn’t return a valid output, the reply might not be triggered. It’s important that the tool returns a valid object or string. • Agent Handoff: When multiple agent tasks are returned or a handoff happens, reply generation can sometimes be suppressed. Try to ensure only one agent task is returned. • Speech Scheduling: Check that
scheduleSpeech
is enabled when calling
generate_reply
. To move forward, please verify the LLM configuration, session state, and that your tool returns the expected values. If things still aren’t working, detailed logging of agent state transitions and tool executions can be really helpful to pinpoint the root cause. Feel free to reach out if you’d like me to guide you through the debugging process—I’m here to support you every step of the way! Sources: main.py | Agent speech and audio | LiveKit docs | agents/src/voice/agent_activity.ts | tests/test_agent_session.py | Events and error handling | LiveKit docs
b
• Tool Execution Logic: If the tool used in the task doesn’t return a valid output, the reply might not be triggered. It’s important that the tool returns a valid object or string. how to check that?
t
I'm glad you're looking into how LiveKit handles tool outputs! LiveKit automatically checks the outputs during execution to make sure they're valid. A valid tool output is any serializable data type, such as: • Primitive types like
string
,
number
,
boolean
,
null
, or
undefined
• Arrays, as long as all the elements inside are valid • Objects, where all keys are primitives and all values are valid If a tool happens to return something invalid—like a function or an unserializable object—LiveKit will log an error and discard that output. To help you spot these, you can: • Check the logs for any errors related to invalid tool outputs • Look at the
FunctionToolsExecuted
event, which only includes outputs that passed validation • Use assertions in your testing framework to confirm your outputs are as expected To keep things smooth, it’s best to return serializable data types and avoid things like functions, classes, or circular references. If you’d like, I’m here to help you debug any specific tool output you’re working with—just let me know! Sources: Testing and evaluation | LiveKit Docs | Agent Session Management & Turn Detection | livekit/livekit_composite | Dee... | agents/src/voice/agent_activity.ts | livekit-agents/livekit/agents/voice/generation.py
b
class QuestionAnsweredComprehensively(AgentMixin, AgentTask[bool]): """Task to check if the question was answered comprehensively.""" def *__init__*( self, _chat_ctx_: ChatContext | None = None, _evaluation_criteria_: str | None = None, _expected_duration_: int | None = None, ): instructions = get_evaluation_criteria(_evaluation_criteria_, _expected_duration_) voice_stack = build_default_voice_stack(_llm_kwargs_={"tool_choice": "required"}) super().__init__(_chat_ctx_=_chat_ctx_, instructions=instructions, **voice_stack) async def *on_enter*(self): """Initialize the agent and ask the question.""" self.session.say( text=self.session.userdata.question_prompt, _allow_interruptions_=False ) @function_tool() async def *confirm_comprehensive_answer*(self) -> None: """Mark that the current question has been answered comprehensively. Use this tool when, based on the evaluation_criteria and expected_duration provided in the context, the candidate's answer is complete, correct, clear, relevant, and sufficiently detailed. It also applies when very little time remains and the answer is as strong as can be reasonably expected. Calling this tool finalizes the task with a positive result. """ self.complete(True) @function_tool async def *decline_comprehensive_answer*(self) -> None: """Mark that the current question has not yet been answered comprehensively. Use this tool when there are significant gaps, errors, lack of clarity, or insufficient depth in the candidate's answer. It also applies when the content is off-topic and further detail or clarification would be helpful. Calling this tool finalizes the task with a negative result. """ self.complete(False) FunctionCallOutputEvent(item=FunctionCallOutput(id='item_82f7afe09a4a', type='function_call_output', name='decline_comprehensive_answer', call_id='call_ck7u2CgsWJJy6CAuLPYhhYoE', output='', is_error=False, created_at=1763391279.831053), type='function_call_output')] why am I getting output="" for this AgentTask?
t
It looks like you're encountering an empty output (
output=""
) for your
AgentTask
tool, which usually happens when the tool's return value is invalid,
None
, or not properly serialized. Don’t worry, let’s walk through some common causes and how you can fix them: • Invalid Output Type: Make sure your tool returns a serializable type, like a
string
,
number
,
boolean
,
dict
, or
list
. It’s best to avoid returning functions, class instances, or objects that can’t be serialized. • Tool Returns `None`: If your tool is returning
None
explicitly, that will result in an empty string output. Try returning a meaningful value instead to see the results you expect. • Tool Raises an Exception: If there’s an error during the tool’s execution, the output will be marked as an error and show as empty. Checking the logs for any exceptions can really help pinpoint the issue. • Multiple AgentTasks: If more than one
AgentTask
is returned, the output might get ignored. It’s a good idea to ensure only one task is returned at a time. To get this sorted, just double-check that your tool returns valid, serializable data and that any exceptions are handled smoothly. And if you’d like, I’m here to help you debug a specific tool—just let me know! Sources: Tool definition and use | LiveKit docs | agents/src/voice/generation.ts | livekit-agents/livekit/agents/voice/agent_activity.py
b
class QuestionAnsweredComprehensively(AgentMixin, AgentTask[bool]): """Task to check if the question was answered comprehensively.""" def *__init__*( self, _chat_ctx_: ChatContext | None = None, _evaluation_criteria_: str | None = None, _expected_duration_: int | None = None, ): instructions = get_evaluation_criteria(_evaluation_criteria_, _expected_duration_) voice_stack = build_default_voice_stack(_llm_kwargs_={"tool_choice": "required"}) super().__init__(_chat_ctx_=_chat_ctx_, instructions=instructions, **voice_stack) async def *on_enter*(self): """Initialize the agent and ask the question.""" self.session.say( text=self.session.userdata.question_prompt, _allow_interruptions_=False ) @function_tool() async def *confirm_comprehensive_answer*(self) -> None: """Mark that the current question has been answered comprehensively. Use this tool when, based on the evaluation_criteria and expected_duration provided in the context, the candidate's answer is complete, correct, clear, relevant, and sufficiently detailed. It also applies when very little time remains and the answer is as strong as can be reasonably expected. Calling this tool finalizes the task with a positive result. """ self.complete(True) @function_tool async def *decline_comprehensive_answer*(self) -> None: """Mark that the current question has not yet been answered comprehensively. Use this tool when there are significant gaps, errors, lack of clarity, or insufficient depth in the candidate's answer. It also applies when the content is off-topic and further detail or clarification would be helpful. Calling this tool finalizes the task with a negative result. """ self.complete(False) review this implementation and tell me what's wrong?
t
It looks like the tools
confirm_comprehensive_answer
and
decline_comprehensive_answer
are custom-defined. Could you please share if these tools are part of your own implementation, or if you’re expecting them to follow a particular example or built-in behavior? Understanding this will really help me give you a more focused and helpful review of your implementation. Sources: Workflows | LiveKit docs | livekit-agents/livekit/agents/voice/agent.py
b
my own implementation
t
Thank you so much for clarifying! Based on what you've shared, here are a few areas we can gently review together to help pinpoint any issues: • Tool Output: It’s important to make sure that
confirm_comprehensive_answer
and
decline_comprehensive_answer
return valid, serializable outputs. For instance, try to avoid returning
None
or any non-serializable objects. • Task Completion: The
self.complete()
method should be called with a valid result. Let’s double-check that the result passed to
self.complete()
is being properly handled by the parent agent. • Session State: Please ensure the
AgentSession
is active and not in a paused or draining state when these tools run. • Exception Handling: It might be helpful to add some error handling within the tools to log and manage any unexpected issues that come up during execution. • Integration with Parent Agent: Let’s also verify that the parent agent correctly resumes control and processes the task result once the task finishes. If you notice any specific hiccups, like empty outputs or unexpected behavior, please don’t hesitate to reach out. I’m here to help you work through any debugging steps together!