m
hi
t
Thanks for reaching out, Rahib. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
m
1. "How do I dynamically update agent instructions during a conversation? When the agent transitions between different phases/contexts, I need to update the system prompt. Should I call session.update_instruction() or another method?" 2. "What's the best practice for multi-phase conversational agents where each phase has different system prompts? For example, I have a receptionist agent with phases like GREETING, MATCH_RESOLUTION, MANUAL_COLLECTION - should I update instructions on each phase transition?" 3. "In the LiveKit Agent class, when I call update_instruction(), does it immediatel
t
I'd love to understand your situation a bit better so I can help you more effectively! Could you share a bit about how you're hoping to dynamically update agent instructions? For example: • Are you aiming to update instructions in real-time during a live session? • Would you like some tips on structuring system prompts for different phases? • Are you running into any specific challenges or errors when using
update_instruction()
? Any extra details you can provide will really help me guide you in the right direction.
m
Yes, I need to update instructions in real-time during a live voice session. Here's my specific scenario: My Use Case: I have a multi-phase receptionist agent for an IT support company. The agent needs to progress through distinct phases during a single call: 1. GREETING - Answer call, identify caller via phone lookup 2. MATCH_RESOLUTION - Verify client identity if found in database 3. MANUAL_COLLECTION - Collect info if client not found 4. ISSUE_COLLECTION - Gather problem details 5. CALL_CONCLUSION - Confirm and wrap up My Current Setup: - I have a receptionist_phases.jinja2 template with conditional blocks: {% if phase == "greeting" %}...{% elif phase == "match_resolution" %}... - Each phase has different instructions, tone, and available tools - I set initial instructions in Agent.__init__() with the GREETING phase - I have a transition_to_phase(new_phase) method that updates my state The Problem: When I call self.transition_to_phase(Phase.MATCH_RESOLUTION) during the session, my state updates but the agent continues using the old GREETING instructions. The LLM doesn't know the phase changed. Specific Questions: 1. What's the correct method to update instructions? Is it self.session.update_instruction(new_instructions_string) or something else? 2. Where should I call it? Should I add it to my transition_to_phase() method right after updating state? 3. Timing concerns? Does the update take effect immediately for the next LLM call, or do I need to worry about in-flight requests? 4. Do I need to call it in on_user_turn_completed() before the LLM processes the response, or in transition_to_phase() which gets called from on_user_turn_completed()? My Current Code: def transition_to_phase(self, new_phase: str) -> None: state = self.get_state() old_phase = state.current_phase state.transition_to_phase(new_phase) logger.info(f"Phase transition: {old_phase} -> {new_phase}") # TODO: Update instructions here? I need to know the exact API call to dynamically update the system prompt mid-session.
t
Hey there! If you want to update your system prompts dynamically during a live session, the best way is to use the
session.update_instructions(new_instructions_string)
method. It kicks in right away for the next LLM call, so your following interactions will use the fresh instructions. Here’s a simple way to fit it into your workflow: • Just call
session.update_instructions()
inside your
transition_to_phase()
method, right after you update the phase state. This way, the instructions refresh as soon as the phase changes. • No need to stress about ongoing requests — the update will take effect for the very next LLM interaction. • You usually don’t have to call it in
on_user_turn_completed()
unless you have some special logic tied to processing user input. Here’s an example of what your updated
transition_to_phase
method might look like:
Copy code
def transition_to_phase(self, new_phase: str) -> None:
    state = self.get_state()
    old_phase = state.current_phase
    state.transition_to_phase(new_phase)

    logger.info(f"Phase transition: {old_phase} -> {new_phase}")

    # Update instructions dynamically
    new_instructions = self.generate_instructions_for_phase(new_phase)
    self.session.update_instructions(new_instructions)
