purple-daybreak-98125
10/06/2025, 12:23 PMtall-airline-16756
10/06/2025, 12:23 PMtall-airline-16756
10/06/2025, 12:23 PMpurple-daybreak-98125
10/06/2025, 12:25 PMtall-airline-16756
10/06/2025, 12:25 PMprewarm 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 | DeepWikipurple-daybreak-98125
10/06/2025, 12:27 PMtall-airline-16756
10/06/2025, 12:28 PMprewarm 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 AIpurple-daybreak-98125
10/06/2025, 12:29 PMtall-airline-16756
10/06/2025, 12:30 PMprewarm 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:
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!purple-daybreak-98125
10/06/2025, 12:31 PMtall-airline-16756
10/06/2025, 12:31 PMJobProcess.userdata attribute to store preloaded components that your agents can reuse.
Here’s a simple example to guide you:
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!purple-daybreak-98125
10/06/2025, 2:39 PMtall-airline-16756
10/06/2025, 2:39 PMfrom 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 Docspurple-daybreak-98125
10/07/2025, 10:04 AMtall-airline-16756
10/07/2025, 10:04 AMturn_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:
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!purple-daybreak-98125
10/07/2025, 10:10 AMtall-airline-16756
10/07/2025, 10:11 AMprewarm 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:
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!purple-daybreak-98125
10/07/2025, 10:12 AMtall-airline-16756
10/07/2025, 10:13 AMprewarm, 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!purple-daybreak-98125
10/07/2025, 10:16 AMtall-airline-16756
10/07/2025, 10:17 AMctx.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:
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!purple-daybreak-98125
10/07/2025, 10:19 AMtall-airline-16756
10/07/2025, 10:19 AMprewarm 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!purple-daybreak-98125
10/07/2025, 10:28 AMdef 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)tall-airline-16756
10/07/2025, 10:28 AMprewarm 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`:
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!purple-daybreak-98125
10/07/2025, 10:30 AMtall-airline-16756
10/07/2025, 10:30 AMprewarm 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!purple-daybreak-98125
10/07/2025, 10:32 AMtall-airline-16756
10/07/2025, 10:32 AMprewarm 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!purple-daybreak-98125
10/07/2025, 1:05 PMtall-airline-16756
10/07/2025, 1:06 PMprewarm 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!purple-daybreak-98125
10/07/2025, 1:08 PMtall-airline-16756
10/07/2025, 1:09 PMproc.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:
@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:
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!purple-daybreak-98125
10/07/2025, 1:15 PMtall-airline-16756
10/07/2025, 1:16 PMBaseAgent 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:
# 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!purple-daybreak-98125
10/07/2025, 1:18 PMtall-airline-16756
10/07/2025, 1:18 PMon_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:
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!purple-daybreak-98125
10/07/2025, 1:24 PMtall-airline-16756
10/07/2025, 1:24 PMself.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:
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!purple-daybreak-98125
10/07/2025, 1:32 PMtall-airline-16756
10/07/2025, 1:32 PMself.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:
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!