after each user turn completed I want to add a sys...
# ask-ai
b
after each user turn completed I want to add a system message to chat - how to do it?
t
Thanks for reaching out, mateuszkasprowicz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to add a system message after each user turn — you can do that by using the on_user_turn_completed hook and adding a system message to the chat context, then persisting the context. Which language are you using (Python or TypeScript)? I can give the exact snippet you can drop into your Agent class and note where to persist the change. Sources: Pipeline nodes and hooks | LiveKit docs
b
Python
t
Below is a concise Python example you can drop into your Agent class to add a system message after each user turn and persist it.
Copy code
from livekit.agents import Agent, ChatContext, ChatMessage

class MyAgent(Agent):
    async def on_user_turn_completed(
        self,
        turn_ctx: ChatContext,
        new_message: ChatMessage,
    ) -> None:
        # Insert a system message after the user's turn
        turn_ctx.add_message(
            role="system",
            content="Always be polite and concise in your response."
        )

        # Persist the updated chat context so the system message is saved
        await self.update_chat_ctx(turn_ctx)
If you want the system message content to vary per user turn, replace the static string with logic that builds the message from
new_message
or other state. Would you like an example that customizes the system message dynamically?