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.
hotfix(backend): Avoid executing any agent with zero balance (#9902)
Zamil Majdyf5a07f1a3544
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex 1cf49fa856..704ed88e33 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -945,7 +945,7 @@ class BetaUserCredit(UserCredit):class DisabledUserCredit(UserCreditBase):async def get_credits(self, *args, **kwargs) -> int:- return 0+ return 100async def get_transaction_history(self, *args, **kwargs) -> TransactionHistory:return TransactionHistory(transactions=[], next_transaction_time=None)diff --git a/autogpt_platform/backend/backend/executor/database.py b/autogpt_platform/backend/backend/executor/database.pyindex 5ad4791e29..4cb921d631 100644--- a/autogpt_platform/backend/backend/executor/database.py+++ b/autogpt_platform/backend/backend/executor/database.py@@ -53,6 +53,10 @@ async def _spend_credits(return await _user_credit_model.spend_credits(user_id, cost, metadata)+async def _get_credits(user_id: str) -> int:+ return await _user_credit_model.get_credits(user_id)++class DatabaseManager(AppService):def run_service(self) -> None:@@ -97,6 +101,7 @@ class DatabaseManager(AppService):# Creditsspend_credits = exposed_run_and_wait(_spend_credits)+ get_credits = exposed_run_and_wait(_get_credits)# User + User Metadata + User Integrationsget_user_metadata = exposed_run_and_wait(get_user_metadata)diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.pyindex b710472976..f08c7e4155 100644--- a/autogpt_platform/backend/backend/executor/manager.py+++ b/autogpt_platform/backend/backend/executor/manager.py@@ -598,11 +598,11 @@ class Executor:node_exec: NodeExecutionEntry,execution_count: int,execution_stats: GraphExecutionStats,- ) -> int:+ ):block = get_block(node_exec.block_id)if not block:logger.error(f"Block {node_exec.block_id} not found.")- return execution_count+ returncost, matching_filter = block_usage_cost(block=block, input_data=node_exec.data)if cost > 0:@@ -622,7 +622,7 @@ class Executor:)execution_stats.cost += cost- cost, execution_count = execution_usage_cost(execution_count)+ cost, usage_count = execution_usage_cost(execution_count)if cost > 0:cls.db_client.spend_credits(user_id=node_exec.user_id,@@ -631,16 +631,14 @@ class Executor:graph_exec_id=node_exec.graph_exec_id,graph_id=node_exec.graph_id,input={- "execution_count": execution_count,+ "execution_count": usage_count,"charge": "Execution Cost",},- reason=f"Execution Cost for ex_id:{node_exec.graph_exec_id} g_id:{node_exec.graph_id}",+ reason=f"Execution Cost for {usage_count} blocks of ex_id:{node_exec.graph_exec_id} g_id:{node_exec.graph_id}",),)execution_stats.cost += cost- return execution_count-@classmethod@time_measureddef _on_graph_execution(@@ -677,11 +675,18 @@ class Executor:cancel_thread.start()try:+ if cls.db_client.get_credits(graph_exec.user_id) <= 0:+ raise InsufficientBalanceError(+ user_id=graph_exec.user_id,+ message="You have no credits left to run an agent.",+ balance=0,+ amount=1,+ )+queue = ExecutionQueue[NodeExecutionEntry]()for node_exec in graph_exec.start_node_execs:queue.add(node_exec)- exec_cost_counter = 0running_executions: dict[str, AsyncResult] = {}def make_exec_callback(exec_data: NodeExecutionEntry):@@ -737,9 +742,9 @@ class Executor:)try:- exec_cost_counter = cls._charge_usage(+ cls._charge_usage(node_exec=queued_node_exec,- execution_count=exec_cost_counter + 1,+ execution_count=increment_execution_count(graph_exec.user_id),execution_stats=execution_stats,)except InsufficientBalanceError as error:@@ -1101,6 +1106,19 @@ def synchronized(key: str, timeout: int = 60):lock.release()+def increment_execution_count(user_id: str) -> int:+ """+ Increment the execution count for a given user,+ this will be used to charge the user for the execution cost.+ """+ r = redis.get_redis()+ k = f"uec:{user_id}" # User Execution Count global key+ counter = cast(int, r.incr(k))+ if counter == 1:+ r.expire(k, settings.config.execution_counter_expiration_time)+ return counter++def llprint(message: str):"""Low-level print/log helper function for use in signal handlers.diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex ca912f9f61..b23bbd7212 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -104,19 +104,21 @@ class UsageTransactionMetadata(BaseModel):def execution_usage_cost(execution_count: int) -> tuple[int, int]:"""- Calculate the cost of executing a graph based on the number of executions.+ Calculate the cost of executing a graph based on the current number of node executions.Args:- execution_count: Number of executions+ execution_count: Number of node executionsReturns:- Tuple of cost amount and remaining execution count+ Tuple of cost amount and the number of execution count that is included in the cost."""return (- execution_count- // config.execution_cost_count_threshold- * config.execution_cost_per_threshold,- execution_count % config.execution_cost_count_threshold,+ (+ config.execution_cost_per_threshold+ if execution_count % config.execution_cost_count_threshold == 0+ else 0+ ),+ config.execution_cost_count_threshold,)diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 272e4f578d..6da50a0629 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -117,6 +117,10 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):default=1,description="Cost per execution in cents after each threshold.",)+ execution_counter_expiration_time: int = Field(+ default=60 * 60 * 24,+ description="Time in seconds after which the execution counter is reset.",+ )model_config = SettingsConfigDict(env_file=".env",