Synchronous Communication
Overview
uAgents often send their messages in a “fire and forget” manner, not they are forgetting, but they’re not blocked
by no response. This isn’t always useful as sometimes your agents can only do something with an extra piece of
information. send_and_receive()
allows you to send a message and effectively block the handler until you get a
response.
The additional positive of this is that by using send_and_receive()
you are possibly reducing how many handlers you
would need to implement when compared with just using send()
calls.
The example below shows three agents that are messaging each other with send_and_receive()
and send()
.
from uagents import Agent, Bureau, Context, Model
class Message(Model):
message: str
alice = Agent(name="alice")
bob = Agent(name="bob")
clyde = Agent(name="clyde")
@alice.on_interval(period=5.0)
async def send_message(ctx: Context):
msg = Message(message="Hey Bob, how's Clyde?")
reply, status = await ctx.send_and_receive(bob.address, msg, response_type=Message)
if isinstance(reply, Message):
ctx.logger.info(f"Received awaited response from bob: {reply.message}")
else:
ctx.logger.info(f"Failed to receive response from bob: {status}")
@bob.on_message(model=Message)
async def handle_message_and_reply(ctx: Context, sender: str, msg: Message):
ctx.logger.info(f"Received message: {msg.message}")
new_msg = Message(message="How are you, Clyde?")
reply, status = await ctx.send_and_receive(
clyde.address, new_msg, response_type=Message
)
if isinstance(reply, Message):
ctx.logger.info(f"Received awaited response from clyde: {reply.message}")
await ctx.send(sender, Message(message="Clyde is doing alright!"))
else:
ctx.logger.info(f"Failed to receive response from clyde: {status}")
@clyde.on_message(model=Message)
async def handle_message(ctx: Context, sender: str, msg: Message):
ctx.logger.info(f"Received message from {sender}: {msg.message}")
await ctx.send(sender, Message(message="I'm doing alright!"))
bureau = Bureau([alice, bob, clyde])
if __name__ == "__main__":
bureau.run()
Expected output
Run the example script: python main.py
By running the above script, you should be able to see something similar within the terminal output:
INFO: [alice]: Starting agent with address: agent1qwmt0al3dd334n4f4rs3dw496n02cjackcxfg8l3vfl5m0pf7k5nqamf6rx
INFO: [ bob]: Starting agent with address: agent1qd7uqtycfr00xkhlpqatvkjdcgfrtf0xh93fncaqa8pf6upvn9jdjcuwzjh
INFO: [clyde]: Starting agent with address: agent1qvnf3qvc7y24gekpmtd8ar2lpskw8jnc5zzakgcjtku3u798e8lg2vugkgv
INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: [ bob]: Received message: Hey Bob, how's Clyde?
INFO: [clyde]: Received message from agent1qd7uqtycfr00xkhlpqatvkjdcgfrtf0xh93fncaqa8pf6upvn9jdjcuwzjh: How are you, Clyde?
INFO: [ bob]: Received awaited response from clyde: I'm doing alright!
INFO: [alice]: Received awaited response from bob: Clyde is doing alright!