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(platform): recommend experts from onboarding brain dumps (#14462)
Abhimanyu Yadav1be93fc470e2
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex a090f9a099..2f38586471 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -351,6 +351,13 @@ AUTOMOD_API_KEY=# matching NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_BRAIN_DUMP in frontend/.env.# FORCE_FLAG_ONBOARDING_BRAIN_DUMP=true+# Expert-first onboarding (`onboarding-expert-team`, child of `hire-experts`):+# the dump also produces expert recommendations and AutoPilot acts as the+# Head of AI. Needs both flags; pair with the NEXT_PUBLIC_* twins in+# frontend/.env.+# FORCE_FLAG_HIRE_EXPERTS=true+# FORCE_FLAG_ONBOARDING_EXPERT_TEAM=true+# Speech-to-text model for the brain dump. Requires a direct OpenAI key# (OPENAI_INTERNAL_API_KEY, else OPENAI_API_KEY) — OpenRouter has no# /audio/transcriptions endpoint. Falls back automatically on failure.diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/db.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/db.pyindex ff0cf049ac..033d4efe8c 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/db.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/db.py@@ -43,9 +43,10 @@ _IN_FLIGHT_STATUSES = frozenset(# Everything a single take owns. One row per user means a new take# inherits whatever the last one left here, so unless these are cleared-# ``/recording``, ``/intro`` and ``/recommended-providers`` keep serving-# the *previous* take's audio, transcript, greeting and picks whenever the-# new one fails, is skipped or is abandoned half-recorded.+# ``/recording``, ``/intro``, ``/recommended-providers`` and+# ``/recommended-experts`` keep serving the *previous* take's audio,+# transcript, greeting, picks and team whenever the new one fails, is+# skipped or is abandoned half-recorded.## ``greetingSeen`` belongs with them. It is only ever written True and# short-circuits the intro endpoint, so a new take that inherited it would@@ -63,6 +64,7 @@ _TAKE_OWNED_RESET: dict[str, Any] = {"greeting": None,"suggestedPrompts": Json([]),"recommendedProviders": Json(None),+ "recommendedExperts": Json(None),"greetingSeen": False,}diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/db_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/db_test.pyindex 4dbe456cdb..b554815b7b 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/db_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/db_test.py@@ -123,9 +123,9 @@ async def test_a_new_recording_id_clears_every_column_the_last_take_owned(There is one row per user, so anything left behind here is served asif it belonged to the new recording: ``/recording`` hands back the- previous audio, ``/intro`` its greeting and transcript, and- ``/recommended-providers`` its picks — for a take that may never get- past its first part.+ previous audio, ``/intro`` its greeting and transcript,+ ``/recommended-providers`` its picks and ``/recommended-experts`` its+ team — for a take that may never get past its first part."""mocker.patch.object(db,@@ -144,6 +144,7 @@ async def test_a_new_recording_id_clears_every_column_the_last_take_owned(assert update["transcriptLang"] is Noneassert update["greeting"] is Noneassert update["recommendedProviders"] == Json(None)+ assert update["recommendedExperts"] == Json(None)# Non-nullable with a ``[]`` default, so it is emptied, not nulled.assert update["suggestedPrompts"] == Json([])@@ -166,6 +167,7 @@ async def test_retrying_the_same_take_keeps_what_that_take_produced(create = upsert.await_args.kwargs["data"]["create"]update = upsert.await_args.kwargs["data"]["update"]assert create["recommendedProviders"] == Json(None)+ assert create["recommendedExperts"] == Json(None)assert set(update) == {"recordingId", "status", "inputMode", "errorCode"}@@ -177,6 +179,7 @@ async def test_greeting_only_create_sets_recommended_providers(create = upsert.await_args.kwargs["data"]["create"]assert create["recommendedProviders"] == Json(None)+ assert create["recommendedExperts"] == Json(None)assert create["greetingSeen"] is Truediff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/intro.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/intro.pyindex 5e56ac367b..eba31fb959 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/intro.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/intro.py@@ -31,6 +31,9 @@ settings = Settings()_MODEL = os.environ.get("BRAIN_DUMP_GREETING_MODEL", "anthropic/claude-sonnet-5")_TIMEOUT_SECONDS = 30+# The Langfuse copy of these instructions wins whenever it is reachable,+# so it must be versioned in lockstep with ``_LOCAL_PROMPT`` — a voice+# change made only here is invisible in prod.LANGFUSE_PROMPT_NAME = os.environ.get("BRAIN_DUMP_GREETING_PROMPT_NAME", "Brain Dump Greeting")@@ -71,19 +74,26 @@ PROMPT_ICONS = frozenset(DEFAULT_PROMPT_ICON = "sparkle"# The local fallback for the Langfuse-managed instructions. The greeting-# reflects the dump back so the user can see they were heard; the suggested+# diagnoses the dump so the user can see they were heard; the suggested# prompts are what turn that into an action. A Langfuse edit must keep the# same JSON contract — a malformed generation degrades to the template.-_LOCAL_PROMPT = """You are AutoPilot, an AI teammate that can run real \-recurring automations: watch sources, draft content, send digests, build \-agents that work while the user sleeps. A new user just recorded a short \-spoken brain dump about their work. Write the greeting they will see when \-they first open the app.+_LOCAL_PROMPT = """You are AutoPilot, this user's built-in Head of AI. \+You are theirs alone, never shared, and you run a team for them: you can \+build real recurring automations (watch sources, draft content, send \+digests, run agents while they sleep) and you can bring in experts to own \+whole areas of their work. A new user just recorded a short spoken brain \+dump about their work. Write the greeting they will see when they first \+open the app.Return ONLY valid JSON with exactly these keys:- "greeting": 2-3 sentences, max 450 characters, second person, warm and \-concrete. Show them you listened by naming the specific things they \-actually said. This is their FIRST time in the app — never say "welcome \+concrete. Diagnose, the way a consultant would on day one: name the \+specific problems you heard in their own terms ("you have a marketing \+problem and a support problem"), then say you are putting a team \+together to take them on. NEVER name a specific expert, and never say \+anyone has been hired or assigned — the team is proposed separately, \+below your text, and naming someone here would promise a colleague who \+may not exist. This is their FIRST time in the app — never say "welcome \back" or imply any prior visit or conversation. The app already renders \"Hey, <name>" directly above this text, so NEVER use the user's name or \any other salutation ("good to have you here", "welcome") — open \@@ -263,18 +273,19 @@ def _parse_prompts(raw: object) -> list[SuggestedPrompt]:def fallback_intro(transcript: str) -> tuple[str, list[SuggestedPrompt]]:"""A greeting that is true even when the model gave us nothing.- Deliberately makes no claim about *what* was said — inventing detail- here would be worse than being generic.+ Deliberately makes no claim about *what* was said, and names nobody —+ inventing either would be worse than being generic."""if not transcript.strip():return (- "I'm ready when you are. Tell me what your week looks like and "- "I'll find the parts worth handing over. Here are a few places "- "we could start.",+ "I'm your Head of AI here. Tell me what your week looks like "+ "and I'll work out who and what you need. Here are a few "+ "places we could start.",fallback_prompts(),)return (- "Thanks for talking me through your work — I've got it. "+ "Thanks for talking me through your work — I've got it. I'm your "+ "Head of AI here, and I'll start putting a team around this. ""Here are a few places I can start.",fallback_prompts(),)diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/intro_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/intro_test.pyindex e3d2092003..24e47cffa7 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/intro_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/intro_test.py@@ -80,3 +80,41 @@ async def test_greeting_prompt_survives_an_empty_registry(content = client.chat.completions.create.await_args.kwargs["messages"][0]["content"]assert content.startswith(intro._LOCAL_PROMPT[:40])assert greeting == GENERATION["greeting"]+++def test_the_local_prompt_asks_for_the_head_of_ai_voice():+ """The greeting diagnoses and promises a team; it never casts it.++ The team section under the greeting is built from filtered template+ ids, so prose that names an expert can promise a colleague who was+ never recommended — or does not exist on the roster at all.+ """+ assert "Head of AI" in intro._LOCAL_PROMPT+ assert "NEVER name a specific expert" in intro._LOCAL_PROMPT+ # The JSON contract the parser depends on is unchanged.+ assert '"greeting"' in intro._LOCAL_PROMPT+ assert '"prompts"' in intro._LOCAL_PROMPT+++async def test_the_generation_contract_is_still_greeting_plus_prompts(+ client: MagicMock,+):+ greeting, suggested = await intro.generate_intro(TRANSCRIPT)++ assert greeting == GENERATION["greeting"]+ assert [p.title for p in suggested] == [+ item["title"] for item in GENERATION["prompts"]+ ]+++def test_the_fallback_greeting_names_nobody():+ """It runs when the model gave us nothing, so it can claim nothing.++ Naming an expert here would be a hire the roster never made.+ """+ for transcript in ("", TRANSCRIPT):+ greeting, suggested = intro.fallback_intro(transcript)+ assert "Head of AI" in greeting+ assert not any(name in greeting for name in ("Maria", "Max", "Frankie"))+ assert suggested == intro.fallback_prompts()diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/models.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/models.pyindex 9d73a45522..0fe14d5d75 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/models.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/models.py@@ -1,6 +1,6 @@"""Request / response models for the onboarding brain dump."""-from typing import Annotated+from typing import Annotated, Literalfrom prisma.enums import BrainDumpInputMode, BrainDumpStatusfrom pydantic import BaseModel, Field, StringConstraints@@ -99,6 +99,62 @@ class SuggestedPrompt(BaseModel):icon: str = "sparkle"+class RecommendedExpert(BaseModel):+ """One roster template AutoPilot suggests hiring first.++ ``template_id`` is always a live template — the model only ever picks+ ids off the roster it was shown, and anything else is dropped before+ storage. ``name``/``role``/``avatar_url`` are copied from that+ template server-side rather than trusted from the model, so a card+ can never introduce an expert who does not exist.+ """++ template_id: str+ name: str+ role: str+ avatar_url: str | None = None+ reason: str = ""+ workflow_names: list[str] = []+++class RaiseSuggestion(BaseModel):+ """The "raise your own" door, prefilled for a gap the roster can't fill.++ ``role`` is one of the ``/raise`` wizard's role ids so the link can+ seed the draft; a suggestion naming anything else is dropped.+ """++ role: str+ reason: str = ""+++class ExpertRecommendations(BaseModel):+ """The team AutoPilot proposes after the dump.++ ``source`` says where it came from: "llm" for a real read of the+ transcript, "fallback" for the deterministic role/pain-point mapping,+ and "disabled" for a run where the feature flag was off (recorded so+ the reader can tell it apart from a job that never finished).+ """++ diagnosis: str = ""+ experts: list[RecommendedExpert] = []+ raise_suggestion: RaiseSuggestion | None = None+ source: Literal["llm", "fallback", "disabled"] = "fallback"+++class RecommendedExpertsResponse(BaseModel):+ """The team section's content, polled by the onboarding loading screen.++ ``ready`` is false only while the background job is still running.+ ``team`` is null when the feature is off — a team with no experts is+ a real answer, so the client cannot use emptiness to tell them apart.+ """++ ready: bool+ team: ExpertRecommendations | None = None++class IntroCardResponse(BaseModel):"""Content for the copilot home's onboarding greeting.@@ -120,6 +176,13 @@ class IntroCardResponse(BaseModel):"""The full transcript of the recorded dump, so the greeting page canoffer a copy button. Only present on Path A while the greeting isstill showing."""+ team: ExpertRecommendations | None = None+ """The experts to hire first, with the "raise your own" door beside+ them. Null when the feature is off, and while ``team_pending``."""+ team_pending: bool = False+ """True while the team is still being assembled — the client keeps+ polling ``/recommended-experts`` rather than rendering an empty+ section over a team that is seconds away."""class RecommendedProvider(BaseModel):diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/prompts.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/prompts.pyindex 83a2418e34..6af94fac33 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/prompts.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/prompts.py@@ -7,8 +7,7 @@ prompts under it are the generic set from ``intro.fallback_prompts``."""PATH_B_GREETING = (- "No rush — you can tell me about your work whenever you like. "- "Tap the microphone below and talk for a couple of minutes, and I'll "- "start finding the things worth taking off your plate. Until then, "- "here are a few places we could start."+ "I'm your Head of AI — I build the team that does the work you don't "+ "want to. Tell me what slows you down, or tap the microphone and tell "+ "me about your week, and I'll help you put the right team to work.")diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/recommend_experts.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/recommend_experts.pynew file mode 100644index 0000000000..f760eaf2be--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/recommend_experts.py@@ -0,0 +1,390 @@+"""The team AutoPilot proposes off the back of the brain dump.++Runs as its own background job beside the greeting and the provider+recommendations — same contract as ``recommend.py``: never raises, never+touches the dump status, and always ends with a storable answer.++Two things make this stricter than the provider job. The roster is+content that lags demand (there is no Support or Research template+today), so a need nobody covers has to degrade into a "raise your own"+suggestion rather than a bad hire. And a hire card names a person: the+model only ever picks template ids, and the name, role and avatar on the+card are copied from the template here, so a hallucinated id can never+become a colleague the user is invited to hire.+"""++import asyncio+import logging+import os++from backend.api.features.experts.models import Expert+from backend.api.features.onboarding_dump.models import (+ ExpertRecommendations,+ RaiseSuggestion,+ RecommendedExpert,+)+from backend.api.features.onboarding_dump.parsing import parse_response_json+from backend.util.clients import get_openai_client++logger = logging.getLogger(__name__)++# Same reasoning as the provider job: matching needs against a roster is+# a matching task, and the onboarding loading screen waits on it.+_MODEL = os.environ.get("BRAIN_DUMP_RECOMMEND_MODEL", "anthropic/claude-haiku-4-5")+_TIMEOUT_SECONDS = 30++MAX_EXPERTS = 16+MAX_REASON_CHARS = 140+MAX_DIAGNOSIS_CHARS = 240+MAX_WORKFLOW_NAMES = 3++# The ``/raise`` wizard's role ids. A suggestion is a prefilled link into+# that wizard, so anything outside this set would land on a blank draft.+RAISE_ROLES = frozenset(+ {+ "marketer",+ "sales",+ "developer",+ "researcher",+ "writer",+ "analyst",+ "recruiter",+ "support",+ "operations",+ }+)++# Said without having read anything: the fallback runs when there is no+# transcript, or when the model that would have read it failed.+FALLBACK_DIAGNOSIS = "Here's a first team based on your role and what slows you down."++_PROMPT = """You are AutoPilot, this user's built-in Head of AI. They \+just recorded a brain dump about their work, and your job is to come back \+like a consultant would: name the problems you heard, then propose the \+first hires that take those problems off their plate.++Below is their transcript, what they told the signup wizard, and the \+experts you can actually hire for them today.++Return ONLY valid JSON with exactly these keys:+- "diagnosis": 1-2 sentences, max {max_diagnosis} characters, second \+person, naming the specific problems you heard ("you have a marketing \+problem and a support problem"). Never name an expert here.+- "experts": an array of at most {max_experts} objects, most useful \+first, each with:+ - "template_id": an id copied EXACTLY from the roster below+ - "reason": one sentence, max {max_reason} characters, second person, \+tying this expert to something they actually said+ - "workflow_names": the workflows from THAT expert's list that match \+their work, copied exactly; an empty array is fine+- "raise_suggestion": either null, or an object with "role" and "reason" \+— use it only for a real need that NO expert on the roster covers, and \+only with a role from this list: {raise_roles}. The "reason" is one \+sentence, max {max_reason} characters, second person.++Rules: never invent a template id or a workflow name that is not below; \+never recommend an expert the transcript gives no evidence for (fewer, \+better hires beat filling every available slot); do not promise anything the \+listed workflows cannot do.++Roster:+{roster}++Signup answers:+{answers}++Transcript:+{transcript}+"""+++async def generate_expert_recommendations(+ transcript: str,+ *,+ user_role: str | None,+ pain_points: list[str],+ templates: list[Expert],+) -> ExpertRecommendations:+ """Return the team to propose for ``transcript``.++ Never raises. Every failure path — no transcript, no client, a dead+ or malformed generation, a generation with nothing usable left after+ filtering — resolves to :func:`fallback_expert_recommendations`, so+ the greeting page always has a team to render and the client always+ stops polling.+ """+ text = transcript.strip()+ fallback = fallback_expert_recommendations(user_role, pain_points, templates)+ if not text:+ return fallback++ client = get_openai_client(prefer_openrouter=True)+ if client is None:+ logger.warning("Brain dump team: no LLM client configured")+ return fallback++ prompt = _PROMPT.format(+ max_diagnosis=MAX_DIAGNOSIS_CHARS,+ max_experts=MAX_EXPERTS,+ max_reason=MAX_REASON_CHARS,+ raise_roles=", ".join(sorted(RAISE_ROLES)),+ roster=roster_lines(templates),+ answers=_answer_lines(user_role, pain_points),+ transcript=text,+ )+ data = None+ # One retry, for the same reason the greeting has one: a truncated or+ # non-JSON generation is cheaper to redo than to ship around.+ for attempt in range(2):+ try:+ response = await asyncio.wait_for(+ client.chat.completions.create(+ model=_MODEL,+ messages=[{"role": "user", "content": prompt}],+ temperature=0.2,+ max_tokens=1200,+ ),+ timeout=_TIMEOUT_SECONDS,+ )+ data = parse_response_json(response.choices[0].message.content or "")+ except Exception as e: # degrades to the fallback below+ logger.warning(+ "Brain dump team generation failed (attempt %s): %s", attempt + 1, e+ )+ continue+ if data is not None:+ break+ logger.warning("Brain dump team: non-JSON output (attempt %s)", attempt + 1)+ if data is None:+ return fallback++ team = _parse_team(data, templates)+ if not team.experts and team.raise_suggestion is None:+ # Nothing survived filtering, so there is no door to open. The+ # deterministic mapping is a worse answer than a good generation+ # and a better one than an empty section.+ return fallback+ return team+++def roster_lines(templates: list[Expert]) -> str:+ """The hireable roster as one line per template."""+ return "\n".join(+ f"- {template.id}: {template.name} — {template.role}. "+ f"{(template.tagline or '').strip()}. "+ f"Workflows: {', '.join(_template_workflow_names(template))}"+ for template in templates+ )+++def _answer_lines(user_role: str | None, pain_points: list[str]) -> str:+ lines = [f"- Role: {user_role}"] if user_role else []+ if pain_points:+ lines.append(f"- Slows them down: {', '.join(pain_points)}")+ return "\n".join(lines) or "- (none given)"+++def _template_workflow_names(template: Expert) -> list[str]:+ return [+ workflow.name.strip()+ for workflow in template.workflows+ if workflow.name and workflow.name.strip()+ ]+++def _parse_team(data: dict, templates: list[Expert]) -> ExpertRecommendations:+ by_id = {template.id: template for template in templates}+ items = data.get("experts")+ experts: list[RecommendedExpert] = []+ seen: set[str] = set()+ for item in items if isinstance(items, list) else []:+ if not isinstance(item, dict) or not isinstance(item.get("template_id"), str):+ continue+ template = by_id.get(item["template_id"].strip())+ if template is None or template.id in seen:+ continue+ seen.add(template.id)+ experts.append(+ _from_template(+ template,+ reason=item.get("reason"),+ workflow_names=item.get("workflow_names"),+ )+ )+ if len(experts) == MAX_EXPERTS:+ break++ diagnosis = data.get("diagnosis")+ return ExpertRecommendations(+ diagnosis=(+ diagnosis.strip()[:MAX_DIAGNOSIS_CHARS]+ if isinstance(diagnosis, str)+ else ""+ ),+ experts=experts,+ raise_suggestion=_parse_raise_suggestion(data.get("raise_suggestion")),+ source="llm",+ )+++def _from_template(+ template: Expert, *, reason: object, workflow_names: object+) -> RecommendedExpert:+ return RecommendedExpert(+ template_id=template.id,+ name=template.name,+ role=template.role,+ avatar_url=template.avatar_url,+ reason=reason.strip()[:MAX_REASON_CHARS] if isinstance(reason, str) else "",+ workflow_names=_matched_workflow_names(template, workflow_names),+ )+++def _matched_workflow_names(template: Expert, requested: object) -> list[str]:+ """The requested names that are really this template's, its spelling.++ Matching is case-insensitive because the model retypes the names, but+ the chips on the card have to read exactly as the workflow does.+ """+ real = {name.lower(): name for name in _template_workflow_names(template)}+ matched: list[str] = []+ for name in requested if isinstance(requested, list) else []:+ if not isinstance(name, str):+ continue+ actual = real.get(name.strip().lower())+ if actual is not None and actual not in matched:+ matched.append(actual)+ if len(matched) == MAX_WORKFLOW_NAMES:+ break+ return matched+++def _parse_raise_suggestion(raw: object) -> RaiseSuggestion | None:+ if not isinstance(raw, dict) or not isinstance(raw.get("role"), str):+ return None+ role = raw["role"].strip().lower()+ if role not in RAISE_ROLES:+ return None+ reason = raw.get("reason")+ return RaiseSuggestion(+ role=role,+ reason=reason.strip()[:MAX_REASON_CHARS] if isinstance(reason, str) else "",+ )+++# The wizard's role ids, mapped to the template *roles* that cover them —+# roles rather than template ids or names so a renamed or re-seeded+# template still matches, and a missing one is simply skipped.+_ROLE_TEMPLATE_ROLES: dict[str, tuple[str, ...]] = {+ "Founder/CEO": ("sales", "marketing"),+ "Marketing": ("marketing",),+ "Sales/BD": ("sales",),+ "Operations": ("ops", "office ops", "executive assistant"),+ "Product/PM": ("project management", "ops"),+ "Engineering": ("engineering", "code quality"),+ "HR/People": ("recruiting", "talent sourcing", "ops"),+}+_PAIN_TEMPLATE_ROLES: dict[str, tuple[str, ...]] = {+ "Social media": ("marketing",),+ "Finding leads": ("sales",),+ "Email & outreach": ("sales",),+ "Reports & data": ("ops",),+ "Scheduling": ("ops",),+ "CRM & data entry": ("ops",),+}++# Needs the roster may have no template for — the honest answer is the+# raise door, not the nearest expert. A raise is only suggested when none+# of the template roles that cover it made the team (_RAISE_COVERED_BY),+# so an environment seeded with the engineering or people rosters never+# claims nobody covers a role it just recommended.+_ROLE_RAISE_ROLES: dict[str, str] = {+ "Engineering": "developer",+ "HR/People": "recruiter",+}+_PAIN_RAISE_ROLES: dict[str, str] = {+ "Customer support": "support",+ "Research": "researcher",+}+_RAISE_COVERED_BY: dict[str, tuple[str, ...]] = {+ "developer": ("engineering", "code quality"),+ "recruiter": ("recruiting", "talent sourcing"),+}+++def fallback_expert_recommendations(+ user_role: str | None,+ pain_points: list[str],+ templates: list[Expert],+) -> ExpertRecommendations:+ """A team derived from the signup wizard's answers alone.++ Used wherever the model's read of the transcript is unavailable: a+ skipped dump, a failed generation, a process that died mid-job. It+ claims nothing about what the user said, because in those cases we+ may not have heard anything at all.+ """+ wanted = [+ *_ROLE_TEMPLATE_ROLES.get(user_role or "", ()),+ *(+ role+ for point in pain_points+ for role in _PAIN_TEMPLATE_ROLES.get(point, ())+ ),+ ]+ prioritized = [+ template+ for role in dict.fromkeys(wanted)+ for template in templates+ if template.role.strip().lower() == role+ ]+ picked: list[Expert] = []+ seen: set[str] = set()+ for template in [*prioritized, *templates]:+ if template.id not in seen:+ picked.append(template)+ seen.add(template.id)+ if len(picked) == MAX_EXPERTS:+ break++ picked_roles = {template.role.strip().lower() for template in picked}+ return ExpertRecommendations(+ diagnosis=FALLBACK_DIAGNOSIS,+ experts=[_fallback_expert(template) for template in picked],+ raise_suggestion=_fallback_raise(user_role, pain_points, picked_roles),+ source="fallback",+ )+++def _fallback_expert(template: Expert) -> RecommendedExpert:+ # The tagline already says what the expert does; without one, fall back+ # to the role so the card never reads blank.+ tagline = (template.tagline or "").strip()+ reason = tagline or f"Covers {template.role.strip().lower()} for you."+ return RecommendedExpert(+ template_id=template.id,+ name=template.name,+ role=template.role,+ avatar_url=template.avatar_url,+ reason=reason[:MAX_REASON_CHARS],+ workflow_names=_template_workflow_names(template)[:MAX_WORKFLOW_NAMES],+ )+++def _fallback_raise(+ user_role: str | None, pain_points: list[str], picked_roles: set[str]+) -> RaiseSuggestion | None:+ role = _ROLE_RAISE_ROLES.get(user_role or "") or next(+ (+ _PAIN_RAISE_ROLES[point]+ for point in pain_points+ if point in _PAIN_RAISE_ROLES+ ),+ None,+ )+ if role is None or picked_roles & set(_RAISE_COVERED_BY.get(role, ())):+ return None+ return RaiseSuggestion(+ role=role,+ reason=f"Nobody on the roster covers this yet — you can raise a {role} of your own.",+ )diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/recommend_experts_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/recommend_experts_test.pynew file mode 100644index 0000000000..81457da06e--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/recommend_experts_test.py@@ -0,0 +1,449 @@+"""Tests for the expert-recommendation job.++A hire card names a person and offers to add them to the user's team, so+the filtering here is the whole safety story: only live template ids,+only that template's real workflows, only raise roles the ``/raise``+wizard can actually open. The deterministic fallback gets the same+scrutiny — it is what Path B, a flag-off run and a dead LLM all serve.+"""++import json+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest+from pytest_mock import MockerFixture++from backend.api.features.experts.models import Expert, ExpertWorkflowRef+from backend.api.features.onboarding_dump import recommend_experts++TRANSCRIPT = "LinkedIn posts and cold outreach eat my week, and tickets pile up."+++def _template(+ template_id: str, name: str, role: str, workflows: list[str] = []+) -> Expert:+ return Expert.model_construct(+ id=template_id,+ name=name,+ avatar_url=f"/experts/{name.lower()}.svg",+ role=role,+ tagline=f"{name} handles {role.lower()}.",+ bio=None,+ skills=[],+ identity="",+ voice_preferences="",+ boundaries="",+ protected_soul_rules=[],+ is_template=True,+ source_template_id=None,+ is_archived=False,+ workflows=[+ ExpertWorkflowRef.model_construct(+ id=f"wf-{index}",+ store_listing_version_id=None,+ library_agent_id=None,+ graph_id=None,+ name=workflow,+ description=None,+ )+ for index, workflow in enumerate(workflows)+ ],+ )+++MARIA = _template(+ "tpl-maria",+ "Maria",+ "Marketing",+ ["LinkedIn Post Generator", "Automated Blog Writer", "Webpage Copy Improver"],+)+MAX = _template("tpl-max", "Max", "Sales", ["Lead Finder", "Contact Enricher"])+FRANKIE = _template("tpl-frankie", "Frankie", "Ops", ["Meeting Brief"])+ROSTER = [MARIA, MAX, FRANKIE]+ELI = _template("tpl-eli", "Eli", "Engineering")+NADIA = _template("tpl-nadia", "Nadia", "Code quality")+RHEA = _template("tpl-rhea", "Rhea", "Recruiting")+SHAY = _template("tpl-shay", "Shay", "Talent sourcing")+FULL_ROSTER = [*ROSTER, ELI, NADIA, RHEA, SHAY]+++def test_parse_drops_unknown_and_duplicate_templates():+ data = {+ "diagnosis": "You have a marketing problem.",+ "experts": [+ {"template_id": "tpl-maria", "reason": "You post on LinkedIn weekly."},+ {"template_id": "tpl-maria", "reason": "Duplicate."},+ {"template_id": "tpl-hallucinated", "reason": "Invented."},+ "not-a-dict",+ {"reason": "missing template_id"},+ {"template_id": "tpl-max", "reason": "Cold outreach eats your week."},+ ],+ }++ team = recommend_experts._parse_team(data, ROSTER)++ assert [e.template_id for e in team.experts] == ["tpl-maria", "tpl-max"]+ assert team.source == "llm"+ assert team.diagnosis == "You have a marketing problem."+++def test_parse_copies_identity_from_the_template_not_the_model():+ data = {+ "experts": [+ {+ "template_id": "tpl-maria",+ "name": "Impostor",+ "role": "CFO",+ "avatar_url": "https://evil.example/avatar.png",+ "reason": "x" * 500,+ }+ ]+ }++ expert = recommend_experts._parse_team(data, ROSTER).experts[0]++ assert expert.name == "Maria"+ assert expert.role == "Marketing"+ assert expert.avatar_url == "/experts/maria.svg"+ assert len(expert.reason) == recommend_experts.MAX_REASON_CHARS+++def test_parse_caps_the_number_of_experts_and_the_diagnosis():+ roster = [_template(f"tpl-{i}", f"Expert{i}", "Ops") for i in range(18)]+ data = {+ "diagnosis": "y" * 900,+ "experts": [{"template_id": t.id} for t in roster],+ }++ team = recommend_experts._parse_team(data, roster)++ assert len(team.experts) == recommend_experts.MAX_EXPERTS+ assert len(team.diagnosis) == recommend_experts.MAX_DIAGNOSIS_CHARS+++def test_parse_keeps_only_that_templates_real_workflows():+ data = {+ "experts": [+ {+ "template_id": "tpl-maria",+ "workflow_names": [+ "linkedin post generator",+ "Meeting Brief",+ "Made Up Workflow",+ "Automated Blog Writer",+ 12,+ ],+ }+ ]+ }++ expert = recommend_experts._parse_team(data, ROSTER).experts[0]++ # Matched case-insensitively, rendered in the workflow's own spelling.+ assert expert.workflow_names == ["LinkedIn Post Generator", "Automated Blog Writer"]+++ "raw",+ [+ None,+ "support",+ {"reason": "no role"},+ {"role": "chief happiness officer", "reason": "Not a raise role."},+ ],+)+def test_parse_drops_raise_suggestions_the_wizard_cannot_open(raw: object):+ team = recommend_experts._parse_team({"raise_suggestion": raw}, ROSTER)++ assert team.raise_suggestion is None+++def test_parse_keeps_a_valid_raise_suggestion():+ team = recommend_experts._parse_team(+ {"raise_suggestion": {"role": "Support", "reason": "Tickets pile up."}}, ROSTER+ )++ assert team.raise_suggestion is not None+ assert team.raise_suggestion.role == "support"+ assert team.raise_suggestion.reason == "Tickets pile up."+++ ("user_role", "pain_points", "expected_lead", "expected_raise"),+ [+ ("Marketing", [], ["Maria"], None),+ ("Sales/BD", [], ["Max"], None),+ ("Operations", [], ["Frankie"], None),+ ("Product/PM", [], ["Frankie"], None),+ ("Founder/CEO", [], ["Max", "Maria"], None),+ ("Engineering", [], [], "developer"),+ ("HR/People", [], ["Frankie"], "recruiter"),+ (None, ["Social media"], ["Maria"], None),+ (None, ["Finding leads"], ["Max"], None),+ (None, ["Email & outreach"], ["Max"], None),+ (None, ["Reports & data"], ["Frankie"], None),+ (None, ["Scheduling"], ["Frankie"], None),+ (None, ["CRM & data entry"], ["Frankie"], None),+ (None, ["Customer support"], [], "support"),+ (None, ["Research"], [], "researcher"),+ (+ "Marketing",+ ["Finding leads", "Scheduling"],+ ["Maria", "Max", "Frankie"],+ None,+ ),+ ("Other", ["Something else"], [], None),+ ],+)+def test_the_fallback_maps_wizard_answers_to_the_roster(+ user_role: str | None,+ pain_points: list[str],+ expected_lead: list[str],+ expected_raise: str | None,+):+ team = recommend_experts.fallback_expert_recommendations(+ user_role, pain_points, ROSTER+ )++ names = [e.name for e in team.experts]+ # The wizard's answers pick who leads; the rest of the roster fills in+ # behind them so the row is never a single card.+ assert names[: len(expected_lead)] == expected_lead+ assert sorted(names) == sorted(t.name for t in ROSTER)+ assert (team.raise_suggestion.role if team.raise_suggestion else None) == (+ expected_raise+ )+ assert team.source == "fallback"+ # Never claims to have heard anything: the fallback runs when we may+ # not have a transcript at all.+ assert team.diagnosis == recommend_experts.FALLBACK_DIAGNOSIS+++ ("user_role", "expected_names"),+ [+ ("Engineering", ["Eli", "Nadia"]),+ ("HR/People", ["Rhea", "Shay", "Frankie"]),+ ],+)+def test_the_fallback_drops_the_raise_door_once_a_template_covers_it(+ user_role: str, expected_names: list[str]+):+ # With the engineering and people rosters seeded, "nobody covers this"+ # would be a lie: the door only opens when the role is still a gap.+ team = recommend_experts.fallback_expert_recommendations(user_role, [], FULL_ROSTER)++ names = [e.name for e in team.experts]+ assert names[: len(expected_names)] == expected_names+ assert len(names) == min(recommend_experts.MAX_EXPERTS, len(FULL_ROSTER))+ assert team.raise_suggestion is None+++def test_the_fallback_skips_roles_with_no_live_template():+ # Content lags demand: the roster may not have every role seeded.+ team = recommend_experts.fallback_expert_recommendations(+ "Founder/CEO", ["Scheduling"], [MARIA]+ )++ assert [e.name for e in team.experts] == ["Maria"]+++def test_the_fallback_survives_an_empty_roster():+ team = recommend_experts.fallback_expert_recommendations(+ "Engineering", ["Customer support"], []+ )++ assert team.experts == []+ # The raise door does not need a roster to open.+ assert team.raise_suggestion is not None+ assert team.raise_suggestion.role == "developer"+++def test_the_fallback_reason_comes_from_the_template():+ expert = recommend_experts.fallback_expert_recommendations(+ "Marketing", [], ROSTER+ ).experts[0]++ assert expert.reason == "Maria handles marketing."+ assert expert.workflow_names == [+ "LinkedIn Post Generator",+ "Automated Blog Writer",+ "Webpage Copy Improver",+ ]+++def test_the_roster_prompt_line_carries_the_workflows():+ lines = recommend_experts.roster_lines([FRANKIE])++ assert lines == (+ "- tpl-frankie: Frankie — Ops. Frankie handles ops.. "+ "Workflows: Meeting Brief"+ )+++def client(mocker: MockerFixture) -> MagicMock:+ fake = MagicMock()+ fake.chat.completions.create = AsyncMock()+ mocker.patch(+ "backend.api.features.onboarding_dump.recommend_experts.get_openai_client",+ return_value=fake,+ )+ return fake+++def _completion(payload: object) -> SimpleNamespace:+ content = payload if isinstance(payload, str) else json.dumps(payload)+ return SimpleNamespace(+ choices=[SimpleNamespace(message=SimpleNamespace(content=content))]+ )+++async def test_a_good_generation_is_marked_as_read_from_the_transcript(+ client: MagicMock,+):+ client.chat.completions.create.return_value = _completion(+ {+ "diagnosis": "You have a marketing problem and a support problem.",+ "experts": [{"template_id": "tpl-maria", "reason": "You post weekly."}],+ "raise_suggestion": {"role": "support", "reason": "Tickets pile up."},+ }+ )++ team = await recommend_experts.generate_expert_recommendations(+ TRANSCRIPT, user_role="Marketing", pain_points=[], templates=ROSTER+ )++ assert team.source == "llm"+ assert [e.name for e in team.experts] == ["Maria"]+ assert team.raise_suggestion is not None+++async def test_a_dead_generation_degrades_to_the_fallback(client: MagicMock):+ client.chat.completions.create.side_effect = RuntimeError("llm down")++ team = await recommend_experts.generate_expert_recommendations(+ TRANSCRIPT, user_role="Sales/BD", pain_points=[], templates=ROSTER+ )++ assert team.source == "fallback"+ assert team.experts[0].name == "Max"+ assert client.chat.completions.create.await_count == 2+++async def test_a_generation_with_nothing_usable_degrades_to_the_fallback(+ client: MagicMock,+):+ # Every id hallucinated and no raise door: there is nothing to render.+ client.chat.completions.create.return_value = _completion(+ {"experts": [{"template_id": "tpl-nope"}], "raise_suggestion": None}+ )++ team = await recommend_experts.generate_expert_recommendations(+ TRANSCRIPT, user_role="Operations", pain_points=[], templates=ROSTER+ )++ assert team.source == "fallback"+ assert team.experts[0].name == "Frankie"+++async def test_non_json_output_is_retried_once_then_falls_back(client: MagicMock):+ client.chat.completions.create.return_value = _completion("no json here")++ team = await recommend_experts.generate_expert_recommendations(+ TRANSCRIPT, user_role="Marketing", pain_points=[], templates=ROSTER+ )++ assert team.source == "fallback"+ assert client.chat.completions.create.await_count == 2+++async def test_no_transcript_never_reaches_the_model(client: MagicMock):+ team = await recommend_experts.generate_expert_recommendations(+ " ", user_role="Marketing", pain_points=[], templates=ROSTER+ )++ assert team.source == "fallback"+ client.chat.completions.create.assert_not_awaited()+++async def test_a_missing_llm_client_degrades_to_the_fallback(mocker: MockerFixture):+ mocker.patch(+ "backend.api.features.onboarding_dump.recommend_experts.get_openai_client",+ return_value=None,+ )++ team = await recommend_experts.generate_expert_recommendations(+ TRANSCRIPT, user_role="Marketing", pain_points=[], templates=ROSTER+ )++ assert team.source == "fallback"+++async def test_the_prompt_carries_the_roster_and_the_wizard_answers(+ client: MagicMock,+):+ client.chat.completions.create.return_value = _completion(+ {"experts": [{"template_id": "tpl-max"}]}+ )++ await recommend_experts.generate_expert_recommendations(+ TRANSCRIPT,+ user_role="Founder/CEO",+ pain_points=["Finding leads"],+ templates=ROSTER,+ )++ content = client.chat.completions.create.await_args.kwargs["messages"][0]["content"]+ assert "- tpl-max: Max — Sales." in content+ assert "Lead Finder, Contact Enricher" in content+ assert "Founder/CEO" in content+ assert "Finding leads" in content+ assert TRANSCRIPT in content+++def test_fallback_prioritizes_all_matching_templates_before_truncating():+ unrelated = [_template(f"other-{i}", f"Other{i}", "Ops") for i in range(16)]+ first = _template("sales-first", "First", "Sales")+ second = _template("sales-second", "Second", " SALES ")+ team = recommend_experts.fallback_expert_recommendations(+ "Sales/BD", ["Finding leads", "Email & outreach"], [*unrelated, first, second]+ )+ ids = [expert.template_id for expert in team.experts]+ assert ids[:2] == [first.id, second.id]+ assert len(ids) == len(set(ids)) == recommend_experts.MAX_EXPERTS+++async def test_prompt_treats_braces_in_user_and_roster_text_as_literal(+ client: MagicMock,+):+ client.chat.completions.create.return_value = _completion(+ {"experts": [{"template_id": "tpl-max"}]}+ )+ transcript = (+ 'I maintain JSON like {"customer": "{name}"} and {missing} placeholders.'+ )+ template = MAX.model_copy(update={"tagline": "Handles {sales} workflows"})+ team = await recommend_experts.generate_expert_recommendations(+ transcript,+ user_role="{Founder}",+ pain_points=["{Reports}"],+ templates=[template],+ )+ content = client.chat.completions.create.await_args.kwargs["messages"][0]["content"]+ assert transcript in content+ assert "{Founder}" in content+ assert "{Reports}" in content+ assert "{sales}" in content+ assert f"at most {recommend_experts.MAX_EXPERTS} objects" in content+ assert "all three slots" not in content+ assert team.source == "llm"diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/routes.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/routes.pyindex 3ab5afd5e6..c1160743b3 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/routes.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/routes.py@@ -26,6 +26,7 @@ from backend.api.features.onboarding_dump.models import (FinalizeResponse,GreetingDoneResponse,IntroCardResponse,+ RecommendedExpertsResponse,RecommendedProvidersResponse,UploadPartResponse,)@@ -224,6 +225,20 @@ async def get_brain_dump_recommended_providers(return await service.get_recommended_providers(user_id)[email protected]("/recommended-experts", operation_id="get_brain_dump_recommended_experts")+async def get_brain_dump_recommended_experts(+ user_id: Annotated[str, Security(get_user_id)],+) -> RecommendedExpertsResponse:+ """The team AutoPilot proposes: who to hire first, and the raise door.++ Written by a background job beside the greeting one; a plain read+ here, with the deterministic fallback filled in for takes the job+ never ran on. ``ready=false`` means keep polling. ``team`` is null+ when the expert-team feature is off for this user.+ """+ return await service.get_recommended_experts(user_id)++@router.post("/intro/complete", operation_id="complete_brain_dump_greeting")async def complete_brain_dump_greeting(user_id: Annotated[str, Security(get_user_id)],diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.pyindex b71f6c25d8..bd6b728fae 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.py@@ -37,6 +37,7 @@ DISCARD_URL = "/onboarding/brain-dump/"INTRO_URL = "/onboarding/brain-dump/intro"INTRO_COMPLETE_URL = "/onboarding/brain-dump/intro/complete"RECOMMENDED_URL = "/onboarding/brain-dump/recommended-providers"+RECOMMENDED_EXPERTS_URL = "/onboarding/brain-dump/recommended-experts"RECORDING_ID = "rec-1"TRANSCRIPT = "I run a small bakery and I want the weekly order emails handled."@@ -581,6 +582,59 @@ def test_intro_returns_greeting_and_prompts_before_completion(dumps: DumpStore):assert all(p["title"] and p["prompt"] for p in body["prompts"])+def test_recommended_experts_are_withheld_while_the_team_flag_is_off(+ dumps: DumpStore,+):+ """The route is gated on the brain-dump flag, the team on its own.++ A user without ``ONBOARDING_EXPERT_TEAM`` gets a final answer with no+ team rather than a section that never resolves.+ """+ upload_part()+ finalize()++ response = client.get(RECOMMENDED_EXPERTS_URL)++ assert response.status_code == 200+ assert response.json() == {"ready": True, "team": None}+++def test_recommended_experts_returns_the_stored_team(+ dumps: DumpStore, mocker: MockerFixture+):+ mocker.patch(+ "backend.api.features.onboarding_dump.service.is_feature_enabled",+ new=AsyncMock(return_value=True),+ )+ upload_part()+ finalize()+ assert dumps.row is not None+ dumps.row.recommendedExperts = {+ "diagnosis": "You have a marketing problem.",+ "experts": [+ {+ "template_id": "tpl-maria",+ "name": "Maria",+ "role": "Marketing",+ "avatar_url": "/experts/maria.svg",+ "reason": "You post on LinkedIn weekly.",+ "workflow_names": ["LinkedIn Post Generator"],+ }+ ],+ "raise_suggestion": {"role": "support", "reason": "Tickets pile up."},+ "source": "llm",+ }++ response = client.get(RECOMMENDED_EXPERTS_URL)++ assert response.status_code == 200+ body = response.json()+ assert body["ready"] is True+ assert body["team"]["source"] == "llm"+ assert [e["name"] for e in body["team"]["experts"]] == ["Maria"]+ assert body["team"]["raise_suggestion"]["role"] == "support"++def test_recommended_providers_are_pending_until_the_job_writes(dumps: DumpStore):upload_part()finalize()@@ -624,6 +678,7 @@ def test_recommended_providers_returns_the_stored_picks(dumps: DumpStore):lambda: client.get(INTRO_URL),lambda: client.post(INTRO_COMPLETE_URL),lambda: client.get(RECOMMENDED_URL),+ lambda: client.get(RECOMMENDED_EXPERTS_URL),],ids=["parts",@@ -634,6 +689,7 @@ def test_recommended_providers_returns_the_stored_picks(dumps: DumpStore):"intro","complete","recommended-providers",+ "recommended-experts",],)def test_every_endpoint_is_404_when_the_flag_is_off(diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/service.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/service.pyindex 1ca0b62e82..79743f446b 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/service.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/service.py@@ -13,19 +13,25 @@ from fastapi import BackgroundTasksfrom prisma import Jsonfrom prisma.enums import BrainDumpInputMode, BrainDumpStatusfrom prisma.models import OnboardingBrainDump+from pydantic import ValidationError+from backend.api.features.experts.experts_db import list_templates+from backend.api.features.experts.models import Expertfrom backend.api.features.onboarding_dump import (db,intro,prompts,quality,recommend,+ recommend_experts,storage,transcription,)from backend.api.features.onboarding_dump.models import (+ ExpertRecommendations,FinalizeResponse,IntroCardResponse,+ RecommendedExpertsResponse,RecommendedProvider,RecommendedProvidersResponse,SuggestedPrompt,@@ -38,6 +44,7 @@ from backend.data.understanding import (get_business_understanding,upsert_business_understanding,)+from backend.util.feature_flag import Flag, is_feature_enabledfrom backend.util.virus_scanner import scan_content_safelogger = logging.getLogger(__name__)@@ -327,19 +334,33 @@ async def _run_background_jobs(transcript: str,input_mode: BrainDumpInputMode,) -> None:- """Run the greeting pipeline and the recommendation job side by side.+ """Run the greeting pipeline and the recommendation jobs side by side.- One background task, not two: ``BackgroundTasks`` awaits what it is+ Snapshot the signup context before extraction updates it; recommendations+ read the current transcript directly. Keep the dump pending until all+ jobs settle so readers do not replace an in-flight team with a fallback.++ One background task, not three: ``BackgroundTasks`` awaits what it isgiven strictly in order, so a second entry would not start until thegreeting's LLM calls had finished — and would never start at all ifsomething escaped the first one. Gathered here they are genuinely- concurrent, and neither can take the other down.+ concurrent, and none can take the others down."""- await asyncio.gather(+ wizard_context = await _safe_understanding(user_id)+ results = await asyncio.gather(_run_completion(user_id, recording_id, transcript, input_mode),_run_provider_recommendations(user_id, recording_id, transcript),+ _run_expert_recommendations(user_id, recording_id, transcript, wizard_context),return_exceptions=True,)+ if results[0] is True:+ try:+ await db.update_dump(+ user_id, recording_id, status=BrainDumpStatus.completed+ )+ except Exception as e:+ logger.error("Brain dump completion failed for user %s: %s", user_id, e)+ await db.mark_failed(user_id, recording_id, "understanding_failed")async def _run_completion(@@ -347,7 +368,7 @@ async def _run_completion(recording_id: str,transcript: str,input_mode: BrainDumpInputMode,-) -> None:+) -> bool:"""Background half of the pipeline, run after the response is sent.Anything that escapes here has no request to report to, so it marks@@ -355,10 +376,14 @@ async def _run_completion(/status) instead of leaving it to hang until its ceiling."""try:- await _extract_and_complete(user_id, recording_id, transcript, input_mode)+ result = await _extract_and_complete(+ user_id, recording_id, transcript, input_mode+ )+ return result.status == BrainDumpStatus.completedexcept Exception as e: # background task, nowhere to raiselogger.error("Brain dump completion failed for user %s: %s", user_id, e)await db.mark_failed(user_id, recording_id, "understanding_failed")+ return Falseasync def _run_provider_recommendations(@@ -416,6 +441,140 @@ def _stored_recommendations(raw: object) -> list[RecommendedProvider]:]+async def _run_expert_recommendations(+ user_id: str,+ recording_id: str,+ transcript: str,+ wizard_context: tuple[str | None, list[str]],+) -> None:+ """The team job, third leg of the background gather.++ Like the provider job it writes one column and never the dump status,+ so it cannot strand the loading screen. It always writes *something*:+ a row left with a null column is "still running" to the reader, and+ the client would poll it until its own ceiling.+ """+ if not await _expert_team_enabled(user_id):+ # Flag off: recorded rather than skipped, so the reader can tell+ # "the feature was off" apart from a job that died — and so no+ # roster read or LLM call is paid for a team nobody will see.+ await _store_team(+ user_id, recording_id, ExpertRecommendations(source="disabled")+ )+ return++ user_role, pain_points = wizard_context+ team = await recommend_experts.generate_expert_recommendations(+ transcript,+ user_role=user_role,+ pain_points=pain_points,+ templates=await _safe_templates(),+ )+ await _store_team(user_id, recording_id, team)+++async def _store_team(+ user_id: str, recording_id: str, team: ExpertRecommendations+) -> None:+ try:+ await db.update_dump(+ user_id, recording_id, recommendedExperts=Json(team.model_dump())+ )+ except Exception as e: # background task, nowhere to raise+ logger.warning(+ "Brain dump expert recommendations not stored for user %s: %s", user_id, e+ )+++async def _expert_team_enabled(user_id: str) -> bool:+ """Whether the expert-team feature is on for ``user_id``.++ ``ONBOARDING_EXPERT_TEAM`` is a child of ``HIRE_EXPERTS``: a user who+ cannot hire must not be shown hire cards.+ """+ return await is_feature_enabled(+ Flag.HIRE_EXPERTS, user_id, default=False+ ) and await is_feature_enabled(Flag.ONBOARDING_EXPERT_TEAM, user_id, default=False)+++async def _safe_understanding(user_id: str) -> tuple[str | None, list[str]]:+ """``(user_role, pain_points)`` from the signup wizard's answers.++ A read that fails costs the recommendation its wizard context, not+ the recommendation.+ """+ try:+ understanding = await get_business_understanding(user_id)+ except Exception as e:+ logger.warning("Brain dump team: understanding read failed: %s", e)+ return None, []+ if understanding is None:+ return None, []+ return understanding.user_role, understanding.pain_points+++async def _safe_templates() -> list[Expert]:+ try:+ return await list_templates()+ except Exception as e:+ logger.warning("Brain dump team: roster read failed: %s", e)+ return []+++async def get_recommended_experts(user_id: str) -> RecommendedExpertsResponse:+ """The team section's content, polled by the onboarding loading screen.++ ``ready=false`` only while the job is still running; every other+ state — flag off, no dump, a dump the job never got to — resolves to+ a final answer here rather than leaving the client polling.+ """+ dump = await db.get_dump(user_id)+ team, pending = await _team_for_intro(user_id, dump)+ return RecommendedExpertsResponse(ready=not pending, team=team)+++async def _team_for_intro(+ user_id: str, dump: OnboardingBrainDump | None+) -> tuple[ExpertRecommendations | None, bool]:+ """``(team, pending)`` for one user, shared by /intro and this reader.++ The invariant both surfaces rely on: with the flag on, a team that is+ not pending is always an object — possibly with no experts — so the+ "raise your own" door is always there to render.+ """+ if not await _expert_team_enabled(user_id):+ return None, False+ if dump is None or _nothing_to_reflect(dump):+ # Path B and every other take with nothing to read: the job never+ # ran, and the wizard's answers are the whole basis for a team.+ return await _fallback_team(user_id), False++ stored = dump.recommendedExperts+ if stored is None:+ if dump.status not in (BrainDumpStatus.completed, BrainDumpStatus.failed):+ return None, True+ # Terminal with nothing written: the job died with the process.+ return await _fallback_team(user_id), False++ try:+ team = ExpertRecommendations.model_validate(stored)+ except ValidationError as e:+ logger.warning("Brain dump team: stored value unusable: %s", e)+ return await _fallback_team(user_id), False+ if team.source == "disabled":+ # Written while the flag was off, and it is on now. Recomputing+ # costs one roster read and strands nobody behind a flag flip.+ return await _fallback_team(user_id), False+ return team, False+++async def _fallback_team(user_id: str) -> ExpertRecommendations:+ user_role, pain_points = await _safe_understanding(user_id)+ return recommend_experts.fallback_expert_recommendations(+ user_role, pain_points, await _safe_templates()+ )++async def _extract_and_complete(user_id: str,recording_id: str,@@ -454,7 +613,6 @@ async def _extract_and_complete(await db.update_dump(user_id,recording_id,- status=BrainDumpStatus.completed,errorCode=None,greeting=greeting,suggestedPrompts=Json([p.model_dump() for p in suggested_prompts]),@@ -558,16 +716,24 @@ async def get_intro_card(user_id: str) -> IntroCardResponse:# the personalised one that is seconds away. Answered before the# session lookup below so that poll does not re-run it every# cycle: someone whose dump is mid-pipeline just recorded it.- return IntroCardResponse(path="A", greeting="", greeting_pending=True)+ return IntroCardResponse(+ path="A",+ greeting="",+ greeting_pending=True,+ team_pending=await _expert_team_enabled(user_id),+ )if await _retire_greeting_if_chatted(user_id):return IntroCardResponse(path="A", greeting="", greeting_done=True)+ team, team_pending = await _team_for_intro(user_id, dump)if dump is None or _nothing_to_reflect(dump):return IntroCardResponse(path="B",greeting=prompts.PATH_B_GREETING,prompts=intro.fallback_prompts(),+ team=team,+ team_pending=team_pending,)greeting = (dump.greeting or "").strip()@@ -580,6 +746,8 @@ async def get_intro_card(user_id: str) -> IntroCardResponse:greeting=greeting,prompts=_stored_prompts(dump.suggestedPrompts),transcript=dump.transcript,+ team=team,+ team_pending=team_pending,)diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.pyindex d250fac560..5bec205ac5 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.py@@ -12,10 +12,12 @@ from unittest.mock import AsyncMockimport pytestfrom fastapi import BackgroundTasks+from prisma import Jsonfrom prisma.enums import BrainDumpInputMode, BrainDumpStatusfrom prisma.models import OnboardingBrainDumpfrom pytest_mock import MockerFixture+from backend.api.features.experts.models import Expertfrom backend.api.features.onboarding_dump import (db,intro,@@ -23,7 +25,12 @@ from backend.api.features.onboarding_dump import (service,transcription,)-from backend.data.understanding import BusinessUnderstandingInput+from backend.api.features.onboarding_dump.models import (+ ExpertRecommendations,+ RecommendedExpert,+ RecommendedExpertsResponse,+)+from backend.data.understanding import BusinessUnderstanding, BusinessUnderstandingInputUSER_ID = "user-1"RECORDING_ID = "rec-1"@@ -37,6 +44,8 @@ LONG_TRANSCRIPT = "the bakery ships pastries every friday morning " * 400_NEW_TAKE_COLUMNS: dict[str, Any] = {**db._TAKE_OWNED_RESET,"suggestedPrompts": [],+ "recommendedProviders": None,+ "recommendedExperts": None,"errorCode": None,}@@ -105,7 +114,7 @@ class DumpStore:if self.row is None or self.row.recordingId != recording_id:return Falsefor name, value in fields.items():- setattr(self.row, name, value)+ setattr(self.row, name, value.data if isinstance(value, Json) else value)status = fields.get("status")if status is not None:self.statuses.append(status)@@ -1204,3 +1213,428 @@ async def test_a_failed_greeting_does_not_cost_the_extraction(assert dumps.row.status == BrainDumpStatus.completedassert dumps.row.greeting == intro.fallback_intro(TRANSCRIPT)[0]extraction["upsert_business_understanding"].assert_awaited_once()+++# --- The expert-team job and its readers -------------------------------+#+# The team is the onboarding's destination, so the contract the tests+# below hold is: with the flag on, a non-pending answer always carries a+# team object, and the flag being off never costs an LLM call.+++def _template(template_id: str, name: str, role: str) -> Expert:+ return Expert.model_construct(+ id=template_id,+ name=name,+ avatar_url=f"/experts/{name.lower()}.svg",+ role=role,+ tagline=f"{name} handles {role.lower()}.",+ bio=None,+ skills=[],+ identity="",+ voice_preferences="",+ boundaries="",+ protected_soul_rules=[],+ is_template=True,+ source_template_id=None,+ is_archived=False,+ workflows=[],+ )+++TEMPLATES = [+ _template("tpl-maria", "Maria", "Marketing"),+ _template("tpl-max", "Max", "Sales"),+ _template("tpl-frankie", "Frankie", "Ops"),+]+++def _stored_team(dumps: DumpStore) -> dict:+ """The team column as a later read returns it."""+ assert dumps.row is not None+ return dumps.row.recommendedExperts+++def team_flag(mocker: MockerFixture) -> AsyncMock:+ """Both flags on. ``ONBOARDING_EXPERT_TEAM`` is a child of+ ``HIRE_EXPERTS``, so the reads are separate and both must pass."""+ mock = AsyncMock(return_value=True)+ mocker.patch.object(service, "is_feature_enabled", new=mock)+ return mock+++def templates(mocker: MockerFixture) -> AsyncMock:+ mock = AsyncMock(return_value=TEMPLATES)+ mocker.patch.object(service, "list_templates", new=mock)+ return mock+++def generate_team(mocker: MockerFixture) -> AsyncMock:+ mock = AsyncMock(+ return_value=ExpertRecommendations(+ diagnosis="You have a marketing problem.",+ experts=[+ RecommendedExpert(+ template_id="tpl-maria", name="Maria", role="Marketing"+ )+ ],+ source="llm",+ )+ )+ mocker.patch(+ "backend.api.features.onboarding_dump.recommend_experts."+ "generate_expert_recommendations",+ new=mock,+ )+ return mock+++async def test_the_flag_being_off_costs_no_llm_call_and_no_roster_read(+ dumps: DumpStore,+ mocker: MockerFixture,+ templates: AsyncMock,+ generate_team: AsyncMock,+):+ """A dark feature must not bill for itself.++ The result is still written: a null column reads as "still running",+ and the client would poll it to its own ceiling.+ """+ mocker.patch.object(+ service, "is_feature_enabled", new=AsyncMock(return_value=False)+ )+ await start_voice_take(dumps)++ await finalize_voice()++ generate_team.assert_not_awaited()+ templates.assert_not_awaited()+ assert _stored_team(dumps) == {+ "diagnosis": "",+ "experts": [],+ "raise_suggestion": None,+ "source": "disabled",+ }+++async def test_the_generated_team_is_stored_with_the_wizard_answers(+ dumps: DumpStore,+ team_flag: AsyncMock,+ templates: AsyncMock,+ generate_team: AsyncMock,+ extraction: dict[str, AsyncMock],+):+ extraction["get_business_understanding"].return_value = (+ BusinessUnderstanding.model_construct(+ user_role="Marketing", pain_points=["Social media"]+ )+ )+ await start_voice_take(dumps)++ await finalize_voice()++ generate_team.assert_awaited_once()+ assert generate_team.await_args.kwargs["user_role"] == "Marketing"+ assert generate_team.await_args.kwargs["pain_points"] == ["Social media"]+ assert generate_team.await_args.kwargs["templates"] == TEMPLATES+ assert _stored_team(dumps)["source"] == "llm"+++async def test_a_failed_team_job_still_stores_an_answer(+ dumps: DumpStore,+ team_flag: AsyncMock,+ templates: AsyncMock,+ generate_team: AsyncMock,+):+ """The job never raises, but the roster read around it can.++ Whatever happens, something lands in the column — the client stops+ polling and the greeting page still has a team to draw.+ """+ templates.side_effect = RuntimeError("database down")+ generate_team.side_effect = (+ lambda transcript, *, user_role, pain_points, templates: (+ ExpertRecommendations(source="fallback")+ )+ )+ await start_voice_take(dumps)++ await finalize_voice()++ assert _stored_team(dumps)["source"] == "fallback"+ assert generate_team.await_args.kwargs["templates"] == []+++async def test_the_team_is_withheld_entirely_while_the_flag_is_off(+ dumps: DumpStore, mocker: MockerFixture+):+ mocker.patch.object(+ service, "is_feature_enabled", new=AsyncMock(return_value=False)+ )+ await start_voice_take(dumps)++ response = await service.get_recommended_experts(USER_ID)+ card = await service.get_intro_card(USER_ID)++ assert response == RecommendedExpertsResponse(ready=True, team=None)+ assert card.team is None+ assert card.team_pending is False+++async def test_the_team_is_pending_while_the_job_is_still_running(+ dumps: DumpStore, team_flag: AsyncMock, templates: AsyncMock+):+ await start_voice_take(dumps)+ await dumps.update_dump(+ USER_ID,+ RECORDING_ID,+ status=BrainDumpStatus.extracting,+ transcript=TRANSCRIPT,+ recommendedExperts=None,+ )++ response = await service.get_recommended_experts(USER_ID)++ assert response.ready is False+ assert response.team is None+++async def test_a_terminal_dump_with_no_stored_team_falls_back(+ dumps: DumpStore, team_flag: AsyncMock, templates: AsyncMock+):+ """The job died with the process, so nothing is coming.++ Left pending the client would poll to its ceiling and then show+ nothing at all.+ """+ await start_voice_take(dumps)+ await dumps.update_dump(+ USER_ID,+ RECORDING_ID,+ status=BrainDumpStatus.completed,+ transcript=TRANSCRIPT,+ recommendedExperts=None,+ )++ response = await service.get_recommended_experts(USER_ID)++ assert response.ready is True+ assert response.team is not None+ assert response.team.source == "fallback"+++async def test_a_stored_team_is_served_as_written(+ dumps: DumpStore, team_flag: AsyncMock, templates: AsyncMock+):+ await start_voice_take(dumps)+ await dumps.update_dump(+ USER_ID,+ RECORDING_ID,+ status=BrainDumpStatus.completed,+ transcript=TRANSCRIPT,+ recommendedExperts={+ "diagnosis": "You have a sales problem.",+ "experts": [{"template_id": "tpl-max", "name": "Max", "role": "Sales"}],+ "raise_suggestion": {"role": "support", "reason": "Tickets pile up."},+ "source": "llm",+ },+ )++ response = await service.get_recommended_experts(USER_ID)++ assert response.ready is True+ assert response.team is not None+ assert response.team.source == "llm"+ assert [e.name for e in response.team.experts] == ["Max"]+ assert response.team.raise_suggestion is not None+ templates.assert_not_awaited()+++async def test_a_malformed_stored_team_falls_back_rather_than_500s(+ dumps: DumpStore, team_flag: AsyncMock, templates: AsyncMock+):+ await start_voice_take(dumps)+ await dumps.update_dump(+ USER_ID,+ RECORDING_ID,+ status=BrainDumpStatus.completed,+ transcript=TRANSCRIPT,+ recommendedExperts={"experts": "not-a-list"},+ )++ response = await service.get_recommended_experts(USER_ID)++ assert response.ready is True+ assert response.team is not None+ assert response.team.source == "fallback"+++async def test_a_team_written_while_the_flag_was_off_is_recomputed(+ dumps: DumpStore, team_flag: AsyncMock, templates: AsyncMock+):+ """A flag flip must not strand the user with an empty section.++ ``source="disabled"`` records that the job declined to spend, not+ that this user has no team.+ """+ await start_voice_take(dumps)+ await dumps.update_dump(+ USER_ID,+ RECORDING_ID,+ status=BrainDumpStatus.completed,+ transcript=TRANSCRIPT,+ recommendedExperts={"source": "disabled"},+ )++ response = await service.get_recommended_experts(USER_ID)++ assert response.ready is True+ assert response.team is not None+ assert response.team.source == "fallback"+ assert response.team.experts+++async def test_a_skipped_dump_still_gets_a_team(+ dumps: DumpStore, team_flag: AsyncMock, templates: AsyncMock+):+ """Path B has no transcript, so the job never ran for it.++ The raise door has to be reachable anyway, which means the section+ needs a team object to render.+ """+ await service.finalize_skipped_dump(USER_ID, RECORDING_ID)++ card = await service.get_intro_card(USER_ID)++ assert card.path == "B"+ assert card.team is not None+ assert card.team.source == "fallback"+ assert card.team_pending is False+++async def test_the_intro_card_carries_the_stored_team(+ dumps: DumpStore,+ team_flag: AsyncMock,+ templates: AsyncMock,+ generate_team: AsyncMock,+):+ await start_voice_take(dumps)++ await finalize_voice()+ card = await service.get_intro_card(USER_ID)++ assert card.path == "A"+ assert card.team is not None+ assert [e.name for e in card.team.experts] == ["Maria"]+ assert card.team_pending is False+++ "hire_enabled,team_enabled",+ [(False, False), (False, True), (True, False), (True, True)],+)+async def test_pending_greeting_only_waits_for_an_enabled_team(+ dumps: DumpStore,+ team_flag: AsyncMock,+ templates: AsyncMock,+ hire_enabled: bool,+ team_enabled: bool,+):+ team_flag.side_effect = lambda flag, *args, **kwargs: (+ hire_enabled if flag == service.Flag.HIRE_EXPERTS else team_enabled+ )+ await start_voice_take(dumps)+ await dumps.update_dump(+ USER_ID,+ RECORDING_ID,+ status=BrainDumpStatus.extracting,+ transcript=TRANSCRIPT,+ )++ card = await service.get_intro_card(USER_ID)++ assert card.greeting_pending is True+ assert card.team_pending is (hire_enabled and team_enabled)+ assert card.team is None+++async def test_team_uses_signup_snapshot_and_stays_pending_until_its_job_finishes(+ dumps: DumpStore,+ team_flag: AsyncMock,+ templates: AsyncMock,+ generate_team: AsyncMock,+ extraction: dict[str, AsyncMock],+):+ saved = asyncio.Event()+ release_team = asyncio.Event()+ extraction["get_business_understanding"].return_value = (+ BusinessUnderstanding.model_construct(+ user_role="Marketing", pain_points=["Social media"]+ )+ )++ async def save_understanding(*args, **kwargs):+ extraction["get_business_understanding"].return_value = (+ BusinessUnderstanding.model_construct(+ user_role="Operations", pain_points=["Reports & data"]+ )+ )+ saved.set()++ async def generate(transcript, **kwargs):+ await saved.wait()+ assert transcript == TRANSCRIPT+ assert kwargs["user_role"] == "Marketing"+ assert kwargs["pain_points"] == ["Social media"]+ await release_team.wait()+ return ExpertRecommendations(source="llm")++ extraction["upsert_business_understanding"].side_effect = save_understanding+ generate_team.side_effect = generate+ await start_voice_take(dumps)+ task = asyncio.create_task(finalize_voice())+ try:+ await asyncio.wait_for(saved.wait(), timeout=2)+ pending = await service.get_recommended_experts(USER_ID)+ assert pending.ready is False+ assert pending.team is None+ finally:+ release_team.set()+ await asyncio.wait_for(task, timeout=2)+ ready = await service.get_recommended_experts(USER_ID)+ assert ready.ready is True+ assert ready.team is not None+ assert ready.team.source == "llm"+++async def test_failed_final_status_write_does_not_leave_the_dump_pending(+ dumps: DumpStore, mocker: MockerFixture+):+ async def update(user_id, recording_id, **fields):+ if fields.get("status") == BrainDumpStatus.completed:+ raise RuntimeError("completion write failed")+ return await dumps.update_dump(user_id, recording_id, **fields)++ mocker.patch.object(service.db, "update_dump", side_effect=update)+ await start_voice_take(dumps)+ await finalize_voice()+ assert dumps.row is not None+ assert dumps.row.status == BrainDumpStatus.failed+ assert dumps.row.errorCode == "understanding_failed"diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex d0bdc6608a..14a4bb88cc 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -110,6 +110,13 @@ class Flag(str, Enum):# experts cohort.HIRE_EXPERTS = "hire-experts"+ # Child of ``HIRE_EXPERTS``: onboarding ends with a team. The brain+ # dump also produces expert recommendations, the copilot greeting+ # grows a team section, and AutoPilot's empty-roster context tells+ # it that it is the Head of AI. Effective only when both are on;+ # fail-closed (default False).+ ONBOARDING_EXPERT_TEAM = "onboarding-expert-team"+# Mirror of the frontend `skills-hub` flag. Gates marketplace skill# browse and install end-to-end: the routes 404 when off, so the dark# launch is not reachable by URL with the shelf hidden. Fail-closed.diff --git a/autogpt_platform/backend/migrations/20260907120000_add_brain_dump_recommended_experts/migration.sql b/autogpt_platform/backend/migrations/20260907120000_add_brain_dump_recommended_experts/migration.sqlnew file mode 100644index 0000000000..a204d8ede6--- /dev/null+++ b/autogpt_platform/backend/migrations/20260907120000_add_brain_dump_recommended_experts/migration.sql@@ -0,0 +1,8 @@+-- The team AutoPilot proposes on the greeting page: a diagnosis, the+-- roster templates worth hiring first, and an optional "raise your own"+-- suggestion for a need no template covers. Written by a background job+-- beside the greeting one, so a slow or failed team never delays the+-- greeting. NULL means "not generated yet"; a stored `source` of+-- "disabled" records a run the feature flag switched off.+ALTER TABLE "OnboardingBrainDump"+ ADD COLUMN "recommendedExperts" JSONB;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex a23ce96bde..6f2a354346 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -343,6 +343,11 @@ model OnboardingBrainDump {/// and the live provider registry. Null until the recommendation/// background job (separate from the greeting one) writes its result.recommendedProviders Json?+ /// The team AutoPilot proposes off the back of the dump: {diagnosis,+ /// experts, raise_suggestion, source}, where every expert is a live+ /// roster template. Null until its background job writes a result;+ /// `source="disabled"` records a run the feature flag switched off.+ recommendedExperts Json?@@index([userId])}diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.defaultindex 8bc59d9008..d19bfad573 100644--- a/autogpt_platform/frontend/.env.default+++ b/autogpt_platform/frontend/.env.default@@ -101,3 +101,9 @@ OPENAI_API_KEY=# FORCE_FLAG_ONBOARDING_BRAIN_DUMP in backend/.env, and restart the dev# server — NEXT_PUBLIC_* vars are inlined at build time.# NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_BRAIN_DUMP=true++# Expert-first onboarding (`onboarding-expert-team`, child of `hire-experts`):+# the greeting page proposes a team from the brain dump. Needs both flags+# on, here and in backend/.env.+# NEXT_PUBLIC_FORCE_FLAG_HIRE_EXPERTS=true+# NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_EXPERT_TEAM=truediff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 8913623154..e37dbcf402 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -11295,6 +11295,30 @@"security": [{ "HTTPBearerJWT": [] }]}},+ "/api/onboarding/brain-dump/recommended-experts": {+ "get": {+ "tags": ["v1", "onboarding", "onboarding", "brain-dump"],+ "summary": "Get Brain Dump Recommended Experts",+ "description": "The team AutoPilot proposes: who to hire first, and the raise door.\n\nWritten by a background job beside the greeting one; a plain read\nhere, with the deterministic fallback filled in for takes the job\nnever ran on. ``ready=false`` means keep polling. ``team`` is null\nwhen the expert-team feature is off for this user.",+ "operationId": "get_brain_dump_recommended_experts",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RecommendedExpertsResponse"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },"/api/onboarding/brain-dump/recommended-providers": {"get": {"tags": ["v1", "onboarding", "onboarding", "brain-dump"],@@ -20755,6 +20779,36 @@"title": "ExpertPod","description": "A named group of hired experts, scoped to the owner."},+ "ExpertRecommendations": {+ "properties": {+ "diagnosis": {+ "type": "string",+ "title": "Diagnosis",+ "default": ""+ },+ "experts": {+ "items": { "$ref": "#/components/schemas/RecommendedExpert" },+ "type": "array",+ "title": "Experts",+ "default": []+ },+ "raise_suggestion": {+ "anyOf": [+ { "$ref": "#/components/schemas/RaiseSuggestion" },+ { "type": "null" }+ ]+ },+ "source": {+ "type": "string",+ "enum": ["llm", "fallback", "disabled"],+ "title": "Source",+ "default": "fallback"+ }+ },+ "type": "object",+ "title": "ExpertRecommendations",+ "description": "The team AutoPilot proposes after the dump.\n\n``source`` says where it came from: \"llm\" for a real read of the\ntranscript, \"fallback\" for the deterministic role/pain-point mapping,\nand \"disabled\" for a run where the feature flag was off (recorded so\nthe reader can tell it apart from a job that never finished)."+ },"ExpertRun": {"properties": {"execution_id": { "type": "string", "title": "Execution Id" },@@ -22988,6 +23042,17 @@"transcript": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Transcript"+ },+ "team": {+ "anyOf": [+ { "$ref": "#/components/schemas/ExpertRecommendations" },+ { "type": "null" }+ ]+ },+ "team_pending": {+ "type": "boolean",+ "title": "Team Pending",+ "default": false}},"type": "object",@@ -26302,6 +26367,16 @@"title": "RaiseResult","description": "Result of raising a blank expert.\n\nAttachments are validated before the expert row is created. A later\ninstall failure is non-fatal and listed in ``failed_attachments`` so\nthe client can surface partial success."},+ "RaiseSuggestion": {+ "properties": {+ "role": { "type": "string", "title": "Role" },+ "reason": { "type": "string", "title": "Reason", "default": "" }+ },+ "type": "object",+ "required": ["role"],+ "title": "RaiseSuggestion",+ "description": "The \"raise your own\" door, prefilled for a gap the roster can't fill.\n\n``role`` is one of the ``/raise`` wizard's role ids so the link can\nseed the draft; a suggestion naming anything else is dropped."+ },"RateLimitResetResponse": {"properties": {"success": { "type": "boolean", "title": "Success" },@@ -26444,6 +26519,43 @@"title": "RecentExecution","description": "Summary of a recent execution for quality assessment.\n\nUsed by the LLM to understand the agent's recent performance with specific examples\nrather than just aggregate statistics."},+ "RecommendedExpert": {+ "properties": {+ "template_id": { "type": "string", "title": "Template Id" },+ "name": { "type": "string", "title": "Name" },+ "role": { "type": "string", "title": "Role" },+ "avatar_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Avatar Url"+ },+ "reason": { "type": "string", "title": "Reason", "default": "" },+ "workflow_names": {+ "items": { "type": "string" },+ "type": "array",+ "title": "Workflow Names",+ "default": []+ }+ },+ "type": "object",+ "required": ["template_id", "name", "role"],+ "title": "RecommendedExpert",+ "description": "One roster template AutoPilot suggests hiring first.\n\n``template_id`` is always a live template — the model only ever picks\nids off the roster it was shown, and anything else is dropped before\nstorage. ``name``/``role``/``avatar_url`` are copied from that\ntemplate server-side rather than trusted from the model, so a card\ncan never introduce an expert who does not exist."+ },+ "RecommendedExpertsResponse": {+ "properties": {+ "ready": { "type": "boolean", "title": "Ready" },+ "team": {+ "anyOf": [+ { "$ref": "#/components/schemas/ExpertRecommendations" },+ { "type": "null" }+ ]+ }+ },+ "type": "object",+ "required": ["ready"],+ "title": "RecommendedExpertsResponse",+ "description": "The team section's content, polled by the onboarding loading screen.\n\n``ready`` is false only while the background job is still running.\n``team`` is null when the feature is off — a team with no experts is\na real answer, so the client cannot use emptiness to tell them apart."+ },"RecommendedProvider": {"properties": {"provider": { "type": "string", "title": "Provider" },diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.tsindex 3121337bbb..f652d1acab 100644--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts@@ -34,6 +34,9 @@ export enum Flag {// Mirror of the backend ``Flag`` enum — the endpoints 404 when off, so// both sides must agree. Off renders the pillbox flow untouched.ONBOARDING_BRAIN_DUMP = "onboarding-brain-dump",+ // Child of HIRE_EXPERTS: the greeting page builds a team from the brain+ // dump. Mirror of the backend ``Flag`` enum; both must be on.+ ONBOARDING_EXPERT_TEAM = "onboarding-expert-team",// Graphiti memory + dream-system gates. Mirror of the backend// ``Flag`` enum in ``backend/util/feature_flag.py``. Frontend reads// them when memory/dream-related UI surfaces ship (P6+ on the@@ -86,6 +89,7 @@ const defaultFlags = {// brain dump for everyone — which is what the backend 404s are meant to// prevent. Use NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_BRAIN_DUMP locally.[Flag.ONBOARDING_BRAIN_DUMP]: false,+ [Flag.ONBOARDING_EXPERT_TEAM]: false,[Flag.GRAPHITI_MEMORY]: false,[Flag.GRAPHITI_COMMUNITIES_ENABLED]: false,[Flag.DREAM_PASS_ENABLED]: false,@@ -154,6 +158,8 @@ function readEnvOverride(flag: Flag): string | undefined {return process.env.NEXT_PUBLIC_FORCE_FLAG_SETTINGS_NOTIFICATIONS;case Flag.ONBOARDING_BRAIN_DUMP:return process.env.NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_BRAIN_DUMP;+ case Flag.ONBOARDING_EXPERT_TEAM:+ return process.env.NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_EXPERT_TEAM;case Flag.GRAPHITI_MEMORY:return process.env.NEXT_PUBLIC_FORCE_FLAG_GRAPHITI_MEMORY;case Flag.GRAPHITI_COMMUNITIES_ENABLED: