can you explain when instructions should be sent f...
# ask-ai
c
can you explain when instructions should be sent for an agent? only at the start or also on generate_reply? i''ve got long instructions and it seems to send them everytime costing a lot of tokens
t
Thanks for reaching out, Nick. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm here to help you understand how to send instructions to an agent, both at the beginning and throughout your conversation, using the
generate_reply
method. Let me walk you through it: • Initial Instructions: These are set right at the start and shape the agent's overall behavior. They apply to every response unless you decide to update them. • Instructions via `generate_reply`: You can also add extra instructions during the conversation. For standard LLMs, these get added on top of the base instructions. For RealtimeModels, they’re handled separately and don’t mix with the base instructions. If you find your instructions are quite long and you’re sending them repeatedly, a handy tip is to use the
update_instructions
method. This lets you refresh the base instructions dynamically, so they’ll apply to all future interactions and help save on token usage. Sources: examples/other/text_only.py | basics/change_agent_instructions.py | Agent speech and audio | LiveKit Docs
c
i'm finding all the instructions and chat history are sent every time.
t
It looks like both instructions and chat history are being sent repeatedly in your setup. No worries—let’s walk through some key points and ways to optimize this together: • Instructions: These are managed separately from the chat history. You can use the
update_instructions
method to update instructions dynamically without having to resend them every single time. • Chat History: LiveKit uses differential updates, which means it only sends the changes in the chat context rather than the entire history. Double-check that this feature is set up correctly in your implementation. • Realtime Models: For realtime models, instructions are sent through session updates and don’t get mixed into the chat history. This helps cut down on unnecessary repetition. To make things run smoother, it’s a good idea to ensure your system is using differential updates and that instructions are being updated dynamically instead of just adding them over and over. If you’d like, I’m here to help with specific configurations or examples—just let me know! Sources: Sending text | LiveKit Docs | Agent Session & Activity Management | livekit/livekit_composite | DeepWiki | Agent speech and audio | LiveKit Docs | examples/voice_agents/realtime_load_chat_history.py | agents/src/voice/generation.ts
c
yes, please give realtime examples
t
I'm glad to share some helpful examples and strategies for optimizing instructions and chat history for realtime models in LiveKit. Let's walk through them together: 1. Loading Chat History To get your realtime agent started with the context of previous conversations, you can do the following:
Copy code
chat_history = [
    {"role": "assistant", "content": "Hello, I am a travel planner. How can I help you?"},
    {"role": "user", "content": "I want to go to Paris this summer."},
    {"role": "assistant", "content": "Paris is a beautiful city. How many days will you be staying?"},
    {"role": "user", "content": "I'll have four days. What are the main attractions I should see?"},
]

chat_ctx = llm.ChatContext.empty()
for item in chat_history:
    chat_ctx.add_message(role=item["role"], content=item["content"])

agent = Agent(
    instructions="You are a helpful travel planner.",
    llm=openai.realtime.RealtimeModel(voice="alloy", model="gpt-4o-mini-realtime-preview"),
    chat_ctx=chat_ctx,
)
2. Dynamic Instruction Updates If you ever need to update the instructions while your agent is running, here's a smooth way to do it:
Copy code
# Update instructions
await agent.update_instructions("New instructions...")

# Update chat context
new_chat_ctx = llm.ChatContext.empty()
new_chat_ctx.add_message(role="system", content="Updated context")
await agent.update_chat_ctx(new_chat_ctx)
3. Instruction Management Managing instruction messages efficiently within the chat context can make a big difference. Here's a neat function to help with that:
Copy code
def updateInstructions(options):
    chatCtx = options['chatCtx']
    instructions = options['instructions']
    idx = chatCtx.indexById(INSTRUCTIONS_MESSAGE_ID)
    if idx is not None:
        chatCtx.items[idx] = ChatMessage.create({
            id: INSTRUCTIONS_MESSAGE_ID,
            role: 'system',
            content: [instructions],
        })
    else:
        chatCtx.items.insert(0, ChatMessage.create({
            id: INSTRUCTIONS_MESSAGE_ID,
            role: 'system',
            content: [instructions],
        }))
4. Multi-Agent Systems When switching between different agents, it's important to keep the chat history intact. Here's how you can do that:
Copy code
@function_tool
def detected_childrens_book(self, context):
    childrens_editor = SpecialistEditorAgent(
        "children's books", 
        chat_ctx=context.session._chat_ctx  # Preserve chat history
    )
    return childrens_editor, "Let's switch to the children's book editor."
If you have any questions or would like me to walk you through any part of this in more detail, please don't hesitate to ask. I'm here to help! Sources: Agent Session & Activity Management | livekit/livekit_composite | DeepWiki | Realtime model plugins | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | plugins/openai/src/realtime/realtime_model.ts | main.py