Creating your first agent ๐ค๐งโ๐ป
Introduction
Once you've installed โ๏ธ๏ธ the uAgents library, it's quite simple to get a minimal use case running. Let our first agent be a simple inialisation and printing out the agent's name.
The agent
-
Let's create a Python script for this task, and name it by running:
touch agent.py
-
We then need to import the
Agent
andContext
classes from theuagents
library, and then create an agent using the classAgent
:from uagents import Agent, Context alice = Agent(name="alice", seed="alice recovery phrase")
It is optional but useful to include a
seed
parameter when creating an agent to set fixed addresses โ๏ธ๏ธ. Otherwise, random addresses will be generated every time you run the agent. Your address is kind of important, as this is how other agents will identify you. -
Let's define a
say_hello()
function for our agent to print a message periodically sayinghello, my name is ...
:@alice.on_event("startup") async def say_hello(ctx: Context): ctx.logger.info(f'hello, my name is {ctx.name}') if __name__ == "__main__": alice.run()
The
.on_event("startup")
decorator defines a behavior for this agent when it is run. In this case, the agent will execute thesay_hello()
function when the agent starts. TheContext
object is a collection of data and functions related to the agent. In this case, we just use the agent'sname
,alice
. The agent executes the function and uses thectx.logger.info()
method to print the message. -
Save the script.
The overall script should look as follows:
from uagents import Agent, Context
alice = Agent(name="alice", seed="alice recovery phrase")
@alice.on_event("startup")
async def say_hello(ctx: Context):
ctx.logger.info(f'hello, my name is {ctx.name}')
if __name__ == "__main__":
alice.run()
Run your agent
Make sure to have activated your virtual environment correctly.
Run the script: python agent.py
The output would be:
[alice]: hello, my name is alice
Congratulations, you have just created your first Agent! We recommend learning about interval tasks โ๏ธ next, then if you want to move really fast going to the Communicating with other Agents guide after.