Local Network Interaction
Introduction
This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to set up a local network interaction between two agents using the uAgents Python library.
Please check out the example code in our examples repo (opens in a new tab) to run this locally.
Supporting documentation
- Creating an agent
- Creating an interval task
- Communicating with other agents
- Communicating with other agents
- Agents address
Agent 1
Self hosted
agent_1.pyfrom uagents import Agent, Context, Model # NOTE: Run agent1.py before running agent2.py class Message(Model): message: str bob = Agent( name="bob", port=8001, seed="bob secret phrase", endpoint=["http://127.0.0.1:8001/submit"], ) @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()
Agent 2
Self hosted
agent_2.pyfrom uagents import Agent, Context, Model class Message(Model): message: str RECIPIENT_ADDRESS = ( "test-agent://agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50" ) alice = Agent( name="alice", port=8000, seed="alice secret phrase", endpoint=["http://127.0.0.1:8000/submit"], ) @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()
Expected output
-
Bob:
INFO: [ bob]: Registering on almanac contract... INFO: [ bob]: Registering on almanac contract...complete INFO: [ bob]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit) INFO: [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob. INFO: [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob. INFO: [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob.
-
Alice:
INFO: [alice]: Registering on almanac contract... INFO: [alice]: Registering on almanac contract...complete INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: Hello there alice. INFO: [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: Hello there alice. INFO: [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: Hello there alice.