ai is will call new function/task but still contin...
# ask-ai
d
ai is will call new function/task but still continuign to talk about previous task... how is that possible? dimension_results = await GetDimensions(chat_ctx=self.chat_ctx) if dimension_results: ask_result = await AskForPhotos(chat_ctx=self.chat_ctx) it will gets dimensions.. calls photos but still talks about dimensions... how?
t
Thanks for reaching out, Billy. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for sharing your observation! What you're seeing happens because the AI system uses asynchronous programming. When the function
GetDimensions
is called, it runs asynchronously, which means the system can keep working on other tasks—like calling `AskForPhotos`—without waiting for the first function to finish. At the same time, the AI keeps track of the previous task (dimensions) by holding onto the conversation history and shared context objects such as
chat_ctx
. This way, it can keep the conversation about dimensions going even while handling the photo-related task. This method helps everything run smoothly and keeps the conversation flowing naturally. Sources: livekit-agents/livekit/agents/voice/generation.py | External data and RAG | LiveKit Docs | Docs::Agents | Agent speech and audio | LiveKit Docs | Docs::Agents
d
class GetDimensions(AgentTask[str]): def __init__(self, chat_ctx=None): super().__init__( instructions="""Ask for dimensions of paint project. DO NOT ASK ANY OTHER QUESTIONS OR SAY ANYTHING AFTER ABOUT NEEDING GALLONS OF PAINT OR CEILING HEIGHT""", chat_ctx=chat_ctx, ) async def on_enter(self) -> None: logger.info("📐 Getting Dimensions") await self.session.generate_reply( instructions="Ask caller for dimensions of room or area. DO NOT ASK ANY OTHER QUESTIONS OR SAY ANYTHING AFTER ABOUT NEEDING GALLONS OF PAINT OR CEILING HEIGHT" ) @function_tool async def collect_dimensions(self, ctx:RunContext[HelperSessionInfo], project_dimensions: str) -> None: """Collect dimensions in square feet. DO NOT ASK ANY OTHER QUESTIONS OR SAY ANYTHING AFTER ABOUT NEEDING GALLONS OF PAINT OR CEILING HEIGHT""" if project_dimensions: ctx.session.userdata.project_dimensions = project_dimensions logger.info(f"👀 Dimensions collected {project_dimensions}") self.complete(True) else: await self.session.generate_reply(instructions="Ask for dimensions")
t
Thank you for sharing the 'GetDimensions' class! It seems like this class isn't part of the documented LiveKit SDKs or features that I'm familiar with. Could you please let me know if this is a custom implementation you've created, or if it belongs to a particular SDK or feature you're using? For instance, are you focusing on video dimensions, or is this connected to another part of LiveKit? I'm here to help you figure this out together! Sources: lib/src/types/video_dimensions.dart | src/room/track/RemoteVideoTrack.test.ts | Sources/LiveKit/Types/Options/VideoCaptureOptions.swift
d
HOW DO I GET THE AI NOT TO SAY ANYTHING AFTER COLLECTING INFORMATION
t
To help you make sure the AI doesn’t say anything after it has gathered the specific information you need, you can use the
StopResponse
exception inside the
on_user_turn_completed
lifecycle hook. This is a handy way to stop the agent from replying once it has everything it needs. Here’s a simple example to illustrate:
Copy code
class DataCollectionAgent(Agent):
    def __init__(self):
        super().__init__(instructions="Gather user data.")
        self.data_collected = False

    async def on_user_turn_completed(self, chat_ctx, new_message):
        if self.data_collected:
            raise StopResponse()  # Prevents further responses
        return await super().on_user_turn_completed(chat_ctx, new_message)

    @function_tool()
    async def collect_data(self, user_input: str):
        self.data_collected = True
        return "Data collected successfully."
