This example shows how to create an agent that maintains state across interactions. It demonstrates a simple counter mechanism, but this pattern can be extended to more complex state management like maintaining conversation context, user preferences, or tracking multi-step processes. Example prompts to try:
  • “Increment the counter 3 times and tell me the final count”
  • “What’s our current count? Add 2 more to it”
  • “Let’s increment the counter 5 times, but tell me each step”
  • “Add 4 to our count and remind me where we started”
  • “Increase the counter twice and summarize our journey”

Code

agent_state.py
from agno.agent import Agent
from agno.models.openai import OpenAIChat


def increment_counter(session_state) -> str:
    """Increment the counter in session state."""
    # Initialize counter if it doesn't exist
    if "count" not in session_state:
        session_state["count"] = 0

    # Increment the counter
    session_state["count"] += 1

    return f"Counter incremented! Current count: {session_state['count']}"


def get_counter(session_state) -> str:
    """Get the current counter value."""
    count = session_state.get("count", 0)
    return f"Current count: {count}"


# Create an Agent that maintains state
agent = Agent(
    model=OpenAIChat(id="gpt-5-mini"),
    # Initialize the session state with a counter starting at 0
    session_state={"count": 0},
    tools=[increment_counter, get_counter],
    # Use variables from the session state in the instructions
    instructions="You can increment and check a counter. Current count is: {count}",
    # Important: Resolve the state in the messages so the agent can see state changes
    resolve_in_context=True,
    markdown=True,
)

# Test the counter functionality
print("Testing counter functionality...")
agent.print_response(
    "Let's increment the counter 3 times and observe the state changes!", stream=True
)
print(f"Final session state: {agent.get_session_state()}")

Usage

1

Create a virtual environment

Open the Terminal and create a python virtual environment.
python3 -m venv .venv
source .venv/bin/activate
2

Install libraries

pip install openai agno
3

Run the agent

python agent_state.py