Skip to content

Commit 86a47f6

Browse files
DeanChensjcopybara-github
authored andcommitted
fix(agents): route user FunctionResponses to sub-agents when is_resumable is False
Previously, find_agent_to_run gated function-response routing on resumability_config.is_resumable, and Runner.run_async called _find_agent_to_run before appending the incoming user message to session.events. As a result, when a non-transferable sub-agent paused on a long-running tool or HITL confirmation in a non-resumable app, the user's FunctionResponse on the next turn was routed to the root agent instead of back to the sub-agent that authored the FunctionCall. User-authored FunctionResponses (author == 'user', such as LRO results or HITL confirmation replies supplied in a new turn) always need to route back to the agent that issued the FunctionCall, even when resumability is disabled. By contrast, agent-authored FunctionResponses from a completed turn (such as skip_summarization=True) should only resume when is_resumable is True. Also add _session_for_routing in Runner.run_async so that an incoming new_message containing a FunctionResponse is visible to _find_agent_to_run without allowing a plain user message to mask a prior agent-authored FunctionResponse during resumable routing. Co-authored-by: Shangjie Chen <[email protected]> PiperOrigin-RevId: 993038002
1 parent 51dbf89 commit 86a47f6

4 files changed

Lines changed: 213 additions & 12 deletions

File tree

‎src/google/adk/agents/_agent_router.py‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,10 @@ def find_agent_to_run(
123123
else None
124124
)
125125
is_resumable = resumability_config and resumability_config.is_resumable
126-
# Only route based on a past function response if resumability is enabled.
127-
# In non-resumable scenarios, a turn ending with function call response
128-
# shouldn't trap the next turn on that same agent if it's not transferable.
129-
# Falling through allows it to return to root.
130-
if event and event.author and is_resumable:
126+
is_user_function_response = (
127+
event is not None and filtered_events[-1].author == "user"
128+
)
129+
if event and event.author and (is_resumable or is_user_function_response):
131130
# `find_agent` returns None when the author does not correspond to any
132131
# agent in the current hierarchy (e.g. the author is "user" or a stale or
133132
# foreign agent name carried over from a previous turn/session). Returning

‎src/google/adk/runners.py‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,27 @@ def _get_function_responses_from_content(
170170
]
171171

172172

173+
def _session_for_routing(
174+
session: Session, new_message: types.Content | None
175+
) -> Session:
176+
"""Includes a user FunctionResponse for routing before `new_message` is saved.
177+
178+
`_find_agent_to_run` runs before `new_message` is appended to
179+
`session.events`, so a user FunctionResponse must be attached here to route
180+
back to the agent that issued the FunctionCall.
181+
"""
182+
if not _get_function_responses_from_content(new_message):
183+
return session
184+
return session.model_copy(
185+
update={
186+
'events': [
187+
*session.events,
188+
Event(author='user', content=new_message),
189+
]
190+
}
191+
)
192+
193+
173194
def _apply_run_config_custom_metadata(
174195
event: Event, run_config: RunConfig | None
175196
) -> None:
@@ -1212,7 +1233,9 @@ async def run_async(
12121233
if has_task_subagent:
12131234
agent_to_run = self.agent
12141235
else:
1215-
agent_to_run = self._find_agent_to_run(session, self.agent)
1236+
agent_to_run = self._find_agent_to_run(
1237+
_session_for_routing(session, new_message), self.agent
1238+
)
12161239
else:
12171240
agent_to_run = self.agent
12181241

‎tests/unittests/agents/test_agent_router.py‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -241,8 +241,8 @@ def test_find_agent_to_run_with_function_response_scenario():
241241
)
242242

243243

