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): Introduce executors shared DB connection (#8340)

Zamil Majdy6f07d24e9303
diff --git a/autogpt_platform/backend/backend/app.py b/autogpt_platform/backend/backend/app.py
index b3c8b52716..5d77ea9632 100644
--- a/autogpt_platform/backend/backend/app.py
+++ b/autogpt_platform/backend/backend/app.py
@@ -24,11 +24,12 @@ def main(**kwargs):
Run all the processes required for the AutoGPT-server (REST and WebSocket APIs).
"""
- from backend.executor import ExecutionManager, ExecutionScheduler
+ from backend.executor import DatabaseManager, ExecutionManager, ExecutionScheduler
from backend.server.rest_api import AgentServer
from backend.server.ws_api import WebsocketServer
run_processes(
+ DatabaseManager(),
ExecutionManager(),
ExecutionScheduler(),
WebsocketServer(),
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 8147f702af..e1fccb4289 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -18,7 +18,7 @@ from backend.blocks.llm import (
LlmModel,
)
from backend.blocks.talking_head import CreateTalkingAvatarVideoBlock
-from backend.data.block import Block, BlockInput
+from backend.data.block import Block, BlockInput, get_block
from backend.util.settings import Config
@@ -96,7 +96,7 @@ class UserCreditBase(ABC):
self,
user_id: str,
user_credit: int,
- block: Block,
+ block_id: str,
input_data: BlockInput,
data_size: float,
run_time: float,
@@ -107,7 +107,7 @@ class UserCreditBase(ABC):
Args:
user_id (str): The user ID.
user_credit (int): The current credit for the user.
- block (Block): The block that is being used.
+ block_id (str): The block ID.
input_data (BlockInput): The input data for the block.
data_size (float): The size of the data being processed.
run_time (float): The time taken to run the block.
@@ -208,12 +208,16 @@ class UserCredit(UserCreditBase):
self,
user_id: str,
user_credit: int,
- block: Block,
+ block_id: str,
input_data: BlockInput,
data_size: float,
run_time: float,
validate_balance: bool = True,
) -> int:
+ block = get_block(block_id)
+ if not block:
+ raise ValueError(f"Block not found: {block_id}")
+
cost, matching_filter = self._block_usage_cost(
block=block, input_data=input_data, data_size=data_size, run_time=run_time
)
diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.py
index 991bef1f3f..4f1be1de1e 100644
--- a/autogpt_platform/backend/backend/data/graph.py
+++ b/autogpt_platform/backend/backend/data/graph.py
@@ -7,7 +7,7 @@ from typing import Any, Literal
import prisma.types
from prisma.models import AgentGraph, AgentGraphExecution, AgentNode, AgentNodeLink
from prisma.types import AgentGraphInclude
-from pydantic import BaseModel, PrivateAttr
+from pydantic import BaseModel
from pydantic_core import PydanticUndefinedType
from backend.blocks.basic import AgentInputBlock, AgentOutputBlock
@@ -51,17 +51,8 @@ class Node(BaseDbModel):
block_id: str
input_default: BlockInput = {} # dict[input_name, default_value]
metadata: dict[str, Any] = {}
-
- _input_links: list[Link] = PrivateAttr(default=[])
- _output_links: list[Link] = PrivateAttr(default=[])
-
- @property
- def input_links(self) -> list[Link]:
- return self._input_links
-
- @property
- def output_links(self) -> list[Link]:
- return self._output_links
+ input_links: list[Link] = []
+ output_links: list[Link] = []
@staticmethod
def from_db(node: AgentNode):
@@ -73,8 +64,8 @@ class Node(BaseDbModel):
input_default=json.loads(node.constantInput),
metadata=json.loads(node.metadata),
)
- obj._input_links = [Link.from_db(link) for link in node.Input or []]
- obj._output_links = [Link.from_db(link) for link in node.Output or []]
+ obj.input_links = [Link.from_db(link) for link in node.Input or []]
+ obj.output_links = [Link.from_db(link) for link in node.Output or []]
return obj
diff --git a/autogpt_platform/backend/backend/data/queue.py b/autogpt_platform/backend/backend/data/queue.py
index fb05be72d1..dd4b9e16ce 100644
--- a/autogpt_platform/backend/backend/data/queue.py
+++ b/autogpt_platform/backend/backend/data/queue.py
@@ -17,14 +17,6 @@ class DateTimeEncoder(json.JSONEncoder):
class AbstractEventQueue(ABC):
- @abstractmethod
- def connect(self):
- pass
-
- @abstractmethod
- def close(self):
- pass
-
@abstractmethod
def put(self, execution_result: ExecutionResult):
pass
@@ -36,26 +28,23 @@ class AbstractEventQueue(ABC):
class RedisEventQueue(AbstractEventQueue):
def __init__(self):
- self.connection = None
self.queue_name = redis.QUEUE_NAME
- def connect(self):
- self.connection = redis.connect()
+ @property
+ def connection(self):
+ return redis.get_redis()
def put(self, execution_result: ExecutionResult):
- if self.connection:
- message = json.dumps(execution_result.model_dump(), cls=DateTimeEncoder)
- logger.info(f"Putting execution result to Redis {message}")
- self.connection.lpush(self.queue_name, message)
+ message = json.dumps(execution_result.model_dump(), cls=DateTimeEncoder)
+ logger.info(f"Putting execution result to Redis {message}")
+ self.connection.lpush(self.queue_name, message)
def get(self) -> ExecutionResult | None:
- if self.connection:
- message = self.connection.rpop(self.queue_name)
- if message is not None and isinstance(message, (str, bytes, bytearray)):
- data = json.loads(message)
- logger.info(f"Getting execution result from Redis {data}")
- return ExecutionResult(**data)
+ message = self.connection.rpop(self.queue_name)
+ if message is not None and isinstance(message, (str, bytes, bytearray)):
+ data = json.loads(message)
+ logger.info(f"Getting execution result from Redis {data}")
+ return ExecutionResult(**data)
+ elif message is not None:
+ logger.error(f"Failed to get execution result from Redis {message}")
return None
-
- def close(self):
- redis.disconnect()
diff --git a/autogpt_platform/backend/backend/exec.py b/autogpt_platform/backend/backend/exec.py
index aaea21e64a..6e902c64df 100644
--- a/autogpt_platform/backend/backend/exec.py
+++ b/autogpt_platform/backend/backend/exec.py
@@ -1,5 +1,5 @@
from backend.app import run_processes
-from backend.executor import ExecutionManager
+from backend.executor import DatabaseManager, ExecutionManager
def main():
@@ -7,6 +7,7 @@ def main():
Run all the processes required for the AutoGPT-server REST API.
"""
run_processes(
+ DatabaseManager(),
ExecutionManager(),
)
diff --git a/autogpt_platform/backend/backend/executor/__init__.py b/autogpt_platform/backend/backend/executor/__init__.py
index 953d09aa07..59a3595eea 100644
--- a/autogpt_platform/backend/backend/executor/__init__.py
+++ b/autogpt_platform/backend/backend/executor/__init__.py
@@ -1,7 +1,9 @@
+from .database import DatabaseManager
from .manager import ExecutionManager
from .scheduler import ExecutionScheduler
__all__ = [
+ "DatabaseManager",
"ExecutionManager",
"ExecutionScheduler",
]
diff --git a/autogpt_platform/backend/backend/executor/database.py b/autogpt_platform/backend/backend/executor/database.py
new file mode 100644
index 0000000000..8257d5c8c0
--- /dev/null
+++ b/autogpt_platform/backend/backend/executor/database.py
@@ -0,0 +1,75 @@
+from functools import wraps
+from typing import Any, Callable, Concatenate, Coroutine, ParamSpec, TypeVar, cast
+
+from backend.data.credit import get_user_credit_model
+from backend.data.execution import (
+ ExecutionResult,
+ create_graph_execution,
+ get_execution_results,
+ get_incomplete_executions,
+ get_latest_execution,
+ update_execution_status,
+ update_graph_execution_stats,
+ update_node_execution_stats,
+ upsert_execution_input,
+ upsert_execution_output,
+)
+from backend.data.graph import get_graph, get_node
+from backend.data.queue import RedisEventQueue
+from backend.util.service import AppService, expose
+from backend.util.settings import Config
+
+P = ParamSpec("P")
+R = TypeVar("R")
+
+
+class DatabaseManager(AppService):
+
+ def __init__(self):
+ super().__init__(port=Config().database_api_port)
+ self.use_db = True
+ self.use_redis = True
+ self.event_queue = RedisEventQueue()
+
+ @expose
+ def send_execution_update(self, execution_result_dict: dict[Any, Any]):
+ self.event_queue.put(ExecutionResult(**execution_result_dict))
+
+ @staticmethod
+ def exposed_run_and_wait(
+ f: Callable[P, Coroutine[None, None, R]]
+ ) -> Callable[Concatenate[object, P], R]:
+ @expose
+ @wraps(f)
+ def wrapper(self, *args: P.args, **kwargs: P.kwargs) -> R:
+ coroutine = f(*args, **kwargs)
+ res = self.run_and_wait(coroutine)
+ return res
+
+ return wrapper
+
+ # Executions
+ create_graph_execution = exposed_run_and_wait(create_graph_execution)
+ get_execution_results = exposed_run_and_wait(get_execution_results)
+ get_incomplete_executions = exposed_run_and_wait(get_incomplete_executions)
+ get_latest_execution = exposed_run_and_wait(get_latest_execution)
+ update_execution_status = exposed_run_and_wait(update_execution_status)
+ update_graph_execution_stats = exposed_run_and_wait(update_graph_execution_stats)
+ update_node_execution_stats = exposed_run_and_wait(update_node_execution_stats)
+ upsert_execution_input = exposed_run_and_wait(upsert_execution_input)
+ upsert_execution_output = exposed_run_and_wait(upsert_execution_output)
+
+ # Graphs
+ get_node = exposed_run_and_wait(get_node)
+ get_graph = exposed_run_and_wait(get_graph)
+
+ # Credits
+ user_credit_model = get_user_credit_model()
+ get_or_refill_credit = cast(
+ Callable[[Any, str], int],
+ exposed_run_and_wait(user_credit_model.get_or_refill_credit),
+ )
+ spend_credits = cast(
+ Callable[[Any, str, int, str, dict[str, str], float, float], int],
+ exposed_run_and_wait(user_credit_model.spend_credits),
+ )
diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.py
index 87f0e8b928..d756dfc6ec 100644
--- a/autogpt_platform/backend/backend/executor/manager.py
+++ b/autogpt_platform/backend/backend/executor/manager.py
@@ -1,4 +1,3 @@
-import asyncio
import atexit
import logging
import multiprocessing
@@ -9,41 +8,33 @@ import threading
from concurrent.futures import Future, ProcessPoolExecutor
from contextlib import contextmanager
from multiprocessing.pool import AsyncResult, Pool
-from typing import TYPE_CHECKING, Any, Coroutine, Generator, TypeVar, cast
+from typing import TYPE_CHECKING, Any, Generator, TypeVar, cast
from pydantic import BaseModel
from redis.lock import Lock as RedisLock
if TYPE_CHECKING:
- from backend.server.rest_api import AgentServer
+ from backend.executor import DatabaseManager
-from backend.data import db, redis
+from backend.data import redis
from backend.data.block import Block, BlockData, BlockInput, BlockType, get_block
-from backend.data.credit import get_user_credit_model
from backend.data.execution import (
ExecutionQueue,
ExecutionResult,
ExecutionStatus,
GraphExecution,
NodeExecution,
- create_graph_execution,
- get_execution_results,
- get_incomplete_executions,
- get_latest_execution,
merge_execution_input,
parse_execution_output,
- update_execution_status,
- update_graph_execution_stats,
- update_node_execution_stats,
- upsert_execution_input,
- upsert_execution_output,
)
-from backend.data.graph import Graph, Link, Node, get_graph, get_node
+from backend.data.graph import Graph, Link, Node
from backend.data.model import CREDENTIALS_FIELD_NAME, CredentialsMetaInput
from backend.integrations.creds_manager import IntegrationCredentialsManager
from backend.util import json
+from backend.util.cache import thread_cached_property
from backend.util.decorator import error_logged, time_measured
from backend.util.logging import configure_logging
+from backend.util.process import set_service_name
from backend.util.service import AppService, expose, get_service_client
from backend.util.settings import Settings
from backend.util.type import convert
@@ -102,8 +93,7 @@ ExecutionStream = Generator[NodeExecution, None, None]
def execute_node(
- loop: asyncio.AbstractEventLoop,
- api_client: "AgentServer",
+ db_client: "DatabaseManager",
creds_manager: IntegrationCredentialsManager,
data: NodeExecution,
execution_stats: dict[str, Any] | None = None,
@@ -113,8 +103,7 @@ def execute_node(
persist the execution result, and return the subsequent node to be executed.
Args:
- loop: The event loop to run the async functions.
- api_client: The client to send execution updates to the server.
+ db_client: The client to send execution updates to the server.
data: The execution data for executing the current node.
execution_stats: The execution statistics to be updated.
@@ -127,17 +116,12 @@ def execute_node(
node_exec_id = data.node_exec_id
node_id = data.node_id
- asyncio.set_event_loop(loop)
-
- def wait(f: Coroutine[Any, Any, T]) -> T:
- return loop.run_until_complete(f)
-
def update_execution(status: ExecutionStatus) -> ExecutionResult:
- exec_update = wait(update_execution_status(node_exec_id, status))
- api_client.send_execution_update(exec_update.model_dump())
+ exec_update = db_client.update_execution_status(node_exec_id, status)
+ db_client.send_execution_update(exec_update.model_dump())
return exec_update
- node = wait(get_node(node_id))
+ node = db_client.get_node(node_id)
node_block = get_block(node.block_id)
if not node_block:
@@ -163,7 +147,6 @@ def execute_node(
input_size = len(input_data_str)
log_metadata.info("Executed node with input", input=input_data_str)
update_execution(ExecutionStatus.RUNNING)
- user_credit = get_user_credit_model()
extra_exec_kwargs = {}
# Last-minute fetch credentials + acquire a system-wide read-write lock to prevent
@@ -178,7 +161,7 @@ def execute_node(
output_size = 0
try:
- credit = wait(user_credit.get_or_refill_credit(user_id))
+ credit = db_client.get_or_refill_credit(user_id)
if credit < 0:
raise ValueError(f"Insufficient credit: {credit}")
@@ -187,11 +170,10 @@ def execute_node(
):
output_size += len(json.dumps(output_data))
log_metadata.info("Node produced output", output_name=output_data)
- wait(upsert_execution_output(node_exec_id, output_name, output_data))
+ db_client.upsert_execution_output(node_exec_id, output_name, output_data)
for execution in _enqueue_next_nodes(
- api_client=api_client,
- loop=loop,
+ db_client=db_client,
node=node,
output=(output_name, output_data),
user_id=user_id,
@@ -212,12 +194,12 @@ def execute_node(
if r.end_time and r.start_time
else 0
)
- wait(user_credit.spend_credits(user_id, credit, node_block, input_data, s, t))
+ db_client.spend_credits(user_id, credit, node_block.id, input_data, s, t)
except Exception as e:
error_msg = str(e)
log_metadata.exception(f"Node execution failed with error {error_msg}")
- wait(upsert_execution_output(node_exec_id, "error", error_msg))
+ db_client.upsert_execution_output(node_exec_id, "error", error_msg)
update_execution(ExecutionStatus.FAILED)
raise e
@@ -232,8 +214,7 @@ def execute_node(
def _enqueue_next_nodes(
- api_client: "AgentServer",
- loop: asyncio.AbstractEventLoop,
+ db_client: "DatabaseManager",
node: Node,
output: BlockData,
user_id: str,
@@ -241,16 +222,14 @@ def _enqueue_next_nodes(
graph_id: str,
log_metadata: LogMetadata,
) -> list[NodeExecution]:
- def wait(f: Coroutine[Any, Any, T]) -> T:
- return loop.run_until_complete(f)
def add_enqueued_execution(
node_exec_id: str, node_id: str, data: BlockInput
) -> NodeExecution:
- exec_update = wait(
- update_execution_status(node_exec_id, ExecutionStatus.QUEUED, data)
+ exec_update = db_client.update_execution_status(
+ node_exec_id, ExecutionStatus.QUEUED, data
)
- api_client.send_execution_update(exec_update.model_dump())
+ db_client.send_execution_update(exec_update.model_dump())
return NodeExecution(
user_id=user_id,
graph_exec_id=graph_exec_id,
@@ -270,20 +249,18 @@ def _enqueue_next_nodes(
if next_data is None:
return enqueued_executions
- next_node = wait(get_node(next_node_id))
+ next_node = db_client.get_node(next_node_id)
# Multiple node can register the same next node, we need this to be atomic
# To avoid same execution to be enqueued multiple times,
# Or the same input to be consumed multiple times.
with synchronized(f"upsert_input-{next_node_id}-{graph_exec_id}"):
# Add output data to the earliest incomplete execution, or create a new one.
- next_node_exec_id, next_node_input = wait(
- upsert_execution_input(
- node_id=next_node_id,
- graph_exec_id=graph_exec_id,
- input_name=next_input_name,
- input_data=next_data,
- )
+ next_node_exec_id, next_node_input = db_client.upsert_execution_input(
+ node_id=next_node_id,
+ graph_exec_id=graph_exec_id,
+ input_name=next_input_name,
+ input_data=next_data,
)
# Complete missing static input pins data using the last execution input.
@@ -293,8 +270,8 @@ def _enqueue_next_nodes(
if link.is_static and link.sink_name not in next_node_input
}
if static_link_names and (
- latest_execution := wait(
- get_latest_execution(next_node_id, graph_exec_id)
+ latest_execution := db_client.get_latest_execution(
+ next_node_id, graph_exec_id
)
):
for name in static_link_names:
@@ -321,7 +298,9 @@ def _enqueue_next_nodes(
# If link is static, there could be some incomplete executions waiting for it.
# Load and complete the input missing input data, and try to re-enqueue them.
- for iexec in wait(get_incomplete_executions(next_node_id, graph_exec_id)):
+ for iexec in db_client.get_incomplete_executions(
+ next_node_id, graph_exec_id
+ ):
idata = iexec.input_data
ineid = iexec.node_exec_id
@@ -434,13 +413,10 @@ class Executor:
@classmethod
def on_node_executor_start(cls):
configure_logging()
-
- cls.loop = asyncio.new_event_loop()
- cls.pid = os.getpid()
-
+ set_service_name("NodeExecutor")
redis.connect()
- cls.loop.run_until_complete(db.connect())
- cls.agent_server_client = get_agent_server_client()
+ cls.pid = os.getpid()
+ cls.db_client = get_db_client()
cls.creds_manager = IntegrationCredentialsManager()
# Set up shutdown handlers
@@ -457,8 +433,6 @@ class Executor:
logger.info(f"[on_node_executor_stop {cls.pid}] ⏳ Releasing locks...")
cls.creds_manager.release_all_locks()
- logger.info(f"[on_node_executor_stop {cls.pid}] ⏳ Disconnecting DB...")
- cls.loop.run_until_complete(db.disconnect())
logger.info(f"[on_node_executor_stop {cls.pid}] ⏳ Disconnecting Redis...")
redis.disconnect()
logger.info(f"[on_node_executor_stop {cls.pid}] ✅ Finished cleanup")
@@ -467,15 +441,13 @@ class Executor:
def on_node_executor_sigterm(cls):
llprint(f"[on_node_executor_sigterm {cls.pid}] ⚠️ SIGTERM received")
if not cls.shutdown_lock.acquire(blocking=False):
- return # already shutting down, no need to self-terminate
+ return # already shutting down
- llprint(f"[on_node_executor_sigterm {cls.pid}] ⏳ Releasing locks...")
+ llprint(f"[on_node_executor_stop {cls.pid}] ⏳ Releasing locks...")
cls.creds_manager.release_all_locks()
- llprint(f"[on_node_executor_sigterm {cls.pid}] ⏳ Disconnecting DB...")
- cls.loop.run_until_complete(db.disconnect())
- llprint(f"[on_node_executor_sigterm {cls.pid}] ⏳ Disconnecting Redis...")
+ llprint(f"[on_node_executor_stop {cls.pid}] ⏳ Disconnecting Redis...")
redis.disconnect()
- llprint(f"[on_node_executor_sigterm {cls.pid}] ✅ Finished cleanup")
+ llprint(f"[on_node_executor_stop {cls.pid}] ✅ Finished cleanup")
sys.exit(0)
@classmethod
@@ -501,8 +473,8 @@ class Executor:
execution_stats["walltime"] = timing_info.wall_time
execution_stats["cputime"] = timing_info.cpu_time
- cls.loop.run_until_complete(
- update_node_execution_stats(node_exec.node_exec_id, execution_stats)
+ cls.db_client.update_node_execution_stats(
+ node_exec.node_exec_id, execution_stats
)
@classmethod
@@ -517,7 +489,7 @@ class Executor:
try:
log_metadata.info(f"Start node execution {node_exec.node_exec_id}")
for execution in execute_node(
- cls.loop, cls.agent_server_client, cls.creds_manager, node_exec, stats
+ cls.db_client, cls.creds_manager, node_exec, stats
):
q.add(execution)
log_metadata.info(f"Finished node execution {node_exec.node_exec_id}")
@@ -529,12 +501,11 @@ class Executor:
@classmethod
def on_graph_executor_start(cls):
configure_logging()
+ set_service_name("GraphExecutor")
+ cls.db_client = get_db_client()
cls.pool_size = settings.config.num_node_workers
- cls.loop = asyncio.new_event_loop()
cls.pid = os.getpid()
-
- cls.loop.run_until_complete(db.connect())
cls._init_node_executor_pool()
logger.info(
f"Graph executor {cls.pid} started with {cls.pool_size} node workers"
@@ -546,8 +517,6 @@ class Executor:
@classmethod
def on_graph_executor_stop(cls):
prefix = f"[on_graph_executor_stop {cls.pid}]"
- logger.info(f"{prefix} ⏳ Disconnecting DB...")
- cls.loop.run_until_complete(db.disconnect())
logger.info(f"{prefix} ⏳ Terminating node executor pool...")
cls.executor.terminate()
logger.info(f"{prefix} ✅ Finished cleanup")
@@ -574,14 +543,12 @@ class Executor:
graph_exec, cancel, log_metadata
)
- cls.loop.run_until_complete(
- update_graph_execution_stats(
- graph_exec_id=graph_exec.graph_exec_id,
- error=error,
- wall_time=timing_info.wall_time,
- cpu_time=timing_info.cpu_time,
- node_count=node_count,
- )
+ cls.db_client.update_graph_execution_stats(
+ graph_exec_id=graph_exec.graph_exec_id,
+ error=error,
+ wall_time=timing_info.wall_time,
+ cpu_time=timing_info.cpu_time,
+ node_count=node_count,
)
@classmethod
@@ -688,10 +655,10 @@ class Executor:
class ExecutionManager(AppService):
+
def __init__(self):
super().__init__(port=settings.config.execution_manager_port)
- self.use_db = True
- self.use_queue = True # we only need the Redis connection
+ self.use_redis = True
self.use_supabase = True
self.pool_size = settings.config.num_graph_workers
self.queue = ExecutionQueue[GraphExecution]()
@@ -734,17 +701,15 @@ class ExecutionManager(AppService):
super().cleanup()
- @property
- def agent_server_client(self) -> "AgentServer":
- # Since every single usage of this property happens from a different thread,
- # there is no value in caching it.
- return get_agent_server_client()
+ @thread_cached_property
+ def db_client(self) -> "DatabaseManager":
+ return get_db_client()
@expose
def add_execution(
self, graph_id: str, data: BlockInput, user_id: str
) -> dict[str, Any]:
- graph: Graph | None = self.run_and_wait(get_graph(graph_id, user_id=user_id))
+ graph: Graph | None = self.db_client.get_graph(graph_id, user_id=user_id)
if not graph:
raise Exception(f"Graph #{graph_id} not found.")
@@ -772,13 +737,11 @@ class ExecutionManager(AppService):
else:
nodes_input.append((node.id, input_data))
- graph_exec_id, node_execs = self.run_and_wait(
- create_graph_execution(
- graph_id=graph_id,
- graph_version=graph.version,
- nodes_input=nodes_input,
- user_id=user_id,
- )
+ graph_exec_id, node_execs = self.db_client.create_graph_execution(
+ graph_id=graph_id,
+ graph_version=graph.version,
+ nodes_input=nodes_input,
+ user_id=user_id,
)
starting_node_execs = []
@@ -793,12 +756,10 @@ class ExecutionManager(AppService):
data=node_exec.input_data,
)
)
- exec_update = self.run_and_wait(
- update_execution_status(
- node_exec.node_exec_id, ExecutionStatus.QUEUED, node_exec.input_data
- )
+ exec_update = self.db_client.update_execution_status(
+ node_exec.node_exec_id, ExecutionStatus.QUEUED, node_exec.input_data
)
- self.agent_server_client.send_execution_update(exec_update.model_dump())
+ self.db_client.send_execution_update(exec_update.model_dump())
graph_exec = GraphExecution(
user_id=user_id,
@@ -833,23 +794,19 @@ class ExecutionManager(AppService):
future.result()
# Update the status of the unfinished node executions
- node_execs = self.run_and_wait(get_execution_results(graph_exec_id))
+ node_execs = self.db_client.get_execution_results(graph_exec_id)
for node_exec in node_execs:
if node_exec.status not in (
ExecutionStatus.COMPLETED,
ExecutionStatus.FAILED,
):
- self.run_and_wait(
- upsert_execution_output(
- node_exec.node_exec_id, "error", "TERMINATED"
- )
+ self.db_client.upsert_execution_output(
+ node_exec.node_exec_id, "error", "TERMINATED"
)
- exec_update = self.run_and_wait(
- update_execution_status(
- node_exec.node_exec_id, ExecutionStatus.FAILED
- )
+ exec_update = self.db_client.update_execution_status(
+ node_exec.node_exec_id, ExecutionStatus.FAILED
)
- self.agent_server_client.send_execution_update(exec_update.model_dump())
+ self.db_client.send_execution_update(exec_update.model_dump())
def _validate_node_input_credentials(self, graph: Graph, user_id: str):
"""Checks all credentials for all nodes of the graph"""
@@ -900,10 +857,10 @@ class ExecutionManager(AppService):
# ------- UTILITIES ------- #
-def get_agent_server_client() -> "AgentServer":
- from backend.server.rest_api import AgentServer
+def get_db_client() -> "DatabaseManager":
+ from backend.executor import DatabaseManager
- return get_service_client(AgentServer, settings.config.agent_server_port)
+ return get_service_client(DatabaseManager, settings.config.database_api_port)
@contextmanager
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 77547cab9b..574765c348 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -5,9 +5,16 @@ from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
-from backend.data import schedule as model
from backend.data.block import BlockInput
+from backend.data.schedule import (
+ ExecutionSchedule,
+ add_schedule,
+ get_active_schedules,
+ get_schedules,
+ update_schedule,
+)
from backend.executor.manager import ExecutionManager
+from backend.util.cache import thread_cached_property
from backend.util.service import AppService, expose, get_service_client
from backend.util.settings import Config
@@ -19,14 +26,15 @@ def log(msg, **kwargs):
class ExecutionScheduler(AppService):
+
def __init__(self, refresh_interval=10):
super().__init__(port=Config().execution_scheduler_port)
self.use_db = True
self.last_check = datetime.min
self.refresh_interval = refresh_interval
- @property
- def execution_manager_client(self) -> ExecutionManager:
+ @thread_cached_property
+ def execution_client(self) -> ExecutionManager:
return get_service_client(ExecutionManager, Config().execution_manager_port)
def run_service(self):
@@ -37,7 +45,7 @@ class ExecutionScheduler(AppService):
time.sleep(self.refresh_interval)
def __refresh_jobs_from_db(self, scheduler: BackgroundScheduler):
- schedules = self.run_and_wait(model.get_active_schedules(self.last_check))
+ schedules = self.run_and_wait(get_active_schedules(self.last_check))
for schedule in schedules:
if schedule.last_updated:
self.last_check = max(self.last_check, schedule.last_updated)
@@ -59,14 +67,13 @@ class ExecutionScheduler(AppService):
def __execute_graph(self, graph_id: str, input_data: dict, user_id: str):
try:
log(f"Executing recurring job for graph #{graph_id}")
- execution_manager = self.execution_manager_client
- execution_manager.add_execution(graph_id, input_data, user_id)
+ self.execution_client.add_execution(graph_id, input_data, user_id)
except Exception as e:
logger.exception(f"Error executing graph {graph_id}: {e}")
@expose
def update_schedule(self, schedule_id: str, is_enabled: bool, user_id: str) -> str:
- self.run_and_wait(model.update_schedule(schedule_id, is_enabled, user_id))
+ self.run_and_wait(update_schedule(schedule_id, is_enabled, user_id))
return schedule_id
@expose
@@ -78,17 +85,16 @@ class ExecutionScheduler(AppService):
input_data: BlockInput,
user_id: str,
) -> str:
- schedule = model.ExecutionSchedule(
+ schedule = ExecutionSchedule(
graph_id=graph_id,
user_id=user_id,
graph_version=graph_version,
schedule=cron,
input_data=input_data,
)
- return self.run_and_wait(model.add_schedule(schedule)).id
+ return self.run_and_wait(add_schedule(schedule)).id
@expose
def get_execution_schedules(self, graph_id: str, user_id: str) -> dict[str, str]:
- query = model.get_schedules(graph_id, user_id=user_id)
- schedules: list[model.ExecutionSchedule] = self.run_and_wait(query)
+ schedules = self.run_and_wait(get_schedules(graph_id, user_id=user_id))
return {v.id: v.schedule for v in schedules}
diff --git a/autogpt_platform/backend/backend/server/integrations/router.py b/autogpt_platform/backend/backend/server/integrations/router.py
index c943600378..a44954b371 100644
--- a/autogpt_platform/backend/backend/server/integrations/router.py
+++ b/autogpt_platform/backend/backend/server/integrations/router.py
@@ -7,16 +7,7 @@ from autogpt_libs.supabase_integration_credentials_store.types import (
CredentialsType,
OAuth2Credentials,
)
-from fastapi import (
- APIRouter,
- Body,
- Depends,
- HTTPException,
- Path,
- Query,
- Request,
- Response,
-)
+from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Request
from pydantic import BaseModel, Field, SecretStr
from backend.integrations.creds_manager import IntegrationCredentialsManager
diff --git a/autogpt_platform/backend/backend/server/rest_api.py b/autogpt_platform/backend/backend/server/rest_api.py
index 4d01a93589..4e84da2292 100644
--- a/autogpt_platform/backend/backend/server/rest_api.py
+++ b/autogpt_platform/backend/backend/server/rest_api.py
@@ -17,12 +17,12 @@ from backend.data import execution as execution_db
from backend.data import graph as graph_db
from backend.data.block import BlockInput, CompletedBlockOutput
from backend.data.credit import get_block_costs, get_user_credit_model
-from backend.data.queue import RedisEventQueue
from backend.data.user import get_or_create_user
from backend.executor import ExecutionManager, ExecutionScheduler
from backend.integrations.creds_manager import IntegrationCredentialsManager
from backend.server.model import CreateGraph, SetGraphActiveVersion
-from backend.util.service import AppService, expose, get_service_client
+from backend.util.cache import thread_cached_property
+from backend.util.service import AppService, get_service_client
from backend.util.settings import AppEnvironment, Config, Settings
from .utils import get_user_id
@@ -32,21 +32,18 @@ logger = logging.getLogger(__name__)
class AgentServer(AppService):
- use_queue = True
_test_dependency_overrides = {}
_user_credit_model = get_user_credit_model()
def __init__(self):
super().__init__(port=Config().agent_server_port)
- self.event_queue = RedisEventQueue()
+ self.use_redis = True
@asynccontextmanager
async def lifespan(self, _: FastAPI):
await db.connect()
- self.event_queue.connect()
await block.initialize_blocks()
yield
- self.event_queue.close()
await db.disconnect()
def run_service(self):
@@ -299,11 +296,11 @@ class AgentServer(AppService):
return wrapper
- @property
+ @thread_cached_property
def execution_manager_client(self) -> ExecutionManager:
return get_service_client(ExecutionManager, Config().execution_manager_port)
- @property
+ @thread_cached_property
def execution_scheduler_client(self) -> ExecutionScheduler:
return get_service_client(ExecutionScheduler, Config().execution_scheduler_port)
@@ -635,11 +632,6 @@ class AgentServer(AppService):
execution_scheduler = self.execution_scheduler_client
return execution_scheduler.get_execution_schedules(graph_id, user_id)
- @expose
- def send_execution_update(self, execution_result_dict: dict[Any, Any]):
- execution_result = execution_db.ExecutionResult(**execution_result_dict)
- self.event_queue.put(execution_result)
-
@classmethod
def update_configuration(
cls,
diff --git a/autogpt_platform/backend/backend/server/ws_api.py b/autogpt_platform/backend/backend/server/ws_api.py
index e58c031c69..5e35693be4 100644
--- a/autogpt_platform/backend/backend/server/ws_api.py
+++ b/autogpt_platform/backend/backend/server/ws_api.py
@@ -7,6 +7,7 @@ from autogpt_libs.auth import parse_jwt_token
from fastapi import Depends, FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
+from backend.data import redis
from backend.data.queue import RedisEventQueue
from backend.data.user import DEFAULT_USER_ID
from backend.server.conn_manager import ConnectionManager
@@ -20,17 +21,14 @@ settings = Settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
- event_queue.connect()
manager = get_connection_manager()
fut = asyncio.create_task(event_broadcaster(manager))
fut.add_done_callback(lambda _: logger.info("Event broadcaster stopped"))
yield
- event_queue.close()
docs_url = "/docs" if settings.config.app_env == AppEnvironment.LOCAL else None
app = FastAPI(lifespan=lifespan)
-event_queue = RedisEventQueue()
_connection_manager = None
logger.info(f"CORS allow origins: {settings.config.backend_cors_allow_origins}")
@@ -51,12 +49,20 @@ def get_connection_manager():
async def event_broadcaster(manager: ConnectionManager):
- while True:
- event = event_queue.get()
- if event is not None:
- await manager.send_execution_result(event)
- else:
- await asyncio.sleep(0.1)
+ try:
+ redis.connect()
+ event_queue = RedisEventQueue()
+ while True:
+ event = event_queue.get()
+ if event:
+ await manager.send_execution_result(event)
+ else:
+ await asyncio.sleep(0.1)
+ except Exception as e:
+ logger.exception(f"Event broadcaster error: {e}")
+ raise
+ finally:
+ redis.disconnect()
async def authenticate_websocket(websocket: WebSocket) -> str:
diff --git a/autogpt_platform/backend/backend/util/cache.py b/autogpt_platform/backend/backend/util/cache.py
new file mode 100644
index 0000000000..30048e8781
--- /dev/null
+++ b/autogpt_platform/backend/backend/util/cache.py
@@ -0,0 +1,21 @@
+import threading
+from functools import wraps
+from typing import Callable, TypeVar
+
+T = TypeVar("T")
+R = TypeVar("R")
+
+
+def thread_cached_property(func: Callable[[T], R]) -> property:
+ local_cache = threading.local()
+
+ @wraps(func)
+ def wrapper(self: T) -> R:
+ if not hasattr(local_cache, "cache"):
+ local_cache.cache = {}
+ key = id(self)
+ if key not in local_cache.cache:
+ local_cache.cache[key] = func(self)
+ return local_cache.cache[key]
+
+ return property(wrapper)
diff --git a/autogpt_platform/backend/backend/util/process.py b/autogpt_platform/backend/backend/util/process.py
index cc6e09a796..218ac749d0 100644
--- a/autogpt_platform/backend/backend/util/process.py
+++ b/autogpt_platform/backend/backend/util/process.py
@@ -17,6 +17,11 @@ def get_service_name():
return _SERVICE_NAME
+def set_service_name(name: str):
+ global _SERVICE_NAME
+ _SERVICE_NAME = name
+
+
class AppProcess(ABC):
"""
A class to represent an object that can be executed in a background process.
@@ -63,9 +68,7 @@ class AppProcess(ABC):
sys.stdout = open(os.devnull, "w")
sys.stderr = open(os.devnull, "w")
- global _SERVICE_NAME
- _SERVICE_NAME = self.service_name
-
+ set_service_name(self.service_name)
logger.info(f"[{self.service_name}] Starting...")
self.run()
except (KeyboardInterrupt, SystemExit) as e:
diff --git a/autogpt_platform/backend/backend/util/retry.py b/autogpt_platform/backend/backend/util/retry.py
index ed05c259a3..5a451726c0 100644
--- a/autogpt_platform/backend/backend/util/retry.py
+++ b/autogpt_platform/backend/backend/util/retry.py
@@ -1,5 +1,6 @@
import logging
import os
+from functools import wraps
from uuid import uuid4
from tenacity import retry, stop_after_attempt, wait_exponential
@@ -21,28 +22,33 @@ def _log_prefix(resource_name: str, conn_id: str):
def conn_retry(resource_name: str, action_name: str, max_retry: int = 5):
conn_id = str(uuid4())
- def before_call(retry_state):
- prefix = _log_prefix(resource_name, conn_id)
- logger.info(f"{prefix} {action_name} started...")
-
- def after_call(retry_state):
- prefix = _log_prefix(resource_name, conn_id)
- if retry_state.outcome.failed:
- # Optionally, you can log something here if needed
- pass
- else:
- logger.info(f"{prefix} {action_name} completed!")
-
def on_retry(retry_state):
prefix = _log_prefix(resource_name, conn_id)
exception = retry_state.outcome.exception()
logger.info(f"{prefix} {action_name} failed: {exception}. Retrying now...")
- return retry(
- stop=stop_after_attempt(max_retry + 1),
- wait=wait_exponential(multiplier=1, min=1, max=30),
- before=before_call,
- after=after_call,
- before_sleep=on_retry,
- reraise=True,
- )
+ def decorator(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ prefix = _log_prefix(resource_name, conn_id)
+ logger.info(f"{prefix} {action_name} started...")
+
+ # Define the retrying strategy
+ retrying_func = retry(
+ stop=stop_after_attempt(max_retry + 1),
+ wait=wait_exponential(multiplier=1, min=1, max=30),
+ before_sleep=on_retry,
+ reraise=True,
+ )(func)
+
+ try:
+ result = retrying_func(*args, **kwargs)
+ logger.info(f"{prefix} {action_name} completed successfully.")
+ return result
+ except Exception as e:
+ logger.error(f"{prefix} {action_name} failed after retries: {e}")
+ raise
+
+ return wrapper
+
+ return decorator
diff --git a/autogpt_platform/backend/backend/util/service.py b/autogpt_platform/backend/backend/util/service.py
index b21e7be8ad..3c4532b5ad 100644
--- a/autogpt_platform/backend/backend/util/service.py
+++ b/autogpt_platform/backend/backend/util/service.py
@@ -1,19 +1,26 @@
import asyncio
+import builtins
import logging
import os
import threading
import time
import typing
-from abc import abstractmethod
-from types import UnionType
+from enum import Enum
+from types import NoneType, UnionType
from typing import (
Annotated,
Any,
Callable,
Coroutine,
+ Dict,
+ FrozenSet,
Iterator,
+ List,
+ Set,
+ Tuple,
Type,
TypeVar,
+ Union,
cast,
get_args,
get_origin,
@@ -23,8 +30,7 @@ import Pyro5.api
from pydantic import BaseModel
from Pyro5 import api as pyro
-from backend.data import db
-from backend.data.queue import AbstractEventQueue, RedisEventQueue
+from backend.data import db, redis
from backend.util.process import AppProcess
from backend.util.retry import conn_retry
from backend.util.settings import Config, Secrets
@@ -51,50 +57,59 @@ def expose(func: C) -> C:
except Exception as e:
msg = f"Error in {func.__name__}: {e.__str__()}"
logger.exception(msg)
- raise Exception(msg, e)
+ raise
# Register custom serializers and deserializers for annotated Pydantic models
for name, annotation in func.__annotations__.items():
- for model in _pydantic_models_from_type_annotation(annotation):
+ try:
+ pydantic_types = _pydantic_models_from_type_annotation(annotation)
+ except Exception as e:
+ raise TypeError(f"Error while exposing {func.__name__}: {e.__str__()}")
+
+ for model in pydantic_types:
logger.debug(
f"Registering Pyro (de)serializers for {func.__name__} annotation "
f"'{name}': {model.__qualname__}"
)
- pyro.register_class_to_dict(
- model,
- lambda obj: {
- "__class__": obj.__class__.__qualname__,
- **obj.model_dump(),
- },
- )
+ pyro.register_class_to_dict(model, _make_custom_serializer(model))
pyro.register_dict_to_class(
- model.__qualname__, _make_pyrodantic_parser(model)
+ model.__qualname__, _make_custom_deserializer(model)
)
return pyro.expose(wrapper) # type: ignore
-def _make_pyrodantic_parser(model: type[BaseModel]):
- def parse_data_into_model(qualname, data: dict):
- logger.debug(f"Parsing Pyroed {model.__qualname__} from data {data}")
+def _make_custom_serializer(model: Type[BaseModel]):
+ def custom_class_to_dict(obj):
+ data = {
+ "__class__": obj.__class__.__qualname__,
+ **obj.model_dump(),
+ }
+ logger.debug(f"Serializing {obj.__class__.__qualname__} with data: {data}")
+ return data
+
+ return custom_class_to_dict
+
+
+def _make_custom_deserializer(model: Type[BaseModel]):
+ def custom_dict_to_class(qualname, data: dict):
+ logger.debug(f"Deserializing {model.__qualname__} from data: {data}")
return model(**data)
- return parse_data_into_model
+ return custom_dict_to_class
class AppService(AppProcess):
shared_event_loop: asyncio.AbstractEventLoop
- event_queue: AbstractEventQueue = RedisEventQueue()
use_db: bool = False
- use_queue: bool = False
+ use_redis: bool = False
use_supabase: bool = False
def __init__(self, port):
self.port = port
self.uri = None
- @abstractmethod
- def run_service(self):
+ def run_service(self) -> None:
while True:
time.sleep(10)
@@ -109,8 +124,8 @@ class AppService(AppProcess):
self.shared_event_loop = asyncio.get_event_loop()
if self.use_db:
self.shared_event_loop.run_until_complete(db.connect())
- if self.use_queue:
- self.event_queue.connect()
+ if self.use_redis:
+ redis.connect()
if self.use_supabase:
from supabase import create_client
@@ -136,9 +151,9 @@ class AppService(AppProcess):
if self.use_db:
logger.info(f"[{self.__class__.__name__}] ⏳ Disconnecting DB...")
self.run_and_wait(db.disconnect())
- if self.use_queue:
+ if self.use_redis:
logger.info(f"[{self.__class__.__name__}] ⏳ Disconnecting Redis...")
- self.event_queue.close()
+ redis.disconnect()
@conn_retry("Pyro", "Starting Pyro Service")
def __start_pyro(self):
@@ -170,31 +185,53 @@ def get_service_client(service_type: Type[AS], port: int) -> AS:
logger.debug(f"Successfully connected to service [{service_name}]")
def __getattr__(self, name: str) -> Callable[..., Any]:
- return getattr(self.proxy, name)
+ res = getattr(self.proxy, name)
+ return res
return cast(AS, DynamicClient())
# --------- UTILITIES --------- #
+builtin_types = [*vars(builtins).values(), NoneType, Enum]
+
def _pydantic_models_from_type_annotation(annotation) -> Iterator[type[BaseModel]]:
# Peel Annotated parameters
if (origin := get_origin(annotation)) and origin is Annotated:
annotation = get_args(annotation)[0]
- if origin := get_origin(annotation):
- if origin is UnionType:
- types = get_args(annotation)
- else:
- types = [origin]
+ origin = get_origin(annotation)
+ args = get_args(annotation)
+
+ if origin in (
+ Union,
+ UnionType,
+ list,
+ List,
+ tuple,
+ Tuple,
+ set,
+ Set,
+ frozenset,
+ FrozenSet,
+ ):
+ for arg in args:
+ yield from _pydantic_models_from_type_annotation(arg)
+ elif origin in (dict, Dict):
+ key_type, value_type = args
+ yield from _pydantic_models_from_type_annotation(key_type)
+ yield from _pydantic_models_from_type_annotation(value_type)
else:
- types = [annotation]
+ annotype = annotation if origin is None else origin
- for annotype in types:
+ # Exclude generic types and aliases
if (
annotype is not None
- and not hasattr(typing, annotype.__name__) # avoid generics and aliases
- and issubclass(annotype, BaseModel)
+ and not hasattr(typing, getattr(annotype, "__name__", ""))
+ and isinstance(annotype, type)
):
- yield annotype
+ if issubclass(annotype, BaseModel):
+ yield annotype
+ elif annotype not in builtin_types and not issubclass(annotype, Enum):
+ raise TypeError(f"Unsupported type encountered: {annotype}")
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index 4be7c98b1e..6e552fadb8 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -117,6 +117,16 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="The port for agent server daemon to run on",
)
+ database_api_host: str = Field(
+ default="0.0.0.0",
+ description="The host for database server API to run on",
+ )
+
+ database_api_port: int = Field(
+ default=8005,
+ description="The port for database server API to run on",
+ )
+
agent_api_host: str = Field(
default="0.0.0.0",
description="The host for agent server API to run on",
diff --git a/autogpt_platform/backend/backend/util/test.py b/autogpt_platform/backend/backend/util/test.py
index 0b2adf77ce..704d6507e0 100644
--- a/autogpt_platform/backend/backend/util/test.py
+++ b/autogpt_platform/backend/backend/util/test.py
@@ -5,7 +5,7 @@ from backend.data.block import Block, initialize_blocks
from backend.data.execution import ExecutionStatus
from backend.data.model import CREDENTIALS_FIELD_NAME
from backend.data.user import create_default_user
-from backend.executor import ExecutionManager, ExecutionScheduler
+from backend.executor import DatabaseManager, ExecutionManager, ExecutionScheduler
from backend.server.rest_api import AgentServer, get_user_id
log = print
@@ -13,6 +13,7 @@ log = print
class SpinTestServer:
def __init__(self):
+ self.db_api = DatabaseManager()
self.exec_manager = ExecutionManager()
self.agent_server = AgentServer()
self.scheduler = ExecutionScheduler()
@@ -23,6 +24,7 @@ class SpinTestServer:
async def __aenter__(self):
self.setup_dependency_overrides()
+ self.db_api.__enter__()
self.agent_server.__enter__()
self.exec_manager.__enter__()
self.scheduler.__enter__()
@@ -39,6 +41,7 @@ class SpinTestServer:
self.scheduler.__exit__(exc_type, exc_val, exc_tb)
self.exec_manager.__exit__(exc_type, exc_val, exc_tb)
self.agent_server.__exit__(exc_type, exc_val, exc_tb)
+ self.db_api.__exit__(exc_type, exc_val, exc_tb)
def setup_dependency_overrides(self):
# Override get_user_id for testing
diff --git a/autogpt_platform/backend/test/data/test_credit.py b/autogpt_platform/backend/test/data/test_credit.py
index ea92d1759d..fe8fbde81c 100644
--- a/autogpt_platform/backend/test/data/test_credit.py
+++ b/autogpt_platform/backend/test/data/test_credit.py
@@ -19,7 +19,7 @@ async def test_block_credit_usage(server: SpinTestServer):
spending_amount_1 = await user_credit.spend_credits(
DEFAULT_USER_ID,
current_credit,
- AITextGeneratorBlock(),
+ AITextGeneratorBlock().id,
{"model": "gpt-4-turbo"},
0.0,
0.0,
@@ -30,7 +30,7 @@ async def test_block_credit_usage(server: SpinTestServer):
spending_amount_2 = await user_credit.spend_credits(
DEFAULT_USER_ID,
current_credit,
- AITextGeneratorBlock(),
+ AITextGeneratorBlock().id,
{"model": "gpt-4-turbo", "api_key": "owned_api_key"},
0.0,
0.0,
diff --git a/autogpt_platform/backend/test/util/test_service.py b/autogpt_platform/backend/test/util/test_service.py
index ad53f28725..458e18b76d 100644
--- a/autogpt_platform/backend/test/util/test_service.py
+++ b/autogpt_platform/backend/test/util/test_service.py
@@ -2,13 +2,12 @@ import pytest
from backend.util.service import AppService, expose, get_service_client
+TEST_SERVICE_PORT = 8765
+
class TestService(AppService):
def __init__(self):
- super().__init__(port=8005)
-
- def run_service(self):
- super().run_service()
+ super().__init__(port=TEST_SERVICE_PORT)
@expose
def add(self, a: int, b: int) -> int:
@@ -29,7 +28,7 @@ class TestService(AppService):
@pytest.mark.asyncio(scope="session")
async def test_service_creation(server):
with TestService():
- client = get_service_client(TestService, 8005)
+ client = get_service_client(TestService, TEST_SERVICE_PORT)
assert client.add(5, 3) == 8
assert client.subtract(10, 4) == 6
assert client.fun_with_async(5, 3) == 8