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): choose generated avatars when raising experts (#14461)
Abhimanyu Yadav6cbdbec5065e
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_avatar.py b/autogpt_platform/backend/backend/copilot/tools/expert_avatar.pynew file mode 100644index 0000000000..b44ca32c69--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/expert_avatar.py@@ -0,0 +1,103 @@+"""Generated expert avatars: a shape, a colour and one accessory.++The frontend draws these from a site-relative ``/avatars/<shape>.<color>.<accessory>.svg``+URL, so an expert raised by AutoPilot gets a face without an upload. The id+lists and the name hash mirror ``components/molecules/BotAvatar/helpers.ts``+so a name seeds the same look on both sides.+"""++AVATAR_SHAPES = ["round", "dome", "squircle", "wide", "bean"]+AVATAR_COLORS = [+ "lavender",+ "plum",+ "amber",+ "sky",+ "mint",+ "coral",+ "indigo",+ "butter",+]+AVATAR_ACCESSORIES = [+ "none",+ "glasses",+ "headset",+ "star",+ "bow",+ "badge",+ "crown",+ "propeller",+ "ears",+ "flower",+ "bowtie",+ "headband",+]++# Accent colour token family -> avatar colour, tuned so the accent and the+# face agree without the model having to pick twice.+_TOKEN_COLORS = {+ "rose": "plum",+ "red": "coral",+ "orange": "coral",+ "amber": "amber",+ "yellow": "butter",+ "lime": "mint",+ "green": "mint",+ "emerald": "mint",+ "teal": "sky",+ "cyan": "sky",+ "sky": "sky",+ "blue": "sky",+ "indigo": "indigo",+ "violet": "lavender",+ "fuchsia": "plum",+}+++def avatar_color_for_token(token: str | None) -> str | None:+ if not token:+ return None+ return _TOKEN_COLORS.get(token.split("-", 1)[0])+++def _hash_seed(value: str) -> int:+ seed = 2166136261+ for char in value:+ seed ^= ord(char)+ seed = (seed * 16777619) & 0xFFFFFFFF+ return seed+++def _seeded_random(seed: int):+ state = seed or 1++ def next_value() -> float:+ nonlocal state+ state = (state * 1664525 + 1013904223) & 0xFFFFFFFF+ return state / 4294967296++ return next_value+++def seeded_avatar(name: str) -> tuple[str, str, str]:+ """Shape / colour / accessory the frontend would seed for *name*."""+ random = _seeded_random(_hash_seed(name.lower()))+ shape = AVATAR_SHAPES[int(random() * len(AVATAR_SHAPES))]+ color = AVATAR_COLORS[int(random() * len(AVATAR_COLORS))]+ accessory = AVATAR_ACCESSORIES[int(random() * len(AVATAR_ACCESSORIES))]+ return shape, color, accessory+++def build_avatar_url(+ name: str,+ *,+ shape: str | None = None,+ accessory: str | None = None,+ color_token: str | None = None,+) -> str:+ """Resolve the generated-avatar URL, seeding whatever was not chosen."""+ seeded_shape, seeded_color, seeded_accessory = seeded_avatar(name)+ return (+ f"/avatars/{shape or seeded_shape}."+ f"{avatar_color_for_token(color_token) or seeded_color}."+ f"{accessory or seeded_accessory}.svg"+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_change_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_change_test.pyindex fff39065de..2ac9725fa8 100644--- a/autogpt_platform/backend/backend/copilot/tools/expert_change_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/expert_change_test.py@@ -48,11 +48,16 @@ _CHARTER = {"role": "Inbox triage","tagline": "Sorts your morning inbox and drafts the routine replies.","color": "violet-300",+ "avatar_shape": "round",+ "avatar_accessory": "glasses","about": "You group the morning inbox and draft routine replies.","boundaries": "You never send a reply yourself.",}+AVATAR_KEYS = {"avatar_shape", "avatar_accessory"}++class _FakeRedis:"""Minimal async Redis: the setex/get/delete surface the tools use."""@@ -228,8 +233,40 @@ class TestPreviewNeverWrites:assert resp.preview.about == _CHARTER["about"]assert resp.preview.boundaries == _CHARTER["boundaries"]assert resp.preview.color == _CHARTER["color"]+ assert resp.preview.avatar_url == "/avatars/round.lavender.glasses.svg"db.create_raised_expert.assert_not_called()+ @pytest.mark.asyncio(loop_scope="session")+ async def test_raise_seeds_an_avatar_from_the_name_when_none_is_picked(self):+ with _env():+ charter = {k: v for k, v in _CHARTER.items() if k not in AVATAR_KEYS}+ resp = await _raise(make_session(_USER), **charter)+ assert isinstance(resp, ExpertChangeProposedResponse)+ # Golden vector cross-checked against the frontend's configForName:+ # "otto" seeds wide/butter/crown and the violet token maps to lavender.+ # A literal, not build_avatar_url(), so a drift in the FNV/LCG+ # constants or pick order fails here instead of comparing the+ # implementation to itself.+ assert resp.preview.avatar_url == "/avatars/wide.lavender.crown.svg"++ @pytest.mark.asyncio(loop_scope="session")+ async def test_raise_rejects_an_unknown_avatar_shape(self):+ with _env():+ resp = await _raise(+ make_session(_USER), **{**_CHARTER, "avatar_shape": "cube"}+ )+ assert isinstance(resp, ErrorResponse)+ assert "avatar_shape" in resp.message++ @pytest.mark.asyncio(loop_scope="session")+ async def test_raise_rejects_an_unknown_avatar_accessory(self):+ with _env():+ resp = await _raise(+ make_session(_USER), **{**_CHARTER, "avatar_accessory": "monocle"}+ )+ assert isinstance(resp, ErrorResponse)+ assert "avatar_accessory" in resp.message+@pytest.mark.asyncio(loop_scope="session")async def test_hire_preview_carries_the_template_tagline(self):with _env():@@ -541,6 +578,7 @@ class TestConfirm:_CHARTER["name"],_CHARTER["role"],None,+ avatar_url=preview.preview.avatar_url,color=_CHARTER["color"],tagline=_CHARTER["tagline"],about=_CHARTER["about"],diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_proposal.py b/autogpt_platform/backend/backend/copilot/tools/expert_proposal.pyindex e1a447175f..13a77177e8 100644--- a/autogpt_platform/backend/backend/copilot/tools/expert_proposal.py+++ b/autogpt_platform/backend/backend/copilot/tools/expert_proposal.py@@ -380,6 +380,7 @@ async def _apply_raise(preview.name,preview.role or None,preview.voice_preferences or None,+ avatar_url=preview.avatar_url,color=preview.color or None,tagline=preview.tagline or None,about=preview.about or None,diff --git a/autogpt_platform/backend/backend/copilot/tools/raise_expert.py b/autogpt_platform/backend/backend/copilot/tools/raise_expert.pyindex d45792245e..011150d5be 100644--- a/autogpt_platform/backend/backend/copilot/tools/raise_expert.py+++ b/autogpt_platform/backend/backend/copilot/tools/raise_expert.py@@ -26,6 +26,7 @@ from backend.data.db_accessors import experts_dbfrom backend.data.redis_client import get_redis_asyncfrom .base import BaseTool+from .expert_avatar import AVATAR_ACCESSORIES, AVATAR_SHAPES, build_avatar_urlfrom .expert_proposal import (ExpertChangeProposal,autopilot_session_guard,@@ -88,19 +89,7 @@ class RaiseExpertTool(BaseTool):@propertydef description(self) -> str:- return (- "Propose a brand-new expert when no roster template fits. Give "- "them a personal first name (the role field carries the job "- "title), a one-line tagline and an accent color, then write "- "their charter: what they own, what good looks like, and where "- "they stop (always fill boundaries — an expert without them "- "oversteps). This tool never writes; it returns the proposed "- "expert plus a one-time confirmation_id. "- "The user sees the whole charter on a card with Approve and "- "Decline buttons, so never repeat it in text — one short line "- "at most, then wait. Only after the user approves, call "- "confirm_expert_change with that id."- )+ return "Preview a new expert when no template fits: personal name, role, tagline, color and charter (ownership, success criteria, boundaries). Returns a one-time confirmation_id; never applies the hire. The card shows the charter, so add at most one short line. Wait for the user's approval before calling confirm_expert_change with that id."@propertydef parameters(self) -> dict[str, Any]:@@ -110,9 +99,7 @@ class RaiseExpertTool(BaseTool):"name": {"type": "string","description": (- "A personal first name the user will call them — "- "like a teammate's name, never a job title. The "- "role field carries the title."+ "Personal first name, not a job title (use role for that)."),},"role": {@@ -122,25 +109,30 @@ class RaiseExpertTool(BaseTool):"tagline": {"type": "string","description": (- "One line, third person, what they do for the user "- "— e.g. 'Finds your leads and their decision-makers.' "- "Under 120 characters. This is what the user reads "- "on their card; the charter is for the expert."+ "Third-person summary under 120 characters, e.g. 'Finds leads and decision-makers.' Shown on the card."),},"color": {"type": "string","enum": COLOR_TOKENS,+ "description": ("Accent token for the avatar and chat theme."),+ },+ "avatar_shape": {+ "type": "string",+ "enum": AVATAR_SHAPES,+ "description": ("Avatar silhouette; omit for a name-seeded shape."),+ },+ "avatar_accessory": {+ "type": "string",+ "enum": AVATAR_ACCESSORIES,"description": (- "Accent color for their avatar and chat theme. "- "Pick one that fits their personality."+ "One accessory suited to their role or personality; omit for a name-seeded choice."),},"about": {"type": "string","description": (- "Their charter in second person: what they own, how "- "they work, what good looks like. Becomes identity."+ "Second-person charter: ownership, working approach and success criteria. Becomes identity."),},"boundaries": {@@ -171,6 +163,8 @@ class RaiseExpertTool(BaseTool):role: str = "",tagline: str = "",color: str = "",+ avatar_shape: str = "",+ avatar_accessory: str = "",about: str = "",boundaries: str = "",voice_preferences: str = "",@@ -191,6 +185,24 @@ class RaiseExpertTool(BaseTool):),session_id=session_id,)+ avatar_shape = avatar_shape.strip()+ if avatar_shape and avatar_shape not in AVATAR_SHAPES:+ return ErrorResponse(+ message=(+ "Invalid expert charter — avatar_shape must be one of: "+ + ", ".join(AVATAR_SHAPES)+ ),+ session_id=session_id,+ )+ avatar_accessory = avatar_accessory.strip()+ if avatar_accessory and avatar_accessory not in AVATAR_ACCESSORIES:+ return ErrorResponse(+ message=(+ "Invalid expert charter — avatar_accessory must be one of: "+ + ", ".join(AVATAR_ACCESSORIES)+ ),+ session_id=session_id,+ )try:params = _RaiseParams(# Collapsed, not just stripped: the roster block in@@ -252,6 +264,12 @@ class RaiseExpertTool(BaseTool):role=params.role,tagline=params.tagline,color=params.color,+ avatar_url=build_avatar_url(+ params.name,+ shape=avatar_shape or None,+ accessory=avatar_accessory or None,+ color_token=params.color or None,+ ),about=soul.identity or "",boundaries=soul.boundaries,voice_preferences=soul.voice_preferences or "",