I'm following your previous recommendation to impl...
# ask-ai
s
I'm following your previous recommendation to implement custom prompt injection within an AgentTask's llm_node override. However, I'm encountering a RuntimeError: no activity context found, the agent is not running when the task tries to call super().llm_node(). My Current Architecture: 1. Agent Setup (working correctly): 2. python 3. 4. Apply to total_agent.... 5. 6. 7. session = AgentSession( 8. _turn_detection_=MultilingualModel(), 9. _allow_interruptions_=True, 10. vad=ctx.proc.userdata["vad"], 11. stt=deepgram.STT(model="nova-3", language="multi"), 12. llm=openai.LLM(model="gpt-4o"), 13. tts=openai.TTS(voice="alloy") 14. ) 15. await session.start(agent=agent, room=ctx.room) 16. 17. 18. 19. 20. Agent Class (working correctly): 21. python 22. 23. Apply to total_agent.... 24. 25. 26. class TotalInterviewAgent(Agent): 27. async def on_user_turn_completed(self, _turn_ctx_, _new_message_): 28. # Call the task to evaluate the conversation 29. result = await self.interview_task.evaluate_and_plan( 30. _turn_ctx_=turn_ctx, 31. _new_message_=new_message.text_content 32. ) 33. 34. 35. 36. 37. AgentTask with llm_node override (this is where the error occurs): 38. python 39. 40. Apply to total_agent.... 41. 42. 43. class InterviewPlanningTask(AgentTask): 44. async def llm_node(self, _chat_ctx_, tools=[], _model_settings_=None): 45. # Add custom system and user prompts 46. chat_ctx.add_message(role="system", content=self.system_prompt) 47. chat_ctx.add_message(role="user", content=custom_user_prompt) 48. 49. # ERROR HAPPENS HERE: RuntimeError: no activity context found 50. async for chunk in super().llm_node(chat_ctx, tools, model_settings): 51. yield chunk 52. 53. async def evaluate_and_plan(self, _turn_ctx_, _new_message_): 54. llm_response = "" 55. async for chunk in self.llm_node(turn_ctx): # This calls the override above 56. llm_response += chunk.delta.content 57. return self.process_llm_response(llm_response) 58. 59. 60. 61. The Question: Is this architecture fundamentally compatible with LiveKit? Can an AgentTask's llm_node override successfully call super().llm_node() when the task is running within an active AgentSession, or does the activity context only exist at the Agent level? If this architecture can work, what am I missing to make super().llm_node() work from within the task? If this architecture cannot work, what's the recommended way to implement custom prompt injection for LLM calls that happen within tasks?"
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! The setup you described can definitely work with LiveKit, but the
RuntimeError: no activity context found
pops up because the
AgentTask
is running outside a valid agent lifecycle context. This error shows up when the task tries to call
super().llm_node()
without an active
AgentActivity
, which is essential for pipeline nodes like
llm_node
. Here’s how you can fix it: • Make sure the
AgentTask
is created and awaited only within supported lifecycle contexts, like inside a tool method decorated with
@function_tool
or within the
on_enter()
or
on_exit()
methods of an active
Agent
. • Double-check that the agent is started within an active
AgentSession
using
session.start(agent=..., room=...)
. This step sets up the necessary activity context. • If you’re overriding
llm_node
, be sure to call
super().llm_node()
inside a valid session and wrap the stream properly so the pipeline keeps running smoothly. If you want to make persistent, session-level changes to LLM behavior, it might be easier to use a regular
Agent
subclass instead of an
AgentTask
. This way, managing the lifecycle is simpler and works nicely with the session’s activity context. Feel free to reach out if you want me to walk you through these steps or if you have any other questions. I’m here to help! Sources: examples/voice_agents/llamaindex-rag/retrieval.py | Workflows | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | Modifying LLM output before TTS | LiveKit Docs
s
Thank you for the clarification! You mentioned that AgentTask should be called within supported lifecycle contexts like on_enter(), on_exit(), or @function_tool methods. I'm currently calling my AgentTask from on_user_turn_completed(): python Apply to total_agent.... class TotalInterviewAgent(Agent): async def on_user_turn_completed(self, _turn_ctx_, _new_message_): # Is this NOT a supported lifecycle context for AgentTask? result = await self.interview_task.evaluate_and_plan(turn_ctx, new_message) Questions: 1. Is on_user_turn_completed() a supported lifecycle context for AgentTask operations? If not, what's the recommended way to process user responses with custom LLM logic? 2. If I need to evaluate each user response with custom prompts and decide the next action, should I: • Use @function_tool decorated methods instead of AgentTask? • Override llm_node in the Agent class rather than using AgentTask? • Use a different approach entirely? 3. What's the recommended pattern for implementing multi-turn conversation logic where each user response needs custom prompt evaluation to determine the next question or action? My goal is to inject custom system/user prompts for each user turn, evaluate the conversation against research goals, and decide whether to continue with planned questions, revise the plan, or end the interview."
t
The
on_user_turn_completed()
method is a handy lifecycle context for
AgentTask
operations in LiveKit. It lets you work with user responses using your own custom logic before the agent replies. This is great for adding personalized prompts, checking user answers, and figuring out what to do next in multi-turn conversations. To help you evaluate each user response with custom prompts and decide the next steps, here are some friendly recommendations: • Use `on_user_turn_completed()`: This is the perfect spot to call your
AgentTask
or add your custom logic. You can tweak the chat context, add prompts, and assess responses right here. • Override
llm_node
in the
Agent
class:
If you want to change LLM behavior for the whole session, overriding
llm_node
in the
Agent
class is a straightforward and effective way—often simpler than using
AgentTask
. • Use
@function_tool
decorated methods:
For specific, tool-like tasks that need custom LLM logic, you can wrap that logic in
@function_tool
methods and call them from
on_user_turn_completed()
. When setting up multi-turn conversation logic, here’s a friendly pattern to follow: 1. Override
on_user_turn_completed()
to handle each user response. 2. Add any custom system and user prompts into the chat context as needed. 3. Use
AgentTask
or
@function_tool
methods to review the conversation and decide what to do next. 4. Update the chat context or generate a reply based on that decision. If you want, I’m here to help with more guidance on these patterns or any other questions you have! Sources: External data and RAG | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | examples/voice_agents/README.md
s
Thank you for confirming that on_user_turn_completed() is a supported lifecycle context for AgentTask operations! I want to clarify one specific technical detail: When my AgentTask's llm_node override calls super().llm_node(chat_ctx, tools, model_settings), I get RuntimeError: no activity context found. Since you've confirmed that AgentTask operations work in on_user_turn_completed(), is the issue that: 1. AgentTask's llm_node should NOT call super().llm_node() because AgentTask doesn't inherit from Agent? 2. AgentTask should use a different method to get LLM responses (like directly calling the LLM instance)? 3. There's a different way to delegate to the default LLM processing from within an AgentTask's llm_node override? In other words: What should an AgentTask's llm_node override call instead of super().llm_node() to get the default LLM processing while still injecting custom prompts?"
t
If you want to get the default LLM processing while adding your own custom prompts in an `AgentTask`'s
llm_node
override, the best way is to call
Agent.default.llm_node()
instead of
super().llm_node()
. This lets you keep the default LLM behavior but still tweak the chat context or tools however you need. Here’s a simple example to show you how it works:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    # Add your custom prompts to the chat context
    chat_ctx.add_message(role="system", content=self.system_prompt)
    chat_ctx.add_message(role="user", content=custom_user_prompt)

    # Then hand it off to the default LLM processing
    async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
        yield chunk
