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
13 changes: 13 additions & 0 deletions src/google/adk/agents/invocation_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from ..events._branch_path import _BranchPath
from ..events._internal_metadata import without_internal_metadata
from ..events._interrupts import extract_event_interrupt_ids
from ..events._interrupts import index_open_interrupts
from ..events._node_path_builder import NodePathBuilder
from ..events.event import Event
from ..live import _active_background_tool
Expand Down Expand Up @@ -829,6 +830,18 @@ def should_pause_invocation(self, event: Event) -> bool:

return False

def _has_open_interrupts(self) -> bool:
"""Returns whether a call of this invocation still awaits its answer.

A resumed agent whose long-running call is still unanswered ends its run
without yielding the call again, so its parent sees no pausing event. The
parent checks this before moving on, so that answering one of several
long-running calls does not end the invocation with the rest unanswered.
"""
return bool(
index_open_interrupts(self._get_events(current_invocation=True))
)


def new_invocation_context_id() -> str:
return "e-" + platform_uuid.new_uuid()
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 @@ -123,6 +123,11 @@ async def _run_async_impl(
if ctx.should_pause_invocation(event):
pause_invocation = True

# A resumed sub-agent still waiting on a long-running call yields no
# pausing event, so check for unanswered calls before moving on.
if ctx.is_resumable and ctx._has_open_interrupts():
pause_invocation = True

if should_exit or pause_invocation:
break # break inner for loop

Expand Down
5 changes: 5 additions & 0 deletions src/google/adk/agents/sequential_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ async def _run_async_impl(
if ctx.should_pause_invocation(event):
pause_invocation = True

# A resumed sub-agent still waiting on a long-running call yields no
# pausing event, so check for unanswered calls before moving on.
if ctx.is_resumable and ctx._has_open_interrupts():
pause_invocation = True

# Skip the rest of the sub-agents if the invocation is paused.
if pause_invocation:
return
Expand Down
138 changes: 138 additions & 0 deletions tests/unittests/runners/test_resume_invocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
from google.adk.agents.base_agent import BaseAgent
from google.adk.agents.invocation_context import InvocationContext
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
Expand Down Expand Up @@ -494,3 +496,139 @@ async def _run_async_impl(
assert not await runner.run_async(
invocation_id=invocation_events[0].invocation_id
)


def _long_running_calls(events: list[Event]) -> list[types.FunctionCall]:
return [
fc
for event in events
for fc in event.get_function_calls()
if fc.name == "test_tool"
]


def _answer(function_call: types.FunctionCall) -> types.Content:
return testing_utils.UserContent(
Part(
function_response=FunctionResponse(
id=function_call.id,
name=function_call.name,
response={"result": "approved"},
)
)
)


def _texts(events: list[Event]) -> list[tuple[str, str]]:
return [
(event.author, part.text)
for event in events
if event.content
for part in event.content.parts or []
if part.text
]


@pytest.mark.parametrize("workflow_agent_cls", [SequentialAgent, LoopAgent])
@pytest.mark.asyncio
async def test_answering_one_of_two_long_running_calls_keeps_workflow_paused(
workflow_agent_cls,
):
"""A sub-agent still waiting on a call keeps its workflow paused."""
first_agent = LlmAgent(
name="first_agent",
model=testing_utils.MockModel.create(
responses=[
[
Part.from_function_call(name="test_tool", args={}),
Part.from_function_call(name="test_tool", args={}),
],
"first agent done",
]
),
tools=[LongRunningFunctionTool(func=test_tool)],
)
next_agent = LlmAgent(
name="next_agent",
model=testing_utils.MockModel.create(responses=["next agent done"]),
)
kwargs = {"max_iterations": 1} if workflow_agent_cls is LoopAgent else {}
runner = testing_utils.InMemoryRunner(
app=App(
name="test_app",
root_agent=workflow_agent_cls(
name="root_agent",
sub_agents=[first_agent, next_agent],
**kwargs,
),
resumability_config=ResumabilityConfig(is_resumable=True),
)
)
first_call, second_call = _long_running_calls(
await runner.run_async("test user query")
)

# The second call is still unanswered, so nothing may run yet.
assert not await runner.run_async(new_message=_answer(first_call))

events = await runner.run_async(new_message=_answer(second_call))
assert _texts(events) == [
("first_agent", "first agent done"),
("next_agent", "next agent done"),
]
assert events[-1].author == "root_agent"
assert events[-1].actions.end_of_agent


@pytest.mark.asyncio
async def test_answering_one_parallel_branch_keeps_sequential_agent_paused():
"""The step after a ParallelAgent waits for every branch's answer."""

def branch(name: str) -> LlmAgent:
return LlmAgent(
name=name,
model=testing_utils.MockModel.create(
responses=[
Part.from_function_call(name="test_tool", args={}),
f"{name} done",
]
),
tools=[LongRunningFunctionTool(func=test_tool)],
)

next_agent = LlmAgent(
name="next_agent",
model=testing_utils.MockModel.create(responses=["next agent done"]),
)
runner = testing_utils.InMemoryRunner(
app=App(
name="test_app",
root_agent=SequentialAgent(
name="root_agent",
sub_agents=[
ParallelAgent(
name="parallel_agent",
sub_agents=[branch("branch_a"), branch("branch_b")],
),
next_agent,
],
),
resumability_config=ResumabilityConfig(is_resumable=True),
)
)
calls = {
event.author: fc
for event in await runner.run_async("test user query")
for fc in event.get_function_calls()
}

events = await runner.run_async(new_message=_answer(calls["branch_a"]))
assert _texts(events) == [("branch_a", "branch_a done")]

events = await runner.run_async(new_message=_answer(calls["branch_b"]))
assert _texts(events) == [
("branch_b", "branch_b done"),
("next_agent", "next agent done"),
]
assert events[-1].author == "root_agent"
assert events[-1].actions.end_of_agent