Remote agents¶
μAgents can also interact remotely from different locations across the internet. All you need to know is the recipient agent's address to query it's information in the Almanac contract. See Addresses for more information about μAgent addresses.
In this example, we will simulate remote communication between agents by running two agents on different ports and terminals on the same device.
Alice¶
We will start by defining agent alice
and the recipient address (bob
's address in this example). Then we will include
a send function and a handler as we have learned in agent interactions:
from uagents.setup import fund_agent_if_low
from uagents import Agent, Context, Model
class Message(Model):
message: str
RECIPIENT_ADDRESS = "agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50"
alice = Agent(
name="alice",
port=8000,
seed="alice secret phrase",
endpoint=["http://127.0.0.1:8000/submit"],
)
fund_agent_if_low(alice.wallet.address())
@alice.on_interval(period=2.0)
async def send_message(ctx: Context):
await ctx.send(RECIPIENT_ADDRESS, Message(message="hello there bob"))
@alice.on_message(model=Message)
async def message_handler(ctx: Context, sender: str, msg: Message):
ctx.logger.info(f"Received message from {sender}: {msg.message}")
if __name__ == "__main__":
alice.run()
Bob¶
In a different script, we will define agent bob
with just a message handler to print out alice
's messages and respond to her afterward.
from uagents.setup import fund_agent_if_low
from uagents import Agent, Context, Model
class Message(Model):
message: str
bob = Agent(
name="bob",
port=8001,
seed="bob secret phrase",
endpoint=["http://127.0.0.1:8001/submit"],
)
fund_agent_if_low(bob.wallet.address())
ctx.logger.info("bob address: ", bob.address)
@bob.on_message(model=Message)
async def message_handler(ctx: Context, sender: str, msg: Message):
ctx.logger.info(f"Received message from {sender}: {msg.message}")
# send the response
await ctx.send(sender, Message(message="hello there alice"))
if __name__ == "__main__":
bob.run()
Now, we first run bob
and then alice
from different terminals. They will register automatically in the Almanac contract using their funds. The received messages will print out in each terminal.
In bob's terminal:
In alice's terminal:
For a more complex example visit restaurant booking demo.