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 entity, hire/install API, roster seeds (#13685)
Ubbe127cf0e1339b
diff --git a/autogpt_platform/backend/backend/api/features/experts/__init__.py b/autogpt_platform/backend/backend/api/features/experts/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.pynew file mode 100644index 0000000000..a5d72faceb--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py@@ -0,0 +1,243 @@+import logging++import prisma.errors+import prisma.models++from backend.api.features.experts.models import Expert, ExpertWorkflowRef, HireResult+from backend.api.features.library import db as library_db++logger = logging.getLogger(__name__)++_WORKFLOW_ROW_INCLUDE = {"LibraryAgent": True, "StoreListingVersion": True}+_WORKFLOW_INCLUDE = {"Workflows": {"include": _WORKFLOW_ROW_INCLUDE}}+++class ExpertTemplateNotFoundError(Exception):+ def __init__(self, template_id: str):+ super().__init__(f"Expert template {template_id} not found")+ self.template_id = template_id+++class ExpertNotFoundError(Exception):+ def __init__(self, expert_id: str):+ super().__init__(f"Expert {expert_id} not found")+ self.expert_id = expert_id+++def _to_workflow_ref(row: prisma.models.ExpertWorkflow) -> ExpertWorkflowRef:+ listing = row.StoreListingVersion+ library_agent = row.LibraryAgent+ return ExpertWorkflowRef(+ id=row.id,+ store_listing_version_id=row.storeListingVersionId,+ library_agent_id=row.libraryAgentId,+ graph_id=library_agent.agentGraphId if library_agent else None,+ name=listing.name if listing else None,+ description=listing.description if listing else None,+ )+++def _to_model(row: prisma.models.Expert) -> Expert:+ return Expert(+ id=row.id,+ name=row.name,+ avatar_url=row.avatarUrl,+ role=row.role,+ tagline=row.tagline,+ identity=row.identity,+ is_template=row.isTemplate,+ source_template_id=row.sourceTemplateId,+ is_archived=row.isArchived,+ workflows=[_to_workflow_ref(w) for w in row.Workflows or []],+ )+++async def list_templates() -> list[Expert]:+ rows = await prisma.models.Expert.prisma().find_many(+ where={"isTemplate": True, "isArchived": False},+ include=_WORKFLOW_INCLUDE,+ )+ return [_to_model(row) for row in rows]+++async def list_experts(user_id: str) -> list[Expert]:+ rows = await prisma.models.Expert.prisma().find_many(+ where={+ "ownerUserId": user_id,+ "isTemplate": False,+ "isArchived": False,+ },+ include=_WORKFLOW_INCLUDE,+ )+ return [_to_model(row) for row in rows]+++async def get_expert(user_id: str, expert_id: str) -> Expert | None:+ row = await prisma.models.Expert.prisma().find_first(+ where={"id": expert_id, "ownerUserId": user_id, "isTemplate": False},+ include=_WORKFLOW_INCLUDE,+ )+ return _to_model(row) if row is not None else None+++async def hire_expert(user_id: str, template_id: str, name: str | None) -> HireResult:+ template = await prisma.models.Expert.prisma().find_first(+ where={"id": template_id, "isTemplate": True, "isArchived": False},+ include=_WORKFLOW_INCLUDE,+ )+ if template is None:+ raise ExpertTemplateNotFoundError(template_id)++ existing = await prisma.models.Expert.prisma().find_first(+ where={"ownerUserId": user_id, "sourceTemplateId": template_id},+ include=_WORKFLOW_INCLUDE,+ )+ if existing is not None:+ return await _existing_hire_result(existing)++ create_data: dict = {+ "ownerUserId": user_id,+ "name": name or template.name,+ "avatarUrl": template.avatarUrl,+ "role": template.role,+ "tagline": template.tagline,+ "identity": template.identity,+ "sourceTemplateId": template.id,+ }+ if template.toolProfile is not None:+ create_data["toolProfile"] = template.toolProfile+ try:+ expert = await prisma.models.Expert.prisma().create(data=create_data)+ except prisma.errors.UniqueViolationError:+ # Lost a concurrent hire race; the winner's row satisfies idempotency.+ raced = await prisma.models.Expert.prisma().find_first(+ where={"ownerUserId": user_id, "sourceTemplateId": template_id},+ include=_WORKFLOW_INCLUDE,+ )+ if raced is None:+ raise+ return await _existing_hire_result(raced)++ failed = await _install_preloads(expert.id, user_id, template.Workflows or [])++ hydrated = await prisma.models.Expert.prisma().find_unique(+ where={"id": expert.id}, include=_WORKFLOW_INCLUDE+ )+ if hydrated is None:+ raise ExpertNotFoundError(expert.id)+ return HireResult(expert=_to_model(hydrated), failed_preloads=failed)+++async def _existing_hire_result(row: prisma.models.Expert) -> HireResult:+ """Idempotent-hire result for an already-existing hired copy.++ Re-hiring an archived expert revives it — the unique+ (ownerUserId, sourceTemplateId) constraint means a fresh row cannot be+ created, and returning the archived row as-is would hand back a+ "successful" hire that stays invisible to list_experts/get_expert.+ """+ if row.isArchived:+ revived = await prisma.models.Expert.prisma().update(+ where={"id": row.id},+ data={"isArchived": False},+ include=_WORKFLOW_INCLUDE,+ )+ if revived is not None:+ row = revived+ return HireResult(expert=_to_model(row), failed_preloads=[])+++async def _install_preloads(+ expert_id: str, user_id: str, preloads: list[prisma.models.ExpertWorkflow]+) -> list[str]:+ """Install template preloads into the hiring user's library.++ Honest partial hire: a failed preload is logged and reported, never+ fatal to the hire itself.+ """+ failed: list[str] = []+ for preload in preloads:+ if preload.storeListingVersionId is None:+ continue+ try:+ library_agent = await library_db.add_store_agent_to_library(+ preload.storeListingVersionId, user_id+ )+ await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": expert_id,+ "storeListingVersionId": preload.storeListingVersionId,+ "libraryAgentId": library_agent.id,+ }+ )+ except Exception:+ logger.exception(+ f"Failed to install preload {preload.storeListingVersionId} "+ f"on expert #{expert_id} for user #{user_id}"+ )+ failed.append(+ preload.StoreListingVersion.name+ if preload.StoreListingVersion+ else preload.storeListingVersionId+ )+ return failed+++async def install_workflow(+ user_id: str, expert_id: str, store_listing_version_id: str+) -> ExpertWorkflowRef:+ expert = await prisma.models.Expert.prisma().find_first(+ where={+ "id": expert_id,+ "ownerUserId": user_id,+ "isTemplate": False,+ "isArchived": False,+ }+ )+ if expert is None:+ raise ExpertNotFoundError(expert_id)++ existing = await prisma.models.ExpertWorkflow.prisma().find_first(+ where={+ "expertId": expert_id,+ "storeListingVersionId": store_listing_version_id,+ },+ include=_WORKFLOW_ROW_INCLUDE,+ )+ if existing is not None:+ return _to_workflow_ref(existing)++ library_agent = await library_db.add_store_agent_to_library(+ store_listing_version_id, user_id+ )+ try:+ row = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": expert_id,+ "storeListingVersionId": store_listing_version_id,+ "libraryAgentId": library_agent.id,+ },+ include=_WORKFLOW_ROW_INCLUDE,+ )+ except prisma.errors.UniqueViolationError:+ # Lost a concurrent duplicate-install race; return the winner's row.+ raced = await prisma.models.ExpertWorkflow.prisma().find_first(+ where={+ "expertId": expert_id,+ "storeListingVersionId": store_listing_version_id,+ },+ include=_WORKFLOW_ROW_INCLUDE,+ )+ if raced is None:+ raise+ return _to_workflow_ref(raced)+ return _to_workflow_ref(row)+++async def archive_expert(user_id: str, expert_id: str) -> None:+ updated = await prisma.models.Expert.prisma().update_many(+ where={"id": expert_id, "ownerUserId": user_id, "isTemplate": False},+ data={"isArchived": True},+ )+ if updated == 0:+ raise ExpertNotFoundError(expert_id)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.pynew file mode 100644index 0000000000..96cf49d73c--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py@@ -0,0 +1,242 @@+import uuid+from unittest.mock import AsyncMock, patch++import prisma.models+import pytest++import backend.api.features.store.model as store_model+from backend.api.features.experts import experts_db+from backend.api.model import CreateGraph+from backend.blocks.io import AgentInputBlock+from backend.data.graph import Graph, Node+from backend.data.user import get_or_create_user+from backend.usecases.sample import create_test_user+from backend.util.test import SpinTestServer++[email protected](scope="session", autouse=True)+def mock_embedding_functions():+ """Mock embedding functions to avoid database/API dependencies+ (mirrors backend/data/graph_test.py)."""+ with patch(+ "backend.api.features.store.db.ensure_embedding",+ new_callable=AsyncMock,+ return_value=True,+ ):+ yield+++async def test_user():+ return await create_test_user()+++async def other_user():+ return await create_test_user(alt_user=True)+++async def _create_seed_user():+ suffix = uuid.uuid4().hex[:8]+ return await get_or_create_user(+ {+ "sub": str(uuid.uuid4()),+ "email": f"expert-seed-{suffix}@example.com",+ "name": "Seed Owner",+ }+ )+++async def _seed_store_listing(server: SpinTestServer) -> str:+ """Create a graph plus an APPROVED store listing on top of it.++ Returns the StoreListingVersion ID, ready for+ ``add_store_agent_to_library``. Mirrors the seeding pattern from+ ``backend/data/graph_test.py::test_access_store_listing_graph``.+ """+ owner = await _create_seed_user()+ admin = await _create_seed_user()++ graph = Graph(+ name=f"Expert seed graph {uuid.uuid4().hex[:8]}",+ description="Seed graph for expert workflow installs",+ nodes=[+ Node(+ block_id=AgentInputBlock().id,+ input_default={"name": "input_1"},+ ),+ ],+ links=[],+ )+ created_graph = await server.agent_server.test_create_graph(+ CreateGraph(graph=graph), owner.id+ )++ # A Profile is required for store submissions; get_or_create_user+ # already ensures one for every user.+ listing = await server.agent_server.test_create_store_listing(+ store_model.StoreSubmissionRequest(+ graph_id=created_graph.id,+ graph_version=created_graph.version,+ slug=created_graph.id,+ name=f"Seed listing {uuid.uuid4().hex[:8]}",+ sub_heading="Seed sub heading",+ video_url=None,+ image_urls=[],+ description="Seed description",+ categories=[],+ ),+ owner.id,+ )+ slv_id = listing.listing_version_id+ assert slv_id is not None, "Failed to create store listing"++ await server.agent_server.test_review_store_listing(+ store_model.ReviewSubmissionRequest(+ store_listing_version_id=slv_id,+ is_approved=True,+ comments="seed",+ ),+ user_id=admin.id,+ )+ return slv_id+++async def _seed_template(+ name: str, preload_listings: list[str]+) -> prisma.models.Expert:+ """Create an Expert roster template plus ExpertWorkflow preload rows.++ The stored name gets a unique suffix so ad-hoc test templates never+ collide with seed.ROSTER's real roster names — seed._upsert_template+ resolves templates by name, and a bare "Maria" here would be silently+ adopted and overwritten by test_seed_roster_round_trip.+ """+ template = await prisma.models.Expert.prisma().create(+ data={+ "name": f"{name} {uuid.uuid4().hex[:8]}",+ "role": f"{name}'s role",+ "identity": f"You are {name}, an expert.",+ "isTemplate": True,+ }+ )+ for slv_id in preload_listings:+ await prisma.models.ExpertWorkflow.prisma().create(+ data={"expertId": template.id, "storeListingVersionId": slv_id}+ )+ return template++[email protected](loop_scope="session")+async def test_hire_expert_is_idempotent(server: SpinTestServer, test_user):+ template = await _seed_template(name="Maria", preload_listings=[])+ first = await experts_db.hire_expert(test_user.id, template.id, None)+ second = await experts_db.hire_expert(test_user.id, template.id, None)+ assert first.expert.id == second.expert.id+ assert not first.expert.is_template+ assert first.expert.source_template_id == template.id++[email protected](loop_scope="session")+async def test_rehire_after_archive_revives_expert(server: SpinTestServer, test_user):+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(test_user.id, template.id, None)+ await experts_db.archive_expert(test_user.id, hired.expert.id)++ revived = await experts_db.hire_expert(test_user.id, template.id, None)++ assert revived.expert.id == hired.expert.id+ assert not revived.expert.is_archived+ assert hired.expert.id in {+ e.id for e in await experts_db.list_experts(test_user.id)+ }++[email protected](loop_scope="session")+async def test_install_workflow_on_archived_expert_raises(+ server: SpinTestServer, test_user+):+ slv_id = await _seed_store_listing(server)+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(test_user.id, template.id, None)+ await experts_db.archive_expert(test_user.id, hired.expert.id)++ with pytest.raises(experts_db.ExpertNotFoundError):+ await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)++[email protected](loop_scope="session")+async def test_hire_installs_preloads_into_library(server: SpinTestServer, test_user):+ slv_id = await _seed_store_listing(server)+ template = await _seed_template(name="Maria", preload_listings=[slv_id])+ result = await experts_db.hire_expert(test_user.id, template.id, None)+ wf = result.expert.workflows[0]+ assert wf.library_agent_id is not None+ assert wf.store_listing_version_id == slv_id+ assert result.failed_preloads == []++[email protected](loop_scope="session")+async def test_hire_reports_failed_preload_without_sinking_hire(+ server: SpinTestServer, test_user+):+ slv_id = await _seed_store_listing(server)+ template = await _seed_template(name="Maria", preload_listings=[slv_id])+ with patch.object(+ experts_db.library_db,+ "add_store_agent_to_library",+ new_callable=AsyncMock,+ side_effect=RuntimeError("install exploded"),+ ):+ result = await experts_db.hire_expert(test_user.id, template.id, None)+ assert not result.expert.is_template+ assert result.expert.workflows == []+ assert len(result.failed_preloads) == 1++[email protected](loop_scope="session")+async def test_get_expert_scopes_by_owner(+ server: SpinTestServer, test_user, other_user+):+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(test_user.id, template.id, None)+ assert await experts_db.get_expert(other_user.id, hired.expert.id) is None+ assert await experts_db.get_expert(test_user.id, hired.expert.id) is not None++[email protected](loop_scope="session")+async def test_install_workflow_duplicate_returns_existing(+ server: SpinTestServer, test_user+):+ slv_id = await _seed_store_listing(server)+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(test_user.id, template.id, None)+ a = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)+ b = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)+ assert a.id == b.id+ assert a.library_agent_id is not None+ assert a.store_listing_version_id == slv_id++[email protected](loop_scope="session")+async def test_seed_roster_round_trip(server: SpinTestServer):+ from backend.api.features.experts import seed++ first_ids = await seed.seed_roster()+ assert len(first_ids) == 3++ templates = await experts_db.list_templates()+ seeded = {t.name: t for t in templates if t.id in first_ids}+ assert {e["name"] for e in seed.ROSTER} == set(seeded)+ for entry in seed.ROSTER:+ template = seeded[entry["name"]]+ assert template.is_template+ assert template.role == entry["role"]+ assert template.identity == entry["identity"]++ second_ids = await seed.seed_roster()+ assert first_ids == second_ids++ templates_after = await experts_db.list_templates()+ seeded_after = [t for t in templates_after if t.id in second_ids]+ assert len(seeded_after) == 3diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.pynew file mode 100644index 0000000000..139b2571e8--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/models.py@@ -0,0 +1,28 @@+from pydantic import BaseModel+++class ExpertWorkflowRef(BaseModel):+ id: str+ store_listing_version_id: str | None+ library_agent_id: str | None+ graph_id: str | None+ name: str | None+ description: str | None+++class Expert(BaseModel):+ id: str+ name: str+ avatar_url: str | None+ role: str+ tagline: str | None+ identity: str+ is_template: bool+ source_template_id: str | None+ is_archived: bool+ workflows: list[ExpertWorkflowRef]+++class HireResult(BaseModel):+ expert: Expert+ failed_preloads: list[str]diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.pynew file mode 100644index 0000000000..f7501a12dc--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py@@ -0,0 +1,99 @@+import autogpt_libs.auth as autogpt_auth_lib+import fastapi+from fastapi import APIRouter, Security+from pydantic import BaseModel, Field++from backend.api.features.experts import experts_db+from backend.api.features.experts.models import Expert, ExpertWorkflowRef, HireResult++router = APIRouter(+ prefix="/experts",+ tags=["experts", "private"],+ dependencies=[Security(autogpt_auth_lib.requires_user)],+)+++class HireRequest(BaseModel):+ template_id: str+ name: str | None = Field(default=None, max_length=100)+++class InstallWorkflowRequest(BaseModel):+ store_listing_version_id: str++[email protected]("/templates", operation_id="list_expert_templates")+async def list_expert_templates() -> list[Expert]:+ return await experts_db.list_templates()+++ "",+ operation_id="hire_expert",+ responses={404: {"description": "Expert template not found"}},+)+async def hire_expert(+ request: HireRequest,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> HireResult:+ try:+ return await experts_db.hire_expert(user_id, request.template_id, request.name)+ except experts_db.ExpertTemplateNotFoundError as e:+ raise fastapi.HTTPException(status_code=404, detail=str(e))++[email protected]("", operation_id="list_experts")+async def list_experts(+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> list[Expert]:+ return await experts_db.list_experts(user_id)+++ "/{expert_id}",+ operation_id="get_expert",+ responses={404: {"description": "Expert not found"}},+)+async def get_expert(+ expert_id: str,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> Expert:+ expert = await experts_db.get_expert(user_id, expert_id)+ if expert is None:+ raise fastapi.HTTPException(status_code=404, detail="Expert not found")+ return expert+++ "/{expert_id}/workflows",+ operation_id="install_expert_workflow",+ responses={404: {"description": "Expert not found"}},+)+async def install_expert_workflow(+ expert_id: str,+ request: InstallWorkflowRequest,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> ExpertWorkflowRef:+ try:+ return await experts_db.install_workflow(+ user_id, expert_id, request.store_listing_version_id+ )+ except experts_db.ExpertNotFoundError as e:+ raise fastapi.HTTPException(status_code=404, detail=str(e))+++ "/{expert_id}",+ operation_id="archive_expert",+ status_code=204,+ responses={404: {"description": "Expert not found"}},+)+async def archive_expert(+ expert_id: str,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> fastapi.Response:+ try:+ await experts_db.archive_expert(user_id, expert_id)+ except experts_db.ExpertNotFoundError as e:+ raise fastapi.HTTPException(status_code=404, detail=str(e))+ return fastapi.Response(status_code=204)diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.pynew file mode 100644index 0000000000..8d74a9f416--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py@@ -0,0 +1,293 @@+"""Tests for the experts API routes.++Pattern mirrors backend/api/features/library/routes_test.py: a local FastAPI+app, the global `mock_jwt_user` auth override fixture, and `experts_db` mocked+with AsyncMock at the route module's import site.+"""++import json+from unittest.mock import AsyncMock++import fastapi+import fastapi.testclient+import pytest+import pytest_mock+from autogpt_libs.auth.dependencies import get_request_context+from autogpt_libs.auth.jwt_utils import get_jwt_payload+from pytest_snapshot.plugin import Snapshot++from backend.api.features.experts import experts_db+from backend.api.features.experts.models import Expert, ExpertWorkflowRef, HireResult+from backend.api.features.experts.routes import router++app = fastapi.FastAPI()+app.include_router(router)++client = fastapi.testclient.TestClient(app)++[email protected](autouse=True)+def setup_app_auth(mock_jwt_user):+ """Setup auth overrides for all tests in this module"""+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ app.dependency_overrides[get_request_context] = mock_jwt_user["get_request_context"]+ yield+ app.dependency_overrides.clear()+++def _make_expert(**overrides) -> Expert:+ values = {+ "id": "expert-1",+ "name": "Maria",+ "avatar_url": None,+ "role": "Marketing Specialist",+ "tagline": "Grows your audience",+ "identity": "You are Maria, a pragmatic marketing specialist.",+ "is_template": False,+ "source_template_id": "template-1",+ "is_archived": False,+ "workflows": [],+ }+ values.update(overrides)+ return Expert(**values)+++def _make_workflow_ref(**overrides) -> ExpertWorkflowRef:+ values = {+ "id": "workflow-ref-1",+ "store_listing_version_id": "listing-version-1",+ "library_agent_id": "library-agent-1",+ "graph_id": "graph-1",+ "name": "SEO Blog Writer",+ "description": "Writes SEO-optimized blog posts",+ }+ values.update(overrides)+ return ExpertWorkflowRef(**values)+++# ─── List templates ────────────────────────────────────────────────────+++def test_list_expert_templates(+ mocker: pytest_mock.MockerFixture,+ configured_snapshot: Snapshot,+) -> None:+ template = _make_expert(+ id="template-1",+ is_template=True,+ source_template_id=None,+ workflows=[+ _make_workflow_ref(library_agent_id=None, graph_id=None),+ ],+ )+ mock_list = mocker.patch(+ "backend.api.features.experts.routes.experts_db.list_templates",+ new_callable=AsyncMock,+ return_value=[template],+ )++ response = client.get("/experts/templates")++ assert response.status_code == 200+ data = response.json()+ assert len(data) == 1+ assert data[0]["id"] == "template-1"+ assert data[0]["is_template"] is True+ mock_list.assert_awaited_once_with()++ configured_snapshot.assert_match(+ json.dumps(data, indent=2, sort_keys=True), "expert_templates_list"+ )+++# ─── Hire ──────────────────────────────────────────────────────────────+++def test_hire_expert_returns_expert_and_empty_failed_preloads(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ hired = _make_expert()+ mock_hire = mocker.patch(+ "backend.api.features.experts.routes.experts_db.hire_expert",+ new_callable=AsyncMock,+ return_value=HireResult(expert=hired, failed_preloads=[]),+ )++ response = client.post("/experts", json={"template_id": "template-1"})++ assert response.status_code == 200+ data = response.json()+ assert data["expert"]["id"] == "expert-1"+ assert data["failed_preloads"] == []+ mock_hire.assert_awaited_once_with(test_user_id, "template-1", None)+++def test_hire_expert_twice_returns_same_expert_id(+ mocker: pytest_mock.MockerFixture,+) -> None:+ hired = _make_expert()+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.hire_expert",+ new_callable=AsyncMock,+ return_value=HireResult(expert=hired, failed_preloads=[]),+ )++ first = client.post("/experts", json={"template_id": "template-1"})+ second = client.post("/experts", json={"template_id": "template-1"})++ assert first.status_code == 200+ assert second.status_code == 200+ assert first.json()["expert"]["id"] == second.json()["expert"]["id"]+++def test_hire_expert_unknown_template_returns_404(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.hire_expert",+ new_callable=AsyncMock,+ side_effect=experts_db.ExpertTemplateNotFoundError("nope"),+ )++ response = client.post("/experts", json={"template_id": "nope"})++ assert response.status_code == 404+++# ─── Get ───────────────────────────────────────────────────────────────+++def test_get_expert_of_other_user_returns_404(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ mock_get = mocker.patch(+ "backend.api.features.experts.routes.experts_db.get_expert",+ new_callable=AsyncMock,+ return_value=None,+ )++ response = client.get("/experts/expert-1")++ assert response.status_code == 404+ mock_get.assert_awaited_once_with(test_user_id, "expert-1")+++def test_get_expert_returns_expert(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ mock_get = mocker.patch(+ "backend.api.features.experts.routes.experts_db.get_expert",+ new_callable=AsyncMock,+ return_value=_make_expert(),+ )++ response = client.get("/experts/expert-1")++ assert response.status_code == 200+ assert response.json()["id"] == "expert-1"+ mock_get.assert_awaited_once_with(test_user_id, "expert-1")+++# ─── Install workflow ──────────────────────────────────────────────────+++def test_install_workflow_duplicate_returns_same_row_id(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ ref = _make_workflow_ref()+ mock_install = mocker.patch(+ "backend.api.features.experts.routes.experts_db.install_workflow",+ new_callable=AsyncMock,+ return_value=ref,+ )++ body = {"store_listing_version_id": "listing-version-1"}+ first = client.post("/experts/expert-1/workflows", json=body)+ second = client.post("/experts/expert-1/workflows", json=body)++ assert first.status_code == 200+ assert second.status_code == 200+ assert first.json()["id"] == second.json()["id"] == "workflow-ref-1"+ assert mock_install.await_args_list == [+ mocker.call(test_user_id, "expert-1", "listing-version-1"),+ mocker.call(test_user_id, "expert-1", "listing-version-1"),+ ]+++def test_install_workflow_unknown_expert_returns_404(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.install_workflow",+ new_callable=AsyncMock,+ side_effect=experts_db.ExpertNotFoundError("nope"),+ )++ response = client.post(+ "/experts/nope/workflows", json={"store_listing_version_id": "listing-1"}+ )++ assert response.status_code == 404+++# ─── Archive + list ────────────────────────────────────────────────────+++def test_delete_then_list_excludes_archived(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ experts = [_make_expert(id="expert-1"), _make_expert(id="expert-2", name="Max")]++ async def _list_experts(user_id: str) -> list[Expert]:+ assert user_id == test_user_id+ return [e for e in experts if not e.is_archived]++ async def _archive_expert(user_id: str, expert_id: str) -> None:+ assert user_id == test_user_id+ for i, expert in enumerate(experts):+ if expert.id == expert_id:+ experts[i] = expert.model_copy(update={"is_archived": True})+ return+ raise experts_db.ExpertNotFoundError(expert_id)++ mocker.patch(+ "backend.api.features.experts.routes.experts_db.list_experts",+ new_callable=AsyncMock,+ side_effect=_list_experts,+ )+ mock_archive = mocker.patch(+ "backend.api.features.experts.routes.experts_db.archive_expert",+ new_callable=AsyncMock,+ side_effect=_archive_expert,+ )++ before = client.get("/experts")+ assert before.status_code == 200+ assert {e["id"] for e in before.json()} == {"expert-1", "expert-2"}++ delete_response = client.delete("/experts/expert-1")+ assert delete_response.status_code == 204+ mock_archive.assert_awaited_once_with(test_user_id, "expert-1")++ after = client.get("/experts")+ assert after.status_code == 200+ assert {e["id"] for e in after.json()} == {"expert-2"}+++def test_delete_unknown_expert_returns_404(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.archive_expert",+ new_callable=AsyncMock,+ side_effect=experts_db.ExpertNotFoundError("nope"),+ )++ response = client.delete("/experts/nope")++ assert response.status_code == 404diff --git a/autogpt_platform/backend/backend/api/features/experts/seed.py b/autogpt_platform/backend/backend/api/features/experts/seed.pynew file mode 100644index 0000000000..698d53e1b0--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/seed.py@@ -0,0 +1,158 @@+"""Dev roster seed for Experts.++Run with: poetry run python -m backend.api.features.experts.seed++Upserts the three roster templates (Maria, Max, Frankie) by template name,+so repeated runs keep the same template ids. Preload workflows are resolved+from store listing slugs; missing listings are logged and skipped, never+fatal.+"""++import asyncio+import logging+from typing import TypedDict++import prisma.models++from backend.data import db as database++logger = logging.getLogger(__name__)+++class RosterEntry(TypedDict):+ name: str+ role: str+ tagline: str+ avatar_url: str | None+ identity: str+ preload_slugs: list[str]+++ROSTER: list[RosterEntry] = [+ {+ "name": "Maria",+ "role": "Marketing",+ "tagline": "Turns your product story into campaigns that land.",+ "avatar_url": None,+ "identity": """You are Maria, a senior marketing strategist with fifteen years of experience across B2B SaaS and consumer brands. You think in terms of positioning first: before any tactic, you want to know who the customer is, what keeps them up at night, and why they would choose this product over doing nothing. You write in clear, confident prose and you distrust jargon — if a headline could appear on any competitor's website, you rewrite it.++Your day-to-day work spans content strategy, social copy, email campaigns, and SEO-aware long-form writing. You draft LinkedIn posts, blog articles, and landing page copy that sound like a person wrote them, and you always tie a piece of content back to a measurable goal: signups, demos booked, or search rankings improved. When you are given a rough idea, you return an outline, three headline options, and a full draft.++You are direct about trade-offs. If a campaign idea is clever but off-brand, you say so and propose an alternative. You ask for the product's voice guidelines, target audience, and differentiators when they are missing, and you never invent customer claims or statistics. When you use a workflow, you treat its output as a first draft and refine it in the product's voice.""",+ "preload_slugs": [+ "linkedin-post-generator",+ "automated-blog-writer",+ "ai-webpage-copy-improver",+ ],+ },+ {+ "name": "Max",+ "role": "Sales",+ "tagline": "Finds the right prospects and opens the right conversations.",+ "avatar_url": None,+ "identity": """You are Max, a sales development expert who has built outbound pipelines for startups and mid-market companies. You believe pipeline problems are usually targeting problems in disguise, so you start every engagement by sharpening the ideal customer profile: industry, size, trigger events, and the specific pain your product removes. Volume without fit is noise, and you say so plainly.++Your core work is prospecting and outreach preparation. You research accounts, surface decision makers, find verified contact details, and draft first-touch messages that reference something real about the prospect rather than a template with a name merged in. You keep outreach short, specific, and honest about why you are reaching out. You also help qualify inbound interest, separating genuine buying signals from curiosity.++You are rigorous about data quality. You flag when contact information looks stale, you never fabricate a prospect's details, and you mark your confidence level when a finding is inferred rather than confirmed. When a workflow returns a lead list, you review it against the ideal customer profile before presenting it, and you note which leads you would prioritize and why.""",+ "preload_slugs": [+ "lead-finder-local-businesses",+ "business-ownerceo-finder",+ "email-address-finder",+ ],+ },+ {+ "name": "Frankie",+ "role": "Ops",+ "tagline": "Keeps the shop running: meetings, follow-ups, and busywork handled.",+ "avatar_url": None,+ "identity": """You are Frankie, an operations specialist who has run the back office for fast-growing teams. Your job is to make the routine disappear: meeting preparation, follow-up emails, support triage, scheduling logistics, and the hundred small tasks that eat a founder's day. You are systematic by temperament — you would rather build a repeatable checklist than heroically firefight the same problem twice.++Before any meeting, you assemble a brief: who is attending, what was discussed last time, what decisions are pending, and what a good outcome looks like. After meetings, you turn notes into action items with owners and dates. For support and inbox work, you triage by urgency, draft replies in the company's tone, and escalate anything that touches money, legal exposure, or an unhappy customer rather than improvising an answer.++You are conservative about commitments. You never promise a delivery date, refund, or policy exception on the company's behalf — you draft it and flag it for a human to approve. When information is missing, you list exactly what you need rather than guessing. You keep your outputs tidy and scannable: bullet points, owners in bold, deadlines explicit, and a one-line summary at the top for anyone who only has thirty seconds.""",+ "preload_slugs": [+ "smart-meeting-brief",+ "automated-support-ai",+ "personalized-morning-coffee-newsletter",+ ],+ },+]+++async def _resolve_active_version_id(slug: str) -> str | None:+ listing = await prisma.models.StoreListing.prisma().find_first(+ where={"slug": slug, "isDeleted": False}+ )+ if listing is None:+ return None+ return listing.activeVersionId+++async def _upsert_template(entry: RosterEntry) -> prisma.models.Expert:+ fields = {+ "role": entry["role"],+ "tagline": entry["tagline"],+ "avatarUrl": entry["avatar_url"],+ "identity": entry["identity"],+ "isArchived": False,+ }+ template = await prisma.models.Expert.prisma().find_first(+ where={"isTemplate": True, "name": entry["name"]},+ order=[{"createdAt": "asc"}, {"id": "asc"}],+ )+ if template is None:+ return await prisma.models.Expert.prisma().create(+ data={"name": entry["name"], "isTemplate": True, **fields}+ )+ updated = await prisma.models.Expert.prisma().update(+ where={"id": template.id}, data=fields+ )+ if updated is None:+ raise RuntimeError(f"Failed to update expert template '{entry['name']}'")+ return updated+++async def _sync_preloads(template_id: str, entry: RosterEntry) -> None:+ existing = await prisma.models.ExpertWorkflow.prisma().find_many(+ where={"expertId": template_id}+ )+ existing_version_ids = {w.storeListingVersionId for w in existing}+ for slug in entry["preload_slugs"]:+ version_id = await _resolve_active_version_id(slug)+ if version_id is None:+ logger.warning(+ f"Store listing slug '{slug}' not found; "+ f"skipping preload for expert '{entry['name']}'"+ )+ continue+ if version_id in existing_version_ids:+ continue+ await prisma.models.ExpertWorkflow.prisma().create(+ data={"expertId": template_id, "storeListingVersionId": version_id}+ )+ existing_version_ids.add(version_id)+++async def seed_roster() -> list[str]:+ """Upsert the roster templates and their preloads. Returns template ids."""+ template_ids = []+ for entry in ROSTER:+ template = await _upsert_template(entry)+ await _sync_preloads(template.id, entry)+ template_ids.append(template.id)+ logger.info(f"Seeded expert template '{entry['name']}' (#{template.id})")+ return template_ids+++async def main() -> None:+ await database.connect()+ try:+ await seed_roster()+ finally:+ await database.disconnect()+++if __name__ == "__main__":+ logging.basicConfig(level=logging.INFO)+ asyncio.run(main())diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex e259308915..92f145abad 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -30,6 +30,7 @@ import backend.api.features.builder.routesimport backend.api.features.chat.routes as chat_routesimport backend.api.features.chat.share as chat_shareimport backend.api.features.executions.review.routes+import backend.api.features.experts.routes as experts_routesimport backend.api.features.library.dbimport backend.api.features.library.modelimport backend.api.features.library.routes@@ -413,6 +414,7 @@ app.include_router(app.include_router(backend.api.features.library.routes.router, tags=["v2"], prefix="/api/library")+app.include_router(experts_routes.router, tags=["v2", "experts"], prefix="/api")app.include_router(backend.api.features.otto.routes.router, tags=["v2", "otto"], prefix="/api/otto")diff --git a/autogpt_platform/backend/migrations/20260727070306_add_expert_entity/migration.sql b/autogpt_platform/backend/migrations/20260727070306_add_expert_entity/migration.sqlnew file mode 100644index 0000000000..98c2d14d9d--- /dev/null+++ b/autogpt_platform/backend/migrations/20260727070306_add_expert_entity/migration.sql@@ -0,0 +1,92 @@+-- AlterTable+ALTER TABLE "ChatSession" ADD COLUMN "expertId" TEXT;++-- CreateTable+CREATE TABLE "Expert" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "ownerUserId" TEXT,+ "name" TEXT NOT NULL,+ "avatarUrl" TEXT,+ "role" TEXT NOT NULL,+ "tagline" TEXT,+ "identity" TEXT NOT NULL,+ "toolProfile" JSONB,+ "isTemplate" BOOLEAN NOT NULL DEFAULT false,+ "sourceTemplateId" TEXT,+ "isArchived" BOOLEAN NOT NULL DEFAULT false,+ "organizationId" TEXT,+ "teamId" TEXT,+ "visibility" "ResourceVisibility" NOT NULL DEFAULT 'PRIVATE',++ CONSTRAINT "Expert_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "ExpertWorkflow" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "expertId" TEXT NOT NULL,+ "storeListingVersionId" TEXT,+ "libraryAgentId" TEXT,++ CONSTRAINT "ExpertWorkflow_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "Expert_ownerUserId_isArchived_idx" ON "Expert"("ownerUserId", "isArchived");++-- CreateIndex+CREATE INDEX "Expert_isTemplate_isArchived_idx" ON "Expert"("isTemplate", "isArchived");++-- CreateIndex+CREATE INDEX "Expert_teamId_idx" ON "Expert"("teamId");++-- CreateIndex+CREATE INDEX "Expert_organizationId_idx" ON "Expert"("organizationId");++-- CreateIndex+CREATE UNIQUE INDEX "Expert_ownerUserId_sourceTemplateId_key" ON "Expert"("ownerUserId", "sourceTemplateId");++-- CreateIndex+CREATE INDEX "ExpertWorkflow_expertId_idx" ON "ExpertWorkflow"("expertId");++-- CreateIndex+CREATE UNIQUE INDEX "ExpertWorkflow_expertId_storeListingVersionId_key" ON "ExpertWorkflow"("expertId", "storeListingVersionId");++-- CreateIndex+-- ChatSession is an existing, write-heavy table. Prisma's `migrate deploy`+-- wraps each migration in a single transaction, and Postgres rejects+-- `CREATE INDEX CONCURRENTLY` inside a transaction block; the plain form+-- briefly holds a ShareLock during the scan. For deployments that can't+-- tolerate that, run the CONCURRENTLY equivalent out-of-band before this+-- migration ships and Postgres will skip the recreate via IF NOT EXISTS+-- (same pattern as 20260516120000_add_creator_search_trgm_indexes).+CREATE INDEX IF NOT EXISTS "ChatSession_expertId_idx" ON "ChatSession"("expertId");++-- AddForeignKey+-- NOT VALID keeps the ACCESS EXCLUSIVE window on ChatSession to a catalog+-- update only — no full-table validation scan under lock. Validation runs+-- in the follow-up migration (separate transaction, SHARE UPDATE EXCLUSIVE+-- only), where it is trivially fast since every existing row has a NULL+-- expertId.+ALTER TABLE "ChatSession" ADD CONSTRAINT "ChatSession_expertId_fkey" FOREIGN KEY ("expertId") REFERENCES "Expert"("id") ON DELETE SET NULL ON UPDATE CASCADE NOT VALID;++-- AddForeignKey+ALTER TABLE "Expert" ADD CONSTRAINT "Expert_ownerUserId_fkey" FOREIGN KEY ("ownerUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "Expert" ADD CONSTRAINT "Expert_sourceTemplateId_fkey" FOREIGN KEY ("sourceTemplateId") REFERENCES "Expert"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "Expert" ADD CONSTRAINT "Expert_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "ExpertWorkflow" ADD CONSTRAINT "ExpertWorkflow_expertId_fkey" FOREIGN KEY ("expertId") REFERENCES "Expert"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "ExpertWorkflow" ADD CONSTRAINT "ExpertWorkflow_storeListingVersionId_fkey" FOREIGN KEY ("storeListingVersionId") REFERENCES "StoreListingVersion"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "ExpertWorkflow" ADD CONSTRAINT "ExpertWorkflow_libraryAgentId_fkey" FOREIGN KEY ("libraryAgentId") REFERENCES "LibraryAgent"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/autogpt_platform/backend/migrations/20260727070307_validate_chat_session_expert_fkey/migration.sql b/autogpt_platform/backend/migrations/20260727070307_validate_chat_session_expert_fkey/migration.sqlnew file mode 100644index 0000000000..e013164911--- /dev/null+++ b/autogpt_platform/backend/migrations/20260727070307_validate_chat_session_expert_fkey/migration.sql@@ -0,0 +1,5 @@+-- Validate the FK added NOT VALID in 20260727070306_add_expert_entity.+-- Runs in its own transaction so the validation scan holds only a+-- SHARE UPDATE EXCLUSIVE lock (writes proceed); every pre-existing+-- ChatSession row has a NULL expertId, so the scan is trivial.+ALTER TABLE "ChatSession" VALIDATE CONSTRAINT "ChatSession_expertId_fkey";diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex 81589775de..4f27a5cb65 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -54,6 +54,7 @@ model User {AgentPresets AgentPreset[]LibraryAgents LibraryAgent[]LibraryFolders LibraryFolder[]+ OwnedExperts Expert[]Profile Profile[]UserOnboarding UserOnboarding?@@ -325,6 +326,11 @@ model ChatSession {Messages ChatMessage[]+ // Expert this session is scoped to; null = plain Autopilot session.+ // Sessions keep expertId for history when the expert is archived (soft delete).+ expertId String?+ Expert Expert? @relation(fields: [expertId], references: [id])+// TenancyorganizationId String?teamId String?@@ -359,6 +365,7 @@ model ChatSession {@@index([teamId, updatedAt])@@index([organizationId])@@index([shareToken])+ @@index([expertId])}// Tracks which workspace files are exposed via a shared chat session.@@ -634,6 +641,8 @@ model LibraryAgent {settings Json @default("{}")+ ExpertWorkflows ExpertWorkflow[]+// TenancyorganizationId String?teamId String?@@ -678,6 +687,74 @@ model LibraryFolder {@@index([organizationId])}+// An Expert is a hireable persona. Roster rows are templates+// (ownerUserId null, isTemplate true); hiring instantiates an owned copy.+// Templates are never chat targets and never owned.+model Expert {+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt++ // null for roster templates; set on hire+ ownerUserId String?+ OwnerUser User? @relation(fields: [ownerUserId], references: [id], onDelete: Cascade)++ name String+ avatarUrl String?+ role String+ tagline String?+ identity String++ toolProfile Json?++ isTemplate Boolean @default(false)+ sourceTemplateId String?+ SourceTemplate Expert? @relation("ExpertFromTemplate", fields: [sourceTemplateId], references: [id])+ HiredCopies Expert[] @relation("ExpertFromTemplate")++ isArchived Boolean @default(false)++ Workflows ExpertWorkflow[]+ ChatSessions ChatSession[]++ // Tenancy+ organizationId String?+ teamId String?+ visibility ResourceVisibility @default(PRIVATE)+ Team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull)++ // Hire idempotency: one hired copy per (user, template). Postgres allows+ // multiple NULL ownerUserId rows, so templates are unaffected.+ @@unique([ownerUserId, sourceTemplateId])+ @@index([ownerUserId, isArchived])+ @@index([isTemplate, isArchived])+ @@index([teamId])+ @@index([organizationId])+}++// Join between an Expert and a workflow (marketplace agent) installed on it.+// Template rows carry only storeListingVersionId; hire resolves each preload+// into the hiring user's LibraryAgent.+model ExpertWorkflow {+ id String @id @default(uuid())+ createdAt DateTime @default(now())++ expertId String+ Expert Expert @relation(fields: [expertId], references: [id], onDelete: Cascade)++ // marketplace source: set on template preloads and marketplace installs+ storeListingVersionId String?+ StoreListingVersion StoreListingVersion? @relation(fields: [storeListingVersionId], references: [id])++ // the hiring user's LibraryAgent; null on template rows+ libraryAgentId String?+ LibraryAgent LibraryAgent? @relation(fields: [libraryAgentId], references: [id])++ // Duplicate install on an expert returns the existing row.+ @@unique([expertId, storeListingVersionId])+ @@index([expertId])+}+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AGENT DEFINITION AND EXECUTION TABLES ////////@@ -1466,6 +1543,8 @@ model StoreListingVersion {// Reviews for this specific versionReviews StoreListingReview[]+ ExpertWorkflows ExpertWorkflow[]+// Note: Embeddings now stored in UnifiedContentEmbedding table// Use contentType=STORE_AGENT and contentId=storeListingVersionId@@ -1872,6 +1951,7 @@ model Team {Presets AgentPreset[]LibraryAgents LibraryAgent[]LibraryFolders LibraryFolder[]+ Experts Expert[]Webhooks IntegrationWebhook[]APIKeys APIKey[]Credentials IntegrationCredential[] @relation("TeamCredentials")diff --git a/autogpt_platform/backend/snapshots/expert_templates_list b/autogpt_platform/backend/snapshots/expert_templates_listnew file mode 100644index 0000000000..c76c5962b2--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_templates_list@@ -0,0 +1,23 @@+[+ {+ "avatar_url": null,+ "id": "template-1",+ "identity": "You are Maria, a pragmatic marketing specialist.",+ "is_archived": false,+ "is_template": true,+ "name": "Maria",+ "role": "Marketing Specialist",+ "source_template_id": null,+ "tagline": "Grows your audience",+ "workflows": [+ {+ "description": "Writes SEO-optimized blog posts",+ "graph_id": null,+ "id": "workflow-ref-1",+ "library_agent_id": null,+ "name": "SEO Blog Writer",+ "store_listing_version_id": "listing-version-1"+ }+ ]+ }+]\ No newline at end of filediff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 39cfb95b55..84fc44ccc2 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -5350,6 +5350,207 @@}}},+ "/api/experts": {+ "get": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "List Experts",+ "operationId": "list_experts",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "items": { "$ref": "#/components/schemas/Expert" },+ "type": "array",+ "title": "Response List Experts"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ },+ "post": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "Hire Expert",+ "operationId": "hire_expert",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HireRequest" }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HireResult" }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Expert template not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },+ "/api/experts/templates": {+ "get": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "List Expert Templates",+ "operationId": "list_expert_templates",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "items": { "$ref": "#/components/schemas/Expert" },+ "type": "array",+ "title": "Response List Expert Templates"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },+ "/api/experts/{expert_id}": {+ "delete": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "Archive Expert",+ "operationId": "archive_expert",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "expert_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Expert Id" }+ }+ ],+ "responses": {+ "204": { "description": "Successful Response" },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Expert not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ },+ "get": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "Get Expert",+ "operationId": "get_expert",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "expert_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Expert Id" }+ }+ ],+ "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}/workflows": {+ "post": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "Install Expert Workflow",+ "operationId": "install_expert_workflow",+ "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/InstallWorkflowRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/ExpertWorkflowRef" }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Expert not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/files/upload": {"post": {"tags": ["v1", "files"],@@ -16429,6 +16630,82 @@"title": "ExecutionStartedResponse","description": "Response for run/schedule actions."},+ "Expert": {+ "properties": {+ "id": { "type": "string", "title": "Id" },+ "name": { "type": "string", "title": "Name" },+ "avatar_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Avatar Url"+ },+ "role": { "type": "string", "title": "Role" },+ "tagline": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Tagline"+ },+ "identity": { "type": "string", "title": "Identity" },+ "is_template": { "type": "boolean", "title": "Is Template" },+ "source_template_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Source Template Id"+ },+ "is_archived": { "type": "boolean", "title": "Is Archived" },+ "workflows": {+ "items": { "$ref": "#/components/schemas/ExpertWorkflowRef" },+ "type": "array",+ "title": "Workflows"+ }+ },+ "type": "object",+ "required": [+ "id",+ "name",+ "avatar_url",+ "role",+ "tagline",+ "identity",+ "is_template",+ "source_template_id",+ "is_archived",+ "workflows"+ ],+ "title": "Expert"+ },+ "ExpertWorkflowRef": {+ "properties": {+ "id": { "type": "string", "title": "Id" },+ "store_listing_version_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Store Listing Version Id"+ },+ "library_agent_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Library Agent Id"+ },+ "graph_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Graph Id"+ },+ "name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Name"+ },+ "description": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Description"+ }+ },+ "type": "object",+ "required": [+ "id",+ "store_listing_version_id",+ "library_agent_id",+ "graph_id",+ "name",+ "description"+ ],+ "title": "ExpertWorkflowRef"+ },"FactListResponse": {"properties": {"user_id": { "type": "string", "title": "User Id" },@@ -17503,6 +17780,34 @@"type": "object","title": "HTTPValidationError"},+ "HireRequest": {+ "properties": {+ "template_id": { "type": "string", "title": "Template Id" },+ "name": {+ "anyOf": [+ { "type": "string", "maxLength": 100 },+ { "type": "null" }+ ],+ "title": "Name"+ }+ },+ "type": "object",+ "required": ["template_id"],+ "title": "HireRequest"+ },+ "HireResult": {+ "properties": {+ "expert": { "$ref": "#/components/schemas/Expert" },+ "failed_preloads": {+ "items": { "type": "string" },+ "type": "array",+ "title": "Failed Preloads"+ }+ },+ "type": "object",+ "required": ["expert", "failed_preloads"],+ "title": "HireResult"+ },"HostScopedCredentials": {"properties": {"id": { "type": "string", "title": "Id" },@@ -17592,6 +17897,17 @@"title": "InputValidationErrorResponse","description": "Response when run_agent receives unknown input fields."},+ "InstallWorkflowRequest": {+ "properties": {+ "store_listing_version_id": {+ "type": "string",+ "title": "Store Listing Version Id"+ }+ },+ "type": "object",+ "required": ["store_listing_version_id"],+ "title": "InstallWorkflowRequest"+ },"InvitationCreateResponse": {"properties": {"id": { "type": "string", "title": "Id" },