Agents protocols
Within the uAgents Framework, protocols
support capturing related message types and handlers.
Protocols are used to facilitate communication and interaction between agents in the Framework.
Indeed, any agent including the same protocol will be able to communicate with each other.
A protocol
is built similar to an agent, but it has no identity and cannot be run. Protocols only contains the message types and handlers that define some components of an agent's functionality.
Let's use a simple restaurant table booking request as an example to better understand what a protocol means and how to build one:
-
Let's start by creating a folder for our protocols. Then, let's create Python script within it, and name it:
mkdir protocols
and
windowsecho. > book.py
-
We import from
uagents
library the necessary classesContext
,Model
, andProtocol
. Then, need to define the type of messages that the handler will receive and send:from uagents import Context, Model, Protocol class BookTableRequest(Model): table_number: int class BookTableResponse(Model): success: bool
We use the
Model
class fromuagents
library to defineBookTableRequest
andBookTableResponse
classes for setting up the structure of messages to be exchanged between your agents. TheBookTableRequest
class represents a request to book a table, containing the desired table number, while theBookTableResponse
class represents the response to that request, indicating whether the booking was successful. -
Now, we would need to define the booking protocol as
book_proto
and also define the desired logic to determine if theBookTableResponse
will be successful or not:book_proto = Protocol() @book_proto.on_message(model=BookTableRequest, replies={BookTableResponse}) async def handle_book_request(ctx: Context, sender: str, msg: BookTableRequest): if ctx.storage.has(str(msg.table_number)): success = False else: success = True ctx.storage.set(str(msg.table_number), sender) # send the response await ctx.send(sender, BookTableResponse(success=success))
-
We can then import our booking protocol from into the script we create for our agent, in the following way:
from protocols.book import book_proto
-
If your agent is called
restaurant
you can include the protocol in this way:restaurant.include(book_proto)
For a better understanding of these concepts, consider having a look at the Agents storage and Exchange protocol resources and consider going through the extensive How to book a table at a restaurant using agents guide in the Agents guides section. Also, checkout the Agents: broadcast for an additional implementation of protocols in agents communication.