|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from typing import Any |
| 18 | +from typing import Union |
| 19 | + |
| 20 | +from google.genai import types |
| 21 | +from typing_extensions import override |
| 22 | + |
| 23 | +from ..agents.llm_agent import LlmAgent |
| 24 | +from ..memory.in_memory_memory_service import InMemoryMemoryService |
| 25 | +from ..models.base_llm import BaseLlm |
| 26 | +from ..utils.context_utils import Aclosing |
| 27 | +from ._forwarding_artifact_service import ForwardingArtifactService |
| 28 | +from .agent_tool import AgentTool |
| 29 | +from .google_search_tool import google_search |
| 30 | +from .tool_context import ToolContext |
| 31 | + |
| 32 | + |
| 33 | +def create_google_search_agent(model: Union[str, BaseLlm]) -> LlmAgent: |
| 34 | + """Create a sub-agent that only uses google_search tool.""" |
| 35 | + return LlmAgent( |
| 36 | + name='google_search_agent', |
| 37 | + model=model, |
| 38 | + description=( |
| 39 | + 'An agent for performing Google search using the `google_search` tool' |
| 40 | + ), |
| 41 | + instruction=""" |
| 42 | + You are a specialized Google search agent. |
| 43 | +
|
| 44 | + When given a search query, use the `google_search` tool to find the related information. |
| 45 | + """, |
| 46 | + tools=[google_search], |
| 47 | + ) |
| 48 | + |
| 49 | + |
| 50 | +class GoogleSearchAgentTool(AgentTool): |
| 51 | + """A tool that wraps a sub-agent that only uses google_search tool. |
| 52 | +
|
| 53 | + This is a workaround to support using google_search tool with other tools. |
| 54 | + TODO(b/448114567): Remove once the workaround is no longer needed. |
| 55 | +
|
| 56 | + Attributes: |
| 57 | + model: The model to use for the sub-agent. |
| 58 | + """ |
| 59 | + |
| 60 | + def __init__(self, agent: LlmAgent): |
| 61 | + self.agent = agent |
| 62 | + super().__init__(agent=self.agent) |
| 63 | + |
| 64 | + @override |
| 65 | + async def run_async( |
| 66 | + self, |
| 67 | + *, |
| 68 | + args: dict[str, Any], |
| 69 | + tool_context: ToolContext, |
| 70 | + ) -> Any: |
| 71 | + from ..agents.llm_agent import LlmAgent |
| 72 | + from ..runners import Runner |
| 73 | + from ..sessions.in_memory_session_service import InMemorySessionService |
| 74 | + |
| 75 | + if isinstance(self.agent, LlmAgent) and self.agent.input_schema: |
| 76 | + input_value = self.agent.input_schema.model_validate(args) |
| 77 | + content = types.Content( |
| 78 | + role='user', |
| 79 | + parts=[ |
| 80 | + types.Part.from_text( |
| 81 | + text=input_value.model_dump_json(exclude_none=True) |
| 82 | + ) |
| 83 | + ], |
| 84 | + ) |
| 85 | + else: |
| 86 | + content = types.Content( |
| 87 | + role='user', |
| 88 | + parts=[types.Part.from_text(text=args['request'])], |
| 89 | + ) |
| 90 | + runner = Runner( |
| 91 | + app_name=self.agent.name, |
| 92 | + agent=self.agent, |
| 93 | + artifact_service=ForwardingArtifactService(tool_context), |
| 94 | + session_service=InMemorySessionService(), |
| 95 | + memory_service=InMemoryMemoryService(), |
| 96 | + credential_service=tool_context._invocation_context.credential_service, |
| 97 | + plugins=list(tool_context._invocation_context.plugin_manager.plugins), |
| 98 | + ) |
| 99 | + |
| 100 | + state_dict = { |
| 101 | + k: v |
| 102 | + for k, v in tool_context.state.to_dict().items() |
| 103 | + if not k.startswith('_adk') # Filter out adk internal states |
| 104 | + } |
| 105 | + session = await runner.session_service.create_session( |
| 106 | + app_name=self.agent.name, |
| 107 | + user_id=tool_context._invocation_context.user_id, |
| 108 | + state=state_dict, |
| 109 | + ) |
| 110 | + |
| 111 | + last_content = None |
| 112 | + last_grounding_metadata = None |
| 113 | + async with Aclosing( |
| 114 | + runner.run_async( |
| 115 | + user_id=session.user_id, session_id=session.id, new_message=content |
| 116 | + ) |
| 117 | + ) as agen: |
| 118 | + async for event in agen: |
| 119 | + # Forward state delta to parent session. |
| 120 | + if event.actions.state_delta: |
| 121 | + tool_context.state.update(event.actions.state_delta) |
| 122 | + if event.content: |
| 123 | + last_content = event.content |
| 124 | + last_grounding_metadata = event.grounding_metadata |
| 125 | + |
| 126 | + if not last_content: |
| 127 | + return '' |
| 128 | + merged_text = '\n'.join(p.text for p in last_content.parts if p.text) |
| 129 | + if isinstance(self.agent, LlmAgent) and self.agent.output_schema: |
| 130 | + tool_result = self.agent.output_schema.model_validate_json( |
| 131 | + merged_text |
| 132 | + ).model_dump(exclude_none=True) |
| 133 | + else: |
| 134 | + tool_result = merged_text |
| 135 | + |
| 136 | + if last_grounding_metadata: |
| 137 | + tool_context.state['temp:_adk_grounding_metadata'] = ( |
| 138 | + last_grounding_metadata |
| 139 | + ) |
| 140 | + return tool_result |
0 commit comments