chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:25:13 +08:00
commit ec2b666284
2231 changed files with 491535 additions and 0 deletions
@@ -0,0 +1,13 @@
# 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.
@@ -0,0 +1,67 @@
# 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.
from google.adk.features import FeatureName
from google.adk.features._feature_registry import temporary_feature_override
from google.adk.tools.retrieval.base_retrieval_tool import BaseRetrievalTool
from google.genai import types
class _TestRetrievalTool(BaseRetrievalTool):
"""Concrete implementation of BaseRetrievalTool for testing."""
def __init__(self):
super().__init__(
name='test_retrieval',
description='A test retrieval tool.',
)
async def run_async(self, *, args, tool_context):
return {'result': 'test'}
def test_get_declaration_with_json_schema_feature_disabled():
"""Test that _get_declaration uses parameters when feature is disabled."""
tool = _TestRetrievalTool()
with temporary_feature_override(FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, False):
declaration = tool._get_declaration()
assert declaration.name == 'test_retrieval'
assert declaration.description == 'A test retrieval tool.'
assert declaration.parameters_json_schema is None
assert isinstance(declaration.parameters, types.Schema)
assert declaration.parameters.type == types.Type.OBJECT
assert 'query' in declaration.parameters.properties
def test_get_declaration_with_json_schema_feature_enabled():
"""Test that _get_declaration uses parameters_json_schema when feature is enabled."""
tool = _TestRetrievalTool()
with temporary_feature_override(FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, True):
declaration = tool._get_declaration()
assert declaration.name == 'test_retrieval'
assert declaration.description == 'A test retrieval tool.'
assert declaration.parameters is None
assert declaration.parameters_json_schema == {
'type': 'object',
'properties': {
'query': {
'type': 'string',
'description': 'The query to retrieve.',
},
},
}
@@ -0,0 +1,150 @@
# 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 FilesRetrieval tool."""
import unittest.mock as mock
from google.adk.tools.retrieval.files_retrieval import _get_default_embedding_model
from google.adk.tools.retrieval.files_retrieval import FilesRetrieval
from llama_index.core.base.embeddings.base import BaseEmbedding
import pytest
class MockEmbedding(BaseEmbedding):
"""Mock embedding model for testing."""
def _get_query_embedding(self, query):
return [0.1] * 384
def _get_text_embedding(self, text):
return [0.1] * 384
async def _aget_query_embedding(self, query):
return [0.1] * 384
async def _aget_text_embedding(self, text):
return [0.1] * 384
class TestFilesRetrieval:
def test_files_retrieval_with_custom_embedding(self, tmp_path):
"""Test FilesRetrieval with custom embedding model."""
# Create test file
test_file = tmp_path / "test.txt"
test_file.write_text("This is a test document for retrieval testing.")
custom_embedding = MockEmbedding()
retrieval = FilesRetrieval(
name="test_retrieval",
description="Test retrieval tool",
input_dir=str(tmp_path),
embedding_model=custom_embedding,
)
assert retrieval.name == "test_retrieval"
assert retrieval.input_dir == str(tmp_path)
assert retrieval.retriever is not None
@mock.patch(
"google.adk.tools.retrieval.files_retrieval._get_default_embedding_model"
)
def test_files_retrieval_uses_default_embedding(
self, mock_get_default_embedding, tmp_path
):
"""Test FilesRetrieval uses default embedding when none provided."""
# Create test file
test_file = tmp_path / "test.txt"
test_file.write_text("This is a test document for retrieval testing.")
mock_embedding = MockEmbedding()
mock_get_default_embedding.return_value = mock_embedding
retrieval = FilesRetrieval(
name="test_retrieval",
description="Test retrieval tool",
input_dir=str(tmp_path),
)
mock_get_default_embedding.assert_called_once()
assert retrieval.name == "test_retrieval"
assert retrieval.input_dir == str(tmp_path)
def test_get_default_embedding_model_import_error(self):
"""Test _get_default_embedding_model handles ImportError correctly."""
# Simulate the package not being installed by making import fail
import builtins
original_import = builtins.__import__
def mock_import(name, *args, **kwargs):
if name == "llama_index.embeddings.google_genai":
raise ImportError(
"No module named 'llama_index.embeddings.google_genai'"
)
return original_import(name, *args, **kwargs)
with mock.patch("builtins.__import__", side_effect=mock_import):
with pytest.raises(ImportError) as exc_info:
_get_default_embedding_model()
# The exception should be re-raised as our custom ImportError with helpful message
assert "llama-index-embeddings-google-genai package not found" in str(
exc_info.value
)
assert "pip install llama-index-embeddings-google-genai" in str(
exc_info.value
)
def test_get_default_embedding_model_success(self):
"""Test _get_default_embedding_model returns Google embedding when available."""
# Mock the module creation to avoid import issues
mock_module = mock.MagicMock()
mock_embedding_instance = MockEmbedding()
mock_module.GoogleGenAIEmbedding.return_value = mock_embedding_instance
with mock.patch.dict(
"sys.modules", {"llama_index.embeddings.google_genai": mock_module}
):
result = _get_default_embedding_model()
mock_module.GoogleGenAIEmbedding.assert_called_once_with(
model_name="gemini-embedding-2-preview",
embed_batch_size=1,
)
assert result == mock_embedding_instance
def test_backward_compatibility(self, tmp_path):
"""Test that existing code without embedding_model parameter still works."""
# Create test file
test_file = tmp_path / "test.txt"
test_file.write_text("This is a test document for retrieval testing.")
with mock.patch(
"google.adk.tools.retrieval.files_retrieval._get_default_embedding_model"
) as mock_get_default:
mock_get_default.return_value = MockEmbedding()
# This should work exactly like before - no embedding_model parameter
retrieval = FilesRetrieval(
name="test_retrieval",
description="Test retrieval tool",
input_dir=str(tmp_path),
)
assert retrieval.name == "test_retrieval"
assert retrieval.input_dir == str(tmp_path)
mock_get_default.assert_called_once()
@@ -0,0 +1,187 @@
# 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.
from google.adk.agents.llm_agent import Agent
from google.adk.tools.function_tool import FunctionTool
from google.adk.tools.retrieval.vertex_ai_rag_retrieval import VertexAiRagRetrieval
from google.genai import types
from ... import testing_utils
def noop_tool(x: str) -> str:
return x
def test_vertex_rag_retrieval_for_gemini_1_x():
responses = [
'response1',
]
mockModel = testing_utils.MockModel.create(responses=responses)
mockModel.model = 'gemini-1.5-pro'
# Calls the first time.
agent = Agent(
name='root_agent',
model=mockModel,
tools=[
VertexAiRagRetrieval(
name='rag_retrieval',
description='rag_retrieval',
rag_corpora=[
'projects/123456789/locations/us-central1/ragCorpora/1234567890'
],
)
],
)
runner = testing_utils.InMemoryRunner(agent)
events = runner.run('test1')
# Asserts the requests.
assert len(mockModel.requests) == 1
assert testing_utils.simplify_contents(mockModel.requests[0].contents) == [
('user', 'test1'),
]
assert len(mockModel.requests[0].config.tools) == 1
assert (
mockModel.requests[0].config.tools[0].function_declarations[0].name
== 'rag_retrieval'
)
assert mockModel.requests[0].tools_dict['rag_retrieval'] is not None
def test_vertex_rag_retrieval_for_gemini_1_x_with_another_function_tool():
responses = [
'response1',
]
mockModel = testing_utils.MockModel.create(responses=responses)
mockModel.model = 'gemini-1.5-pro'
# Calls the first time.
agent = Agent(
name='root_agent',
model=mockModel,
tools=[
VertexAiRagRetrieval(
name='rag_retrieval',
description='rag_retrieval',
rag_corpora=[
'projects/123456789/locations/us-central1/ragCorpora/1234567890'
],
),
FunctionTool(func=noop_tool),
],
)
runner = testing_utils.InMemoryRunner(agent)
events = runner.run('test1')
# Asserts the requests.
assert len(mockModel.requests) == 1
assert testing_utils.simplify_contents(mockModel.requests[0].contents) == [
('user', 'test1'),
]
assert len(mockModel.requests[0].config.tools[0].function_declarations) == 2
assert (
mockModel.requests[0].config.tools[0].function_declarations[0].name
== 'rag_retrieval'
)
assert (
mockModel.requests[0].config.tools[0].function_declarations[1].name
== 'noop_tool'
)
assert mockModel.requests[0].tools_dict['rag_retrieval'] is not None
def test_vertex_rag_retrieval_for_gemini_2_x():
responses = [
'response1',
]
mockModel = testing_utils.MockModel.create(responses=responses)
mockModel.model = 'gemini-2.5-flash'
# Calls the first time.
agent = Agent(
name='root_agent',
model=mockModel,
tools=[
VertexAiRagRetrieval(
name='rag_retrieval',
description='rag_retrieval',
rag_corpora=[
'projects/123456789/locations/us-central1/ragCorpora/1234567890'
],
)
],
)
runner = testing_utils.InMemoryRunner(agent)
events = runner.run('test1')
# Asserts the requests.
assert len(mockModel.requests) == 1
assert testing_utils.simplify_contents(mockModel.requests[0].contents) == [
('user', 'test1'),
]
assert len(mockModel.requests[0].config.tools) == 1
assert mockModel.requests[0].config.tools == [
types.Tool(
retrieval=types.Retrieval(
vertex_rag_store=types.VertexRagStore(
rag_corpora=[
'projects/123456789/locations/us-central1/ragCorpora/1234567890'
]
)
)
)
]
assert 'rag_retrieval' not in mockModel.requests[0].tools_dict
def test_vertex_rag_retrieval_for_non_gemini_with_disabled_check(monkeypatch):
monkeypatch.setenv('ADK_DISABLE_GEMINI_MODEL_ID_CHECK', 'true')
responses = [
'response1',
]
mockModel = testing_utils.MockModel.create(responses=responses)
mockModel.model = 'internal-model-v1'
agent = Agent(
name='root_agent',
model=mockModel,
tools=[
VertexAiRagRetrieval(
name='rag_retrieval',
description='rag_retrieval',
rag_corpora=[
'projects/123456789/locations/us-central1/ragCorpora/1234567890'
],
)
],
)
runner = testing_utils.InMemoryRunner(agent)
runner.run('test1')
assert len(mockModel.requests) == 1
assert len(mockModel.requests[0].config.tools) == 1
assert mockModel.requests[0].config.tools == [
types.Tool(
retrieval=types.Retrieval(
vertex_rag_store=types.VertexRagStore(
rag_corpora=[
'projects/123456789/locations/us-central1/ragCorpora/1234567890'
]
)
)
)
]
assert 'rag_retrieval' not in mockModel.requests[0].tools_dict