Skip to main content
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”
1

Create a Python file

Create a file agent_state.py
2

Add code to file

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


def increment_counter(run_context: RunContext) -> str:
"""Increment the counter in session state."""
# Initialize counter if it doesn't exist
if not run_context.session_state:
    run_context.session_state = {}

if "count" not in run_context.session_state:
    run_context.session_state["count"] = 0

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

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


def get_counter(run_context: RunContext) -> str:
"""Get the current counter value."""
if not run_context.session_state:
    run_context.session_state = {}

count = run_context.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()}")
3

Create a virtual environment

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

Install libraries

pip install openai agno
5

Set OpenAI Key

Set OpenAI Key

Set your OPENAI_API_KEY as an environment variable. You can get one from OpenAI.
export OPENAI_API_KEY=sk-***
6

Run the agent

python agent_state.py