diff --git a/src/google/adk/agents/base_agent.py b/src/google/adk/agents/base_agent.py index 1ab5933c221..c2d61722652 100644 --- a/src/google/adk/agents/base_agent.py +++ b/src/google/adk/agents/base_agent.py @@ -196,7 +196,8 @@ class MyAgent(BaseAgent): Returns: Optional[types.Content]: The content to return to the user. When the content is truthy, the agent run will be skipped and the - provided content will be returned to user. + provided content will be returned to user. Setting event actions such + as escalate without returning content does not skip the agent run. """ after_agent_callback: AfterAgentCallback | None = None """Callback or list of callbacks to be invoked after the agent run. @@ -596,8 +597,8 @@ async def _handle_agent_callbacks( end_invocation_on_content: Whether returned content ends the invocation. Returns: - Optional[Event]: an event if a callback provides content or changed state - or artifacts. + Optional[Event]: an event if a callback provides content or changes + event actions. """ callback_context = CallbackContext(ctx) @@ -634,15 +635,14 @@ async def _handle_agent_callbacks( ctx.end_invocation = True return ret_event - if ( - callback_context.state.has_delta() - or callback_context._event_actions.artifact_delta - ): + # Accessing actions also flushes nested state writes into the state delta. + actions = callback_context.actions + if actions != EventActions(): return Event( invocation_id=ctx.invocation_id, author=self.name, branch=ctx.branch, - actions=callback_context._event_actions, + actions=actions, ) return None @@ -656,8 +656,8 @@ async def _handle_before_agent_callback( ctx: InvocationContext, the invocation context for this agent. Returns: - Optional[Event]: an event if a callback provides content or changed state - or artifacts. + Optional[Event]: an event if a callback provides content or changes + event actions. """ return await self._handle_agent_callbacks( ctx, @@ -677,8 +677,8 @@ async def _handle_after_agent_callback( agent. Returns: - Optional[Event]: an event if a callback provides content or changed state - or artifacts. + Optional[Event]: an event if a callback provides content or changes + event actions. """ return await self._handle_agent_callbacks( invocation_context, diff --git a/src/google/adk/agents/loop_agent.py b/src/google/adk/agents/loop_agent.py index 9f3bf8857a6..b5555732dfd 100644 --- a/src/google/adk/agents/loop_agent.py +++ b/src/google/adk/agents/loop_agent.py @@ -65,6 +65,11 @@ class LoopAgent(BaseAgent): When sub-agent generates an event with escalate or max_iterations are reached, the loop agent will stop. + The escalate flag is checked after the current sub-agent finishes. If a + sub-agent's before_agent_callback sets escalate without returning content, + that sub-agent still runs once before the loop stops; return content from + the callback to skip the sub-agent's run. + .. deprecated:: LoopAgent is deprecated in favor of Workflow and will be removed in a future version. Workflow cannot yet be used as an LlmAgent sub-agent. diff --git a/tests/unittests/agents/test_agent_callback_events.py b/tests/unittests/agents/test_agent_callback_events.py new file mode 100644 index 00000000000..e76b7c0e127 --- /dev/null +++ b/tests/unittests/agents/test_agent_callback_events.py @@ -0,0 +1,258 @@ +# 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. + +"""Runner-level checks for the events emitted by agent callbacks.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from google.adk.agents.base_agent import BaseAgent +from google.adk.agents.callback_context import CallbackContext +from google.adk.agents.llm_agent import LlmAgent +from google.adk.agents.loop_agent import LoopAgent +from google.adk.agents.parallel_agent import ParallelAgent +from google.adk.agents.sequential_agent import SequentialAgent +from google.adk.apps.app import App +from google.adk.apps.app import ResumabilityConfig +from google.adk.events.event import Event +from google.adk.events.event_actions import EventActions +from google.adk.runners import Runner +from google.adk.sessions.in_memory_session_service import InMemorySessionService +from google.adk.tools.function_tool import FunctionTool +from google.genai import types +import pytest + +from .. import testing_utils + + +def _lookup(city: str) -> str: + return f'sunny in {city}' + + +def _book(city: str) -> str: + return f'booked {city}' + + +_LOOKUP = FunctionTool(_lookup) +_BOOK = FunctionTool(_book, require_confirmation=True) + + +def _llm( + name: str, *, tools: tuple[FunctionTool, ...] = (), **kwargs: Any +) -> LlmAgent: + """An LlmAgent that calls each of its tools once, then replies.""" + calls = [ + types.Part.from_function_call(name=tool.name, args={'city': 'x'}) + for tool in tools + ] + replies: list[Any] = [[types.Part(text='done')]] * 6 + return LlmAgent( + name=name, + model=testing_utils.MockModel.create( + responses=([calls] if calls else []) + replies + ), + tools=list(tools), + **kwargs, + ) + + +async def _run( + root: BaseAgent, *, resumable: bool = False, turns: int = 1 +) -> list[Event]: + app = App( + name='callback_events', + root_agent=root, + resumability_config=ResumabilityConfig(is_resumable=resumable), + ) + runner = Runner(app=app, session_service=InMemorySessionService()) + session = await runner.session_service.create_session( + app_name=app.name, user_id='user', state={'nested': {'k': 'v'}} + ) + events = [] + for _ in range(turns): + async for event in runner.run_async( + user_id='user', + session_id=session.id, + new_message=types.UserContent('hi'), + ): + events.append(event) + return events + + +def _describe(part: types.Part) -> str: + if part.function_call: + return f'call:{part.function_call.name}' + if part.function_response: + return f'resp:{part.function_response.name}' + return part.text or '?' + + +def _shape(event: Event) -> tuple[str, str, tuple[str, ...]]: + """Event identity without ids, timestamps, or function call ids.""" + parts = (event.content.parts or []) if event.content else [] + actions = event.actions.model_dump() + return ( + event.author, + '|'.join(map(_describe, parts)), + tuple(sorted(k for k, v in actions.items() if v)), + ) + + +@pytest.mark.parametrize('resumable', [False, True]) +@pytest.mark.parametrize('with_state', [False, True]) +async def test_before_agent_escalate_stops_loop_after_agent_body( + resumable: bool, with_state: bool +) -> None: + """Before-callback escalation stops the loop once the agent body ran. + + Escalation only tells the enclosing loop to stop; it does not end the + invocation, so the escalating agent still runs its body this iteration. + Writing state as well (the workaround on released versions) behaves the same. + """ + + def escalate(callback_context: CallbackContext) -> None: + callback_context.actions.escalate = True + if with_state: + callback_context.state['stopped'] = True + + worker = _llm('worker', before_agent_callback=escalate) + loop = LoopAgent(name='loop', sub_agents=[worker], max_iterations=3) + + events = await _run(loop, resumable=resumable) + + escalations = [e for e in events if e.actions.escalate] + assert [_shape(e) for e in escalations] == [( + 'worker', + '', + ('escalate', 'state_delta') if with_state else ('escalate',), + )] + assert escalations[0].content is None + # The body still ran once after the escalation event, then the loop stopped. + replies = [e for e in events if e.content] + assert [_shape(e) for e in replies] == [('worker', 'done', ())] + assert events.index(escalations[0]) < events.index(replies[0]) + + +@pytest.mark.parametrize('phase', ['before', 'after']) +@pytest.mark.parametrize( + 'field, value', + [ + ('escalate', True), + ('transfer_to_agent', 'helper'), + ('skip_summarization', True), + ], +) +async def test_action_only_callback_matches_state_writing_callback( + phase: str, field: str, value: object +) -> None: + """An action-only callback emits what a state-writing one already emitted.""" + + async def run(with_state: bool) -> tuple[list[Event], list[Event]]: + def callback(callback_context: CallbackContext) -> None: + setattr(callback_context.actions, field, value) + if with_state: + callback_context.state['touched'] = True + + callbacks: dict[str, Any] = {f'{phase}_agent_callback': callback} + root = _llm('root', sub_agents=[_llm('helper')], **callbacks) + events = await _run(root, turns=2) + return events, [e for e in events if getattr(e.actions, field) == value] + + events, emitted = await run(with_state=False) + workaround_events, workaround_emitted = await run(with_state=True) + + # A transfer hands both turns to the helper: before the callback the root + # delegates at once, after it the next turn is routed to the helper. + per_turn = field != 'transfer_to_agent' + assert len(emitted) == len(workaround_emitted) == (2 if per_turn else 1) + for event in emitted: + assert (event.author, event.content) == ('root', None) + assert not event.actions.state_delta + assert [_shape(e) for e in events] == [ + (a, c, tuple(f for f in fields if f != 'state_delta')) + for a, c, fields in map(_shape, workaround_events) + ] + if not per_turn: + assert [e.author for e in events if e.content][-2:] == ['helper'] * 2 + + +def _noop_callbacks(calls: list[str]) -> dict[str, Callable[..., None]]: + def before(callback_context: CallbackContext) -> None: + calls.append(f'before:{callback_context.agent_name}') + # Reads, including of a nested container, must not count as changes. + _ = callback_context.state.get('nested', {}).get('k') + _ = callback_context.actions + + def after(callback_context: CallbackContext) -> None: + calls.append(f'after:{callback_context.agent_name}') + _ = dict(callback_context.state.get('nested', {})) + _ = callback_context.actions == EventActions() + + return {'before_agent_callback': before, 'after_agent_callback': after} + + +def _tree( + kind: str, + tools: tuple[FunctionTool, ...], + callbacks: dict[str, Callable[..., None]], +) -> BaseAgent: + if kind == 'llm': + helper = _llm('helper', tools=tools, **callbacks) + return _llm('root', tools=tools, sub_agents=[helper], **callbacks) + workers = [ + _llm('a', tools=tools, **callbacks), + _llm('b', tools=tools, **callbacks), + ] + if kind == 'sequential': + return SequentialAgent(name='root', sub_agents=workers, **callbacks) + if kind == 'loop': + return LoopAgent( + name='root', sub_agents=workers, max_iterations=2, **callbacks + ) + return ParallelAgent(name='root', sub_agents=workers, **callbacks) + + +@pytest.mark.parametrize('pause', [False, True]) +@pytest.mark.parametrize('resumable', [False, True]) +@pytest.mark.parametrize('kind', ['llm', 'sequential', 'loop', 'parallel']) +async def test_noop_agent_callbacks_emit_no_events( + kind: str, resumable: bool, pause: bool +) -> None: + """No-op callbacks emit nothing, even beside framework-set actions. + + Each run calls tools and, when resumable, checkpoints agent state, so the + framework sets action fields in the same invocation as the callbacks. A + pausing run also requests a tool confirmation, which ends the invocation + before the after-agent callbacks; a non-pausing run reaches all of them. + """ + tools = (_LOOKUP, _BOOK) if pause else (_LOOKUP,) + calls: list[str] = [] + + baseline = await _run(_tree(kind, tools, {}), resumable=resumable) + events = await _run( + _tree(kind, tools, _noop_callbacks(calls)), resumable=resumable + ) + + assert sorted(map(_shape, events)) == sorted(map(_shape, baseline)) + framework_fields = {f for e in baseline for f in _shape(e)[2]} + if pause: + assert 'requested_tool_confirmations' in framework_fields + else: + assert {c for c in calls if c.startswith('after:')} == { + c.replace('before:', 'after:') for c in calls + } + if resumable and kind != 'llm': + assert 'end_of_agent' in framework_fields diff --git a/tests/unittests/agents/test_base_agent.py b/tests/unittests/agents/test_base_agent.py index 0e74a6dc185..efd4864dc50 100644 --- a/tests/unittests/agents/test_base_agent.py +++ b/tests/unittests/agents/test_base_agent.py @@ -33,6 +33,7 @@ from google.adk.apps.app import ResumabilityConfig from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService from google.adk.events.event import Event +from google.adk.events.ui_widget import UiWidget from google.adk.plugins.base_plugin import BasePlugin from google.adk.plugins.plugin_manager import PluginManager from google.adk.sessions.in_memory_session_service import InMemorySessionService @@ -1972,3 +1973,43 @@ async def test_before_agent_callback_bypass_skips_after_callback( assert len(events) == 1 assert events[0].content.parts[0].text == 'agent run is bypassed.' spy_after.assert_not_called() + + +@pytest.mark.parametrize('phase', ['before', 'after']) +@pytest.mark.parametrize('return_content', [False, True]) +async def test_agent_callback_preserves_widgets_without_skipping_execution( + phase: str, return_content: bool +) -> None: + """Callback actions survive, and only before content bypasses the agent.""" + widget = UiWidget(id='result', provider='mcp') + + def callback(callback_context: CallbackContext) -> types.Content | None: + callback_context.actions.render_ui_widgets = [widget] + if return_content: + return types.Content(parts=[types.Part(text='callback')]) + return None + + agent = _TestingAgent( + name='worker', + before_agent_callback=callback if phase == 'before' else None, + after_agent_callback=callback if phase == 'after' else None, + ) + ctx = await _create_parent_invocation_context('widgets', agent, branch='root') + + events = [event async for event in agent.run_async(ctx)] + + callback_events = [e for e in events if e.actions.render_ui_widgets] + assert len(callback_events) == 1 + assert callback_events[0].actions.render_ui_widgets == [widget] + assert callback_events[0].branch == 'root' + assert callback_events[0].invocation_id == ctx.invocation_id + assert callback_events[0].author == agent.name + assert bool(callback_events[0].content) == return_content + replies = [ + e + for e in events + if e.content + and e.content.parts + and e.content.parts[0].text == 'Hello, world!' + ] + assert len(replies) == (0 if phase == 'before' and return_content else 1) diff --git a/tests/unittests/agents/test_loop_agent.py b/tests/unittests/agents/test_loop_agent.py index 29cfc542d1c..a8d7d604098 100644 --- a/tests/unittests/agents/test_loop_agent.py +++ b/tests/unittests/agents/test_loop_agent.py @@ -18,12 +18,15 @@ from unittest.mock import patch from google.adk.agents.base_agent import BaseAgent +from google.adk.agents.callback_context import CallbackContext from google.adk.agents.invocation_context import InvocationContext from google.adk.agents.loop_agent import LoopAgent from google.adk.agents.loop_agent import LoopAgentState from google.adk.apps import ResumabilityConfig from google.adk.events.event import Event from google.adk.events.event_actions import EventActions +from google.adk.plugins.base_plugin import BasePlugin +from google.adk.plugins.plugin_manager import PluginManager from google.adk.sessions.in_memory_session_service import InMemorySessionService from google.genai import types import pytest @@ -364,3 +367,68 @@ async def test_non_resumable_loop_agent_stops_immediately_on_pause_event( assert testing_utils.simplify_resumable_app_events(events) == [ (agent_1.name, f'Hello, async {agent_1.name}!'), ] + + +@pytest.mark.parametrize('source', ['single', 'list', 'plugin', 'noop']) +@pytest.mark.parametrize('return_content', [False, True]) +async def test_after_agent_callback_escalation_stops_loop( + source: str, return_content: bool +) -> None: + """Action-only escalation stops the loop through callbacks and plugins.""" + callback_calls = [] + + def stop(callback_context: CallbackContext) -> types.Content | None: + callback_calls.append('stop') + if source != 'noop': + callback_context.actions.escalate = True + if return_content: + return types.Content(parts=[types.Part(text='done')]) + return None + + def noop(callback_context: CallbackContext) -> None: + callback_calls.append('noop') + + class StopPlugin(BasePlugin): + + async def after_agent_callback( + self, *, agent: BaseAgent, callback_context: CallbackContext + ) -> types.Content | None: + if agent.name == 'worker': + return stop(callback_context) + return None + + child = _TestingAgent( + name='worker', + after_agent_callback=( + [noop, stop] + if source == 'list' + else None + if source == 'plugin' + else stop + ), + ) + loop = LoopAgent(name='loop', sub_agents=[child], max_iterations=3) + ctx = await _create_parent_invocation_context('callback_escalation', loop) + if source == 'plugin': + ctx.plugin_manager = PluginManager(plugins=[StopPlugin(name='stop')]) + + events = [event async for event in loop.run_async(ctx)] + + expected_runs = 3 if source == 'noop' else 1 + replies = [ + e + for e in events + if e.content + and e.content.parts + and e.content.parts[0].text == 'Hello, async worker!' + ] + assert len(replies) == expected_runs + escalations = [e for e in events if e.actions.escalate] + assert len(escalations) == (0 if source == 'noop' else 1) + assert len(events) == expected_runs * ( + 2 if return_content or source != 'noop' else 1 + ) + assert callback_calls == ( + ['noop', 'stop'] if source == 'list' else ['stop'] * expected_runs + ) + assert not ctx.end_invocation