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/library): resolve library "Chat" agent by exact id (#13302)
An Vy Leba415e7e47e7
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_search.py b/autogpt_platform/backend/backend/copilot/tools/agent_search.pyindex ea81badd56..e7381334d4 100644--- a/autogpt_platform/backend/backend/copilot/tools/agent_search.py+++ b/autogpt_platform/backend/backend/copilot/tools/agent_search.py@@ -114,7 +114,13 @@ async def _search_library(user_id: str | None,include_graph: bool = False,) -> ToolResponseBase:- """Search user's library agents, with direct UUID lookup fallback."""+ """Search user's library agents by name/description.++ For UUID-shaped queries this also tries a direct id lookup as a+ convenience. The strict, no-fuzzy-fallback by-id path lives in+ ``lookup_library_agent_by_id`` (dispatched by the tool when ``agent_id``+ is given) — prefer that when the exact id is known.+ """if not user_id:return ErrorResponse(message="User authentication required to search library",@@ -128,6 +134,8 @@ async def _search_library(agents: list[AgentInfo] = []try:+ # Safety net for a UUID passed as the query; the preferred by-id path+ # is the tool's explicit agent_id → lookup_library_agent_by_id.if is_uuid(query):logger.info(f"Query looks like UUID, trying direct lookup: {query}")agent = await _get_library_agent_by_id(user_id, query)@@ -199,7 +207,7 @@ async def _search_library(message = ("Found agents in the user's library. You can provide a link to view "- "an agent at: /library/agents/{agent_id}. Use agent_output to get "+ "an agent at: /library/agents/{agent_id}. Use view_agent_output to get ""execution results, or run_agent to execute. Let the user know we can ""create a custom agent for them based on their needs.")@@ -517,6 +525,69 @@ async def _load_and_format_matched_agents(return agents+async def lookup_library_agent_by_id(+ agent_id: str,+ session_id: str | None,+ user_id: str | None,+ include_graph: bool = False,+) -> ToolResponseBase:+ """Strict direct resolution of one library agent by id.++ Resolves an exact ``library_agent_id`` or ``graph_id`` and never falls back+ to a fuzzy name search — returns ``NoResultsResponse`` when the id doesn't+ resolve. Backs ``find_library_agent``'s ``agent_id`` parameter.+ """+ if not user_id:+ return ErrorResponse(+ message="User authentication required to fetch a library agent",+ session_id=session_id,+ )++ try:+ agent = await _get_library_agent_by_id(user_id, agent_id)+ except DatabaseError as e:+ logger.error(f"Error fetching library agent {agent_id}: {e}", exc_info=True)+ return ErrorResponse(+ message="Failed to fetch the library agent. Please try again.",+ error=str(e),+ session_id=session_id,+ )++ if agent is None:+ return NoResultsResponse(+ message=(+ f"No library agent found with id '{agent_id}'. It may have been "+ "deleted or you may not have access. Retry find_library_agent "+ "with a name query, or create a custom agent."+ ),+ suggestions=[+ "Retry find_library_agent with a name/description query",+ "Check your library at /library",+ ],+ session_id=session_id,+ )++ truncation_notice: str | None = None+ if include_graph:+ truncation_notice = await _enrich_agents_with_graph([agent], user_id)++ message = (+ "Found the requested library agent. Link to it at "+ "/library/agents/{agent_id}. Use view_agent_output for execution "+ "results, or run_agent to execute it."+ )+ if truncation_notice:+ message = f"{message}\n\nNote: {truncation_notice}"++ return AgentsFoundResponse(+ message=message,+ title=f"Loaded agent '{agent.name}'",+ agents=[agent],+ count=1,+ session_id=session_id,+ )++async def _get_library_agent_by_id(user_id: str, agent_id: str) -> AgentInfo | None:"""Fetch a library agent by ID (library agent ID or graph_id).diff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.pyindex d3865b4538..f97465a1a4 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py@@ -4,7 +4,11 @@ from typing import Anyfrom backend.copilot.model import ChatSession-from .agent_search import search_agents, search_library_for_creation+from .agent_search import (+ lookup_library_agent_by_id,+ search_agents,+ search_library_for_creation,+)from .base import BaseToolfrom .models import ToolResponseBase@@ -19,9 +23,10 @@ class FindLibraryAgentTool(BaseTool):@propertydef description(self) -> str:return (- "Search user's library agents. for_creation=true+goal_summary "- "runs the similarity check required by create_agent. Omit query "- "to list all; include_graph=true for nodes+links."+ "Search library agents by name/description, or pass agent_id "+ "(library_agent_id/graph_id) for a direct by-id lookup. "+ "for_creation=true+goal_summary runs the create_agent similarity "+ "check. Omit query to list all; include_graph=true for nodes+links.")@property@@ -33,6 +38,13 @@ class FindLibraryAgentTool(BaseTool):"type": "string","description": "Search by name/description. Omit to list all.",},+ "agent_id": {+ "type": "string",+ "description": (+ "Exact library_agent_id/graph_id for a direct lookup "+ "(no fuzzy fallback). Use when you know the id."+ ),+ },"include_graph": {"type": "boolean","description": (@@ -66,6 +78,7 @@ class FindLibraryAgentTool(BaseTool):user_id: str | None,session: ChatSession,query: str = "",+ agent_id: str = "",include_graph: bool = False,for_creation: bool = False,goal_summary: str = "",@@ -79,6 +92,13 @@ class FindLibraryAgentTool(BaseTool):session_id=session.session_id,user_id=user_id,)+ if agent_id := agent_id.strip():+ return await lookup_library_agent_by_id(+ agent_id=agent_id,+ session_id=session.session_id,+ user_id=user_id,+ include_graph=include_graph,+ )return await search_agents(query=query.strip(),source="library",diff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.pyindex 86d18e13ed..d083465294 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py@@ -5,7 +5,11 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom backend.copilot.tools.find_library_agent import FindLibraryAgentTool-from backend.copilot.tools.models import AgentsFoundResponse, NoResultsResponse+from backend.copilot.tools.models import (+ AgentsFoundResponse,+ ErrorResponse,+ NoResultsResponse,+)from backend.util.exceptions import DatabaseErrorfrom ._test_data import make_session@@ -198,3 +202,88 @@ async def test_default_mode_still_uses_substring_search(tool, session):mock_search.assert_awaited_once()assert mock_search.call_args.kwargs["source"] == "library"assert mock_search.call_args.kwargs["query"] == "email"+++async def test_agent_id_resolves_by_direct_lookup(tool, session):+ """agent_id resolves to a single agent via direct by-id lookup."""+ lib_db = MagicMock()+ lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=None)+ lib_db.get_library_agent = AsyncMock(+ return_value=_mock_library_agent("lib-1", "Weather Bot")+ )++ with patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=lib_db,+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="lib-1",+ )++ assert isinstance(result, AgentsFoundResponse)+ assert result.count == 1+ assert result.agents[0].id == "lib-1"+ assert result.agents[0].name == "Weather Bot"+++async def test_agent_id_missing_returns_no_results(tool, session):+ """An agent_id that resolves to nothing returns NoResults — never a fuzzy+ name-search fallback."""+ lib_db = MagicMock()+ lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=None)+ lib_db.get_library_agent = AsyncMock(return_value=None)++ with patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=lib_db,+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="does-not-exist",+ )++ assert isinstance(result, NoResultsResponse)+++async def test_agent_id_does_not_fall_back_to_query_search(tool, session):+ """When agent_id is provided, the substring search path is never taken —+ a missing id must not silently degrade into a fuzzy name search."""+ lib_db = MagicMock()+ lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=None)+ lib_db.get_library_agent = AsyncMock(return_value=None)+ list_all = AsyncMock()++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=lib_db,+ ),+ ):+ lib_db.list_library_agents = list_all+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="does-not-exist",+ query="weather",+ )++ assert isinstance(result, NoResultsResponse)+ list_all.assert_not_awaited()+++async def test_missing_user_returns_error(tool, session):+ """An unauthenticated by-id lookup is an error, not a search."""+ result = await tool._execute(+ user_id=None,+ session=session,+ agent_id="lib-1",+ )++ assert isinstance(result, ErrorResponse)diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.pyindex d053d95fda..56f45463b2 100644--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py@@ -70,7 +70,11 @@ from backend.copilot.tools import TOOL_REGISTRY# the require_approval gate, and the "STOP before building" caveat the# model needs to halt for user approval instead of rushing into# create_agent.-_CHAR_BUDGET = 40_500+# Bumped 40500 -> 41000 when find_library_agent absorbed direct by-id lookup:+# a new ``agent_id`` parameter (library_agent_id / graph_id) that resolves the+# exact agent with no fuzzy name-search fallback, so the library "Chat" flow is+# reliable without a separate tool. Net smaller than a dedicated tool would add.+_CHAR_BUDGET = 41_000@pytest.fixture(scope="module")diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsxindex f8abebc3ed..f90f76bae3 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx@@ -144,7 +144,7 @@ export function LibraryAgentCard({type="button"onClick={() => {const prompt = encodeURIComponent(- `Tell me about ${name}, its current status, recent runs and how can I get the most out of it`,+ `Tell me about my agent "${name}" (library agent ID: ${id}). Use find_library_agent with this exact agent_id to look it up, then summarize its current status, recent runs, and how I can get the most out of it.`,);router.push(`/copilot?autosubmit=true#prompt=${prompt}`);}}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/helpers.tsindex 6817ada6b9..9270914f87 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/helpers.ts@@ -1,20 +1,24 @@import { SitrepItemData } from "../../types";export function buildAutoPilotPrompt(item: SitrepItemData): string {+ // Embed the exact library agent ID and steer the assistant to resolve it by+ // ID via find_library_agent's agent_id (direct lookup) instead of a fuzzy+ // name search.+ const idHint = ` Use find_library_agent with the exact agent_id ${item.agentID} to look it up.`;switch (item.priority) {case "error":- return `What happened with ${item.agentName}? It says "${item.message}" — can you check the logs and tell me what to fix?`;+ return `What happened with ${item.agentName}? It says "${item.message}" — can you check the logs and tell me what to fix?${idHint}`;case "running":- return `Give me a status update on the ${item.agentName} run — what has it found so far?`;+ return `Give me a status update on the ${item.agentName} run — what has it found so far?${idHint}`;case "stale":- return `${item.agentName} hasn't run recently. Should I keep it or update and re-run it?`;+ return `${item.agentName} hasn't run recently. Should I keep it or update and re-run it?${idHint}`;case "success":- return `Show me what ${item.agentName} found in its last run — summarize the results and any key takeaways.`;+ return `Show me what ${item.agentName} found in its last run — summarize the results and any key takeaways.${idHint}`;case "listening":- return `What is ${item.agentName} listening for? Give me a summary of its trigger configuration.`;+ return `What is ${item.agentName} listening for? Give me a summary of its trigger configuration.${idHint}`;case "scheduled":- return `When is ${item.agentName} scheduled to run next?`;+ return `When is ${item.agentName} scheduled to run next?${idHint}`;case "idle":- return `${item.agentName} has been idle. Should I keep it or update and re-run it?`;+ return `${item.agentName} has been idle. Should I keep it or update and re-run it?${idHint}`;}}