In a multi-agent set up, when we switch from one a...
# ask-ai
p
In a multi-agent set up, when we switch from one agent to another, it seems to take 3-4 seconds on average. Is there a way to cut it down?
t
Thanks for reaching out, Basit. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to understand more about your multi-agent setup so I can assist you better. Could you share a bit more about: • Whether you're using LiveKit's built-in multi-agent features or if it's a custom setup? • What types of agents are involved in the switching—are they human agents, bots, or media processing agents? • If you've noticed any particular logs or metrics during the switching process that stood out? Getting these details will really help us explore the best ways to optimize your experience.
p
We are using livekit’s built in multi-agent feature. We are switching between bots. Basically, we have split the bot functionality into sub agents. For example, we have a greeter agent which is just responsible for greeting and then it switches to an FAQ agent….Within an agent, the latency is pretty good under 1.5 seconds. Whereas, whenever there is a switch we seem to hit 4 secons…
t
To help you reduce the switching time between bots in LiveKit's built-in multi-agent feature, here are some helpful optimizations you can try: • Preload Shared Components: Consider using the
prewarm
function to load reusable components like VAD (Voice Activity Detection) right when the worker starts up. This way, you avoid the extra time spent initializing them during agent handoff. • Preserve Chat Context: When creating the next agent, passing along the current
chat_ctx
keeps the full conversation history intact and helps cut down on reprocessing time. • Share Persistent User Data: Storing session-wide state, like user preferences or session context, in
UserData
can prevent unnecessary recomputation during switches. • Minimize Network Latency: Deploying your agent workers in the same geographic region as your AI services can really help reduce network delays. • Use Realtime LLM Models: Using low-latency models such as OpenAI’s RealtimeModel allows for faster response streaming when agents switch. • Monitor and Optimize: Keep an eye on performance by using LiveKit’s metrics API to track indicators like Time To First Token (TTFT) and spot any bottlenecks. These tips should make your bot switching faster and smoother. If you'd like, I’m here to help with more details on how to implement any of these steps—just let me know! Sources: docs/index.yaml | examples/src/comprehensive_test.ts | examples/voice_agents/multi_agent.py | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | Community & Support | livekit/livekit_composite | DeepWiki
p
are the agents not pre initialized in livekit multi-agent framework already?
t
I’d love to help clarify how agents work in LiveKit's multi-agent framework! Instead of being pre-initialized, an agent instance is created dynamically whenever a job comes in—like when a new room is created and accepted by the program registered with the LiveKit server. This approach helps keep things running smoothly by balancing the load and using resources efficiently across the system. If you’re looking to speed up initialization, a great tip is to use the
prewarm
function. It lets you preload reusable components or shared resources right when the worker starts up, which can really help improve performance during agent handoffs. I hope this makes things a bit clearer for you! Sources: An open source stack for real-time multimodal AI | An open source stack for real-time multimodal AI | Deploying to custom environments | LiveKit Docs | An open source stack for real-time multimodal AI
p
how would we prewarm the multiple agents in livekit….For example our bot has three agents: Greeter, FAQ, Info Collection; Can you help me in prewarming these agents
t
Hi there! To help you prewarm multiple agents like Greeter, FAQ, and Info Collection in LiveKit, you can use the
prewarm
function to load shared resources or reusable components right when the worker starts up. This way, common dependencies are initialized just once and can be reused across agents, which really helps reduce the initialization time during handoffs. Here’s a simple example in JavaScript to guide you:
Copy code
export default defineAgent({
  prewarm: async (proc) => {
    proc.userData.sharedResource = await loadSharedResource();
  },
  entry: async (ctx) => {
    const sharedResource = ctx.proc.userData.sharedResource;
    // Use sharedResource in your agent logic
  }
});
With this approach, you can preload things like language models, databases, or any other shared tools that your Greeter, FAQ, and Info Collection agents might need. Each agent then accesses these preloaded resources through
ctx.proc.userData
, making everything smoother and faster. If you'd like, I’m here to help you tailor this to your specific setup or if you’re working with a different programming language. Just let me know!
p
We are using python
t
In Python, you can gently warm up multiple agents in LiveKit by initializing shared resources at the worker level, making them easily accessible to all agents. A handy way to do this is by using the
JobProcess.userdata
attribute to store preloaded components that your agents can reuse. Here’s a simple example to guide you:
Copy code
from livekit import define_agent

def prewarm_resources(proc):
    # Preload shared resources here
    proc.userdata.shared_resource = load_shared_resource()

