Using agents storage function
Introduction
In this guide, we want to illustrate how storage functions are called and how to use them. We want to create an agent which gets a value from the storage (starting from 0) every second. Then prints it, and puts the new value back into the storage but increased by 1 unit.
Prerequisites
Make sure you have read the following resources before going on with this guide:
Imports needed
Walk-through
-
To start let's create a Python script and name it
storage.py
, we can do this in terminal with the following command:windowsecho. > storage.py
-
Then, we need to open the script in the text editor of choice and import the necessary classes,
Agent
andContext
, from theuagents
library. -
Let's then create an agent named
alice
which logs a message every second using the.on_interval()
decorator, indicating the current count. Theon_interval()
function takes aContext
object as a parameter: theContext
object contains astorage
attribute, which is used to store and retrieve data between method calls:
storage.pyfrom uagents import Agent, Context alice = Agent(name="alice", seed="alice recovery phrase") @alice.on_interval(period=1.0) async def on_interval(ctx: Context): current_count = ctx.storage.get("count") or 0 ctx.logger.info(f"My count is: {current_count}") ctx.storage.set("count", current_count + 1) if __name__ == "__main__": alice.run()
Here, the on_interval()
function retrieves the current count from the storage attribute using the ctx.storage.get()
method. It prints the current_count
value, and then increments it by 1
, and stores the updated count back to the storage attribute using the ctx.storage.set()
method. The current count is then logged using the ctx.logger.info()
method.
- Save the script.
Run the script
On your terminal, make sure you activated the virtual environment.
Run the script: python storage.py
The output should look as follows:
INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: [alice]: My count is: 1 INFO: [alice]: My count is: 2 INFO: [alice]: My count is: 3 ...