Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions src/google/adk/agents/base_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions src/google/adk/agents/loop_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
258 changes: 258 additions & 0 deletions tests/unittests/agents/test_agent_callback_events.py
Original file line number Diff line number Diff line change
@@ -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
41 changes: 41 additions & 0 deletions tests/unittests/agents/test_base_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Loading