What is context.session.agent_state and how does it work?

This question originally came up in our Slack community and the thread has been consolidated here for long-term reference.

What does context.session.agent_state do? I want to update my agent state, but my agent isn’t working as expected in my flow.

Agent state is read-only. It’s used to report to your application what the agent is currently doing, not to control the agent’s behavior.

You can listen for state changes:

def on_agent_state_changed(ev: AgentStateChangedEvent):
    if ev.new_state == "initializing":
        print("Agent is starting up")
    elif ev.new_state == "idle":
        print("Agent is ready but not processing")
    elif ev.new_state == "listening":
        print("Agent is listening for user input")
    elif ev.new_state == "thinking":
        print("Agent is processing user input and generating a response")
    elif ev.new_state == "speaking":
        print("Agent started speaking")

To control agent behavior, you should use the appropriate session methods rather than trying to set the state directly.