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.

fix(backend/copilot): price run_block with the resolved credentials (#15633)

qxyuan8530beded6abdaf
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index ce2405510c..548fc8f252 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -349,8 +349,10 @@ async def execute_block(
try:
for field_name, cred_meta in matched_credentials.items():
credential_field_name = field_name
- if field_name not in input_data:
- input_data[field_name] = cred_meta.model_dump()
+ # Always overwrite: the block runs with the resolved
+ # credential below, so the input it is priced on must name
+ # that same credential, not whatever the model passed.
+ input_data[field_name] = cred_meta.model_dump()
if cred_meta.provider == ProviderName.CODEX:
lease = await creds_manager.acquire_lease(user_id, cred_meta.id)
credential_leases[field_name] = lease
@@ -1404,8 +1406,10 @@ async def check_spend_approval(
threshold (SECRT-2599). None means the block may run."""
if session.expert_id is None:
return None
+ # Price with the credentials the run will use, not the model's own.
+ resolved = {f: m.model_dump() for f, m in prep.matched_credentials.items()}
cost, _ = block_usage_cost(
- prep.block, prep.input_data, use_preflight_estimate=False
+ prep.block, {**prep.input_data, **resolved}, use_preflight_estimate=False
)
if cost <= 0:
return None
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index b5d635d6b7..2cf1834523 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -19,6 +19,7 @@ from backend.copilot.tools.helpers import (
BlockPreparation,
_single_provider,
check_hitl_review,
+ check_spend_approval,
execute_block,
get_block_provider,
get_inputs_from_schema,
@@ -204,6 +205,102 @@ class TestExecuteBlockCreditCharging:
assert call_kwargs["cost"] == 10
assert call_kwargs["metadata"].reason == "copilot_block_execution"
+ async def test_prices_with_resolved_credentials_not_model_supplied(self):
+ """A credentials value the model wrote into input_data must not change
+ the price: the block runs with the resolved credential, so it is priced
+ (and charged) with that one."""
+ block = _make_block()
+ credit_patch, mock_credit = _patch_credit_db(get_credits_return=100)
+ resolved = CredentialsMetaInput(
+ id=exa_credentials.id,
+ provider=exa_credentials.provider,
+ type=exa_credentials.type,
+ )
+ creds_manager_cls = MagicMock()
+ creds_manager_cls.return_value.get = AsyncMock(return_value=exa_credentials)
+ priced: list[dict] = []
+
+ def _price(_block, input_data, **_kwargs):
+ priced.append(dict(input_data))
+ creds = input_data.get("credentials") or {}
+ return (10, {}) if creds.get("id") == exa_credentials.id else (0, {})
+
+ with (
+ _patch_workspace(),
+ _patch_user_db(),
+ patch("backend.copilot.tools.helpers.block_usage_cost", side_effect=_price),
+ patch(
+ "backend.copilot.tools.helpers.IntegrationCredentialsManager",
+ creds_manager_cls,
+ ),
+ credit_patch,
+ ):
+ result = await execute_block(
+ block=block,
+ block_id="block-1",
+ input_data={
+ "text": "hello",
+ "credentials": {"id": "stub", "provider": "exa", "type": "api_key"},
+ },
+ user_id=_USER,
+ session_id=_SESSION,
+ node_exec_id="exec-stub",
+ matched_credentials={"credentials": resolved},
+ dry_run=False,
+ )
+
+ assert isinstance(result, BlockOutputResponse)
+ assert priced and priced[0]["credentials"]["id"] == exa_credentials.id
+ mock_credit.spend_credits.assert_awaited_once()
+ assert mock_credit.spend_credits.call_args.kwargs["cost"] == 10
+
+ async def test_spend_approval_prices_with_resolved_credentials(self):
+ """The expert spend threshold is judged on what the run will cost, so a
+ credentials value the model wrote must not hide a paid block from it."""
+ resolved = CredentialsMetaInput(
+ id=exa_credentials.id,
+ provider=exa_credentials.provider,
+ type=exa_credentials.type,
+ )
+ prep = BlockPreparation(
+ block=_make_block(),
+ block_id="block-1",
+ input_data={
+ "text": "hello",
+ "credentials": {"id": "stub", "provider": "exa", "type": "api_key"},
+ },
+ matched_credentials={"credentials": resolved},
+ input_schema={},
+ credentials_fields={"credentials"},
+ required_non_credential_keys=set(),
+ provided_input_keys={"text"},
+ synthetic_graph_id=f"{COPILOT_SESSION_PREFIX}{_SESSION}",
+ synthetic_node_id=f"{COPILOT_NODE_PREFIX}block-1",
+ )
+
+ def _price(_block, input_data, **_kwargs):
+ creds = input_data.get("credentials") or {}
+ return (10, {}) if creds.get("id") == exa_credentials.id else (0, {})
+
+ approvals = MagicMock()
+ approvals.spend_approval_required = AsyncMock(return_value=None)
+ with (
+ patch("backend.copilot.tools.helpers.block_usage_cost", side_effect=_price),
+ patch(
+ "backend.copilot.tools.helpers.spend_approval_db",
+ return_value=approvals,
+ ),
+ ):
+ result = await check_spend_approval(
+ prep, _USER, make_session(_USER, expert_id="expert-a")
+ )
+
+ assert result is None
+ approvals.spend_approval_required.assert_awaited_once()
+ # The model's own value stays on the request; only the price follows
+ # the resolved credential.
+ assert prep.input_data["credentials"]["id"] == "stub"
+
async def test_returns_error_when_insufficient_credits_before_exec(self):
"""Pre-execution check should return ErrorResponse when balance < cost."""
block = _make_block()