How can I access the live updates made to system i...
# ask-ai
a
How can I access the live updates made to system instruction in the
llm_node
, from the agent's chat_ctx property? i.e. while collecting metrics, so that it can be logged in the system for future debugging
t
Thanks for reaching out, Balakrishnan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you access live updates made to system instructions in the llm_node from the agent's chat_ctx property for logging metrics, you can set up real-time monitoring right within the llm_node method. Here’s a friendly example to guide you:
Copy code
async def llm_node(
    self,
    chat_ctx: llm.ChatContext,
    tools: list[llm.FunctionTool],
    model_settings: ModelSettings,
):
    # Monitor instruction changes in real-time
    instruction_msg = chat_ctx.get_by_id(INSTRUCTIONS_MESSAGE_ID)
    if instruction_msg:
        current_instructions = instruction_msg.content[0] if instruction_msg.content else ""
        
        # Log instruction update with timestamp
        logger.info(f"[REAL-TIME] Instructions accessed at {time.time()}: {current_instructions[:100]}...")
        
        # Store for metrics collection
        if not hasattr(self, '_last_instructions') or self._last_instructions != current_instructions:
            self._last_instructions = current_instructions
            self._instruction_update_count = getattr(self, '_instruction_update_count', 0) + 1
            logger.info(f"[INSTRUCTION UPDATE #{self._instruction_update_count}] New instructions detected")
    
    return Agent.default.llm_node(self, chat_ctx, tools, model_settings)
This setup lets you: • Access the current instructions easily using
chat_ctx.get_by_id(INSTRUCTIONS_MESSAGE_ID)
. • Log updates instantly with timestamps, which is great for debugging and tracking metrics. • Keep track of changes by comparing the latest instructions to the previous version. If you’d like to tweak this further or have any specific needs, please don’t hesitate to reach out—I’m here to help! Sources: examples/voice_agents/fast-preresponse.py | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | Logs, metrics, and telemetry | LiveKit Docs
f
What about this scenario? I insert whatever system messages i wnat in the llm_node function and do yield chunk. And in the handler function of the session.on("metrics_collected"), i want all these system messages listed. How can i acheive that
t
To list all system messages inserted in the llm_node function and access them in the session.on("metrics_collected") handler, you’ll want to work directly with the chat context, since the metrics_collected event doesn’t provide access to the message content. Here’s a friendly guide on how you can do this: 1. Access Chat Context Directly: You can take a look at the current chat context to gather all system messages:
Copy code
# Access the chat context from your agent or session
chat_ctx_items = agent.chat_ctx.items
system_messages = [item for item in chat_ctx_items if item.role == "system"]
for msg in system_messages:
    print(f"System message: {msg.text_content}")
2. Use the
conversation_item_added
Event
: This event triggers whenever a message (including system messages) is added to the conversation:
Copy code
@session.on("conversation_item_added")
def on_conversation_item_added(event: ConversationItemAddedEvent):
    if event.item.role == "system":
        print(f"System message added: {event.item.text_content}")
3. Combine with Metrics Collection: If you’d like to log system messages along with metrics, a handy approach is to store the system messages in a list during their insertion in llm_node, then access this list in the metrics_collected handler. Here’s an example:
Copy code
# In llm_node, store system messages
self.system_messages = []
self.system_messages.append("Your system message here")

# In metrics_collected handler
@session.on("metrics_collected")
def on_metrics_collected(event):
    for msg in self.system_messages:
        print(f"System message: {msg}")
I hope this helps! If anything isn’t clear or you’d like me to walk you through any part, just let me know—I’m here to help! Sources: Events and error handling | LiveKit Docs | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | Logs, metrics, and telemetry | LiveKit Docs | docs/index.yaml | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
a
when we system instruction like this we would only get the system_instruction we pass for inference, the realtime updates in system instruction was still not accessible
how do we handle it?
t
To help you handle real-time updates to system instructions in llm_node and make them easily accessible for logging or metrics, here are some friendly approaches you can try: 1. Dynamic Updates in llm_node: You can use the update_instructions utility to dynamically adjust the system instructions while your code is running:
Copy code
from livekit.agents.voice.generation import update_instructions

async def llm_node(self, chat_ctx: llm.ChatContext, tools: list[llm.FunctionTool], model_settings: ModelSettings):
    # Generate new instructions dynamically
    new_instructions = "Your updated instructions here"

    # Update instructions in the chat context
    update_instructions(chat_ctx, instructions=new_instructions, add_if_missing=True)

    # Log the update
    print(f"Updated instructions: {new_instructions[:100]}...")

    return Agent.default.llm_node(self, chat_ctx, tools, model_settings)
2. Centralized Updates with AgentActivity: For a more organized way, consider using the AgentActivity class to manage instruction updates smoothly:
Copy code
async def update_instructions(self, instructions: str):
    self._agent._instructions = instructions

    if self._rt_session is not None:
        await self._rt_session.update_instructions(instructions)
    else:
        update_instructions(self._agent._chat_ctx, instructions=instructions, add_if_missing=True)
3. Logging and Metrics Collection: It’s super helpful to keep track of instruction changes for debugging or metrics. Here’s a simple way to log those updates:
Copy code
def _log_instruction_update(self, old_instructions: str, new_instructions: str):
    update_data = {
        "timestamp": time.time(),
        "old_instructions": old_instructions,
        "new_instructions": new_instructions,
    }
    print(f"Instruction update: {update_data}")
4. Accessing Updates in Metrics Handlers: You can also store all updated instructions in a list during llm_node execution and then access them later in your metrics_collected handler:
Copy code
# In llm_node
self.instruction_updates = []
self.instruction_updates.append(new_instructions)

# In metrics_collected handler
@session.on("metrics_collected")
def on_metrics_collected(event):
    for update in self.instruction_updates:
        print(f"Instruction update: {update}")
I hope these ideas make it easier for you to manage and track your system instruction updates in real-time! If anything isn’t clear or you’d like to dive deeper into any part, just let me know—I’m here to help. Sources: examples/voice_agents/dynamic_tool_creation.py | agents/src/voice/agent_activity.ts | Logs, metrics, and telemetry | LiveKit Docs