@@ -337,6 +337,8 @@ def _find_agent_to_run(
337
337
"""Finds the agent to run to continue the session.
338
338
339
339
A qualified agent must be either of:
340
+ - The agent that returned a function call and the last user message is a
341
+ function response to this function call.
340
342
- The root agent;
341
343
- An LlmAgent who replied last and is capable to transfer to any other agent
342
344
in the agent hierarchy.
@@ -348,6 +350,15 @@ def _find_agent_to_run(
348
350
Returns:
349
351
The agent of the last message in the session or the root agent.
350
352
"""
353
+ # If the last event is a function response, should send this response to
354
+ # the agent that returned the corressponding function call regardless the
355
+ # type of the agent. e.g. a remote a2a agent may surface a credential
356
+ # request as a special long running function tool call.
357
+ event = _find_function_call_event_if_last_event_is_function_response (
358
+ session
359
+ )
360
+ if event and event .author :
361
+ return root_agent .find_agent (event .author )
351
362
for event in filter (lambda e : e .author != 'user' , reversed (session .events )):
352
363
if event .author == root_agent .name :
353
364
# Found root agent.
@@ -527,3 +538,35 @@ def __init__(self, agent: BaseAgent, *, app_name: str = 'InMemoryRunner'):
527
538
session_service = self ._in_memory_session_service ,
528
539
memory_service = InMemoryMemoryService (),
529
540
)
541
+
542
+
543
+ def _find_function_call_event_if_last_event_is_function_response (
544
+ session : Session ,
545
+ ) -> Optional [Event ]:
546
+ events = session .events
547
+ if not events :
548
+ return None
549
+
550
+ last_event = events [- 1 ]
551
+ if (
552
+ last_event .content
553
+ and last_event .content .parts
554
+ and any (part .function_response for part in last_event .content .parts )
555
+ ):
556
+
557
+ function_call_id = next (
558
+ part .function_response .id
559
+ for part in last_event .content .parts
560
+ if part .function_response
561
+ )
562
+ for i in range (len (events ) - 2 , - 1 , - 1 ):
563
+ event = events [i ]
564
+ # looking for the system long running request euc function call
565
+ function_calls = event .get_function_calls ()
566
+ if not function_calls :
567
+ continue
568
+
569
+ for function_call in function_calls :
570
+ if function_call .id == function_call_id :
571
+ return event
572
+ return None
0 commit comments