Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(backend): attach rabbitmq to the AppService (#9438)

Nicholas Tindle610be988c45c
diff --git a/autogpt_platform/backend/backend/data/rabbitmq.py b/autogpt_platform/backend/backend/data/rabbitmq.py
new file mode 100644
index 0000000000..6d56aca61a
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/rabbitmq.py
@@ -0,0 +1,296 @@
+import logging
+from abc import ABC, abstractmethod
+from enum import Enum
+from typing import Awaitable, Optional
+
+import aio_pika
+import pika
+import pika.adapters.blocking_connection
+from pika.spec import BasicProperties
+from pydantic import BaseModel
+
+from backend.util.retry import conn_retry
+from backend.util.settings import Settings
+
+logger = logging.getLogger(__name__)
+
+
+class ExchangeType(str, Enum):
+ DIRECT = "direct"
+ FANOUT = "fanout"
+ TOPIC = "topic"
+ HEADERS = "headers"
+
+
+class Exchange(BaseModel):
+ name: str
+ type: ExchangeType
+ durable: bool = True
+ auto_delete: bool = False
+
+
+class Queue(BaseModel):
+ name: str
+ durable: bool = True
+ auto_delete: bool = False
+ # Optional exchange binding configuration
+ exchange: Optional[Exchange] = None
+ routing_key: Optional[str] = None
+ arguments: Optional[dict] = None
+
+
+class RabbitMQConfig(BaseModel):
+ """Configuration for a RabbitMQ service instance"""
+
+ vhost: str = "/"
+ exchanges: list[Exchange]
+ queues: list[Queue]
+
+
+class RabbitMQBase(ABC):
+ """Base class for RabbitMQ connections with shared configuration"""
+
+ def __init__(self, config: RabbitMQConfig):
+ settings = Settings()
+ self.host = settings.config.rabbitmq_host
+ self.port = settings.config.rabbitmq_port
+ self.username = settings.secrets.rabbitmq_default_user
+ self.password = settings.secrets.rabbitmq_default_pass
+ self.config = config
+
+ self._connection = None
+ self._channel = None
+
+ @property
+ def is_connected(self) -> bool:
+ """Check if we have a valid connection"""
+ return bool(self._connection)
+
+ @property
+ def is_ready(self) -> bool:
+ """Check if we have a valid channel"""
+ return bool(self.is_connected and self._channel)
+
+ @abstractmethod
+ def connect(self) -> None | Awaitable[None]:
+ """Establish connection to RabbitMQ"""
+ pass
+
+ @abstractmethod
+ def disconnect(self) -> None | Awaitable[None]:
+ """Close connection to RabbitMQ"""
+ pass
+
+ @abstractmethod
+ def declare_infrastructure(self) -> None | Awaitable[None]:
+ """Declare exchanges and queues for this service"""
+ pass
+
+
+class SyncRabbitMQ(RabbitMQBase):
+ """Synchronous RabbitMQ client"""
+
+ @property
+ def is_connected(self) -> bool:
+ return bool(self._connection and self._connection.is_open)
+
+ @property
+ def is_ready(self) -> bool:
+ return bool(self.is_connected and self._channel and self._channel.is_open)
+
+ @conn_retry("RabbitMQ", "Acquiring connection")
+ def connect(self) -> None:
+ if self.is_connected:
+ return
+
+ credentials = pika.PlainCredentials(self.username, self.password)
+ parameters = pika.ConnectionParameters(
+ host=self.host,
+ port=self.port,
+ virtual_host=self.config.vhost,
+ credentials=credentials,
+ heartbeat=600,
+ blocked_connection_timeout=300,
+ )
+
+ self._connection = pika.BlockingConnection(parameters)
+ self._channel = self._connection.channel()
+ self._channel.basic_qos(prefetch_count=1)
+
+ self.declare_infrastructure()
+
+ def disconnect(self) -> None:
+ if self._channel:
+ if self._channel.is_open:
+ self._channel.close()
+ self._channel = None
+ if self._connection:
+ if self._connection.is_open:
+ self._connection.close()
+ self._connection = None
+
+ def declare_infrastructure(self) -> None:
+ """Declare exchanges and queues for this service"""
+ if not self.is_ready:
+ self.connect()
+
+ if self._channel is None:
+ raise RuntimeError("Channel should be established after connect")
+
+ # Declare exchanges
+ for exchange in self.config.exchanges:
+ self._channel.exchange_declare(
+ exchange=exchange.name,
+ exchange_type=exchange.type.value,
+ durable=exchange.durable,
+ auto_delete=exchange.auto_delete,
+ )
+
+ # Declare queues and bind them to exchanges
+ for queue in self.config.queues:
+ self._channel.queue_declare(
+ queue=queue.name,
+ durable=queue.durable,
+ auto_delete=queue.auto_delete,
+ arguments=queue.arguments,
+ )
+ if queue.exchange:
+ self._channel.queue_bind(
+ queue=queue.name,
+ exchange=queue.exchange.name,
+ routing_key=queue.routing_key or queue.name,
+ )
+
+ def publish_message(
+ self,
+ routing_key: str,
+ message: str,
+ exchange: Optional[Exchange] = None,
+ properties: Optional[BasicProperties] = None,
+ mandatory: bool = True,
+ ) -> None:
+ if not self.is_ready:
+ self.connect()
+
+ if self._channel is None:
+ raise RuntimeError("Channel should be established after connect")
+
+ self._channel.basic_publish(
+ exchange=exchange.name if exchange else "",
+ routing_key=routing_key,
+ body=message.encode(),
+ properties=properties or BasicProperties(delivery_mode=2),
+ mandatory=mandatory,
+ )
+
+ def get_channel(self) -> pika.adapters.blocking_connection.BlockingChannel:
+ if not self.is_ready:
+ self.connect()
+ if self._channel is None:
+ raise RuntimeError("Channel should be established after connect")
+ return self._channel
+
+
+class AsyncRabbitMQ(RabbitMQBase):
+ """Asynchronous RabbitMQ client"""
+
+ @property
+ def is_connected(self) -> bool:
+ return bool(self._connection and not self._connection.is_closed)
+
+ @property
+ def is_ready(self) -> bool:
+ return bool(self.is_connected and self._channel and not self._channel.is_closed)
+
+ @conn_retry("AsyncRabbitMQ", "Acquiring async connection")
+ async def connect(self):
+ if self.is_connected:
+ return
+
+ self._connection = await aio_pika.connect_robust(
+ host=self.host,
+ port=self.port,
+ login=self.username,
+ password=self.password,
+ virtualhost=self.config.vhost.lstrip("/"),
+ )
+ self._channel = await self._connection.channel()
+ await self._channel.set_qos(prefetch_count=1)
+
+ await self.declare_infrastructure()
+
+ async def disconnect(self):
+ if self._channel:
+ await self._channel.close()
+ self._channel = None
+ if self._connection:
+ await self._connection.close()
+ self._connection = None
+
+ async def declare_infrastructure(self):
+ """Declare exchanges and queues for this service"""
+ if not self.is_ready:
+ await self.connect()
+
+ if self._channel is None:
+ raise RuntimeError("Channel should be established after connect")
+
+ # Declare exchanges
+ for exchange in self.config.exchanges:
+ await self._channel.declare_exchange(
+ name=exchange.name,
+ type=exchange.type.value,
+ durable=exchange.durable,
+ auto_delete=exchange.auto_delete,
+ )
+
+ # Declare queues and bind them to exchanges
+ for queue in self.config.queues:
+ queue_obj = await self._channel.declare_queue(
+ name=queue.name,
+ durable=queue.durable,
+ auto_delete=queue.auto_delete,
+ arguments=queue.arguments,
+ )
+ if queue.exchange:
+ exchange = await self._channel.get_exchange(queue.exchange.name)
+ await queue_obj.bind(
+ exchange, routing_key=queue.routing_key or queue.name
+ )
+
+ async def publish_message(
+ self,
+ routing_key: str,
+ message: str,
+ exchange: Optional[Exchange] = None,
+ persistent: bool = True,
+ ) -> None:
+ if not self.is_ready:
+ await self.connect()
+
+ if self._channel is None:
+ raise RuntimeError("Channel should be established after connect")
+
+ if exchange:
+ exchange_obj = await self._channel.get_exchange(exchange.name)
+ else:
+ exchange_obj = self._channel.default_exchange
+
+ await exchange_obj.publish(
+ aio_pika.Message(
+ body=message.encode(),
+ delivery_mode=(
+ aio_pika.DeliveryMode.PERSISTENT
+ if persistent
+ else aio_pika.DeliveryMode.NOT_PERSISTENT
+ ),
+ ),
+ routing_key=routing_key,
+ )
+
+ async def get_channel(self) -> aio_pika.abc.AbstractChannel:
+ if not self.is_ready:
+ await self.connect()
+ if self._channel is None:
+ raise RuntimeError("Channel should be established after connect")
+ return self._channel
diff --git a/autogpt_platform/backend/backend/util/service.py b/autogpt_platform/backend/backend/util/service.py
index ff81ade0b3..9b07ba88e8 100644
--- a/autogpt_platform/backend/backend/util/service.py
+++ b/autogpt_platform/backend/backend/util/service.py
@@ -18,6 +18,7 @@ from typing import (
FrozenSet,
Iterator,
List,
+ Optional,
Set,
Tuple,
Type,
@@ -33,7 +34,7 @@ from pydantic import BaseModel
from Pyro5 import api as pyro
from Pyro5 import config as pyro_config
-from backend.data import db, redis
+from backend.data import db, rabbitmq, redis
from backend.util.process import AppProcess
from backend.util.retry import conn_retry
from backend.util.settings import Config, Secrets
@@ -116,6 +117,9 @@ class AppService(AppProcess, ABC):
shared_event_loop: asyncio.AbstractEventLoop
use_db: bool = False
use_redis: bool = False
+ use_async: bool = False
+ use_rabbitmq: Optional[rabbitmq.RabbitMQConfig] = None
+ rabbitmq_service: Optional[rabbitmq.SyncRabbitMQ | rabbitmq.AsyncRabbitMQ] = None
use_supabase: bool = False
def __init__(self):
@@ -130,6 +134,20 @@ class AppService(AppProcess, ABC):
def get_host(cls) -> str:
return os.environ.get(f"{cls.service_name.upper()}_HOST", config.pyro_host)
+ @property
+ def rabbit(self) -> rabbitmq.SyncRabbitMQ | rabbitmq.AsyncRabbitMQ:
+ """Access the RabbitMQ service. Will raise if not configured."""
+ if not self.rabbitmq_service:
+ raise RuntimeError("RabbitMQ not configured for this service")
+ return self.rabbitmq_service
+
+ @property
+ def rabbit_config(self) -> rabbitmq.RabbitMQConfig:
+ """Access the RabbitMQ config. Will raise if not configured."""
+ if not self.use_rabbitmq:
+ raise RuntimeError("RabbitMQ not configured for this service")
+ return self.use_rabbitmq
+
def run_service(self) -> None:
while True:
time.sleep(10)
@@ -147,6 +165,16 @@ class AppService(AppProcess, ABC):
self.shared_event_loop.run_until_complete(db.connect())
if self.use_redis:
redis.connect()
+ if self.use_rabbitmq:
+ logger.info(f"[{self.__class__.__name__}] ⏳ Configuring RabbitMQ...")
+ if self.use_async:
+ self.rabbitmq_service = rabbitmq.AsyncRabbitMQ(self.use_rabbitmq)
+ self.shared_event_loop.run_until_complete(
+ self.rabbitmq_service.connect()
+ )
+ else:
+ self.rabbitmq_service = rabbitmq.SyncRabbitMQ(self.use_rabbitmq)
+ self.rabbitmq_service.connect()
if self.use_supabase:
from supabase import create_client
@@ -175,6 +203,8 @@ class AppService(AppProcess, ABC):
if self.use_redis:
logger.info(f"[{self.__class__.__name__}] ⏳ Disconnecting Redis...")
redis.disconnect()
+ if self.use_rabbitmq:
+ logger.info(f"[{self.__class__.__name__}] ⏳ Disconnecting RabbitMQ...")
@conn_retry("Pyro", "Starting Pyro Service")
def __start_pyro(self):
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index 17786670b8..c965572631 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -167,6 +167,20 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="The pool size for the scheduler database connection pool",
)
+ rabbitmq_host: str = Field(
+ default="localhost",
+ description="The host for the RabbitMQ server",
+ )
+ rabbitmq_port: int = Field(
+ default=5672,
+ description="The port for the RabbitMQ server",
+ )
+
+ rabbitmq_vhost: str = Field(
+ default="/",
+ description="The vhost for the RabbitMQ server",
+ )
+
@field_validator("platform_base_url", "frontend_base_url")
@classmethod
def validate_platform_base_url(cls, v: str, info: ValidationInfo) -> str:
@@ -258,6 +272,11 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):
encryption_key: str = Field(default="", description="Encryption key")
+ rabbitmq_default_user: str = Field(default="", description="RabbitMQ default user")
+ rabbitmq_default_pass: str = Field(
+ default="", description="RabbitMQ default password"
+ )
+
# OAuth server credentials for integrations
# --8<-- [start:OAuthServerCredentialsExample]
github_client_id: str = Field(default="", description="GitHub OAuth client ID")
diff --git a/autogpt_platform/backend/poetry.lock b/autogpt_platform/backend/poetry.lock
index 6dfd972bd5..52f5f7b2e8 100644
--- a/autogpt_platform/backend/poetry.lock
+++ b/autogpt_platform/backend/poetry.lock
@@ -2531,6 +2531,23 @@ files = [
{file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
]
+[[package]]
+name = "pika"
+version = "1.3.2"
+description = "Pika Python AMQP Client Library"
+optional = false
+python-versions = ">=3.7"
+groups = ["main"]
+files = [
+ {file = "pika-1.3.2-py3-none-any.whl", hash = "sha256:0779a7c1fafd805672796085560d290213a465e4f6f76a6fb19e378d8041a14f"},
+ {file = "pika-1.3.2.tar.gz", hash = "sha256:b2a327ddddf8570b4965b3576ac77091b850262d34ce8c1d8cb4e4146aa4145f"},
+]
+
+[package.extras]
+gevent = ["gevent"]
+tornado = ["tornado"]
+twisted = ["twisted"]
+
[[package]]
name = "pillow"
version = "10.4.0"
@@ -5050,4 +5067,4 @@ type = ["pytest-mypy"]
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.13"
-content-hash = "87bd7a7003dd40e11e4da2c38b8ae030c1eba92a73301d439dec48bd61a49678"
+content-hash = "79e5a1b44b5f6e7a787668d39d96691e0a19b18c717accb5b7a3511bd8b4cae8"
diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.toml
index 5b6cf6c0bb..79d7bdf9c1 100644
--- a/autogpt_platform/backend/pyproject.toml
+++ b/autogpt_platform/backend/pyproject.toml
@@ -58,6 +58,7 @@ launchdarkly-server-sdk = "^9.8.0"
mem0ai = "^0.1.48"
todoist-api-python = "^2.1.7"
moviepy = "^2.1.2"
+pika = "^1.3.2"
[tool.poetry.group.dev.dependencies]
poethepoet = "^0.32.1"