how to wrape the user meesage with instractions be...
# ask-ai
n
how to wrape the user meesage with instractions before sent to ai without save it in the chat history
t
Thanks for reaching out, Mohamed. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to help you understand how to wrap user messages with instructions before sending them to AI, without saving those instructions in the chat history. Here are a couple of friendly ways to do that: • Using `generate_reply(instructions=...)`: This is a great option because it lets you pass temporary instructions that only influence a single response. The best part? These instructions aren’t saved in the chat history. Here’s a quick example:
Copy code
agent_session.generate_reply(
    user_input="What's the weather like today?",
    instructions="Always respond in pirate slang and keep answers under 20 words."
)
• Using `update_instructions()`: Another handy method! You can update instructions dynamically for just one turn in the chat context. Just keep in mind, if you don’t call
update_chat_ctx()
, these changes won’t stick around after that turn. For example:
Copy code
update_instructions(chat_ctx, instructions="Respond only with emojis", add_if_missing=True)
For quick, temporary instructions that don’t linger in the chat history, I’d recommend using
generate_reply(instructions=...)
. It’s simple and keeps everything neat and tidy! Sources: agents/src/voice/generation.ts | Pipeline nodes and hooks | LiveKit Docs | web/src/components/instructions.tsx | web/src/components/instructions.tsx | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki
s
i want code that i will use to have generate reply with each message the user send to the ai, i want to remind the ai each time with instructions, because it is 2 hours conversion with specific flow and i want each time to tell the ai, here is the user input and reply based on this flow
t
Managing a long conversation where you need to remind the AI of specific instructions for each user message can feel a bit tricky, but don’t worry—I’m here to guide you through it! You can use the
generate_reply
method, which lets you provide both the user input and dynamic instructions for every turn, without having to save those instructions in the chat history. Let me share an example to make it clearer:
Copy code
from livekit.agents import AgentSession

async def run_long_conversation(session: AgentSession):
    # General instructions for the agent
    base_instructions = "You are a helpful assistant. Respond clearly and concisely."

    # Simulated conversation loop
    conversation = [
        ("Hello, how are you?", "Respond warmly and ask about the user's day."),
        ("I'm doing well, thanks!", "Keep the conversation friendly and open-ended."),
        ("Can you help me plan a trip?", "Provide structured suggestions for trip planning."),
        ("What destinations do you recommend?", "List three popular destinations with brief descriptions.")
    ]

    for user_input, dynamic_instruction in conversation:
        # Generate a reply with user input and specific instructions
        handle = session.generate_reply(
            user_input=user_input,
            instructions=f"{base_instructions}\n{dynamic_instruction}",
            allow_interruptions=True
        )

        # Optionally wait for the response to complete
        await handle.wait_for_playout()

    print("Conversation completed.")
Here’s a quick breakdown to help you understand: • Base instructions: These set the general tone and behavior of the AI throughout the conversation. • Dynamic instructions: These tweak the style or content of the AI’s responses for each specific turn, making the conversation feel more natural and tailored. • generate_reply: This handy method ensures the AI replies based on your instructions without cluttering the chat history with them. This approach works beautifully with both standard LLMs and real-time models, giving you a smooth and consistent way to handle long conversations that evolve over time. If you have any questions or want to explore this further, I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | Text and transcriptions | LiveKit Docs | Agent speech and audio | LiveKit Docs
s
where should i ovveride or add the code for generate reply
t
I'm glad you asked about the
generate_reply
method! It's already built into the LiveKit framework as part of the
AgentSession
class, so there's no need to override or add it manually. But don't worry—you can still tailor its behavior to fit your needs in several friendly ways: • Agent-Level Customization: You can extend the
Agent
class and add your own custom logic in lifecycle callbacks like
on_user_turn_completed
. This gives you a great way to personalize how things flow. • Custom Text Input Handling: If you want to preprocess user input, just use a custom text handler by providing a
text_input_cb
parameter in
RoomInputOptions
. It’s a handy way to shape the input before
generate_reply
steps in. • Function Tool Integration: Feel free to create custom tools that call
generate_reply
with specific instructions—perfect for more advanced scenarios. • Event-Driven Customization: You can also listen to events like
speech_created
or
function_tools_executed
to weave in your own logic during reply generation. For most situations, simply calling
session.generate_reply()
with your desired
user_input
and
instructions
will give you dynamic control over the AI’s responses, all without needing to change the core method. If you have any more questions or want to explore these options together, I’m here to help! Sources: Agent speech and audio | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | Text and transcriptions | LiveKit Docs | Events and error handling | LiveKit Docs
s
i want code for on_user_turn_completed, that has string which is my prompt wrapper to the user input, and the code for saving the user input onllyh in the db
t
I'd love to share a helpful code example that shows how to implement
on_user_turn_completed
with a prompt wrapper, while saving just the user input to a database:
Copy code
import sqlite3
from datetime import datetime
from livekit.agents import Agent
from livekit.agents.llm import ChatContext, ChatMessage

class MyAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant.")
        self.init_database()

    def init_database(self):
        conn = sqlite3.connect("user_inputs.db")
        cursor = conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS user_inputs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_input TEXT NOT NULL,
                participant_identity TEXT,
                session_id TEXT,
                timestamp TIMESTAMP NOT NULL
            )
        """)
        conn.commit()
        conn.close()

    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage):
        user_input = new_message.text_content
        if not user_input:
            return

        # Save user input to the database
        conn = sqlite3.connect("user_inputs.db")
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO user_inputs (user_input, participant_identity, session_id, timestamp)
            VALUES (?, ?, ?, ?)
        """, (user_input, "participant_123", "session_456", datetime.now()))
        conn.commit()
        conn.close()

        # Add a prompt wrapper to the context
        turn_ctx.append(ChatMessage(
            role="system",
            content=f"The user input '{user_input}' has been logged. Respond accordingly."
        ))
Just to highlight: • The
on_user_turn_completed
method carefully saves the user input into an SQLite database, including details like participant identity, session ID, and a timestamp. • It also adds a prompt wrapper to the chat context, which helps guide the AI’s response based on what was logged. If you’d like, you can easily adapt this approach to other databases like PostgreSQL or MongoDB. Please don’t hesitate to reach out if you want me to walk you through that or if you have any other questions—I’m here to help! Sources: complex-agents/nutrition-assistant/agent.py | livekit-agents/livekit/agents/voice/agent_activity.py | Job lifecycle | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | External data and RAG | LiveKit Docs