By doing this, you’ll make sure your agent’s behavior stays perfectly in sync with the current phase of the conversation. If you have any questions or want to chat more about it, I’m here to help! Sources: plugins/google/src/beta/realtime/realtime_api.ts | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
m
do i need to await this ? I am getting this error /Users/reverse/PycharmProjects/cmetric/cmetric-voicekit/src/agent.py173 RuntimeWarning: coroutine 'Agent.update_instructions' was never awaited self.update_instructions(new_instructions)
t
It looks like the error you ran into happens because
session.update_instructions()
is an asynchronous method and needs to be awaited. If it’s not awaited, Python will give you a runtime warning about an unawaited coroutine. To help you fix this, you can update your code like this:
Copy code
async def transition_to_phase(self, new_phase: str) -> None:
    state = self.get_state()
    old_phase = state.current_phase
    state.transition_to_phase(new_phase)

    logger.info(f"Phase transition: {old_phase} -> {new_phase}")

    # Update instructions dynamically
    new_instructions = self.generate_instructions_for_phase(new_phase)
    await self.session.update_instructions(new_instructions)
By adding
await
, you make sure the instructions update completes properly before moving on. If you have any more questions or want me to walk you through this, just let me know — I’m here to help! Sources: docs/index.yaml | OpenAI TTS integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | plugins/openai/src/realtime/realtime_model.ts | Gemini Live API integration guide | LiveKit Docs
m
Why cant i see session.userdata in the langfuse tracing ?
t
I understand that the
session.userdata
attribute isn’t automatically included in Langfuse tracing because the telemetry system doesn’t expose custom session state like
userdata
in OpenTelemetry spans by default. But don’t worry, you can make it visible by explicitly including it during your tracer setup. Here are two friendly ways to do this: 1. Pass
userdata
via
metadata
in `setup_langfuse`:
Copy code
trace_provider = setup_langfuse(
    metadata={
        "user_name": session.userdata.user_name,  # assuming userdata has this field
        "age": session.userdata.age,
    }
)
2. Use a Custom
SpanProcessor
to Dynamically Add `userdata`:
Copy code
from opentelemetry.sdk.trace import SpanProcessor

class UserDataSpanProcessor(SpanProcessor):
    def __init__(self, session):
        self.session = session

    def on_start(self, span, parent_context):
        userdata = self.session.userdata
        if hasattr(userdata, "user_name"):
            span.set_attribute("user_name", userdata.user_name)
        if hasattr(userdata, "age"):
            span.set_attribute("age", userdata.age)

    def on_end(self, span):
        pass

# Apply the custom processor
trace_provider.add_span_processor(UserDataSpanProcessor(session))
Both of these methods will help you include
userdata
in your Langfuse traces smoothly. If you have any questions or need a hand with this, just let me know—I’m here to help! Sources: Workflows | LiveKit Docs | Docs::Agents | examples/voice_agents/README.md | Setting custom user_id and session_id in Langfuse traces | docs/index.yaml
m
can i do this
Copy code
# Start the session
    await session.start(
        agent=agent,
        room=ctx.room,
        room_input_options=room_input_options,
    )

    # Setup Langfuse tracing with metadata
    setup_langfuse(
        metadata={
            "room_name": ctx.room.name,
            "userdata": session.userdata,
            "company_config": "cloudmetrics",
        }
    )
? Affter session start?
t
Just a quick heads-up: the
setup_langfuse
function should be called before
session.start()
in LiveKit. This helps make sure your telemetry is set up correctly and that important session-level spans like "Session start" are captured in your tracing data. If you want to include
session.userdata
in the metadata, you can simply extract its values and pass them to
setup_langfuse
before starting the session. Here's a little example to guide you:
Copy code
async def entrypoint(ctx: JobContext):
    # Initialize custom userdata
    userdata = MyUserDataClass(first_name="Alice", user_id="12345")

    # Create session with userdata
    session = AgentSession(userdata=userdata)

    # Pass userdata fields into Langfuse metadata before starting session
    trace_provider = setup_langfuse(
        metadata={
            "user_id": userdata.user_id,
            "customer_name": userdata.first_name,
            "session_initiator": ctx.room.name
        }
    )

    await session.start(agent=MyAgent(), room=ctx.room)
This way, your
userdata
is nicely included in the tracing metadata, and your telemetry gets properly initialized. If anything’s unclear or you’d like me to walk you through it further, just let me know—I’m here to help! Sources: Workflows | LiveKit Docs | complex-agents/note-taking-assistant/agent.py | Setting custom user_id and session_id in Langfuse traces | livekit-agents/livekit/agents/voice/agent_session.py | Docs::Agents