244-
def test_find_agent_to_run_skips_function_response_when_not_resumable():
245-
"""Function response routing is skipped when session is not resumable."""
244+
def test_find_agent_to_run_skips_agent_function_response_when_not_resumable():
245+
"""Agent function response does not trap next turn when not resumable."""
246246
root, _, _, _ = _make_agent_tree()
247247
call_event = Event(
248248
invocation_id="inv1",
@@ -258,6 +258,50 @@ def test_find_agent_to_run_skips_function_response_when_not_resumable():
258258
],
259259
),
260260
)
261+
response_event = Event(
262+
invocation_id="inv1",
263+
author="non_transferable",
264+
content=types.Content(
265+
role="user",
266+
parts=[
267+
types.Part(
268+
function_response=types.FunctionResponse(
269+
id="func_456", name="test_func", response={}
270+
)
271+
)
272+
],
273+
),
274+
)
275+
session = Session(
276+
id="s1",
277+
app_name="app",
278+
user_id="u1",
279+
events=[call_event, response_event],
280+
)
281+
resumability_config = ResumabilityConfig(is_resumable=False)
282+
283+
agent = _agent_router.find_agent_to_run(session, root, resumability_config)
284+
285+
assert agent == root
286+
287+
288+
def test_find_agent_to_run_routes_user_function_response_when_not_resumable():
289+
"""User function response routes to sub-agent even when not resumable."""
290+
root, _, _, non_transferable = _make_agent_tree()
291+
call_event = Event(
292+
invocation_id="inv1",
293+
author="non_transferable",
294+
content=types.Content(
295+
role="model",
296+
parts=[
297+
types.Part(
298+
function_call=types.FunctionCall(
299+
id="func_456", name="test_func", args={}
300+
)
301+
)
302+
],
303+
),
304+
)
261305
response_event = Event(
262306
invocation_id="inv2",
263307
author="user",
@@ -280,10 +324,9 @@ def test_find_agent_to_run_skips_function_response_when_not_resumable():
280324
)
281325
resumability_config = ResumabilityConfig(is_resumable=False)
282326

283-
assert (
284-
_agent_router.find_agent_to_run(session, root, resumability_config)
285-
== root
286-
)
327+
agent = _agent_router.find_agent_to_run(session, root, resumability_config)
328+
329+
assert agent == non_transferable
287330

288331

289332
def test_find_agent_to_run_function_response_takes_precedence():

‎tests/unittests/test_runners.py‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
from google.adk.sessions.session import Session
5656
from google.adk.tools.agent_tool import AgentTool
5757
from google.adk.tools.base_toolset import BaseToolset
58+
from google.adk.tools.long_running_tool import LongRunningFunctionTool
5859
from google.adk.workflow import BaseNode
5960
from google.adk.workflow import START
6061
from google.adk.workflow._workflow import Workflow
@@ -5691,5 +5692,140 @@ async def _counted_tool() -> dict[str, str]:
56915692
assert responses == [{"error": "Invocation was aborted by client."}]
56925693

56935694

5695+
async def test_run_async_routes_user_function_response_to_subagent_when_not_resumable():
5696+
"""User FunctionResponse routes to sub-agent without resumability."""
5697+
5698+
def _pending_lro() -> None:
5699+
"""Starts a long-running operation."""
5700+
return None
5701+
5702+
sub_agent = LlmAgent(
5703+
name="sub_agent",
5704+
disallow_transfer_to_parent=True,
5705+
disallow_transfer_to_peers=True,
5706+
model=testing_utils.MockModel.create(
5707+
responses=[
5708+
types.Part.from_function_call(name="_pending_lro", args={}),
5709+
"Subagent finished LRO",
5710+
]
5711+
),
5712+
tools=[LongRunningFunctionTool(func=_pending_lro)],
5713+
)
5714+
root_agent = LlmAgent(
5715+
name="root_agent",
5716+
model=testing_utils.MockModel.create(
5717+
responses=[
5718+
types.Part.from_function_call(
5719+
name="transfer_to_agent", args={"agent_name": "sub_agent"}
5720+
),
5721+
"Root handled next turn",
5722+
]
5723+
),
5724+
sub_agents=[sub_agent],
5725+
)
5726+
runner = testing_utils.InMemoryRunner(root_agent)
5727+
5728+
# Turn 1: Root transfers to sub_agent, which emits LRO FunctionCall.
5729+
turn1_events = await runner.run_async("Start LRO")
5730+
lro_calls = [
5731+
fc
5732+
for e in turn1_events
5733+
if e.author == "sub_agent"
5734+
for fc in e.get_function_calls()
5735+
if fc.name == "_pending_lro"
5736+
]
5737+
assert len(lro_calls) == 1
5738+
lro_fc = lro_calls[0]
5739+
5740+
# Turn 2: User supplies FunctionResponse for the LRO without resumability.
5741+
fr_part = types.Part.from_function_response(
5742+
name="_pending_lro", response={"status": "completed"}
5743+
)
5744+
fr_part.function_response.id = lro_fc.id
5745+
turn2_events = await runner.run_async(types.UserContent(parts=[fr_part]))
5746+
assert [e.author for e in turn2_events] == ["sub_agent"]
5747+
assert _texts([e.content for e in turn2_events]) == ["Subagent finished LRO"]
5748+
5749+
# Turn 3: Plain text message returns to root_agent since sub_agent is non-transferable.
5750+
turn3_events = await runner.run_async("Next turn")
5751+
assert [e.author for e in turn3_events] == ["root_agent"]
5752+
assert _texts([e.content for e in turn3_events]) == ["Root handled next turn"]
5753+
5754+
5755+
async def test_run_async_does_not_hide_prior_agent_function_response_when_resumable():
5756+
"""Plain user message does not hide prior agent FunctionResponse."""
5757+
sub_agent = LlmAgent(
5758+
name="sub_agent",
5759+
disallow_transfer_to_parent=True,
5760+
disallow_transfer_to_peers=True,
5761+
model=testing_utils.MockModel.create(
5762+
responses=["Subagent resumed after agent FR"]
5763+
),
5764+
)
5765+
root_agent = LlmAgent(
5766+
name="root_agent",
5767+
model=testing_utils.MockModel.create(responses=["Root response"]),
5768+
sub_agents=[sub_agent],
5769+
)
5770+
app = App(
5771+
name=TEST_APP_ID,
5772+
root_agent=root_agent,
5773+
resumability_config=ResumabilityConfig(is_resumable=True),
5774+
)
5775+
session_service = InMemorySessionService()
5776+
runner = Runner(app=app, session_service=session_service)
5777+
session = await session_service.create_session(
5778+
app_name=TEST_APP_ID, user_id=TEST_USER_ID, session_id=TEST_SESSION_ID
5779+
)
5780+
await session_service.append_event(
5781+
session,
5782+
Event(
5783+
invocation_id="inv_1",
5784+
author="sub_agent",
5785+
content=types.Content(
5786+
role="model",
5787+
parts=[
5788+
types.Part(
5789+
function_call=types.FunctionCall(
5790+
id="fc_1", name="tool_fn", args={}
5791+
)
5792+
)
5793+
],
5794+
),
5795+
),
5796+
)
5797+
await session_service.append_event(
5798+
session,
5799+
Event(
5800+
invocation_id="inv_1",
5801+
author="sub_agent",
5802+
content=types.Content(
5803+
role="user",
5804+
parts=[
5805+
types.Part(
5806+
function_response=types.FunctionResponse(
5807+
id="fc_1", name="tool_fn", response={"ok": True}
5808+
)
5809+
)
5810+
],
5811+
),
5812+
),
5813+
)
5814+
5815+
events = [
5816+
e
5817+
async for e in runner.run_async(
5818+
user_id=TEST_USER_ID,
5819+
session_id=TEST_SESSION_ID,
5820+
new_message=types.UserContent(parts=[types.Part(text="Continue")]),
5821+
)
5822+
]
5823+
5824+
assert {e.author for e in events} == {"sub_agent"}
5825+
assert _texts([e.content for e in events]) == [
5826+
"Subagent resumed after agent FR"
5827+
]
5828+
5829+
56945830
if __name__ == "__main__":
56955831
pytest.main([__file__])

0 commit comments

Comments
 (0)