Options for running your Agents
Run a local Agent with an endpoint
In some scenarios, you may want to run an agent on your own hardware or infrastructure; luckily this is very easy to do on any system that support Python 3.10.
This system is pretty simple, as to get you started as quickly as possible. We’re going to run this Agent on any device you’d like, in this scenario we’re running on a VM, but you could run this on your laptop, raspberry pi or tweak for Agentverse.
Imports needed
The Agent
Consider the following Agent:
from uagents import Agent, Context, Protocol, Model
import random
from uagents import Field
import sys
agent = Agent(
name="dungeonsanddragonsdiceroll",
port=6145,
seed="RANDOM STRINGS",
endpoint=["http://YOUR_IP:6145/submit"],
)
@agent.on_event("startup")
async def hi(ctx: Context):
ctx.logger.info(agent.address)
class Request(Model):
dice_sides: int = Field(description="How many sides does your dice need?")
class Response(Model):
text: str = Field(description="Text response for dice roll")
dice_roll_protocol = Protocol("DungeonsAndDragonsDiceRoll")
@dice_roll_protocol.on_message(model=Request, replies={Response})
async def roll_dice(ctx: Context, sender: str, msg: Request):
result = str(random.randint(1, msg.dice_sides))
message = f"Dice roll result: {result}"
await ctx.send(
sender, Response(message=message)
)
agent.include(dice_roll_protocol, publish_manifest=True)
agent.run()
To correctly run this code, you must provide the name
, seed
, port
, and endpoint
parameters. Ensure the Agent has sufficient funds to register with the Almanac contract.
The Agent must run on infrastructure that allows opening a port
. In this example, we use port 6145
and an endpoint
.
The Agent is initialized with an endpoint and a port to receive messages and allow other Agents to communicate with
it. The protocol
, defines the Request Model, with a single variable of dice sides
with a type of int
. The
agent responds with the Response Model, which returns the response as a string.
The on_message()
function processes incoming messages and returns a random number between 1 and the specified dice_sides
from the message.
Finally, .run()
starts the Agent.
We can now run our Agent with the following command: python agent_endpoint.py
Expected output:
INFO: [dungeonsanddragonsdiceroll]: Manifest published successfully: DungeonsAndDragonsDiceRoll
INFO: [dungeonsanddragonsdiceroll]: Registration on Almanac API successful
INFO: [dungeonsanddragonsdiceroll]: Registering on almanac contract...
INFO: [dungeonsanddragonsdiceroll]: Registering on almanac contract...complete
INFO: [dungeonsanddragonsdiceroll]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A6145&address=agent1qvwk0ntr38yyghccrg530hnnm88r5uske4hdcalsa7gqp7sjgx42k4mp62r
INFO: [dungeonsanddragonsdiceroll]: Starting server on http://0.0.0.0:6145 (Press CTRL+C to quit)
Running an Agent with Docker
This example shows how to run an agent using the uAgents library inside a Docker container with Docker Compose. It walks you through setting up everything you need so you can easily build and run the agent.
Project Structure
.agent_with_docker
├── Dockerfile
├── poetry.lock
├── pyproject.toml
├── README.md
└── src
└── agent.py
Agent with Docker
agent.py
This example demonstrates a simple agent-based communication system using the uAgents library. The data_sender
agent sends a DataPacket
message to the data_receiver
agent every 4 seconds. Upon receiving the message, data_receiver
logs it and sends an acknowledgment back to data_sender. Both agents log the messages they receive. The agents are running with Docker Compose using Docker.
from uagents import Agent, Bureau, Context, Model
class DataPacket(Model):
message: str
data_sender = Agent(name="data_sender", seed="data_sender recovery phrase")
data_receiver = Agent(name="data_receiver", seed="data_receiver recovery phrase")
@data_sender.on_interval(period=4.0)
async def send_data_packet(ctx: Context):
"""
Event handler that gets triggered at regular intervals (every 4 seconds).
Args:
ctx (Context): The context in which the event is triggered.
Returns:
None: This function does not return any value but sends a DataPacket message from data_sender to data_receiver at intervals of (every 4 seconds).
"""
await ctx.send(
data_receiver.address, DataPacket(message="Initiating data transfer")
)
@data_sender.on_message(model=DataPacket)
async def data_sender_message_handler(ctx: Context, sender: str, msg: DataPacket):
"""
Event handler that gets triggered when data_sender receives a DataPacket message.
Args:
ctx (Context): The context in which the event is triggered.
sender (str): The address of the sender.
msg (DataPacket): The message received.
Returns:
None: This function does not return any value but logs the received message.
"""
ctx.logger.info(f"Data Sender received a message from {sender}: {msg.message}")
@data_receiver.on_message(model=DataPacket)
async def data_receiver_message_handler(ctx: Context, sender: str, msg: DataPacket):
"""
Event handler that gets triggered when data_receiver receives a DataPacket message.
Args:
ctx (Context): The context in which the event is triggered.
sender (str): The address of the sender.
msg (DataPacket): The message received.
Returns:
None: This function does not return any value but logs the received message and sends an acknowledgment back to data_sender.
"""
ctx.logger.info(f"Data Receiver received a message from {sender}: {msg.message}")
await ctx.send(
data_sender.address, DataPacket(message="Acknowledging data transfer")
)
bureau = Bureau()
bureau.add(data_sender)
bureau.add(data_receiver)
if __name__ == "__main__":
bureau.run()
Dockerfile
This Dockerfile sets up a Python environment with Poetry for dependency management. It installs necessary system packages, sets up the working directory, installs dependencies specified in pyproject.toml
, and runs agent.py
using Poetry. The application listens on port 8000.
FROM python:3.12-slim
ENV PATH="$PATH:/root/.local/bin"
RUN apt-get update && \
apt-get install -y curl gcc && \
curl -sSL https://install.python-poetry.org/ | python3 -
WORKDIR /app
ADD pyproject.toml poetry.lock /app/
RUN poetry install
ADD . /app
EXPOSE 8000
ENTRYPOINT ["poetry", "run"]
CMD ["python", "agent.py"]
Poetry Dependencies
[tool.poetry.dependencies]
python = "^3.10"
uagents = { version = "^0.13.0", python = ">=3.10,<3.13" }
Run
- Navigate to the root Folder of the Example.
- Run
docker build -t agent . && docker run -it agent