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”
from agno.agent import Agentfrom agno.models.openai import OpenAIChatdef 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 stateagent = 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 functionalityprint("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()}")