I want to make my Agent State aware, so i have a s...
# ask-ai
w
I want to make my Agent State aware, so i have a state(e.g. greeting_completed, identity_asked, users_intent,...) and i want this to inject into the LLM, so that it knows the current state (like a Statemachine). How and where should i inject this state?
t
Thanks for reaching out, Lukas. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help your agent become state-aware and smoothly inject state (like
greeting_completed
,
identity_asked
) into the LLM, here are some friendly approaches you can try: 1. Use
userData
for State Management:
A great way is to store custom state flags in the
userData
object when you create an
AgentSession
. This state stays accessible throughout lifecycle hooks, tools, and the LLM context, making it easy to keep track.
session = AgentSession(userdata={"greeting_completed": False, "identity_asked": False})
2. Inject State into LLM via `llm_node()`: You can override the
llm_node()
method to dynamically add state info to the LLM’s system message before each inference. This helps the model stay aware of the current state.
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    state_info = f"Internal state: greeting_completed={self.session.userdata.get('greeting_completed', False)}"
    chat_ctx.items.insert(0, llm.ChatMessage(role="system", content=state_info))
    return await super().llm_node(chat_ctx, tools, model_settings)
3. Update State in Lifecycle Hooks: Hooks like
on_user_turn_completed()
are perfect for checking user input and updating your state flags on the fly.
Copy code
async def on_user_turn_completed(self, turn_ctx, new_message):
    if "name is" in new_message.content:
        self.session.userdata["greeting_completed"] = True
4. Modify Chat Context Directly: Another helpful option is to use
update_chat_ctx()
to replace or tweak the entire chat context with state-aware content, giving you full control. I hope these tips make it easier for you to track and inject state into the LLM context, so it behaves just like a state machine. If you’d like me to walk you through any part or provide more examples, just let me know—I’m here to help! Sources: Web and mobile frontends | LiveKit Docs | rpc/rpc_agent.py | tests/test_agent_session.py | examples/src/gemini_realtime_agent.ts | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki