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
+13
View File
@@ -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.
+225
View File
@@ -0,0 +1,225 @@
# 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 unittest.mock import Mock
from google.adk.agents.base_agent import BaseAgent
from google.adk.agents.context_cache_config import ContextCacheConfig
from google.adk.apps.app import App
from google.adk.apps.app import ResumabilityConfig
from google.adk.plugins.base_plugin import BasePlugin
from google.adk.workflow._base_node import BaseNode
import pytest
class TestApp:
"""Tests for App class."""
def test_app_initialization(self):
"""Test that the app is initialized correctly without plugins."""
mock_agent = Mock(spec=BaseAgent)
app = App(name="test_app", root_agent=mock_agent)
assert app.name == "test_app"
assert app.root_agent == mock_agent
assert app.plugins == []
def test_app_initialization_with_plugins(self):
"""Test that the app is initialized correctly with plugins."""
mock_agent = Mock(spec=BaseAgent)
mock_plugin = Mock(spec=BasePlugin)
app = App(name="test_app", root_agent=mock_agent, plugins=[mock_plugin])
assert app.name == "test_app"
assert app.root_agent == mock_agent
assert app.plugins == [mock_plugin]
def test_app_initialization_without_cache_config(self):
"""Test that the app is initialized correctly without context cache config."""
mock_agent = Mock(spec=BaseAgent)
app = App(name="test_app", root_agent=mock_agent)
assert app.name == "test_app"
assert app.root_agent == mock_agent
assert app.context_cache_config is None
def test_app_initialization_with_cache_config(self):
"""Test that the app is initialized correctly with context cache config."""
mock_agent = Mock(spec=BaseAgent)
cache_config = ContextCacheConfig(
cache_intervals=15, ttl_seconds=3600, min_tokens=1024
)
app = App(
name="test_app",
root_agent=mock_agent,
context_cache_config=cache_config,
)
assert app.name == "test_app"
assert app.root_agent == mock_agent
assert app.context_cache_config == cache_config
assert app.context_cache_config.cache_intervals == 15
assert app.context_cache_config.ttl_seconds == 3600
assert app.context_cache_config.min_tokens == 1024
def test_app_initialization_with_resumability_config(self):
"""Test that the app is initialized correctly with app config."""
mock_agent = Mock(spec=BaseAgent)
resumability_config = ResumabilityConfig(
is_resumable=True,
)
app = App(
name="test_app",
root_agent=mock_agent,
resumability_config=resumability_config,
)
assert app.name == "test_app"
assert app.root_agent == mock_agent
assert app.resumability_config == resumability_config
assert app.resumability_config.is_resumable
def test_app_with_all_components(self):
"""Test app with all components: agent, plugins, and cache config."""
mock_agent = Mock(spec=BaseAgent)
mock_plugin = Mock(spec=BasePlugin)
cache_config = ContextCacheConfig(
cache_intervals=20, ttl_seconds=7200, min_tokens=2048
)
resumability_config = ResumabilityConfig(
is_resumable=True,
)
app = App(
name="full_test_app",
root_agent=mock_agent,
plugins=[mock_plugin],
context_cache_config=cache_config,
resumability_config=resumability_config,
)
assert app.name == "full_test_app"
assert app.root_agent == mock_agent
assert app.plugins == [mock_plugin]
assert app.context_cache_config == cache_config
assert app.resumability_config == resumability_config
assert app.resumability_config.is_resumable
def test_app_cache_config_defaults(self):
"""Test that cache config has proper defaults when created."""
mock_agent = Mock(spec=BaseAgent)
cache_config = ContextCacheConfig() # Use defaults
app = App(
name="default_cache_app",
root_agent=mock_agent,
context_cache_config=cache_config,
)
assert app.context_cache_config.cache_intervals == 10 # Default
assert app.context_cache_config.ttl_seconds == 1800 # Default 30 minutes
assert app.context_cache_config.min_tokens == 0 # Default
def test_app_context_cache_config_is_optional(self):
"""Test that context_cache_config is truly optional."""
mock_agent = Mock(spec=BaseAgent)
# Should work without context_cache_config
app = App(name="no_cache_app", root_agent=mock_agent)
assert app.context_cache_config is None
# Should work with explicit None
app = App(
name="explicit_none_app",
root_agent=mock_agent,
context_cache_config=None,
)
assert app.context_cache_config is None
def test_app_resumability_config_defaults(self):
"""Test that app config has proper defaults when created."""
mock_agent = Mock(spec=BaseAgent)
app = App(
name="default_resumability_config_app",
root_agent=mock_agent,
resumability_config=ResumabilityConfig(),
)
assert app.resumability_config is not None
assert not app.resumability_config.is_resumable # Default
def test_app_resumability_config_is_optional(self):
"""Test that resumability_config is truly optional."""
mock_agent = Mock(spec=BaseAgent)
app = App(name="no_resumability_config_app", root_agent=mock_agent)
assert app.resumability_config is None
app = App(
name="explicit_none_resumability_config_app",
root_agent=mock_agent,
resumability_config=None,
)
assert app.resumability_config is None
def test_app_rejects_invalid_name(self):
"""Test that invalid application names are rejected."""
mock_agent = Mock(spec=BaseAgent)
with pytest.raises(ValueError):
App(name="../escape_attempt", root_agent=mock_agent)
with pytest.raises(ValueError):
App(name="nested/path", root_agent=mock_agent)
with pytest.raises(ValueError):
App(name="windows\\path", root_agent=mock_agent)
def test_app_name_must_be_valid(self):
mock_agent = Mock(spec=BaseAgent)
# Hyphens are allowed
App(name="valid-name", root_agent=mock_agent)
with pytest.raises(ValueError):
App(name="invalid name", root_agent=mock_agent)
with pytest.raises(ValueError):
App(name="invalid@name", root_agent=mock_agent)
def test_app_name_cannot_be_user(self):
mock_agent = Mock(spec=BaseAgent)
with pytest.raises(ValueError):
App(name="user", root_agent=mock_agent)
class TestAppRootNode:
"""Tests for App.root_agent accepting BaseNode."""
def test_app_with_root_node(self):
"""Test App creation with a BaseNode as root_agent."""
node = BaseNode(name="test_node")
app = App(name="test_app", root_agent=node)
assert app.root_agent is node
def test_app_rejects_none_root_agent(self):
"""Test that not providing root_agent raises."""
with pytest.raises(ValueError, match="root_agent must be provided"):
App(name="test_app")
def test_app_rejects_invalid_root_agent(self):
"""Test that root_agent must be a BaseAgent or BaseNode instance."""
with pytest.raises(
TypeError, match="root_agent must be a BaseAgent or BaseNode"
):
App(name="test_app", root_agent="not_a_node")
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,212 @@
# 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.
"""End-to-end test: Runner + event compaction.
Exercises the full ``runner.run_async`` path with a mock model, an in-memory
session service, and token-threshold event compaction.
"""
from google.adk.agents.llm_agent import Agent
from google.adk.apps.app import App
from google.adk.apps.app import EventsCompactionConfig
from google.adk.apps.llm_event_summarizer import LlmEventSummarizer
from google.adk.events.event import Event
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.genai import types
from google.genai.types import Content
from google.genai.types import Part
import pytest
from .. import testing_utils
def _function_call_event(timestamp, invocation_id, call_id):
return Event(
timestamp=timestamp,
invocation_id=invocation_id,
author="agent",
content=Content(
role="model",
parts=[
Part(
function_call=types.FunctionCall(
id=call_id, name="tool", args={}
)
)
],
),
)
def _function_response_event(timestamp, invocation_id, call_id, tokens=None):
usage = (
types.GenerateContentResponseUsageMetadata(prompt_token_count=tokens)
if tokens is not None
else None
)
return Event(
timestamp=timestamp,
invocation_id=invocation_id,
author="user",
content=Content(
role="user",
parts=[
Part(
function_response=types.FunctionResponse(
id=call_id, name="tool", response={"result": "ok"}
)
)
],
),
usage_metadata=usage,
)
@pytest.mark.asyncio
async def test_runner_compaction_does_not_break_execution():
"""Compaction must not orphan a function response, or the runner breaks.
Mocks two tool calls with distinct ids: ``call-1`` is finished (it has a
function_response) while ``call-2`` is still pending (no response). Because
``call-2`` sits between ``call-1``'s call and its response,
compaction could summarize ``call-1``'s function_call while leaving its
function_response behind -- an orphan with no matching call.
Runs the full ``runner.run_async`` path with token-threshold compaction and
checks that compaction works properly: it must keep every call together
with its response. Otherwise, the prompt assembly will raise ``ValueError``
("No function call event found ...") and ``run_async`` will crash before
the model is ever reached.
"""
agent_model = testing_utils.MockModel.create(responses=["final answer"])
agent = Agent(name="agent", model=agent_model)
app = App(
name="test_app",
root_agent=agent,
events_compaction_config=EventsCompactionConfig(
compaction_interval=10_000,
overlap_size=0,
token_threshold=1_000,
event_retention_size=0,
summarizer=LlmEventSummarizer(
llm=testing_utils.MockModel.create(responses=["summary"])
),
),
)
session_service = InMemorySessionService()
session = await session_service.create_session(
app_name="test_app", user_id="u1", session_id="s1"
)
events = [
Event(
timestamp=1.0,
invocation_id="inv1",
author="user",
content=Content(role="user", parts=[Part(text="hello")]),
),
_function_call_event(2.0, "inv2", "call-1"),
_function_call_event(3.0, "inv3", "call-2"), # stays pending
# Last event and carries a high token count to trigger token compaction.
_function_response_event(4.0, "inv3", "call-1", tokens=100_000),
]
for event in events:
await session_service.append_event(session=session, event=event)
runner = Runner(app=app, session_service=session_service)
# No new_message: just (re)process the existing session.
# If we allow compaction to orphan the function response,
# this will raise ValueError before the model is reached.
produced = [
event
async for event in runner.run_async(
user_id="u1", session_id="s1", new_message=None
)
]
# We got past request assembly and actually called the model.
assert (
agent_model.requests
), "model was never called; compaction orphaned the response"
assert produced
# call-1's function_call survived in the assembled prompt (not compacted).
prompt_call_ids = []
for content in agent_model.requests[-1].contents:
for part in content.parts or []:
if part.function_call is not None:
prompt_call_ids.append(part.function_call.id)
assert "call-1" in prompt_call_ids
@pytest.mark.asyncio
async def test_runner_appends_sliding_window_compaction_event():
"""The runner loop, not compaction, persists the sliding-window event.
Compaction now yields its event and the runner is the single append site.
With a sliding-window config (no token threshold), the full ``run_async``
path must leave a compaction event persisted in the session -- proving the
runner performed the append the compaction function no longer does.
"""
agent_model = testing_utils.MockModel.create(responses=["final answer"])
agent = Agent(name="agent", model=agent_model)
app = App(
name="test_app",
root_agent=agent,
events_compaction_config=EventsCompactionConfig(
compaction_interval=2,
overlap_size=0,
summarizer=LlmEventSummarizer(
llm=testing_utils.MockModel.create(responses=["summary"])
),
),
)
session_service = InMemorySessionService()
session = await session_service.create_session(
app_name="test_app", user_id="u1", session_id="s1"
)
events = [
Event(
timestamp=1.0,
invocation_id="inv1",
author="user",
content=Content(role="user", parts=[Part(text="hello")]),
),
Event(
timestamp=2.0,
invocation_id="inv2",
author="user",
content=Content(role="user", parts=[Part(text="world")]),
),
]
for event in events:
await session_service.append_event(session=session, event=event)
runner = Runner(app=app, session_service=session_service)
async for _ in runner.run_async(
user_id="u1", session_id="s1", new_message=None
):
pass
refreshed = await session_service.get_session(
app_name="test_app", user_id="u1", session_id="s1"
)
compaction_events = [
event for event in refreshed.events if event.actions.compaction
]
assert (
compaction_events
), "runner did not append the sliding-window compaction event"
@@ -0,0 +1,265 @@
# 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.
import unittest
from unittest.mock import AsyncMock
from google.adk.apps.llm_event_summarizer import LlmEventSummarizer
from google.adk.events.event import Event
from google.adk.events.event_actions import EventActions
from google.adk.events.event_actions import EventCompaction
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.genai import types
from google.genai.types import Content
from google.genai.types import FunctionCall
from google.genai.types import FunctionResponse
from google.genai.types import Part
import pytest
@pytest.mark.parametrize(
'env_variables', ['GOOGLE_AI', 'VERTEX'], indirect=True
)
class TestLlmEventSummarizer(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.mock_llm = AsyncMock(spec=BaseLlm)
self.mock_llm.model = 'test-model'
self.compactor = LlmEventSummarizer(llm=self.mock_llm)
def _create_event(
self, timestamp: float, text: str, author: str = 'user'
) -> Event:
return Event(
timestamp=timestamp,
author=author,
content=Content(parts=[Part(text=text)]),
)
async def test_maybe_compact_events_success(self):
events = [
self._create_event(1.0, 'Hello', 'user'),
self._create_event(2.0, 'Hi there!', 'model'),
]
expected_conversation_history = 'user: Hello\nmodel: Hi there!'
expected_prompt = self.compactor._DEFAULT_PROMPT_TEMPLATE.format(
conversation_history=expected_conversation_history
)
llm_response = LlmResponse(
content=Content(parts=[Part(text='Summary')]),
usage_metadata=None,
)
async def async_gen():
yield llm_response
self.mock_llm.generate_content_async.return_value = async_gen()
compacted_event = await self.compactor.maybe_summarize_events(events=events)
self.assertIsNotNone(compacted_event)
self.assertEqual(
compacted_event.actions.compaction.compacted_content.parts[0].text,
'Summary',
)
self.assertEqual(compacted_event.author, 'user')
self.assertIsNone(compacted_event.usage_metadata)
self.assertIsNotNone(compacted_event.actions)
self.assertIsNotNone(compacted_event.actions.compaction)
self.assertEqual(compacted_event.actions.compaction.start_timestamp, 1.0)
self.assertEqual(compacted_event.actions.compaction.end_timestamp, 2.0)
self.assertEqual(
compacted_event.actions.compaction.compacted_content.parts[0].text,
'Summary',
)
self.mock_llm.generate_content_async.assert_called_once()
args, kwargs = self.mock_llm.generate_content_async.call_args
llm_request = args[0]
self.assertIsInstance(llm_request, LlmRequest)
self.assertEqual(llm_request.model, 'test-model')
self.assertEqual(llm_request.contents[0].role, 'user')
self.assertEqual(llm_request.contents[0].parts[0].text, expected_prompt)
self.assertFalse(kwargs['stream'])
async def test_maybe_compact_events_empty_llm_response(self):
events = [
self._create_event(1.0, 'Hello', 'user'),
]
llm_response = LlmResponse(content=None, usage_metadata=None)
async def async_gen():
yield llm_response
self.mock_llm.generate_content_async.return_value = async_gen()
compacted_event = await self.compactor.maybe_summarize_events(events=events)
self.assertIsNone(compacted_event)
async def test_maybe_compact_events_includes_usage_metadata(self):
events = [
self._create_event(1.0, 'Hello', 'user'),
self._create_event(2.0, 'Hi there!', 'model'),
]
usage_metadata = types.GenerateContentResponseUsageMetadata(
prompt_token_count=10,
candidates_token_count=5,
)
llm_response = LlmResponse(
content=Content(parts=[Part(text='Summary')]),
usage_metadata=usage_metadata,
)
async def async_gen():
yield llm_response
self.mock_llm.generate_content_async.return_value = async_gen()
compacted_event = await self.compactor.maybe_summarize_events(events=events)
self.assertIsNotNone(compacted_event)
self.assertEqual(compacted_event.usage_metadata, usage_metadata)
self.assertEqual(compacted_event.usage_metadata.prompt_token_count, 10)
self.assertEqual(compacted_event.usage_metadata.candidates_token_count, 5)
async def test_maybe_compact_events_empty_input(self):
compacted_event = await self.compactor.maybe_summarize_events(events=[])
self.assertIsNone(compacted_event)
self.mock_llm.generate_content_async.assert_not_called()
def test_format_events_for_prompt(self):
events = [
self._create_event(1.0, 'User says...', 'user'),
self._create_event(2.0, 'Model replies...', 'model'),
self._create_event(3.0, 'Another user input', 'user'),
self._create_event(4.0, 'More model text', 'model'),
# Event with no content
Event(timestamp=5.0, author='user'),
# Event with empty content part
Event(
timestamp=6.0,
author='model',
content=Content(parts=[Part(text='')]),
),
# Event with function call
Event(
timestamp=7.0,
author='model',
content=Content(
parts=[
Part(
function_call=FunctionCall(
id='call_1', name='tool', args={'q': 'x'}
)
)
]
),
),
# Event with function response
Event(
timestamp=8.0,
author='model',
content=Content(
parts=[
Part(
function_response=FunctionResponse(
id='call_1',
name='tool',
response={'result': 'done'},
)
)
]
),
),
]
expected_formatted_history = (
'user: User says...\nmodel: Model replies...\nuser: Another user'
' input\nmodel: More model text\nmodel called tool:'
" tool({'q': 'x'})\nTool response from tool: {'result': 'done'}"
)
formatted_history = self.compactor._format_events_for_prompt(events)
self.assertEqual(formatted_history, expected_formatted_history)
def test_format_events_for_prompt_includes_thoughts(self):
events = [
self._create_event(1.0, 'What is the weather?', 'user'),
Event(
timestamp=2.0,
author='model',
content=Content(
parts=[
Part(text='Let me check the tool output.', thought=True),
Part(text='It is sunny.'),
]
),
),
]
expected_formatted_history = (
'user: What is the weather?\nmodel (thought): Let me check the tool'
' output.\nmodel: It is sunny.'
)
formatted_history = self.compactor._format_events_for_prompt(events)
self.assertEqual(formatted_history, expected_formatted_history)
def test_format_events_for_prompt_skips_compaction_event_thought(self):
events = [
Event(
timestamp=1.0,
author='model',
content=Content(
parts=[
Part(text='Stale summarizer reasoning.', thought=True),
Part(text='Prior summary.'),
]
),
actions=EventActions(
compaction=EventCompaction(
start_timestamp=0.0,
end_timestamp=1.0,
compacted_content=Content(parts=[Part(text='Prior')]),
)
),
),
self._create_event(2.0, 'New user input', 'user'),
]
expected_formatted_history = 'model: Prior summary.\nuser: New user input'
formatted_history = self.compactor._format_events_for_prompt(events)
self.assertEqual(formatted_history, expected_formatted_history)
def test_format_events_for_prompt_truncates_large_tool_response(self):
limit = self.compactor._MAX_TOOL_CONTENT_CHARS
large_value = 'x' * (limit + 500)
events = [
Event(
timestamp=1.0,
author='model',
content=Content(
parts=[
Part(
function_response=FunctionResponse(
id='call_1',
name='search',
response={'data': large_value},
)
)
]
),
),
]
formatted_history = self.compactor._format_events_for_prompt(events)
self.assertIn('Tool response from search:', formatted_history)
self.assertIn('... [truncated', formatted_history)
self.assertLess(len(formatted_history), len(large_value))