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 get_platform_info tool for tier-aware AutoPilot (#13000)
Nicholas Tindle4f2d6bdd9f8b
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.pyindex 0c72a3f50a..f3930c5ec4 100644--- a/autogpt_platform/backend/backend/copilot/baseline/service.py+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py@@ -1577,6 +1577,7 @@ async def stream_chat_completion_baseline(session_id,session.messages,budget_ctx=budget_ctx,+ user_id=user_id,)if prefixed is not None:# Reverse scan so we update the current turn's user message, notdiff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.pyindex b3b4452dd3..5531fdd5e9 100644--- a/autogpt_platform/backend/backend/copilot/permissions.py+++ b/autogpt_platform/backend/backend/copilot/permissions.py@@ -91,6 +91,7 @@ ToolName = Literal["get_agent_building_guide","get_doc_page","get_mcp_guide",+ "get_platform_info","get_sub_session_result","list_folders","list_workspace_files",diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 6ca31c7c24..f9427f2d80 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -4182,6 +4182,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuessession.messages,warm_ctx=warm_ctx,env_ctx=env_ctx_content,+ user_id=user_id,)if prefixed_message is not None:current_message = prefixed_messagediff --git a/autogpt_platform/backend/backend/copilot/service.py b/autogpt_platform/backend/backend/copilot/service.pyindex 00460233a7..1b4b6629fe 100644--- a/autogpt_platform/backend/backend/copilot/service.py+++ b/autogpt_platform/backend/backend/copilot/service.py@@ -111,7 +111,7 @@ BUDGET_CONTEXT_TAG = "budget_context"# sdk/service.py, baseline/service.py, dry_run_loop_test.py, and# prompt_cache_test.py. The leading underscore is retained for backwards# compatibility; CACHEABLE_SYSTEM_PROMPT is exported as the public alias.-_CACHEABLE_SYSTEM_PROMPT = f"""You are an AI automation assistant helping users build and run automations.+_CACHEABLE_SYSTEM_PROMPT = f"""You are AutoPilot, the AI assistant on the AutoGPT platform, helping users build and run automations.Your goal is to help users automate tasks by:- Understanding their needs and business context@@ -394,6 +394,7 @@ async def inject_user_context(warm_ctx: str = "",env_ctx: str = "",budget_ctx: str = "",+ user_id: str | None = None,) -> str | None:"""Prepend trusted context blocks to the first user message.@@ -458,6 +459,13 @@ async def inject_user_context(final_message = sanitized_messageelse:raw_ctx = format_understanding_for_prompt(understanding)+ # Append subscription tier so the agent has ambient awareness.+ if user_id:+ from .rate_limit import get_user_tier++ tier = await get_user_tier(user_id)+ tier_line = f"Plan: {tier.value}"+ raw_ctx = f"{raw_ctx}\n{tier_line}" if raw_ctx else tier_lineif not raw_ctx:# All BusinessUnderstanding fields are empty/None — injecting an# empty <user_context>\n\n</user_context> block adds no value anddiff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.pyindex 7e5613f864..a060e96346 100644--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py@@ -38,6 +38,7 @@ from .manage_folders import (MoveFolderTool,UpdateFolderTool,)+from .platform_info import PlatformInfoToolfrom .run_agent import RunAgentToolfrom .run_block import RunBlockToolfrom .run_mcp_tool import RunMCPToolTool@@ -107,6 +108,8 @@ TOOL_REGISTRY: dict[str, BaseTool] = {# Feature request tools"search_feature_requests": SearchFeatureRequestsTool(),"create_feature_request": CreateFeatureRequestTool(),+ # Platform info (subscription, billing)+ "get_platform_info": PlatformInfoTool(),# Agent generation tools (local validation/fixing)"validate_agent_graph": ValidateAgentGraphTool(),"fix_agent_graph": FixAgentGraphTool(),diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex e45ff19e34..03084d1e4a 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -91,6 +91,9 @@ class ResponseType(str, Enum):# PlanningTODO_WRITE = "todo_write"+ # Platform info+ PLATFORM_INFO = "platform_info"+# Base response modelclass ToolResponseBase(BaseModel):@@ -877,3 +880,12 @@ class TodoWriteResponse(ToolResponseBase):type: ResponseType = ResponseType.TODO_WRITEtodos: list[TodoItem] = Field(default_factory=list)+++class PlatformInfoResponse(ToolResponseBase):+ """Response from the ``get_platform_info`` tool."""++ type: ResponseType = ResponseType.PLATFORM_INFO+ topic: str+ tier: str | None = None+ billing_url: str | None = "/settings/billing"diff --git a/autogpt_platform/backend/backend/copilot/tools/platform_info.py b/autogpt_platform/backend/backend/copilot/tools/platform_info.pynew file mode 100644index 0000000000..abba0cffed--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/platform_info.py@@ -0,0 +1,134 @@+"""Platform info tool — on-demand subscription and billing data for AutoPilot."""++import logging+from typing import Any++from backend.copilot.model import ChatSession+from backend.copilot.rate_limit import get_user_tier++from .base import BaseTool+from .models import ErrorResponse, PlatformInfoResponse, ToolResponseBase++logger = logging.getLogger(__name__)++# Human-friendly tier names shown to the user.+_TIER_DISPLAY_NAMES: dict[str, str] = {+ "NO_TIER": "No active subscription",+ "BASIC": "Basic",+ "PRO": "Pro",+ "MAX": "Max",+ "BUSINESS": "Business",+ "ENTERPRISE": "Enterprise",+}+++class PlatformInfoTool(BaseTool):+ """Provides the user's subscription tier and billing link on demand."""++ @property+ def name(self) -> str:+ return "get_platform_info"++ @property+ def description(self) -> str:+ return "Call when the user asks about their plan, billing, or account."++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {+ "topic": {+ "type": "string",+ "enum": ["subscription"],+ "description": "The platform topic to query.",+ },+ },+ "required": ["topic"],+ }++ @property+ def requires_auth(self) -> bool:+ return True++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ topic: str = "subscription",+ **kwargs: Any,+ ) -> ToolResponseBase:+ session_id = session.session_id++ if topic == "subscription":+ return await self._handle_subscription(user_id, session_id)++ return ErrorResponse(+ message=f"Unknown topic '{topic}'. Available topics: subscription",+ error="invalid_topic",+ session_id=session_id,+ )++ async def _handle_subscription(+ self,+ user_id: str | None,+ session_id: str | None,+ ) -> ToolResponseBase:+ if not user_id:+ return ErrorResponse(+ message="Authentication required.",+ error="missing_user_id",+ session_id=session_id,+ )++ # When billing is disabled (self-hosted, beta cohort), skip tier+ # lookup and report open access — there is no billing page to manage.+ from backend.util.feature_flag import Flag, is_feature_enabled++ billing_enabled = await is_feature_enabled(+ Flag.ENABLE_PLATFORM_PAYMENT, user_id+ )+ if not billing_enabled:+ return PlatformInfoResponse(+ message=(+ "Billing is not enabled on this deployment. "+ "You have open access to the platform. "+ "You are AutoPilot, running on the AutoGPT platform. "+ "Under the hood you may use models via OpenRouter or Claude SDK, "+ "but only mention the AutoGPT platform to the user — "+ "that is the only thing they can manage or change. "+ "Never direct users to external AI provider billing pages."+ ),+ topic="subscription",+ tier="OPEN_ACCESS",+ billing_url=None,+ session_id=session_id,+ )++ try:+ tier = await get_user_tier(user_id)+ except Exception:+ logger.exception("Failed to fetch subscription info for user %s", user_id)+ return ErrorResponse(+ message="Could not retrieve subscription info.",+ error="tier_lookup_failed",+ session_id=session_id,+ )++ display_name = _TIER_DISPLAY_NAMES.get(tier.value, tier.value)++ return PlatformInfoResponse(+ message=(+ f"You are on the {display_name} plan. "+ "You can manage your billing and subscription at Settings → Billing. "+ "You are AutoPilot, running on the AutoGPT platform. "+ "Under the hood you may use models via OpenRouter or Claude SDK, "+ "but only mention the AutoGPT platform to the user — "+ "that is the only thing they can manage or change. "+ "Never direct users to external AI provider billing pages."+ ),+ topic="subscription",+ tier=tier.value,+ billing_url="/settings/billing",+ session_id=session_id,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/test_platform_info.py b/autogpt_platform/backend/backend/copilot/tools/test_platform_info.pynew file mode 100644index 0000000000..464663e9e0--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/test_platform_info.py@@ -0,0 +1,207 @@+"""Tests for the get_platform_info tool."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.rate_limit import SubscriptionTier+from backend.copilot.tools.models import ResponseType+from backend.copilot.tools.platform_info import PlatformInfoTool++# Shorthand patch targets+_TIER_PATH = "backend.copilot.tools.platform_info.get_user_tier"+_FLAG_PATH = "backend.util.feature_flag.is_feature_enabled"+++def tool():+ return PlatformInfoTool()+++def mock_session():+ session = MagicMock()+ session.session_id = "test-session-123"+ return session+++def _billing_enabled():+ """Mock ``is_feature_enabled`` returning True (billing ON)."""+ return patch(_FLAG_PATH, new_callable=AsyncMock, return_value=True)+++def _billing_disabled():+ """Mock ``is_feature_enabled`` returning False (billing OFF)."""+ return patch(_FLAG_PATH, new_callable=AsyncMock, return_value=False)+++class TestPlatformInfoTool:+ def test_name(self, tool):+ assert tool.name == "get_platform_info"++ def test_requires_auth(self, tool):+ assert tool.requires_auth is True++ def test_is_available(self, tool):+ assert tool.is_available is True++ def test_parameters_schema(self, tool):+ params = tool.parameters+ assert params["type"] == "object"+ assert "topic" in params["properties"]+ assert "subscription" in params["properties"]["topic"]["enum"]++ @pytest.mark.asyncio+ async def test_subscription_topic_pro(self, tool, mock_session):+ with (+ _billing_enabled(),+ patch(+ _TIER_PATH, new_callable=AsyncMock, return_value=SubscriptionTier.PRO+ ),+ ):+ result = await tool._execute(+ user_id="user-1", session=mock_session, topic="subscription"+ )++ assert result.type == ResponseType.PLATFORM_INFO+ assert result.tier == "PRO"+ assert result.billing_url == "/settings/billing"+ assert "Pro" in result.message+ assert "Settings" in result.message++ @pytest.mark.asyncio+ async def test_subscription_topic_no_tier(self, tool, mock_session):+ with (+ _billing_enabled(),+ patch(+ _TIER_PATH,+ new_callable=AsyncMock,+ return_value=SubscriptionTier.NO_TIER,+ ),+ ):+ result = await tool._execute(+ user_id="user-1", session=mock_session, topic="subscription"+ )++ assert result.type == ResponseType.PLATFORM_INFO+ assert result.tier == "NO_TIER"+ assert "No active subscription" in result.message++ @pytest.mark.asyncio+ async def test_subscription_topic_max(self, tool, mock_session):+ with (+ _billing_enabled(),+ patch(+ _TIER_PATH, new_callable=AsyncMock, return_value=SubscriptionTier.MAX+ ),+ ):+ result = await tool._execute(+ user_id="user-1", session=mock_session, topic="subscription"+ )++ assert result.tier == "MAX"+ assert "Max" in result.message++ @pytest.mark.asyncio+ async def test_subscription_topic_business(self, tool, mock_session):+ """Business tier is valid — user can be on it, we just don't advertise it."""+ with (+ _billing_enabled(),+ patch(+ _TIER_PATH,+ new_callable=AsyncMock,+ return_value=SubscriptionTier.BUSINESS,+ ),+ ):+ result = await tool._execute(+ user_id="user-1", session=mock_session, topic="subscription"+ )++ assert result.tier == "BUSINESS"+ assert "Business" in result.message++ @pytest.mark.asyncio+ async def test_subscription_no_user_id(self, tool, mock_session):+ result = await tool._execute(+ user_id=None, session=mock_session, topic="subscription"+ )+ assert result.type == ResponseType.ERROR++ @pytest.mark.asyncio+ async def test_invalid_topic(self, tool, mock_session):+ result = await tool._execute(+ user_id="user-1", session=mock_session, topic="invalid"+ )+ assert result.type == ResponseType.ERROR+ assert "Unknown topic" in result.message++ @pytest.mark.asyncio+ async def test_tier_lookup_failure(self, tool, mock_session):+ with (+ _billing_enabled(),+ patch(+ _TIER_PATH,+ new_callable=AsyncMock,+ side_effect=Exception("DB down"),+ ),+ ):+ result = await tool._execute(+ user_id="user-1", session=mock_session, topic="subscription"+ )++ assert result.type == ResponseType.ERROR+ assert "Could not retrieve" in result.message++ def test_tool_appears_in_registry(self):+ from backend.copilot.tools import TOOL_REGISTRY++ assert "get_platform_info" in TOOL_REGISTRY+ assert isinstance(TOOL_REGISTRY["get_platform_info"], PlatformInfoTool)++ def test_openai_schema(self, tool):+ schema = tool.as_openai_tool()+ assert schema["type"] == "function"+ assert schema["function"]["name"] == "get_platform_info"++ @pytest.mark.asyncio+ async def test_response_mentions_autogpt_platform(self, tool, mock_session):+ """Platform identity context is in the response, not the description."""+ with (+ _billing_enabled(),+ patch(_TIER_PATH, return_value=SubscriptionTier.PRO),+ ):+ result = await tool._execute(+ user_id="u1", session=mock_session, topic="subscription"+ )+ assert "AutoGPT" in result.message+ assert "AutoPilot" in result.message++ # -- Feature flag: billing disabled (self-hosted / beta) --++ @pytest.mark.asyncio+ async def test_billing_disabled_returns_open_access(self, tool, mock_session):+ """When ENABLE_PLATFORM_PAYMENT is off, report open access."""+ with _billing_disabled():+ result = await tool._execute(+ user_id="user-1", session=mock_session, topic="subscription"+ )++ assert result.type == ResponseType.PLATFORM_INFO+ assert result.tier == "OPEN_ACCESS"+ assert result.billing_url is None+ assert "open access" in result.message.lower()+ assert "AutoPilot" in result.message++ @pytest.mark.asyncio+ async def test_billing_disabled_skips_tier_lookup(self, tool, mock_session):+ """When billing is off, get_user_tier should never be called."""+ tier_mock = AsyncMock()+ with (+ _billing_disabled(),+ patch(_TIER_PATH, tier_mock),+ ):+ await tool._execute(+ user_id="user-1", session=mock_session, topic="subscription"+ )++ tier_mock.assert_not_called()diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 47aae7efb4..0935cd744e 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15239,7 +15239,8 @@"memory_search","memory_forget_candidates","memory_forget_confirm",- "todo_write"+ "todo_write",+ "platform_info"],"title": "ResponseType","description": "Types of tool responses."