define_agent(
    prewarm=prewarm_resources,
    entry=lambda ctx: run_agent(ctx)
)

def run_agent(ctx):
    # Access prewarmed resources
    shared_resource = ctx.proc.userdata.shared_resource
    # Use the shared resource in your agent logic
With this approach, you can preload important components like language models, databases, or other tools that all your agents (Greeter, FAQ, and Info Collection) might need. Each agent can then easily tap into these preloaded resources through
ctx.proc.userdata
. If you have any questions or need a hand tailoring this to your specific setup, please feel free to ask—I'm here to help!
p
Can we share STT, LLM, and TTS across agents too? Can you give me an example of doing that in code?
t
Absolutely, you can share STT, LLM, and TTS components across agents in LiveKit. Here’s a friendly example in Python to help you get started:
Copy code
from livekit.agents import stt, llm, tts
from livekit.plugins import deepgram, openai, cartesia, silero

def prewarm_resources(proc):
    # Preload shared resources
    proc.userdata.stt = deepgram.STT(model="nova-3", language="multi")
    proc.userdata.llm = openai.LLM(model="gpt-4o-mini")
    proc.userdata.tts = cartesia.TTS(voice="39b376fc-488e-4d0c-8b37-e00b72059fdd")
    proc.userdata.vad = silero.VAD.load()

define_agent(
    prewarm=prewarm_resources,
    entry=lambda ctx: run_agent(ctx)
)

def run_agent(ctx):
    # Access prewarmed resources
    stt_instance = ctx.proc.userdata.stt
    llm_instance = ctx.proc.userdata.llm
    tts_instance = ctx.proc.userdata.tts
    vad_instance = ctx.proc.userdata.vad

    # Use these shared resources in your agent logic
With this approach, the STT, LLM, and TTS components are set up just once during the worker startup and saved in
proc.userdata
. This way, each agent can easily tap into these ready-to-go resources, helping everything run smoothly and quickly during agent handoffs. If you have any questions or would like me to walk you through more examples, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | docs/index.yaml | Pipeline nodes and hooks | LiveKit Docs
p
Can we share turn_detector = EnglishModel() across different agents too without having to intialize it again. if yes. show me an examples..
t
Absolutely, you can share the
turn_detector
(like
EnglishModel()
) across different agents in LiveKit by preloading it when the worker starts up and storing it in
proc.userdata
. Here’s a simple example to guide you through it:
Copy code
from livekit.agents import define_agent
from some_library import EnglishModel

def prewarm_resources(proc):
    # Preload the turn detector model
    proc.userdata.turn_detector = EnglishModel()

define_agent(
    prewarm=prewarm_resources,
    entry=lambda ctx: run_agent(ctx)
)

def run_agent(ctx):
    # Access the preloaded turn detector
    turn_detector = ctx.proc.userdata.turn_detector

    # Use the turn detector in your agent logic
    result = turn_detector.detect_turn("Sample input")
    print(result)
With this approach, the
EnglishModel
is set up just once during the worker startup and saved in
proc.userdata
. This way, all agents can tap into this shared instance, which helps avoid reinitializing it multiple times and boosts performance. If you’d like, I’m here to help with any more details or examples you might need—just let me know!
p
I am confused. We are settimg STT, TTS, LLM in the entrypoint function. Is that for all agents or just the main agent? Could you tell me how I would share STT, TTS, LLM, VAD, and turn detector across all my agents and what to change in entrypoint and if I need to add any other functions…
t
I’m glad you reached out! When you set STT, TTS, LLM, and other components in the entrypoint function, they get initialized specifically for the agent being created at that moment. To make things smoother and share these components across all agents, a great approach is to preload them during the worker startup using the
prewarm
function and store them in
proc.userdata
. This way, every agent can easily access the same shared instances without needing to reinitialize them each time. Here’s a friendly example of how you can adjust your setup:
Copy code
from livekit.agents import define_agent
from some_library import EnglishModel
from livekit.plugins import deepgram, openai, cartesia, silero

def prewarm_resources(proc):
    # Preload shared resources
    proc.userdata.stt = deepgram.STT(model="nova-3", language="multi")
    proc.userdata.llm = openai.LLM(model="gpt-4o-mini")
    proc.userdata.tts = cartesia.TTS(voice="39b376fc-488e-4d0c-8b37-e00b72059fdd")
    proc.userdata.vad = silero.VAD.load()
    proc.userdata.turn_detector = EnglishModel()