This way, you stay fully compatible with the LiveKit framework and avoid that pesky
RuntimeError: no activity context found
issue. If anything’s unclear or you want a hand setting this up, just let me know—I’m happy to help! Sources: Pipeline nodes and hooks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | Agents 0.x migration guide | LiveKit Docs
s
Thank you for the guidance about using Agent.default.llm_node(). I'm still getting the same RuntimeError: no activity context found error, and I think I understand why. When I call Agent.default.llm_node(self, chat_ctx, tools, model_settings) from within my AgentTask's llm_node override, the self parameter refers to the task instance, not the agent instance. But Agent.default.llm_node() expects the first parameter to be an actual Agent instance with an active context. How do I properly pass the active Agent instance to Agent.default.llm_node() from within an AgentTask? My current code structure: python Apply class InterviewPlanningTask(AgentTask): async def llm_node(self, _chat_ctx_, tools, _model_settings_): # Add custom prompts chat_ctx.add_message(role="system", content=self.system_prompt) # ERROR: 'self' here is the task, not the agent async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings): yield chunk Should I: 1. Pass the agent instance to the task constructor and use Agent.default.llm_node(self.agent, ...)? 2. Access the agent through some property on the task? 3. Use a completely different approach? The error occurs when Agent.default.llm_node() tries to call agent._get_activity_or_raise() but receives a task instance instead of an agent instance."
t
Hey there! To make sure you’re passing the active Agent instance correctly to
Agent.default.llm_node()
from within an
AgentTask
, you’ll want to pass the right agent instance as the first argument. Since
self
in your
AgentTask
points to the task itself and not the agent, you’ll need to explicitly pass the agent instance to
Agent.default.llm_node()
. Here are a couple of friendly ways to do this: 1. Pass the agent instance when you create the task: When you’re setting up the task, pass the agent instance as an argument and save it as a property on the task. Then, in your override, use
Agent.default.llm_node(self.agent, ...)
.
class InterviewPlanningTask(AgentTask):\n    def __init__(self, agent, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.agent = agent\n\n    async def llm_node(self, chat_ctx, tools, model_settings):\n        chat_ctx.add_message(role=\"system\", content=self.system_prompt)\n        async for chunk in Agent.default.llm_node(self.agent, chat_ctx, tools, model_settings):\n            yield chunk\n
2. Grab the agent from the task’s session: If your task is running inside an active session, you can get the agent instance through
self.session.agent
, as long as the session is set up properly.
async def llm_node(self, chat_ctx, tools, model_settings):\n    chat_ctx.add_message(role=\"system\", content=self.system_prompt)\n    async for chunk in Agent.default.llm_node(self.session.agent, chat_ctx, tools, model_settings):\n        yield chunk\n
Either way, this makes sure the right agent instance gets passed to
Agent.default.llm_node()
, so you won’t run into the
RuntimeError: no activity context found
problem. If you want me to walk you through it or have any questions, just let me know—I’m happy to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Pipeline nodes and hooks | LiveKit Docs
s
Thank you for the guidance! I tried both approaches you suggested, but I'm still getting the RuntimeError: no activity context found error. Issue with self.session.agent approach: When I try to use Agent.default.llm_node(self.session.agent, ...), I get an AttributeError because my AgentTask doesn't seem to have a session property. My current setup: python Apply class TotalInterviewAgent(Agent): async def on_user_turn_completed(self, _turn_ctx_, _new_message_): # Create task and call it self.interview_task = InterviewPlanningTask(...) result = await self.interview_task.evaluate_and_plan(...) class InterviewPlanningTask(AgentTask): async def llm_node(self, _chat_ctx_, tools, _model_settings_): # This fails: AttributeError: 'InterviewPlanningTask' object has no attribute 'session' async for chunk in Agent.default.llm_node(self.session.agent, chat_ctx, tools, model_settings): yield chunk Questions: 1. How does an AgentTask get access to the session or agent instance? 2. Should I pass the agent instance to the task constructor as you mentioned in option 1? 3. Or is there a different way AgentTask instances are supposed to be created/used that automatically gives them access to the session? I'm creating the task manually in on_user_turn_completed - is this the correct pattern, or should tasks be created differently?"
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!