With this setup, your agent will gracefully stop responding once the data collection is complete. If you’d like, I’m here to help you with any part of this implementation—just let me know! Sources: Docs::Agents | Pipeline nodes and hooks | LiveKit Docs | How to Set Up Speech-to-Text Input with Text-Only Output in LiveKit Agents | examples/voice_agents/multi_agent.py | home_assistant/homeautomation.py
d
class HelperAgent(Agent): def __init__(self, tools=None, userdata: Optional[HelperSessionInfo] = None ): self.background_audio = None self.userdata = userdata self.client_name = userdata.client_name instructions = f""" FOLLOW THESE RULES STRICTLY: """ super().__init__(instructions=instructions) async def on_enter(self) -> None: if self.userdata.has_existing_booking: logger.info("🔮 Checking Bookings") result = await AlreadyBooked(chat_ctx=self.chat_ctx) can i pass the client name to the already booked task agent? and use it on the on_enter class AlreadyBooked(AgentTask[bool]): def __init__(self, chat_ctx=None): super().__init__( instructions="""Let caller know they have an existing booking and them if they want to speak with someone""", chat_ctx=chat_ctx, ) async def on_enter(self) -> None: logger.info("👀 Booking EXISTS!") await self.session.generate_reply( instructions=f"Ask if they want to speak with someone in regards to their painting project" )
t
Absolutely, you can pass the
client_name
to the
AlreadyBooked
task agent and use it in the
on_enter
method by utilizing the
userdata
attribute of the session. Let me walk you through how you can do this: 1. Define a UserData class: Start by creating a dataclass to hold shared data like
client_name
.
Copy code
from dataclasses import dataclass

@dataclass
class UserData:
    client_name: str | None = None
2. Initialize the session with UserData: When you create the session, pass an instance of
UserData
.
session = AgentSession[UserData](userdata=UserData(client_name="John Doe"))
3. Access the data in `on_enter`: Inside the
on_enter
method, you can get the
client_name
using
self.session.userdata
.
Copy code
class AlreadyBooked(AgentTask[bool]):
    async def on_enter(self) -> None:
        client_name = self.session.userdata.client_name
        await self.session.generate_reply(
            instructions=f"Hello {client_name}, you have an existing booking. Would you like to speak with someone?"
        )
This way, the
client_name
stays accessible across your agents and tasks. If anything isn’t clear or you’d like me to help you further, just let me know—I’m here to help! Sources: Workflows | LiveKit Docs | examples/voice_agents/multi_agent.py | avatars/hedra/education_avatar/agent.py
d
self.session.userdata doesnt show any variables so im not sure if it will work. but ill try
t
If
self.session.userdata
isn't showing any variables, let's make sure that the
userdata
attribute is properly initialized when you create the session. For example:
Copy code
session = AgentSession[UserData](userdata=UserData(client_name="John Doe"))
Also, please double-check that the
UserData
class is correctly defined and includes the variables you need, like
client_name
. If you run into any trouble, just let me know—I'm here to help you through it!
d
# Configure voice processing pipeline with dataclass session = AgentSession[HelperSessionInfo]( userdata=HelperSessionInfo( phone_number=phone_number, twilio_number=twilio_number, start_time=datetime.now(), participant_identity=participant_identity ), stt=deepgram.STT(model="nova-3", language="multi"), llm=groq.LLM( model="moonshotai/kimi-k2-instruct-0905", temperature=0.1 ), tts=deepgram.TTS(model="aura-2-delia-en"), vad=silero.VAD.load(), turn_detection="vad", max_endpointing_delay=6.0, min_endpointing_delay=0.9 ) # check if caller has booking session.userdata.has_existing_booking = bool(await check_booking_cache(session)) # Initialize insurance agent agent = HelperAgent(userdata=session.userdata) try: await session.start(agent=agent, room=ctx.room) except Exception as e: logger.error(f"❌ Error during agent session: {e}") raise if name == "__main__": agents.cli.run_app(agents.WorkerOptions( entrypoint_fnc=entrypoint, agent_name="telephony_agent" ))
t
Thanks for sharing the code snippet! It looks like you’re on the right track by initializing the
userdata
attribute with an instance of
HelperSessionInfo
. Since
session.userdata
is being filled with values like
phone_number
and
has_existing_booking
, it should work smoothly when accessed in your agent or task. If you’re still running into any issues, here are a few things to double-check: • Make sure the
HelperSessionInfo
class is properly defined with all the necessary fields. • Confirm that
userdata
is being passed correctly to the agent, just like you have in your code (
agent = HelperAgent(userdata=session.userdata)
). • Verify you’re accessing the variables in
userdata
using the right attribute names (for example,
self.session.userdata.has_existing_booking
). Please don’t hesitate to reach out if you’d like me to help you debug this further—I’m here to support you!
d
it worked. thanks!
t
You're very welcome! I'm so happy to hear that it worked for you. If anything else comes up or you have more questions, please don't hesitate to reach out—I'm here to help whenever you need.