1. How does an AgentTask get access to the session...
# ask-ai
s
1. How does an AgentTask get access to the session or agent instance?
t
Thanks for reaching out, Jason. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! Just wanted to share how an
AgentTask
in LiveKit can access the session and agent instance—it’s pretty straightforward: • Session Access: You can get to the session through the
session
property of the
AgentTask
. This works by grabbing the related
AgentSession
using
_get_activity_or_raise().session
. For example, if you want to generate a reply, you’d use
self.session.generate_reply()
. • Agent Instance Access: Since
AgentTask
inherits from the
Agent
class, it is an agent instance itself. So, inside its methods like
on_enter
or
on_exit
,
self
refers to the agent instance. That means you can easily access its properties and methods, like
self.instructions
or
self.chat_ctx
. Behind the scenes, the framework keeps the connection between the
AgentTask
and its
AgentSession
running smoothly through an
AgentActivity
object. This way, everything works together seamlessly—making your life a bit easier! Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | Workflows | LiveKit Docs
s
Thank you for explaining that AgentTask inherits from Agent! However, I'm still getting the same RuntimeError: no activity context found when I call Agent.default.llm_node(self, ...) from within my AgentTask's llm_node override. My specific setup: python Apply class TotalInterviewAgent(Agent): async def on_user_turn_completed(self, _turn_ctx_, _new_message_): # I create the task here self.interview_task = InterviewPlanningTask(...) result = await self.interview_task.evaluate_and_plan(turn_ctx, ...) class InterviewPlanningTask(AgentTask): async def llm_node(self, _chat_ctx_, tools, _model_settings_): # This still fails with RuntimeError: no activity context found async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings): yield chunk Questions: 1. Is there a specific way AgentTask instances need to be created or initialized to have the proper activity context? 2. Should I be creating the task differently than just InterviewPlanningTask(...)? 3. Does the task need to be explicitly connected to the session before calling llm_node? The error occurs when Agent.default.llm_node() tries to call agent._get_activity_or_raise(), suggesting the task doesn't have the proper activity context even though it inherits from Agent."
t
Hey there! That pesky error
RuntimeError: no activity context found
pops up because the
_get_activity_or_raise()
method expects a running
AgentActivity
. This activity only gets set up when your agent is properly started within an
AgentSession
. Here’s how you can fix it: 1. Make Sure Everything’s Initialized Right: First, create an instance of your
Agent
subclass and set it up with all the parameters it needs. 2. Start the AgentSession: Use the
AgentSession
class to handle the agent’s lifecycle. For example:
Copy code
async def main():
    sess = AgentSession(
        turn_detection=..., stt=stt_instance, llm=llm_instance, tts=tts_instance
    )
    await sess.start(agent)
    await sess.aclose()
3. Understand the Activity Context: When you call
AgentSession.start()
, it creates an
AgentActivity
behind the scenes. This sets up the context so methods like
llm_node
can run smoothly without errors. Just a heads-up: if you try calling
llm_node
directly on an
AgentTask
before the task is managed by a started
AgentSession
, you’ll hit this error. So, make sure your task is connected to the session by running it within the session lifecycle. Hope this helps clear things up! Sources: livekit-agents/livekit/agents/voice/generation.py | Pipeline nodes and hooks | LiveKit Docs
s
Thank you! That explains the activity context issue perfectly. I understand now that AgentTask needs to be managed by the AgentSession to have the proper context. My current approach (causing the error): python Apply class TotalInterviewAgent(Agent): async def on_user_turn_completed(self, _turn_ctx_, _new_message_): # I manually create and call the task - this is wrong! self.interview_task = InterviewPlanningTask(...) result = await self.interview_task.evaluate_and_plan(...) _# This calls llm_node without proper context_ What's the correct way to use AgentTask with AgentSession? Should I: 1. Add the task to the session using some method like session.add_task()? 2. Replace the main agent with the task using session.start(agent=task)? 3. Use a different pattern entirely for task-based LLM processing? I want to use the task's llm_node override for custom prompt injection, but I need to understand how to properly integrate it with the AgentSession lifecycle so it has the correct activity context."
t
Hey there! To smoothly integrate
AgentTask
with
AgentSession
and make sure the activity context is just right, here’s a friendly step-by-step guide: 1. Define the Task: Start by extending the
AgentTask
class and implementing methods like
on_enter
to kick off your interactions. When your task wraps up, just call
self.complete()
to return the results. Here’s a quick example:
class InterviewPlanningTask(AgentTask[bool]):\n    async def on_enter(self):\n        await self.session.generate_reply(instructions=\"Start planning the interview.\")\n    def complete_task(self, result):\n        self.complete(result)
2. Run the Task: Next, create and await the task while your
AgentSession
is active. For example:
class TotalInterviewAgent(Agent):\n    async def on_enter(self):\n        result = await InterviewPlanningTask()\n        if result:\n            await self.session.generate_reply(instructions=\"Interview planning completed.\")
3. Context Management: Make sure you create and await the task only inside
on_enter
,
on_exit
, or tool functions of another
Agent
. This way, the
AgentSession
provides the proper activity context you need. 4. Session Configuration: Your task will naturally inherit settings like
llm
,
stt
, and
tts
from the
AgentSession
, unless you specify them when creating the task. 5. Typed Results: If you want to structure your outputs neatly, use custom dataclasses. Here’s an example:
from dataclasses import dataclass\n\n@dataclass\nclass InterviewPlan:\n    steps: list\n\nclass InterviewPlanningTask(AgentTask[InterviewPlan]):\n    def complete_plan(self, steps):\n        self.complete(InterviewPlan(steps=steps))
To wrap it up, remember that
AgentTask
needs to run within the active lifecycle of an
AgentSession
. It’s not meant to be manually created and called outside this context. So, keep your task creation and awaiting inside your session’s agent methods, like
on_enter
. If you have any questions or want to chat more about this, I’m here to help! Sources: livekit-agents/livekit/agents/__init__.py | Workflows | LiveKit Docs