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/copilot): add include_graph option to find_library_agent (#12622)
Zamil Majdya50e95f210af
diff --git a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.mdindex 1719a2a45a..cdb436429e 100644--- a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md+++ b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md@@ -28,23 +28,30 @@ Steps:### Workflow for Creating/Editing Agents-1. **Discover blocks**: Call `find_block(query, include_schemas=true)` to+1. **If editing**: First narrow to the specific agent by UUID, then fetch its+ graph: `find_library_agent(query="<agent_id>", include_graph=true)`. This+ returns the full graph structure (nodes + links). **Never edit blindly** —+ always inspect the current graph first so you know exactly what to change.+ Avoid using `include_graph=true` with broad keyword searches, as fetching+ multiple graphs at once is expensive and consumes LLM context budget.+2. **Discover blocks**: Call `find_block(query, include_schemas=true)` tosearch for relevant blocks. This returns block IDs, names, descriptions,and full input/output schemas.-2. **Find library agents**: Call `find_library_agent` to discover reusable+3. **Find library agents**: Call `find_library_agent` to discover reusableagents that can be composed as sub-agents via `AgentExecutorBlock`.-3. **Generate JSON**: Build the agent JSON using block schemas:- - Use block IDs from step 1 as `block_id` in nodes+4. **Generate/modify JSON**: Build or modify the agent JSON using block schemas:+ - Use block IDs from step 2 as `block_id` in nodes- Wire outputs to inputs using links- Set design-time config in `input_default`- Use `AgentInputBlock` for values the user provides at runtime-4. **Write to workspace**: Save the JSON to a workspace file so the user+ - When editing, apply targeted changes and preserve unchanged parts+5. **Write to workspace**: Save the JSON to a workspace file so the usercan review it: `write_workspace_file(filename="agent.json", content=...)`-5. **Validate**: Call `validate_agent_graph` with the agent JSON to check+6. **Validate**: Call `validate_agent_graph` with the agent JSON to checkfor errors-6. **Fix if needed**: Call `fix_agent_graph` to auto-fix common issues,+7. **Fix if needed**: Call `fix_agent_graph` to auto-fix common issues,or fix manually based on the error descriptions. Iterate until valid.-7. **Save**: Call `create_agent` (new) or `edit_agent` (existing) with+8. **Save**: Call `create_agent` (new) or `edit_agent` (existing) withthe final `agent_json`### Agent JSON Structurediff --git a/autogpt_platform/backend/backend/copilot/tools/agent_search.py b/autogpt_platform/backend/backend/copilot/tools/agent_search.pyindex d5a98a2a55..011b2d7565 100644--- a/autogpt_platform/backend/backend/copilot/tools/agent_search.py+++ b/autogpt_platform/backend/backend/copilot/tools/agent_search.py@@ -2,6 +2,7 @@from __future__ import annotations+import asyncioimport loggingfrom typing import TYPE_CHECKING, Literal@@ -9,7 +10,7 @@ if TYPE_CHECKING:from backend.api.features.library.model import LibraryAgentfrom backend.api.features.store.model import StoreAgent, StoreAgentDetails-from backend.data.db_accessors import library_db, store_db+from backend.data.db_accessors import graph_db, library_db, store_dbfrom backend.util.exceptions import DatabaseError, NotFoundErrorfrom .models import (@@ -34,12 +35,13 @@ async def search_agents(source: SearchSource,session_id: str | None = None,user_id: str | None = None,+ include_graph: bool = False,) -> ToolResponseBase:"""Search for agents in marketplace or user library."""if source == "marketplace":return await _search_marketplace(query, session_id)else:- return await _search_library(query, session_id, user_id)+ return await _search_library(query, session_id, user_id, include_graph)async def _search_marketplace(query: str, session_id: str | None) -> ToolResponseBase:@@ -105,7 +107,10 @@ async def _search_marketplace(query: str, session_id: str | None) -> ToolResponsasync def _search_library(- query: str, session_id: str | None, user_id: str | None+ query: str,+ session_id: str | None,+ user_id: str | None,+ include_graph: bool = False,) -> ToolResponseBase:"""Search user's library agents, with direct UUID lookup fallback."""if not user_id:@@ -149,6 +154,10 @@ async def _search_library(session_id=session_id,)+ truncation_notice: str | None = None+ if include_graph and agents:+ truncation_notice = await _enrich_agents_with_graph(agents, user_id)+if not agents:if not query:return NoResultsResponse(@@ -182,13 +191,17 @@ async def _search_library(else:title = f"Found {len(agents)} agent{'s' if len(agents) != 1 else ''} in your library for '{query}'"+ 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 "+ "execution results, or run_agent to execute. Let the user know we can "+ "create a custom agent for them based on their needs."+ )+ if truncation_notice:+ message = f"{message}\n\nNote: {truncation_notice}"+return AgentsFoundResponse(- 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 "- "execution results, or run_agent to execute. Let the user know we can "- "create a custom agent for them based on their needs."- ),+ message=message,title=title,agents=agents,count=len(agents),@@ -196,6 +209,81 @@ async def _search_library()+_MAX_GRAPH_FETCHES = 10+++_GRAPH_FETCH_TIMEOUT = 15 # seconds+++async def _enrich_agents_with_graph(+ agents: list[AgentInfo], user_id: str+) -> str | None:+ """Fetch and attach full Graph (nodes + links) to each agent in-place.++ Only the first ``_MAX_GRAPH_FETCHES`` agents with a ``graph_id`` are+ enriched. If some agents are skipped, a truncation notice is returned+ so the caller can surface it to the copilot.++ Graphs are fetched with ``for_export=True`` so that credentials, API keys,+ and other secrets in ``input_default`` are stripped before the data reaches+ the LLM context.++ Returns a truncation notice string when some agents were skipped, or+ ``None`` when all eligible agents were enriched.+ """+ with_graph_id = [a for a in agents if a.graph_id]+ fetchable = with_graph_id[:_MAX_GRAPH_FETCHES]+ if not fetchable:+ return None++ gdb = graph_db()++ async def _fetch(agent: AgentInfo) -> None:+ graph_id = agent.graph_id+ if not graph_id:+ return+ try:+ graph = await gdb.get_graph(+ graph_id,+ version=agent.graph_version,+ user_id=user_id,+ for_export=True,+ )+ if graph is None:+ logger.warning("Graph not found for agent %s", graph_id)+ agent.graph = graph+ except Exception as e:+ logger.warning("Failed to fetch graph for agent %s: %s", graph_id, e)++ try:+ await asyncio.wait_for(+ asyncio.gather(*[_fetch(a) for a in fetchable]),+ timeout=_GRAPH_FETCH_TIMEOUT,+ )+ except asyncio.TimeoutError:+ logger.warning(+ "include_graph: timed out after %ds fetching graphs", _GRAPH_FETCH_TIMEOUT+ )++ skipped = len(with_graph_id) - len(fetchable)+ if skipped > 0:+ logger.warning(+ "include_graph: fetched graphs for %d/%d agents "+ "(_MAX_GRAPH_FETCHES=%d, %d skipped)",+ len(fetchable),+ len(with_graph_id),+ _MAX_GRAPH_FETCHES,+ skipped,+ )+ return (+ f"Graph data included for {len(fetchable)} of "+ f"{len(with_graph_id)} eligible agents (limit: {_MAX_GRAPH_FETCHES}). "+ f"To fetch graphs for remaining agents, narrow your search to a "+ f"specific agent by UUID."+ )+ return None++def _marketplace_agent_to_info(agent: StoreAgent | StoreAgentDetails) -> AgentInfo:"""Convert a marketplace agent (StoreAgent or StoreAgentDetails) to an AgentInfo."""return AgentInfo(diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_search_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_search_test.pyindex c3268ff5c3..d7ba3ccc90 100644--- a/autogpt_platform/backend/backend/copilot/tools/agent_search_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/agent_search_test.py@@ -1,11 +1,12 @@"""Tests for agent search direct lookup functionality."""+import asynciofrom unittest.mock import AsyncMock, MagicMock, patchimport pytest-from .agent_search import search_agents-from .models import AgentsFoundResponse, NoResultsResponse+from .agent_search import _enrich_agents_with_graph, search_agents+from .models import AgentInfo, AgentsFoundResponse, NoResultsResponse_TEST_USER_ID = "test-user-agent-search"@@ -133,10 +134,10 @@ class TestMarketplaceSlugLookup:class TestLibraryUUIDLookup:"""Tests for UUID direct lookup in library search."""- @pytest.mark.asyncio(loop_scope="session")- async def test_uuid_lookup_found_by_graph_id(self):- """UUID query matching a graph_id returns the agent directly."""- agent_id = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"+ @staticmethod+ def _make_mock_library_agent(+ agent_id: str = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",+ ) -> MagicMock:mock_agent = MagicMock()mock_agent.id = "lib-agent-id"mock_agent.name = "My Library Agent"@@ -150,6 +151,13 @@ class TestLibraryUUIDLookup:mock_agent.graph_version = 1mock_agent.input_schema = {}mock_agent.output_schema = {}+ return mock_agent++ @pytest.mark.asyncio(loop_scope="session")+ async def test_uuid_lookup_found_by_graph_id(self):+ """UUID query matching a graph_id returns the agent directly."""+ agent_id = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"+ mock_agent = self._make_mock_library_agent(agent_id)mock_lib_db = MagicMock()mock_lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=mock_agent)@@ -168,3 +176,427 @@ class TestLibraryUUIDLookup:assert isinstance(response, AgentsFoundResponse)assert response.count == 1assert response.agents[0].name == "My Library Agent"++ @pytest.mark.asyncio(loop_scope="session")+ async def test_include_graph_fetches_graph(self):+ """include_graph=True attaches BaseGraph to agent results."""+ from backend.data.graph import BaseGraph++ agent_id = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"+ mock_agent = self._make_mock_library_agent(agent_id)+ mock_lib_db = MagicMock()+ mock_lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=mock_agent)++ fake_graph = BaseGraph(id=agent_id, name="My Library Agent", description="test")+ mock_graph_db = MagicMock()+ mock_graph_db.get_graph = AsyncMock(return_value=fake_graph)++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_graph_db,+ ),+ ):+ response = await search_agents(+ query=agent_id,+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=True,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert response.agents[0].graph is not None+ assert response.agents[0].graph.id == agent_id+ mock_graph_db.get_graph.assert_awaited_once_with(+ agent_id,+ version=1,+ user_id=_TEST_USER_ID,+ for_export=True,+ )++ @pytest.mark.asyncio(loop_scope="session")+ async def test_include_graph_false_skips_fetch(self):+ """include_graph=False (default) does not fetch graph data."""+ agent_id = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"+ mock_agent = self._make_mock_library_agent(agent_id)+ mock_lib_db = MagicMock()+ mock_lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=mock_agent)++ mock_graph_db = MagicMock()+ mock_graph_db.get_graph = AsyncMock()++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_graph_db,+ ),+ ):+ response = await search_agents(+ query=agent_id,+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=False,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert response.agents[0].graph is None+ mock_graph_db.get_graph.assert_not_awaited()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_include_graph_handles_fetch_failure(self):+ """include_graph=True still returns agents when graph fetch fails."""+ agent_id = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"+ mock_agent = self._make_mock_library_agent(agent_id)+ mock_lib_db = MagicMock()+ mock_lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=mock_agent)++ mock_graph_db = MagicMock()+ mock_graph_db.get_graph = AsyncMock(side_effect=Exception("DB down"))++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_graph_db,+ ),+ ):+ response = await search_agents(+ query=agent_id,+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=True,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert response.agents[0].graph is None++ @pytest.mark.asyncio(loop_scope="session")+ async def test_include_graph_handles_none_return(self):+ """include_graph=True handles get_graph returning None."""+ agent_id = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"+ mock_agent = self._make_mock_library_agent(agent_id)+ mock_lib_db = MagicMock()+ mock_lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=mock_agent)++ mock_graph_db = MagicMock()+ mock_graph_db.get_graph = AsyncMock(return_value=None)++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_graph_db,+ ),+ ):+ response = await search_agents(+ query=agent_id,+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=True,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert response.agents[0].graph is None+++class TestEnrichAgentsWithGraph:+ """Tests for _enrich_agents_with_graph edge cases."""++ @staticmethod+ def _make_mock_library_agent(+ agent_id: str = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",+ graph_id: str | None = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",+ ) -> MagicMock:+ mock_agent = MagicMock()+ mock_agent.id = f"lib-{agent_id[:8]}"+ mock_agent.name = f"Agent {agent_id[:8]}"+ mock_agent.description = "A library agent"+ mock_agent.creator_name = "testuser"+ mock_agent.status.value = "HEALTHY"+ mock_agent.can_access_graph = True+ mock_agent.has_external_trigger = False+ mock_agent.new_output = False+ mock_agent.graph_id = graph_id+ mock_agent.graph_version = 1+ mock_agent.input_schema = {}+ mock_agent.output_schema = {}+ return mock_agent++ @pytest.mark.asyncio(loop_scope="session")+ async def test_truncation_surfaces_in_response(self):+ """When >_MAX_GRAPH_FETCHES agents have graphs, the response contains a truncation notice."""+ from backend.copilot.tools.agent_search import _MAX_GRAPH_FETCHES+ from backend.data.graph import BaseGraph++ agent_count = _MAX_GRAPH_FETCHES + 5+ mock_agents = []+ for i in range(agent_count):+ uid = f"a1b2c3d4-e5f6-4a7b-8c9d-{i:012d}"+ mock_agents.append(self._make_mock_library_agent(uid, uid))++ mock_lib_db = MagicMock()+ mock_search_results = MagicMock()+ mock_search_results.agents = mock_agents+ mock_lib_db.list_library_agents = AsyncMock(return_value=mock_search_results)++ fake_graph = BaseGraph(id="x", name="g", description="d")+ mock_gdb = MagicMock()+ mock_gdb.get_graph = AsyncMock(return_value=fake_graph)++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_gdb,+ ),+ ):+ response = await search_agents(+ query="",+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=True,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert mock_gdb.get_graph.await_count == _MAX_GRAPH_FETCHES+ enriched = [a for a in response.agents if a.graph is not None]+ assert len(enriched) == _MAX_GRAPH_FETCHES+ assert "Graph data included for" in response.message+ assert str(_MAX_GRAPH_FETCHES) in response.message++ @pytest.mark.asyncio(loop_scope="session")+ async def test_mixed_graph_id_presence(self):+ """Agents without graph_id are skipped during enrichment."""+ from backend.data.graph import BaseGraph++ agent_with = self._make_mock_library_agent(+ "aaaa0000-0000-0000-0000-000000000001",+ "aaaa0000-0000-0000-0000-000000000001",+ )+ agent_without = self._make_mock_library_agent(+ "bbbb0000-0000-0000-0000-000000000002",+ graph_id=None,+ )++ mock_lib_db = MagicMock()+ mock_search_results = MagicMock()+ mock_search_results.agents = [agent_with, agent_without]+ mock_lib_db.list_library_agents = AsyncMock(return_value=mock_search_results)++ fake_graph = BaseGraph(+ id="aaaa0000-0000-0000-0000-000000000001", name="g", description="d"+ )+ mock_gdb = MagicMock()+ mock_gdb.get_graph = AsyncMock(return_value=fake_graph)++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_gdb,+ ),+ ):+ response = await search_agents(+ query="",+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=True,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert len(response.agents) == 2+ assert response.agents[0].graph is not None+ assert response.agents[1].graph is None+ mock_gdb.get_graph.assert_awaited_once()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_partial_failure_across_multiple_agents(self):+ """When some graph fetches fail, successful ones still have graphs attached."""+ from backend.data.graph import BaseGraph++ id_ok = "aaaa0000-0000-0000-0000-000000000001"+ id_fail = "bbbb0000-0000-0000-0000-000000000002"+ agent_ok = self._make_mock_library_agent(id_ok, id_ok)+ agent_fail = self._make_mock_library_agent(id_fail, id_fail)++ mock_lib_db = MagicMock()+ mock_search_results = MagicMock()+ mock_search_results.agents = [agent_ok, agent_fail]+ mock_lib_db.list_library_agents = AsyncMock(return_value=mock_search_results)++ fake_graph = BaseGraph(id=id_ok, name="g", description="d")++ async def _side_effect(graph_id, **kwargs):+ if graph_id == id_fail:+ raise Exception("DB error")+ return fake_graph++ mock_gdb = MagicMock()+ mock_gdb.get_graph = AsyncMock(side_effect=_side_effect)++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_gdb,+ ),+ ):+ response = await search_agents(+ query="",+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=True,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert response.agents[0].graph is not None+ assert response.agents[0].graph.id == id_ok+ assert response.agents[1].graph is None++ @pytest.mark.asyncio(loop_scope="session")+ async def test_keyword_search_with_include_graph(self):+ """include_graph works via keyword search (non-UUID path)."""+ from backend.data.graph import BaseGraph++ agent_id = "cccc0000-0000-0000-0000-000000000003"+ mock_agent = self._make_mock_library_agent(agent_id, agent_id)++ mock_lib_db = MagicMock()+ mock_search_results = MagicMock()+ mock_search_results.agents = [mock_agent]+ mock_lib_db.list_library_agents = AsyncMock(return_value=mock_search_results)++ fake_graph = BaseGraph(id=agent_id, name="g", description="d")+ mock_gdb = MagicMock()+ mock_gdb.get_graph = AsyncMock(return_value=fake_graph)++ with (+ patch(+ "backend.copilot.tools.agent_search.library_db",+ return_value=mock_lib_db,+ ),+ patch(+ "backend.copilot.tools.agent_search.graph_db",+ return_value=mock_gdb,+ ),+ ):+ response = await search_agents(+ query="email",+ source="library",+ session_id="s",+ user_id=_TEST_USER_ID,+ include_graph=True,+ )++ assert isinstance(response, AgentsFoundResponse)+ assert response.agents[0].graph is not None+ assert response.agents[0].graph.id == agent_id+ mock_gdb.get_graph.assert_awaited_once()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_timeout_preserves_successful_fetches(self):+ """On timeout, agents that already fetched their graph keep the result."""+ fast_agent = AgentInfo(+ id="a1",+ name="Fast",+ description="d",+ source="library",+ graph_id="fast-graph",+ )+ slow_agent = AgentInfo(+ id="a2",+ name="Slow",+ description="d",+ source="library",+ graph_id="slow-graph",+ )+ fake_graph = MagicMock()+ fake_graph.id = "graph-1"++ async def mock_get_graph(+ graph_id, *, version=None, user_id=None, for_export=False+ ):+ if graph_id == "fast-graph":+ return fake_graph+ await asyncio.sleep(999)+ return MagicMock()++ mock_gdb = MagicMock()+ mock_gdb.get_graph = AsyncMock(side_effect=mock_get_graph)++ with (+ patch("backend.copilot.tools.agent_search.graph_db", return_value=mock_gdb),+ patch("backend.copilot.tools.agent_search._GRAPH_FETCH_TIMEOUT", 0.1),+ ):+ await _enrich_agents_with_graph([fast_agent, slow_agent], _TEST_USER_ID)++ assert fast_agent.graph is fake_graph+ assert slow_agent.graph is None++ @pytest.mark.asyncio(loop_scope="session")+ async def test_enrich_success(self):+ """All agents get their graphs when no timeout occurs."""+ agent = AgentInfo(+ id="a1", name="Test", description="d", source="library", graph_id="g1"+ )+ fake_graph = MagicMock()+ fake_graph.id = "graph-1"++ mock_gdb = MagicMock()+ mock_gdb.get_graph = AsyncMock(return_value=fake_graph)++ with patch(+ "backend.copilot.tools.agent_search.graph_db", return_value=mock_gdb+ ):+ result = await _enrich_agents_with_graph([agent], _TEST_USER_ID)++ assert agent.graph is fake_graph+ assert result is None++ @pytest.mark.asyncio(loop_scope="session")+ async def test_enrich_skips_agents_without_graph_id(self):+ """Agents without graph_id are not fetched."""+ agent_no_id = AgentInfo(+ id="a1", name="Test", description="d", source="library", graph_id=None+ )++ mock_gdb = MagicMock()+ mock_gdb.get_graph = AsyncMock()++ with patch(+ "backend.copilot.tools.agent_search.graph_db", return_value=mock_gdb+ ):+ result = await _enrich_agents_with_graph([agent_no_id], _TEST_USER_ID)++ mock_gdb.get_graph.assert_not_called()+ assert result is Nonediff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.pyindex 6b0d2ace2a..a5714ff8df 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py@@ -20,7 +20,8 @@ class FindLibraryAgentTool(BaseTool):def description(self) -> str:return ("Search user's library agents. Returns graph_id, schemas for sub-agent composition. "- "Omit query to list all."+ "Omit query to list all. Set include_graph=true to also fetch the full "+ "graph structure (nodes + links) for debugging or editing.")@property@@ -32,6 +33,15 @@ class FindLibraryAgentTool(BaseTool):"type": "string","description": "Search by name/description. Omit to list all.",},+ "include_graph": {+ "type": "boolean",+ "description": (+ "When true, includes the full graph structure "+ "(nodes + links) for each found agent. "+ "Use when you need to inspect, debug, or edit an agent."+ ),+ "default": False,+ },},"required": [],}@@ -45,6 +55,7 @@ class FindLibraryAgentTool(BaseTool):user_id: str | None,session: ChatSession,query: str = "",+ include_graph: bool = False,**kwargs,) -> ToolResponseBase:return await search_agents(@@ -52,4 +63,5 @@ class FindLibraryAgentTool(BaseTool):source="library",session_id=session.session_id,user_id=user_id,+ include_graph=include_graph,)diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex a4919a5ed6..a0d1ad13ef 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -6,6 +6,7 @@ from typing import Any, Literalfrom pydantic import BaseModel, Field+from backend.data.graph import BaseGraphfrom backend.data.model import CredentialsMetaInput@@ -122,6 +123,10 @@ class AgentInfo(BaseModel):default=None,description="Input schema for the agent, including field names, types, and defaults",)+ graph: BaseGraph | None = Field(+ default=None,+ description="Full graph structure (nodes + links) when include_graph is requested",+ )class AgentsFoundResponse(ToolResponseBase):diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex e6fc222921..7dee773a3b 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -7495,6 +7495,13 @@],"title": "Inputs","description": "Input schema for the agent, including field names, types, and defaults"+ },+ "graph": {+ "anyOf": [+ { "$ref": "#/components/schemas/BaseGraph-Output" },+ { "type": "null" }+ ],+ "description": "Full graph structure (nodes + links) when include_graph is requested"}},"type": "object",