define_agent(
    prewarm=prewarm_resources,
    entry=lambda ctx: run_agent(ctx)
)

def run_agent(ctx):
    # Access preloaded resources
    stt_instance = ctx.proc.userdata.stt
    llm_instance = ctx.proc.userdata.llm
    tts_instance = ctx.proc.userdata.tts
    vad_instance = ctx.proc.userdata.vad
    turn_detector = ctx.proc.userdata.turn_detector

    # Use these shared resources in your agent logic
    result = turn_detector.detect_turn("Sample input")
    print(result)
To break it down: • The
prewarm_resources
function takes care of initializing all shared components just once during the worker startup. • The
entry
function then accesses these preloaded components through
ctx.proc.userdata
and uses them seamlessly in your agent’s logic. This setup helps all agents share the same instances of STT, TTS, LLM, VAD, and the turn detector, which cuts down on repeated initialization and boosts performance. If anything feels unclear or you want to dive deeper, please don’t hesitate to ask—I’m here to help!
p
So if I only have these in the entrypoint and not the way you have mentioned, then my agents wont be sharing the resources?
t
You're absolutely right! When you initialize STT, TTS, LLM, VAD, and other components directly in the entrypoint function without a shared approach like
prewarm
, each agent ends up creating its own separate instance of these resources. This can cause higher initialization overhead and use more resources than necessary. To make sure all agents share the same resources smoothly, it's best to preload these components during worker startup using the
prewarm
function and save them in
proc.userdata
. This way, every agent can tap into the same pre-initialized instances, which really helps with performance and keeps things consistent. If you’d like, I’m here to help you with this or clarify anything else. Just let me know!
p
Let me share the code I have in entry point. I am using prewarm… In entrypoint we have vad = ctx.proc.userdata.get(“vad”) tts_engine = await ensure_tts( ctx, provider=provider, # e.g. “eleven_turbo_v2", “google-tts”, etc. selected_item=voices, # the dict from frontend tts_instructions=ttsinstructions, voice_settings=settings, ) Then we have this ensure_tts function async def ensure_tts(ctx, provider: str, selected_item: dict, tts_instructions: str | None, voice_settings=None): “”" provider: ‘openai/gpt-4o-mini-tts’, ‘deepgram/aura2’, ‘google-tts’, ‘azure’, ‘eleven_turbo_v2’, ‘eleven_flash_v2’, ‘mistv2’, ‘arcana’, ‘elevenlabs’ (fallback) selected_item: voice config from frontend (voice_name, voice_id, model, bot_name, speed, etc.) “”" if “engine_cache” not in ctx.proc.userdata: ctx.proc.userdata[“engine_cache”] = {“tts”: {}, “stt”: {}, “llm”: {}, “realtime”: {}} if “engine_locks” not in ctx.proc.userdata: ctx.proc.userdata[“engine_locks”] = defaultdict(asyncio.Lock) provider = (provider or “”).lower() cache = ctx.proc.userdata[“engine_cache”][“tts”] locks = ctx.proc.userdata[“engine_locks”] key = _cache_key( “tts”, provider, selected_item.get(“voice_id”), selected_item.get(“voice_name”), selected_item.get(“model”), selected_item.get(“bot_name”), selected_item.get(“speed”), ) if key in cache: return cache[key] async with locks[key]: if key in cache: return cache[key] if provider == “deepgram/aura2”: tts = deepgram.TTS(model=selected_item[“voice_name”]) elif provider == “google-tts”: voice_name = selected_item[“voice_name”] language_tag = “-”.join(voice_name.split(“-”, 2)[:2]) tts = google.TTS(voice_name=voice_name, language=language_tag) elif provider == “azure”: tts = azure.TTS(voice=selected_item[“voice_name”]) elif provider in {“mistv2”, “arcana”}: speaker = selected_item[“bot_name”] model = selected_item[“model”] if provider == “mistv2”: tts = rime.TTS( model=model, speaker=speaker, speed_alpha=0.9, reduce_latency=True, phonemize_between_brackets=True, ) else: # arcana tts = rime.TTS( model=model, speaker=speaker, repetition_penalty=1.13, temperature=0.5, top_p=1.0, ) elif provider in {“eleven_turbo_v2", “eleven_flash_v2”, “elevenlabs”}: from livekit.plugins.elevenlabs import TTS as ElTTS tts = ElTTS( voice_id=selected_item.get(“voice_id”), model=selected_item.get(“model”), voice_settings=voice_settings, # your dataclass or dict works enable_ssml_parsing=True if provider != “elevenlabs” else False, ) elif provider == “openai/gpt-4o-mini-tts”: tts = lk_openai.TTS( voice=selected_item[“voice_name”], speed=selected_item.get(“speed”), instructions=tts_instructions, ) else: # default → OpenAI TTS tts = lk_openai.TTS( voice=selected_item[“voice_name”], speed=selected_item.get(“speed”), instructions=tts_instructions, ) if hasattr(tts, “prewarm”): try: tts.prewarm() except Exception: pass cache[key] = tts return tts
t
Thank you so much for sharing your code! It looks like you’re already doing a great job by using
ctx.proc.userdata
to cache and share resources like TTS across agents. This is a smart way to make sure resources are reused instead of being reinitialized for every agent, which can save a lot of time and effort. To help you make sure all components (STT, TTS, LLM, VAD, and turn detector) are shared smoothly across agents, here’s a friendly step-by-step guide you can follow: 1. In your
prewarm
function, go ahead and initialize all the shared resources (like STT, LLM, VAD, and turn detector) and store them in
ctx.proc.userdata
. 2. Then, in the
entry
function, you can easily retrieve these preloaded resources from
ctx.proc.userdata
and use them in your agent’s logic. 3. For components such as TTS, where instances are created dynamically based on parameters, just make sure to consistently use the caching mechanism you have in your
ensure_tts
function. This helps avoid unnecessary reinitializations. Here’s a little example to show how you might extend your current setup to include all components:
Copy code
def prewarm_resources(proc):
    proc.userdata.stt = deepgram.STT(model="nova-3", language="multi")
    proc.userdata.llm = openai.LLM(model="gpt-4o-mini")
    proc.userdata.vad = silero.VAD.load()
    proc.userdata.turn_detector = EnglishModel()
    proc.userdata.engine_cache = {"tts": {}, "stt": {}, "llm": {}, "realtime": {}}
    proc.userdata.engine_locks = defaultdict(asyncio.Lock)

def run_agent(ctx):
    vad = ctx.proc.userdata.get("vad")
    turn_detector = ctx.proc.userdata.get("turn_detector")

    # Example: Using ensure_tts to retrieve or create a TTS instance
    tts_engine = await ensure_tts(
        ctx,
        provider="eleven_turbo_v2",
        selected_item=voices,  # the dict from frontend
        tts_instructions=tts_instructions,
        voice_settings=settings,
    )

    # Use the shared resources in your agent logic
    result = turn_detector.detect_turn("Sample input")
    print(result)
By preloading all your shared components in
prewarm_resources
and leveraging caching mechanisms like the one in your
ensure_tts
function, you’ll be set up for efficient resource sharing across all agents. If you have any questions or want to dive deeper into any part of this, please don’t hesitate to ask—I’m here to help!
p
Can turn detector initialization take extra latency..
t
I completely understand how extra latency during the initialization of the turn detector can be a bit frustrating, especially when it involves loading large models or complex setups. A great way to ease this is by preloading the turn detector during the worker startup using the
prewarm
function. This way, it gets initialized just once and is shared across all agents, so you won’t have to worry about reinitializing it every time. If you’re still seeing noticeable latency during initialization, it might help to profile the process to pinpoint any specific bottlenecks and work on optimizing them. Please feel free to reach out if you’d like a hand with this or need any further guidance—I’m here to help!
p
So we are getting the models dynamically from front_end. So initially in prewarm, the llm, stt, and tts entries are blank. So now my concern is if I don’t have these models defined in pre-warm, then these won’t be initialized until the model runs? which defeats the purpose of pre-warm, no? Here is my pre-warm
Copy code
def prewarm_fnc(proc: JobProcess):
    """
    Preload cheap+universal assets and setup caches for engines to be reused.
    Runs once for each idle worker process.
    """
    # Universal VAD (cheap to load and usable for most sessions)
    # If you later want provider-specific VADs, make this a dict keyed by name.
    proc.userdata["vad"] = silero.VAD.load()
    # proc.userdata["turn_detection"] = EnglishModel()   
    # Async-safe caches (reused across jobs in this process)
    proc.userdata["engine_cache"] = {
        "llm": {},        # key -> LLM instance
        "stt": {},        # key -> STT instance
        "tts": {},        # key -> TTS instance
        "realtime": {},   # key -> RealtimeModel instance
    }
    
    # Per-key locks to avoid double-initialization under load
    proc.userdata["engine_locks"] = defaultdict(asyncio.Lock)
t
You’re absolutely right that if the models (LLM, STT, TTS) aren’t initialized in the
prewarm
function, they’ll only be created dynamically when first accessed during runtime. This means the initialization delay will still happen during that first use, which doesn’t quite take full advantage of prewarming. To help with this, while still keeping the flexibility of dynamic model selection from the frontend, a good approach is to prewarm default or commonly used models in the
prewarm
function. These preloaded models can serve as handy placeholders until the specific models requested by the frontend are ready. Here’s a way you could adjust your `prewarm_fnc`:
Copy code
def prewarm_fnc(proc: JobProcess):
    """
    Preload cheap+universal assets and setup caches for engines to be reused.
    Runs once for each idle worker process.
    """
    # Preload universal VAD
    proc.userdata["vad"] = silero.VAD.load()

    # Preload default models for LLM, STT, and TTS
    proc.userdata["engine_cache"] = {
        "llm": {"default": openai.LLM(model="gpt-4o-mini")},
        "stt": {"default": deepgram.STT(model="nova-3", language="multi")},
        "tts": {"default": cartesia.TTS(voice="default-voice-id")},
        "realtime": {},
    }

    # Per-key locks to avoid double-initialization under load
    proc.userdata["engine_locks"] = defaultdict(asyncio.Lock)
Here’s what’s happening in this setup: • We preload default models during the worker startup and keep them in the
engine_cache
. • When the frontend requests a specific model, the system can either use the preloaded default or initialize the requested one on the fly. • This way, some models are ready to go right away, which helps reduce latency for the most common cases. Please feel free to reach out if you’d like me to walk you through this in more detail or help with the implementation. I’m here to support you!
p
In my current implementation, the initial agent definitely doesnt take advantage of pre-warm, but what about the hand off agents and other agents…Do they get advantage or no?
t
I totally understand how this can feel a bit tricky! In your current setup, if the models (LLM, STT, TTS) are dynamically initialized during runtime and not preloaded in the
prewarm
function, the initial agent won’t get the benefits of prewarming. But the good news is that subsequent agents, including handoff agents, can still take advantage of the cached models if they’re stored in
proc.userdata["engine_cache"]
after the first initialization. Here’s a simple breakdown: • Initial Agent: If the models aren’t preloaded, they’ll be initialized on the spot during first use, which might cause some delay. • Handoff and Other Agents: Once the models are initialized and cached in
proc.userdata["engine_cache"]
, any following agents can reuse these cached versions, skipping reinitialization and indirectly benefiting from prewarming. If you want all agents, including the very first one, to enjoy the perks of prewarming, a great approach is to preload default or frequently used models right in the
prewarm
function. That way, the initial agent can hit the ground running with preloaded models, and any models requested dynamically can still be cached for others to reuse. Please feel free to reach out if you’d like me to walk you through this in more detail or help optimize your setup—I’m here to help!
p
Is there no way to assign the front-end model value dynamically to pre_warm?
t
I totally understand where you’re coming from! The
prewarm
function actually runs during worker startup, which happens before any specific session or frontend input is available. Because of this, it can’t directly use values that come dynamically from the frontend at runtime. But don’t worry, there’s a great way to handle this with a hybrid approach: 1. Preload Default Models: You can have the
prewarm
function load some default or commonly used models right away, so you have resources ready to go immediately. 2. Dynamic Initialization with Caching: Then, when the frontend requests a specific model, you can initialize it on the fly if it’s not already cached. After that, store it in
proc.userdata["engine_cache"]
so future requests can reuse it easily. This way, you get the best of both worlds: • Your system starts with some resources preloaded and ready. • Frontend-specific models are brought in dynamically and cached for smoother future use. If you’d like, I’m here to help you set this up or clarify any part of it—just let me know!
p
I want you to explain to me step wise…how the stt, llm, tts, vad are assigned for multi agent. We are assignig them once in entrypoint…but at hand off…..i believe the entry point is not called again…how does the new agent get its models
t
Let me walk you through a clear, step-by-step explanation of how STT, LLM, TTS, and VAD are assigned and reused in a multi-agent setup. I hope this helps make things a bit easier to understand! 1. Prewarm Phase: When the worker starts up, the
prewarm
function runs. This is a great time to preload shared resources like VAD or default models for STT, LLM, and TTS, which get stored in
proc.userdata
. These resources are then ready and available for all agents within the same worker process. 2. Initial Agent Creation (Entrypoint): When the very first agent is created, the
entry
function is called. Here, the agent pulls the preloaded resources (like VAD) from
ctx.proc.userdata
. If a specific model (such as STT, LLM, or TTS) isn’t preloaded yet, it gets dynamically initialized and saved in
proc.userdata["engine_cache"]
for future use. This helps keep things running smoothly! 3. Agent Handoff: When a handoff happens, the current agent creates a new agent instance. The new agent doesn’t call the
entry
function again but instead inherits the session context and can access those shared resources (like VAD and cached models) from
proc.userdata
. If the new agent needs a model that isn’t cached yet, it will initialize it on the spot and add it to the cache. 4. Subsequent Agents: Any agents that come after in the same worker process can simply reuse the preloaded or cached resources from
proc.userdata
. This smart reuse avoids unnecessary initialization and keeps everything efficient across agents. So, to sum it up: the
entry
function runs only when an agent is first created. After that, during handoffs, new agents tap into the shared resources from
proc.userdata
, which helps maintain continuity and efficiency. If you’d like, I’m more than happy to provide further clarifications or examples—just let me know!
p
This makes sense. I want to understand further where in the code is this hand off thing happening where the new agent gets assigned the shared resources. I want to ensure that the new agent is not initializing anything though the shared resources are available and pre warmed.
t
In a multi-agent setup, the handoff process usually involves creating a new agent instance and smoothly transferring the session context. The new agent then accesses shared resources from
proc.userdata
, which were thoughtfully preloaded during the
prewarm
phase. Let me walk you through how this works in detail: 1. Handoff Trigger: Typically, the handoff is triggered by a function tool or a specific event in the current agent. For example:
Copy code
@function_tool
async def switch_to_new_agent(self):
    return NewAgent()
1. New Agent Initialization: When the new agent is created, it inherits the session context from the previous agent. This includes access to
ctx.proc.userdata
, where the shared resources (like STT, LLM, TTS, VAD) are stored. 2. Accessing Shared Resources: The new agent retrieves these preloaded resources from
ctx.proc.userdata
. For example:
Copy code
class NewAgent(Agent):
    async def on_enter(self):
        stt = self.session.proc.userdata["stt"]
        llm = self.session.proc.userdata["llm"]
        tts = self.session.proc.userdata["tts"]
        vad = self.session.proc.userdata["vad"]
        # Use these resources without reinitializing them
1. Ensuring No Reinitialization: To make sure the new agent isn’t reinitializing resources, you might consider adding some logging or debugging statements in the
prewarm
function and the agent’s
on_enter
method. This can really help confirm that the resources are being reused from
proc.userdata
and not created anew. If you’d like, I’m here to help you set up that logging or provide any further guidance to make sure the shared resources are being used just right during handoff. Just let me know—I’m happy to assist!
p
I am sharing my base class on_enter function. I don’t see it using the shared resources: import logging from livekit.agents.voice import Agent, RunContext from shared.models import UserData logger = logging.getLogger(name) RunContext_T = RunContext[UserData] greeting = False class BaseAgent(Agent): async def on_enter(self) -> None: logger.info(f”session object: {self.session}“) logger.info(f”session type: {type(self.session)}“) logger.info(“==== SESSION INITIALIZED ====“) logger.info(f”LLM: -> {self.session.llm}“) logger.info(f”STT: -> {self.session.stt}“) logger.info(f”TTS: -> {self.session.tts}“) agent_name = self.class.name logger.info(f”entering task {agent_name}“) userdata: UserData = self.session.userdata chat_ctx = self.chat_ctx.copy() # Bring over some turns from the previous agent for continuity if isinstance(userdata.prev_agent, Agent): truncated = userdata.prev_agent.chat_ctx.copy( exclude_instructions=True, exclude_function_call=False ) existing_ids = {item.id for item in chat_ctx.items} items_copy = [it for it in truncated.items if it.id not in existing_ids] chat_ctx.items.extend(items_copy) # Inject current user state into system context chat_ctx.add_message( role=“system”, content=f”You are {agent_name}. Current user data:\n{userdata.summarize()}“, ) logger.info(f”Sajjad You are {agent_name}. Current user data:\n{userdata.summarize()}“) await self.update_chat_ctx(chat_ctx) self.session.generate_reply(tool_choice=“auto”) async def _transfer_to(self, name: str, context: RunContext_T): userdata = context.userdata current = context.session.current_agent next_agent = userdata.agents[name] userdata.prev_agent = current return next_agent So does that mean it re intializes them? but how does it know which ones to use if it re-initializes…..
t
Thank you so much for sharing your
BaseAgent
class! I took a close look at the code, and it seems that the
on_enter
function doesn’t explicitly initialize or reinitialize the STT, LLM, TTS, or VAD components. Instead, it accesses these components through
self.session
, which is part of the session context that’s passed to the agent. Here’s a little breakdown of how it all works: 1. Session Context: The
self.session
object holds references to the STT, LLM, TTS, and other components. These references are usually set up when the session is first created and then reused during agent handoffs. 2. Shared Resources: If the STT, LLM, TTS, and VAD were preloaded and cached in
proc.userdata
during the
prewarm
phase, the session will use those preloaded instances. This helps make sure the components aren’t reinitialized during handoffs. 3. Handoff Process: When a handoff happens, the
_transfer_to
method assigns the next agent (for example,
next_agent = userdata.agents[name]
). The new agent then inherits the session context, including those preloaded or cached components. If you want to double-check that the shared resources are being reused and not reinitialized, a helpful approach is to add some logging in the
prewarm
function and the
on_enter
method. This way, you can track exactly when and how the components are accessed. For example:
Copy code
# In prewarm function
logger.info("Preloading STT, LLM, TTS, and VAD")

# In on_enter method
logger.info(f"Using STT: {self.session.stt}")
logger.info(f"Using LLM: {self.session.llm}")
logger.info(f"Using TTS: {self.session.tts}")
To sum it up, the
on_enter
function relies on the session context and doesn’t reinitialize the components. Those references should already point to the preloaded or cached resources. Please feel free to reach out if you’d like me to walk you through this further or help verify the behavior — I’m here to support you!
p
but to be on the safe side shouldnt we just add the assignment in on_enter…how would we do it
t
To make sure the correct shared resources (STT, LLM, TTS, VAD) are always assigned to your agent, a helpful approach is to explicitly assign them in the
on_enter
method by retrieving them from
proc.userdata
. This way, you can be confident that the agent is using the preloaded or cached resources, even if the session context feels a bit unclear. Here’s a friendly example of how you can adjust the
on_enter
method to explicitly assign these shared resources:
Copy code
class BaseAgent(Agent):

    async def on_enter(self) -> None:
        # Retrieve shared resources from proc.userdata
        self.session.stt = self.session.proc.userdata.get("stt")
        self.session.llm = self.session.proc.userdata.get("llm")
        self.session.tts = self.session.proc.userdata.get("tts")
        self.session.vad = self.session.proc.userdata.get("vad")

        # Log the assigned resources for verification
        logger.info(f"Assigned STT: {self.session.stt}")
        logger.info(f"Assigned LLM: {self.session.llm}")
        logger.info(f"Assigned TTS: {self.session.tts}")
        logger.info(f"Assigned VAD: {self.session.vad}")

        # Continue with the rest of the on_enter logic
        agent_name = self.__class__.__name__
        logger.info(f"Entering task {agent_name}")

        userdata: UserData = self.session.userdata
        chat_ctx = self.chat_ctx.copy()

        # Bring over some turns from the previous agent for continuity
        if isinstance(userdata.prev_agent, Agent):
            truncated = userdata.prev_agent.chat_ctx.copy(
                exclude_instructions=True, exclude_function_call=False
            )
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [it for it in truncated.items if it.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        # Inject current user state into system context
        chat_ctx.add_message(
            role="system",
            content=f"You are {agent_name}. Current user data:\n{userdata.summarize()}",
        )
        logger.info(f"You are {agent_name}. Current user data:\n{userdata.summarize()}")

        await self.update_chat_ctx(chat_ctx)
        self.session.generate_reply(tool_choice="auto")
By taking this step to explicitly assign the shared resources in
on_enter
, you’re helping your agent consistently use the right preloaded or cached instances. If you have any questions or want to explore this further, I’m here to help!
p
it gave an error that object has no attribute .proc do we need to import any thing
t
It looks like the error is happening because
self.session.proc
isn’t directly accessible in your current setup. No worries though! You can actually access the shared resources through
self.session.userdata
, which is the right way to get session-specific data in LiveKit. Here’s a revised version of the
on_enter
method that should help you out:
Copy code
class BaseAgent(Agent):

    async def on_enter(self) -> None:
        # Retrieve shared resources from session.userdata
        self.session.stt = self.session.userdata.get("stt")
        self.session.llm = self.session.userdata.get("llm")
        self.session.tts = self.session.userdata.get("tts")
        self.session.vad = self.session.userdata.get("vad")

        # Log the assigned resources for verification
        logger.info(f"Assigned STT: {self.session.stt}")
        logger.info(f"Assigned LLM: {self.session.llm}")
        logger.info(f"Assigned TTS: {self.session.tts}")
        logger.info(f"Assigned VAD: {self.session.vad}")

        # Continue with the rest of the on_enter logic
        agent_name = self.__class__.__name__
        logger.info(f"Entering task {agent_name}")

        userdata: UserData = self.session.userdata
        chat_ctx = self.chat_ctx.copy()

        # Bring over some turns from the previous agent for continuity
        if isinstance(userdata.prev_agent, Agent):
            truncated = userdata.prev_agent.chat_ctx.copy(
                exclude_instructions=True, exclude_function_call=False
            )
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [it for it in truncated.items if it.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        # Inject current user state into system context
        chat_ctx.add_message(
            role="system",
            content=f"You are {agent_name}. Current user data:\n{userdata.summarize()}",
        )
        logger.info(f"You are {agent_name}. Current user data:\n{userdata.summarize()}")

        await self.update_chat_ctx(chat_ctx)
        self.session.generate_reply(tool_choice="auto")
By retrieving the shared resources from
self.session.userdata
, this should clear up the error you’re seeing. If anything else comes up or you’d like some more help, just let me know—I’m here for you!
p
It now gives the error: Oct 07 132946 ip-172-31-8-141 python3[234250]: File “/home/ubuntu/voice-ai-multiagent-backend/agents/base.py”, line 24, in on_enter Oct 07 132946 ip-172-31-8-141 python3[234250]: self.session.stt = self.session.userdata.get(“stt”) Oct 07 132946 ip-172-31-8-141 python3[234250]: ^^^^^^^^^^^^^^^^^^^^^^^^^ Oct 07 132946 ip-172-31-8-141 python3[234250]: AttributeError: ‘UserData’ object has no attribute ‘get’ {“pid”: 234407, “job_id”: “AJ_RSfVH5rzKpHU”} self.session.stt = self.session.userdata.get(“stt”)
t
It looks like the error is happening because
self.session.userdata
is an object (probably a custom class) and doesn’t have a
get
method like a dictionary does. To fix this, you’ll want to access the attributes of
self.session.userdata
directly, assuming those values are stored as attributes rather than inside a dictionary. Here’s an updated version of the
on_enter
method that should help:
Copy code
class BaseAgent(Agent):

    async def on_enter(self) -> None:
        # Retrieve shared resources directly from userdata attributes
        self.session.stt = self.session.userdata.stt
        self.session.llm = self.session.userdata.llm
        self.session.tts = self.session.userdata.tts
        self.session.vad = self.session.userdata.vad

        # Log the assigned resources for verification
        logger.info(f"Assigned STT: {self.session.stt}")
        logger.info(f"Assigned LLM: {self.session.llm}")
        logger.info(f"Assigned TTS: {self.session.tts}")
        logger.info(f"Assigned VAD: {self.session.vad}")

        # Continue with the rest of the on_enter logic
        agent_name = self.__class__.__name__
        logger.info(f"Entering task {agent_name}")

        userdata: UserData = self.session.userdata
        chat_ctx = self.chat_ctx.copy()

        # Bring over some turns from the previous agent for continuity
        if isinstance(userdata.prev_agent, Agent):
            truncated = userdata.prev_agent.chat_ctx.copy(
                exclude_instructions=True, exclude_function_call=False
            )
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [it for it in truncated.items if it.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        # Inject current user state into system context
        chat_ctx.add_message(
            role="system",
            content=f"You are {agent_name}. Current user data:\n{userdata.summarize()}",
        )
        logger.info(f"You are {agent_name}. Current user data:\n{userdata.summarize()}")

        await self.update_chat_ctx(chat_ctx)
        self.session.generate_reply(tool_choice="auto")
In this approach, we’re directly accessing the shared resources as attributes of
self.session.userdata
. Just make sure your
UserData
class has these attributes (like
stt
,
llm
,
tts
, and
vad
) properly set up, whether during initialization or somewhere else in your code. If anything is unclear or you want me to walk you through any part of this, please don’t hesitate to ask. I’m here to help!