This tutorial will show you how to create a simple yet effective multi-agent application using the uAgents framework. We set up three agents — Directory, Seller, and Buyer — that communicate via well-defined message protocols to simulate a real-world marketplace interaction. In order to show discovery, negotiations, and transactions among agents running in parallel, we create message schemas, specify agent behaviors and implement requests-responses cycles. We can then understand how agents work together, exchange information, and maintain efficient decentralized workflows. Take a look at the Full Codes here.
!pip -q install "uagents>=0.11.2"
import asyncio, random
Type List, Dict or Optional instead of typing it.
From uagents Import Agent, Context Bureau, Model, Protocol
class ServiceAnnounce(Model):
category:
endpoint: str
Class ServiceQuery (Model)
Category:
Class ServiceList (Model)
Addresses:[str]
Class OfferRequestModel:
Maximum price: Int
Class Offer (Model)
Price:
qty: int
Class Order (Model:
qty: int
Class Receipt (Model)
qty: int
total: int
OK: Bool
Please note that this is not mandatory[str] No.
Installing uAgents and defining our message models is where we start. Structured data types are created for queries, announcements, orders and offers. This allows agents to share information easily. Visit the Full Codes here.
registry_proto = Protocol(name="registry", version="1.0")
trade_proto = Protocol(name="trade", version="1.0")
It is possible to use the following code: Agent = directory"directory", seed="dir-seed-001")
Seller = Agent Name="seller", seed="seller-seed-001")
Buyer = Agent (name)"buyer", seed="buyer-seed-001")
directory.include(registry_proto)
seller.include(trade_proto)
buyer.include(registry_proto)
buyer.include(trade_proto)
@registry_proto.on_message(model=ServiceAnnounce)
async def on_announce(ctx: Context, sender: str, msg: ServiceAnnounce):
reg = await ctx.storage.get("reg") or {}
reg.setdefault(msg.category, set()).add(sender)
await ctx.storage.set("reg", reg)
ctx.logger.info(f"Registered {sender} under '{msg.category}'")
@registry_proto.on_message(model=ServiceQuery)
async def on_query(ctx: Context, sender: str, msg: ServiceQuery):
reg = await ctx.storage.get("reg") or {}
addrs = sorted(list(reg.get(msg.category, set())))
await ctx.send(sender, ServiceList(addresses=addrs))
ctx.logger.info(f"Returned {len(addrs)} providers for '{msg.category}'")
The Registry protocol is used to manage service discovery. We create the Buyer, Seller and Directory agents. Directory responds to both announcements and inquiries, which allows agents to find each other and register dynamically. See the Full Codes here.
CATALOG : Dict[str, Dict[str, int]] = {
"camera": {"price": 120, "qty": 3},
"laptop": {"price": 650, "qty": 2},
"headphones": {"price": 60, "qty": 5},
}
@seller.on_event("startup")
async def seller_start(ctx: Context):
await ctx.send(directory.address, ServiceAnnounce(category="electronics", endpoint=seller.address))
ctx.logger.info("Seller announced to directory")
@trade_proto.on_message(model=OfferRequest)
async def on_offer_request(ctx: Context, sender: str, req: OfferRequest):
item = CATALOG.get(req.item)
No item
await ctx.send(sender, Offer(item=req.item, price=0, qty=0))
You can return to your original language by clicking here.
Price = max(1, item["price"] * (0.9 + 0.2 * random.random())))
if price > req.max_price or item["qty"]
Create the Seller Agent’s Catalog and add logic to respond to order requests. By adding stock management and variable pricing, we simulate the real world of trading. Take a look at the Full Codes here.
@buyer.on_event("startup")
async def buyer_start(ctx: Context):
ctx.logger.info("Buyer querying directory for electronics...")
resp = await ctx.ask(directory.address, ServiceQuery(category="electronics"), expects=ServiceList, timeout=5.0)
If you are a seller, your address is the same as yours. []
If you are not a seller:
You can return to your original language by clicking here.
Target = Sellers[0]
desired = "laptop"
budget = 700
ctx.logger.info(f"Requesting offer for '{desired}' within budget {budget} from {target}")
offer = await ctx.ask(target, OfferRequest(item=desired, max_price=budget), expects=Offer, timeout=5.0)
If not an offer, then offer.price is 1 otherwise 0
If quantity == zero:
You can return to your original language by clicking here.
ctx.logger.info(f"Placing order for {qty} x {offer.item} at {offer.price}")
receipt = await ctx.ask(target, Order(item=offer.item, qty=qty), expects=Receipt, timeout=5.0)
When receipt and receipt.
ctx.logger.info(f"ORDER SUCCESS: {receipt.qty} x {receipt.item} | total={receipt.total}")
The Buyer Agent is programmed to find sellers, ask for offers and place orders according to budget and availability. The buyer’s asynchronous interaction with the seller is observed to ensure a successful purchase. See the Full Codes here.
@buyer.on_interval(period=6.0)
async def periodic_discovery(ctx: Context):
seen = await ctx.storage.get("seen"() or (0
if seen >= 1:
You can return to your original language by clicking here.
await ctx.storage.set("seen", seen + 1)
ctx.logger.info("Periodic discovery tick -> re-query directory")
resp = await ctx.ask(directory.address, ServiceQuery(category="electronics"), expects=ServiceList, timeout=3.0)
n = len(resp.addresses) if resp else 0
ctx.logger.info(f"Periodic: directory reports {n} seller(s)")
bureau = Bureau()
bureau.add(directory)
bureau.add(seller)
bureau.add(buyer)
async def run_demo(seconds=10):
task = asyncio.create_task(bureau.run_async())
try:
await asyncio.sleep(seconds)
finally:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
print("n✅ Demo run complete.n")
try:
loop = asyncio.get_running_loop()
await run_demo(10)
Except RuntimeError
asyncio.run(run_demo(10))
The Bureau will then run the agents in parallel. The asynchronous time is launched to watch the simulation of the marketplace unfold.
As a conclusion, our agents have discovered one another, made an offer, completed the transaction, all using message-based interaction. The uAgents framework simplifies multiagent orchestration, combining communication, state management and structure seamlessly in Python. This example allows us to see how uAgents can help create dynamic and autonomous systems. It also gives insight on how we could extend the architecture of this system for complex AI collaborations, decentralized markets, intelligent service networks or even complex marketplaces.
Click here to find out more Full Codes here. Check out our GitHub Page for Tutorials, Codes and Notebooks. Also, feel free to follow us on Twitter Join our Facebook group! 100k+ ML SubReddit Subscribe Now our Newsletter. Wait! What? now you can join us on telegram as well.
Asif Razzaq serves as the CEO at Marktechpost Media Inc. As an entrepreneur, Asif has a passion for harnessing Artificial Intelligence to benefit society. Marktechpost is his latest venture, a media platform that focuses on Artificial Intelligence. It is known for providing in-depth news coverage about machine learning, deep learning, and other topics. The content is technically accurate and easy to understand by an audience of all backgrounds. This platform has over 2,000,000 monthly views which shows its popularity.

