All governance proposals for the ASI Alliance merger have PASSED with overwhelming support. Stay tuned for updates.

article

Microagents - Storage Function

A guide to understand how Microagents use storage.
2023-05-220 min readjosh

Welcome! In this guide I will illustrate how storage function is called and how to use it. Make sure your environment is set up correctly (make sure you checkout our earlier videos).

We want to create a Microagent which gets a value from the storage (starting from 0) every second. Then prints it, and puts such new value back into the storage but increased by 1 unit.

First of all, create a script and name it agent_storage.py.

code-icon
code-icon
touch agent_storage.py

Now we are ready to start writing some code.

code-icon
code-icon
from 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()

We created a Microagent named alice which logs a message every second using the @alice.on_interval decorator.

The on_interval method takes a Context object as a parameter. This one contains a storage attribute, which is used to store and retrieve data between method calls. In our example, the on_interval method retrieves the current count from the storage attribute using the ctx.storage.get() method. It prints the current count value, and then increments the count 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.

Make sure to save your script and that you are in the right directory. Also, make sure that you activated your virtual environment. Now, go on your terminal and run the script.

code-icon
code-icon
python agent_storage.py

The output should look as follows:

As you can see, we created a Microagent which is incrementing a value and printing the new value once it is incremented.


More from Fetch

light-leftellipse-orangeellipse-orange