diff --git a/src/google/adk/tools/agent_tool.py b/src/google/adk/tools/agent_tool.py index 14f0d9f8651..8c92c4e46fa 100644 --- a/src/google/adk/tools/agent_tool.py +++ b/src/google/adk/tools/agent_tool.py @@ -50,6 +50,7 @@ from ..agents.base_agent import BaseAgent from ..agents.invocation_context import InvocationContext from ..apps._configs import EventsCompactionConfig + from ..models.llm_request import LlmRequest from ..sessions.session import Session @@ -146,6 +147,38 @@ def _get_output_schema(agent: BaseAgent) -> Optional[SchemaType]: return None +async def _resolve_agent_description( + agent: BaseAgent, tool_context: ToolContext +) -> Optional[str]: + """Returns the description to show the model for an agent that reads it lazily. + + An agent like `RemoteA2aAgent` can only learn its description from the remote + agent's card, which takes a network call, so `agent.description` is empty + until then. ADK already resolves it that way when such an agent is a + `transfer_to_agent` target (see `_build_transfer_target_info`); this does the + same when the agent is exposed to the model as a tool. The result is reused + from the transfer path's per-invocation cache, falls back to + `agent.description` if the lookup fails, and keeps the same fencing of text + that arrived over the network. + + Args: + agent: The agent the tool wraps. + tool_context: The tool context of the request being built. + + Returns: + The resolved description, or None for an agent that has no such hook, which + keeps using `agent.description` as before. + """ + if not callable(getattr(agent, '_get_transfer_description', None)): + return None + from ..flows.llm_flows.extensions._agent_transfer import _build_transfer_target_info + + info = await _build_transfer_target_info( + agent, tool_context._invocation_context + ) + return info.description + + class AgentTool(BaseTool): """A tool that wraps an agent. @@ -196,6 +229,29 @@ def populate_name(cls, data: Any) -> Any: data['name'] = data['agent'].name return data + def _describe(self, agent_description: str) -> str: + """Returns the tool description to declare for the wrapped agent's own.""" + return agent_description + + @override + async def process_llm_request( + self, *, tool_context: ToolContext, llm_request: LlmRequest + ) -> None: + await super().process_llm_request( + tool_context=tool_context, llm_request=llm_request + ) + # `_get_declaration` is synchronous and can only see `agent.description`. + # For an agent that reads it lazily, replace it in the declaration that was + # just added, so no shared state is touched. + description = await _resolve_agent_description(self.agent, tool_context) + if not description or description == self.agent.description: + return + for tool in reversed(llm_request.config.tools or []): + for declaration in reversed(tool.function_declarations or []): + if declaration.name == self.name: + declaration.description = self._describe(description) + return + @override def _get_declaration(self) -> types.FunctionDeclaration: from ..utils.variant_utils import GoogleLLMVariant @@ -208,12 +264,12 @@ def _get_declaration(self) -> types.FunctionDeclaration: func=input_schema, variant=self._api_variant ) # Override the description with the agent's description - result.description = self.agent.description + result.description = self._describe(self.agent.description) else: if is_feature_enabled(FeatureName.JSON_SCHEMA_FOR_FUNC_DECL): result = types.FunctionDeclaration( name=self.name, - description=self.agent.description, + description=self._describe(self.agent.description), parameters_json_schema={ 'type': 'object', 'properties': { @@ -233,7 +289,7 @@ def _get_declaration(self) -> types.FunctionDeclaration: }, required=['request'], ), - description=self.agent.description, + description=self._describe(self.agent.description), name=self.name, ) @@ -644,6 +700,14 @@ def __init__( ) self._defers_response = True + @override + def _describe(self, agent_description: str) -> str: + suffix = ( + '\nIMPORTANT: This tool delegates execution to a specialized agent.' + ' Do NOT call this tool in parallel with any other tools.' + ) + return f'{agent_description or ""}{suffix}'.strip() + @override def _get_declaration(self) -> types.FunctionDeclaration: from ..utils.variant_utils import GoogleLLMVariant @@ -657,12 +721,7 @@ def _get_declaration(self) -> types.FunctionDeclaration: func=input_schema ) ) - base_desc = self.agent.description or '' - suffix = ( - '\nIMPORTANT: This tool delegates execution to a specialized agent.' - ' Do NOT call this tool in parallel with any other tools.' - ) - result.description = f'{base_desc}{suffix}'.strip() + result.description = self._describe(self.agent.description) result.name = self.name if self._api_variant != GoogleLLMVariant.GEMINI_API: diff --git a/tests/unittests/a2a/agent/test_remote_a2a_agent.py b/tests/unittests/a2a/agent/test_remote_a2a_agent.py index c3ea93f6afc..dbd8bc72f77 100644 --- a/tests/unittests/a2a/agent/test_remote_a2a_agent.py +++ b/tests/unittests/a2a/agent/test_remote_a2a_agent.py @@ -1613,6 +1613,58 @@ async def test_get_transfer_description_fences_remote_card_description(self): assert desc.endswith(QUOTED_CONTENT_END) assert agent_card.description in desc + @pytest.mark.asyncio + @pytest.mark.parametrize("task_mode", [False, True]) + async def test_tool_declaration_uses_the_card_description(self, task_mode): + """As a tool, the agent shows the model the (fenced) description of its card. + + The agent has no description of its own, so the card is the only place it is + written. It must reach the model whether the agent is wrapped in AgentTool + or delegated to in task mode, as it does for a transfer target. + """ + from google.adk.agents.llm_agent import Agent + from google.adk.models.llm_request import LlmRequest + from google.adk.tools.agent_tool import _TaskAgentTool + from google.adk.tools.agent_tool import AgentTool + from google.adk.tools.tool_context import ToolContext + + from tests.unittests import testing_utils + + agent_card = create_test_agent_card() + agent = RemoteA2aAgent( + name="test_agent", agent_card="https://example.com/agent.json" + ) + assert not agent.description + tool = _TaskAgentTool(agent) if task_mode else AgentTool(agent) + root = Agent( + name="root", model=testing_utils.MockModel.create(responses=[]) + ) + invocation_context = await testing_utils.create_invocation_context(root) + llm_request = LlmRequest() + + with patch.object( + agent, + "_resolve_agent_card", + new_callable=AsyncMock, + return_value=agent_card, + ): + await tool.process_llm_request( + tool_context=ToolContext(invocation_context), llm_request=llm_request + ) + + (declaration,) = llm_request.config.tools[0].function_declarations + assert declaration.name == "test_agent" + assert declaration.description.startswith(QUOTED_CONTENT_BEGIN) + assert agent_card.description in declaration.description + assert QUOTED_CONTENT_END in declaration.description + assert declaration.description.endswith( + "Do NOT call this tool in parallel with any other tools." + if task_mode + else QUOTED_CONTENT_END + ) + # The agent itself is untouched: the description is resolved per request. + assert not agent.description + @pytest.mark.asyncio async def test_ensure_resolved_already_resolved(self): """Test _ensure_resolved when already resolved.""" diff --git a/tests/unittests/tools/test_agent_tool_lazy_description.py b/tests/unittests/tools/test_agent_tool_lazy_description.py new file mode 100644 index 00000000000..535af2d2d8a --- /dev/null +++ b/tests/unittests/tools/test_agent_tool_lazy_description.py @@ -0,0 +1,140 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the description an AgentTool declares for an agent that reads it lazily. + +`RemoteA2aAgent` only learns its description from the remote agent's card, so +`agent.description` is empty when the model request is built. ADK resolves it +through `_get_transfer_description` when the agent is a `transfer_to_agent` +target; these tests cover the same for an agent exposed as a tool (`AgentTool`, +or the delegation tool of a task-mode sub-agent). +""" + +from unittest.mock import AsyncMock + +from google.adk.agents.base_agent import BaseAgent +from google.adk.agents.llm_agent import Agent +from google.adk.models.llm_request import LlmRequest +from google.adk.tools.agent_tool import _TaskAgentTool +from google.adk.tools.agent_tool import AgentTool +from google.adk.tools.tool_context import ToolContext +import pytest + +from .. import testing_utils + +_TASK_SUFFIX = ( + '\nIMPORTANT: This tool delegates execution to a specialized agent. Do NOT' + ' call this tool in parallel with any other tools.' +) + + +class _LazyDescriptionAgent(BaseAgent): + """An agent whose description is only available asynchronously.""" + + resolved: str = 'resolved description' + fails: bool = False + + async def _get_transfer_description(self, ctx) -> str: + if self.fails: + raise RuntimeError('the card cannot be reached') + return self.resolved + + +async def _declare(tool: AgentTool, invocation_context=None): + """Runs `process_llm_request` and returns the declaration it added.""" + if invocation_context is None: + root = Agent( + name='root', model=testing_utils.MockModel.create(responses=[]) + ) + invocation_context = await testing_utils.create_invocation_context(root) + llm_request = LlmRequest() + await tool.process_llm_request( + tool_context=ToolContext(invocation_context), llm_request=llm_request + ) + declarations = llm_request.config.tools[0].function_declarations + assert len(declarations) == 1 + return declarations[0] + + +@pytest.mark.asyncio +async def test_agent_tool_declares_the_lazily_resolved_description(): + agent = _LazyDescriptionAgent(name='lazy') + assert agent.description == '' + + declaration = await _declare(AgentTool(agent)) + + assert declaration.name == 'lazy' + assert declaration.description == 'resolved description' + # The agent itself is not changed: the description is per request. + assert agent.description == '' + + +@pytest.mark.asyncio +async def test_task_tool_declares_the_resolved_description_before_its_suffix(): + agent = _LazyDescriptionAgent(name='lazy') + + declaration = await _declare(_TaskAgentTool(agent)) + + assert declaration.description == f'resolved description{_TASK_SUFFIX}' + assert agent.description == '' + + +@pytest.mark.asyncio +async def test_task_tool_without_a_description_keeps_only_its_suffix(): + agent = _LazyDescriptionAgent(name='lazy', fails=True) + + declaration = await _declare(_TaskAgentTool(agent)) + + assert declaration.description == _TASK_SUFFIX.strip() + + +@pytest.mark.asyncio +async def test_agent_tool_falls_back_to_the_local_description_on_failure(): + agent = _LazyDescriptionAgent( + name='lazy', description='local description', fails=True + ) + + declaration = await _declare(AgentTool(agent)) + + assert declaration.description == 'local description' + + +@pytest.mark.asyncio +async def test_agent_tool_leaves_an_ordinary_agent_unchanged(): + agent = Agent( + name='plain', + description='plain description', + model=testing_utils.MockModel.create(responses=[]), + ) + assert not hasattr(agent, '_get_transfer_description') + + declaration = await _declare(AgentTool(agent)) + + assert declaration.description == 'plain description' + + +@pytest.mark.asyncio +async def test_description_is_resolved_once_per_invocation(): + agent = _LazyDescriptionAgent(name='lazy') + hook = AsyncMock(return_value='resolved description') + object.__setattr__(agent, '_get_transfer_description', hook) + root = Agent(name='root', model=testing_utils.MockModel.create(responses=[])) + invocation_context = await testing_utils.create_invocation_context(root) + + first = await _declare(AgentTool(agent), invocation_context) + second = await _declare(_TaskAgentTool(agent), invocation_context) + + assert first.description == 'resolved description' + assert second.description == f'resolved description{_TASK_SUFFIX}' + assert hook.await_count == 1