Agents protocols
protocols represent message types and handlers, protocols are used to facilitate communication and interaction between agents in the Framework.
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.
They’re a simple way of adding additional Message types and the handlers for them. For example if you have an agent that primarily responds to a single handler, you could extend that agent with an additional protocol to respond to n more message types.
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 protocolsand
windowsecho. > book.py -
We import from
uagentslibrary 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: boolWe use the
Modelclass fromuagentslibrary to defineBookTableRequestandBookTableResponseclasses for setting up the structure of messages to be exchanged between your agents. TheBookTableRequestclass represents a request to book a table, containing the desired table number, while theBookTableResponseclass represents the response to that request, indicating whether the booking was successful. -
Now, we would need to define the booking protocol as
book_protoand also define the desired logic to determine if theBookTableResponsewill 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
restaurantyou 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. Also, check out the Agents: broadcast
guide for an additional implementation of protocols in Agents communication.