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): add expert budget endpoint and run source (#14399)

Abhimanyu Yadav16c7bc5a575b
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index 6d71de089b..4b994ab1b3 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -39,6 +39,7 @@ from backend.api.features.experts.models import (
ExpertIdentity,
ExpertPod,
ExpertRun,
+ ExpertRunSource,
ExpertRunStatus,
ExpertSoulFieldsPatch,
ExpertSoulUpdate,
@@ -404,6 +405,7 @@ async def list_expert_runs(
where={"userId": user_id, "expertId": expert_id, "isDeleted": False},
order={"createdAt": "desc"},
take=limit,
+ include={"AgentPreset": True},
)
if not executions:
return []
@@ -590,6 +592,13 @@ def _node_exec_inputs(
}
+def _run_source(execution: prisma.models.AgentGraphExecution) -> ExpertRunSource:
+ preset = getattr(execution, "AgentPreset", None)
+ if preset is None:
+ return "manual"
+ return "trigger" if preset.webhookId else "scheduled"
+
+
def _to_expert_run(
execution: prisma.models.AgentGraphExecution,
workflow: prisma.models.ExpertWorkflow | None,
@@ -618,6 +627,7 @@ def _to_expert_run(
output_type=output_type,
output_key=output_key,
needs_review=needs_review,
+ source=_run_source(execution),
started_at=execution.startedAt,
ended_at=execution.endedAt,
link=run_link(library_agent_id, execution.id),
@@ -1074,6 +1084,28 @@ async def update_avatar(user_id: str, expert_id: str, avatar_url: str | None) ->
return expert
+async def update_budget(
+ user_id: str, expert_id: str, weekly_budget: int | None
+) -> Expert:
+ updated = await prisma.models.Expert.prisma().update_many(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ "visibility": ResourceVisibility.PRIVATE,
+ },
+ data={"weeklyBudget": weekly_budget},
+ )
+ if updated == 0:
+ raise ExpertNotFoundError(expert_id)
+
+ expert = await get_expert(user_id, expert_id)
+ if expert is None:
+ raise ExpertNotFoundError(expert_id)
+ return expert
+
+
async def update_soul_if_current(
user_id: str,
expert_id: str,
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index 7e24605035..9d49678451 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -3480,6 +3480,29 @@ def test_to_expert_run_uses_workflow_name_and_deep_link():
)
+def test_to_expert_run_reports_how_the_run_started():
+ manual = experts_db._to_expert_run(
+ _run_execution(), _run_workflow(), "table", "result", needs_review=False
+ )
+ scheduled = experts_db._to_expert_run(
+ _run_execution(AgentPreset=SimpleNamespace(webhookId=None)),
+ _run_workflow(),
+ "table",
+ "result",
+ needs_review=False,
+ )
+ triggered = experts_db._to_expert_run(
+ _run_execution(AgentPreset=SimpleNamespace(webhookId="wh-1")),
+ _run_workflow(),
+ "table",
+ "result",
+ needs_review=False,
+ )
+ assert manual.source == "manual"
+ assert scheduled.source == "scheduled"
+ assert triggered.source == "trigger"
+
+
def test_to_expert_run_names_a_library_only_workflow():
run = experts_db._to_expert_run(
_run_execution(),
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.py
index 0b62062895..9a49cae3e8 100644
--- a/autogpt_platform/backend/backend/api/features/experts/models.py
+++ b/autogpt_platform/backend/backend/api/features/experts/models.py
@@ -186,6 +186,11 @@ class ExpertPod(BaseModel):
created_at: datetime
+# How an expert run was started: from a cron preset, a webhook preset, or
+# by hand (including from chat).
+ExpertRunSource = Literal["scheduled", "trigger", "manual"]
+
+
class ExpertRun(BaseModel):
"""One expert-attributed execution, for the /team Work surface."""
@@ -198,6 +203,7 @@ class ExpertRun(BaseModel):
# Which output pin was classified, so the viewer opens exactly that value.
output_key: str | None
needs_review: bool
+ source: ExpertRunSource = "manual"
started_at: datetime | None
ended_at: datetime | None
link: str | None
@@ -333,6 +339,15 @@ class ExpertSoulUpdate(BaseModel):
return _strip_optional_soul_field(value)
+class ExpertBudgetUpdate(BaseModel):
+ """Set an expert's weekly spend cap in credits (100 = $1).
+
+ ``None`` falls back to the platform default; ``0`` disables the cap.
+ """
+
+ weekly_budget: int | None = Field(default=None, ge=0, le=WEEKLY_BUDGET_MAX_CREDITS)
+
+
class ExpertAvatarUpdate(BaseModel):
"""Swap an expert's picture. ``None`` clears it back to the generated marble."""
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.py
index 98f11e1cf8..38fe5bf892 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py
@@ -15,6 +15,7 @@ from backend.api.features.experts.models import (
Expert,
ExpertActivity,
ExpertAvatarUpdate,
+ ExpertBudgetUpdate,
ExpertCredentialRef,
ExpertDetachPreview,
ExpertIdentity,
@@ -438,6 +439,22 @@ async def update_expert_avatar(
raise fastapi.HTTPException(status_code=404, detail=str(e))
+ "/{expert_id}/budget",
+ operation_id="update_expert_budget",
+ responses={404: {"description": "Expert not found"}},
+)
+async def update_expert_budget(
+ expert_id: str,
+ request: ExpertBudgetUpdate,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> Expert:
+ try:
+ return await experts_db.update_budget(user_id, expert_id, request.weekly_budget)
+ except experts_db.ExpertNotFoundError as e:
+ raise fastapi.HTTPException(status_code=404, detail=str(e))
+
+
@router.post(
"/{expert_id}/workflows",
operation_id="install_expert_workflow",
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
index 7263411722..41d034373b 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
@@ -21,6 +21,7 @@ from backend.api.features.experts import experts_db
from backend.api.features.experts.errors import ExpertScheduleCleanupError
from backend.api.features.experts.models import (
PROTECTED_SOUL_RULES,
+ WEEKLY_BUDGET_MAX_CREDITS,
Expert,
ExpertActivity,
ExpertActivityDay,
@@ -954,6 +955,105 @@ def test_update_expert_soul_not_found_returns_404(
# ─── Avatar ────────────────────────────────────────────────────────────
+def test_update_expert_budget_returns_updated_expert(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_budget",
+ new_callable=AsyncMock,
+ return_value=_make_expert(weekly_budget=5_000),
+ )
+
+ response = client.patch("/experts/expert-1/budget", json={"weekly_budget": 5000})
+
+ assert response.status_code == 200
+ assert response.json()["weekly_budget"] == 5_000
+ mock_update.assert_awaited_once_with(test_user_id, "expert-1", 5_000)
+
+
+def test_update_expert_budget_null_restores_default(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_budget",
+ new_callable=AsyncMock,
+ return_value=_make_expert(weekly_budget=None),
+ )
+
+ response = client.patch("/experts/expert-1/budget", json={"weekly_budget": None})
+
+ assert response.status_code == 200
+ assert response.json()["weekly_budget"] is None
+ mock_update.assert_awaited_once_with(test_user_id, "expert-1", None)
+
+
+def test_update_expert_budget_rejects_negative(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_budget",
+ new_callable=AsyncMock,
+ )
+
+ response = client.patch("/experts/expert-1/budget", json={"weekly_budget": -1})
+
+ assert response.status_code == 422
+ mock_update.assert_not_awaited()
+
+
+def test_update_expert_budget_accepts_the_upper_bound(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_budget",
+ new_callable=AsyncMock,
+ return_value=_make_expert(weekly_budget=WEEKLY_BUDGET_MAX_CREDITS),
+ )
+
+ response = client.patch(
+ "/experts/expert-1/budget", json={"weekly_budget": WEEKLY_BUDGET_MAX_CREDITS}
+ )
+
+ assert response.status_code == 200
+ mock_update.assert_awaited_once_with(
+ test_user_id, "expert-1", WEEKLY_BUDGET_MAX_CREDITS
+ )
+
+
+def test_update_expert_budget_rejects_above_the_upper_bound(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_budget",
+ new_callable=AsyncMock,
+ )
+
+ response = client.patch(
+ "/experts/expert-1/budget",
+ json={"weekly_budget": WEEKLY_BUDGET_MAX_CREDITS + 1},
+ )
+
+ assert response.status_code == 422
+ mock_update.assert_not_awaited()
+
+
+def test_update_expert_budget_not_found_returns_404(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_budget",
+ new_callable=AsyncMock,
+ side_effect=experts_db.ExpertNotFoundError("expert-1"),
+ )
+
+ response = client.patch("/experts/expert-1/budget", json={"weekly_budget": 100})
+
+ assert response.status_code == 404
+
+
def test_update_expert_avatar_returns_updated_expert(
mocker: pytest_mock.MockerFixture,
test_user_id: str,
diff --git a/autogpt_platform/backend/snapshots/expert_runs_list b/autogpt_platform/backend/snapshots/expert_runs_list
index 63e23955e9..bb3ace8a12 100644
--- a/autogpt_platform/backend/snapshots/expert_runs_list
+++ b/autogpt_platform/backend/snapshots/expert_runs_list
@@ -9,6 +9,7 @@
"needs_review": false,
"output_key": "result",
"output_type": "table",
+ "source": "manual",
"started_at": null,
"status": "completed"
},
@@ -22,6 +23,7 @@
"needs_review": false,
"output_key": "result",
"output_type": "doc",
+ "source": "manual",
"started_at": null,
"status": "completed"
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 69d7f02f20..03946d4963 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -6501,6 +6501,52 @@
}
}
},
+ "/api/experts/{expert_id}/budget": {
+ "patch": {
+ "tags": ["v2", "experts", "experts", "private"],
+ "summary": "Update Expert Budget",
+ "operationId": "update_expert_budget",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Expert Id" }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ExpertBudgetUpdate" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/Expert" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Expert not found" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/experts/{expert_id}/credentials": {
"get": {
"tags": ["v2", "experts", "experts", "private"],
@@ -19969,6 +20015,20 @@
"title": "ExpertAvatarUpdate",
"description": "Swap an expert's picture. ``None`` clears it back to the generated marble."
},
+ "ExpertBudgetUpdate": {
+ "properties": {
+ "weekly_budget": {
+ "anyOf": [
+ { "type": "integer", "maximum": 1000000.0, "minimum": 0.0 },
+ { "type": "null" }
+ ],
+ "title": "Weekly Budget"
+ }
+ },
+ "type": "object",
+ "title": "ExpertBudgetUpdate",
+ "description": "Set an expert's weekly spend cap in credits (100 = $1).\n\n``None`` falls back to the platform default; ``0`` disables the cap."
+ },
"ExpertCredentialRef": {
"properties": {
"credential_id": { "type": "string", "title": "Credential Id" },
@@ -20061,6 +20121,12 @@
"title": "Output Key"
},
"needs_review": { "type": "boolean", "title": "Needs Review" },
+ "source": {
+ "type": "string",
+ "enum": ["scheduled", "trigger", "manual"],
+ "title": "Source",
+ "default": "manual"
+ },
"started_at": {
"anyOf": [
{ "type": "string", "format": "date-time" },