Skip to content
Closed
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
93 changes: 90 additions & 3 deletions src/google/adk/workflow/_llm_agent_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from ..agents.llm.task._finish_task_tool import FINISH_TASK_SUCCESS_RESULT
from ..agents.llm.task._finish_task_tool import FINISH_TASK_TOOL_NAME as _FINISH_TASK_FC_NAME
from ..events.event import Event
from ..flows.llm_flows.functions import REQUEST_CONFIRMATION_FUNCTION_CALL_NAME
from ..utils._schema_utils import validate_schema
from ..utils.content_utils import to_user_content

Expand Down Expand Up @@ -77,6 +78,81 @@ def _extract_task_delegation_fcs(
]


def _event_has_eager_tool_calls(
event: Event, tools_dict: Mapping[str, ToolUnion]
) -> bool:
"""True if this event has FCs that produce FR events in the current step.

Task-delegation tools (``_TaskAgentTool``) and other deferred / long-running
tools do not emit an FR from ``handle_function_calls_async``; the chat
wrapper synthesizes task FRs itself. Regular tools (including long-running or
deferred tools that return a value) do emit FRs in the same LLM step, after
the model FC event. The wrapper must drain those FR events before closing the
generator, or they are lost and the session history becomes unbalanced for
Gemini.

Args:
event: The event containing function calls.
tools_dict: Map of tool names to Tool objects.

Returns:
True if the event has eager tool calls.
"""
from ..tools.agent_tool import _TaskAgentTool # pylint: disable=g-import-not-at-top

for fc in event.get_function_calls():
if not fc.name:
continue
tool = tools_dict.get(fc.name)
if tool is None or isinstance(tool, _TaskAgentTool):
continue
return True
return False


async def _drain_pending_tool_response_events(
run_iter: AsyncGenerator[Event, None],
) -> AsyncGenerator[Event, None]:
"""Yield remaining non-model events from the current LLM step.

After a mixed model turn (regular tools + task delegation), the LLM flow
still has pending function-response events. Closing the generator before
reading them drops regular-tool FRs.

Stops after the first event that carries function responses, or before the
next model-role event (which would start another LLM round without
synthesized task FRs).

Args:
run_iter: The generator to drain events from.

Yields:
Events from the current LLM step.
"""
async for pending_event in run_iter:
if (
pending_event.content is not None
and pending_event.content.role == 'model'
):
# Tool confirmation events have role 'model' but they are part of the
# current step (asking for confirmation before executing the tool).
# We must yield them and continue draining the actual FR.
is_confirmation = any(
fc.name == REQUEST_CONFIRMATION_FUNCTION_CALL_NAME
for fc in pending_event.get_function_calls()
)
if is_confirmation:
yield pending_event
continue

# Next LLM round already started; abandon it by stopping iteration.
# Closing the outer generator cancels further work.
return
yield pending_event
if pending_event.get_function_responses():
return


def _find_unresolved_task_delegations(
session: Session,
owner: str,
Expand Down Expand Up @@ -392,10 +468,21 @@ async def run_llm_agent_as_node(
async for event in run_iter:
yield event
task_fcs = _extract_task_delegation_fcs(event, tools_dict)
for fc in task_fcs:
output = await _dispatch_task_fc(agent, fc, ctx)
yield _synthesize_task_fr_event(fc, output)
if task_fcs:
# Mixed turns (regular tool FC + task FC) still have pending
# regular-tool FR events in this generator. Drain them before
# breaking, otherwise aclosing drops them and the session is
# left with unbalanced FC/FR history that Gemini rejects.
if _event_has_eager_tool_calls(event, tools_dict):
async with aclosing(
_drain_pending_tool_response_events(run_iter)
) as drain_iter:
async for pending_event in drain_iter:
yield pending_event

for fc in task_fcs:
output = await _dispatch_task_fc(agent, fc, ctx)
yield _synthesize_task_fr_event(fc, output)
had_task_fc = True
break # close this run_iter; outer loop re-enters
if event.actions.transfer_to_agent:
Expand Down
Loading