adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Deterministic Method to Exit a LoopAgent and Continue a Parent SequentialAgent

Open sanderbeirlaen opened this issue 1 year ago • 4 comments

** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.

Is your feature request related to a problem? Please describe. Yes. Currently, it's not possible to build a deterministic, multi-step pipeline using SequentialAgent that contains a LoopAgent which needs to exit early. This is a common and important use case for creating complex, reliable agent workflows.

I'm frustrated because the available agents present a logical conflict for this requirement:

The SequentialAgent provides a guaranteed execution order, which is perfect for a production pipeline.

However, the only way to exit a LoopAgent immediately is by using tool_context.actions.escalate = True.

This escalate signal propagates all the way to the root and halts the parent SequentialAgent, preventing any subsequent steps in the pipeline from running. This makes it impossible to have a step that runs after the loop completes.

Describe the solution you'd like The ideal solution would be a deterministic way for a LoopAgent to terminate itself and return control to its parent SequentialAgent, allowing the sequence to continue.

There could be two potential ways to implement this:

  1. A New Property on LoopAgent: A new configuration property on LoopAgent could change its behavior when it receives an escalate signal. This seems like the cleanest solution.

In the LoopAgent definition

refinement_loop = LoopAgent( name="RefinementLoop", sub_agents=[...], # New property: when this loop receives an escalate signal, # it stops itself but does not propagate the signal further up. halt_on_escalate=True )

  1. A Scoped escalate Action: Alternatively, a new parameter could be added to the escalate action to define its scope.

In a tool function

This would only escalate one level up (to the LoopAgent), stopping the loop

but not its parent SequentialAgent.

tool_context.actions.escalate(scope='local') # or level=1

Either of these would make the LoopAgent a predictable "black box" that can manage its own early exit without disrupting a guaranteed sequential pipeline.

Describe alternatives you've considered I have considered and tested two alternative architectures, but both have significant drawbacks:

Using an LlmAgent as an Orchestrator: This can solve the control flow problem, but it introduces non-determinism. For our production use case, relying on an LLM to follow procedural tool-calling instructions is a risk we need to avoid. We require a guaranteed execution path.

Using a State Flag: Setting a flag in the context (e.g., ctx.state["loop_is_done"] = True) avoids the escalate problem but keeps looping and doesn't exit even after the max iterations is reached.

I considered using a custom agent to make my own sequence agent and see how it behaves there but i've not tested this yet.

Additional context Here is a minimal, reproducible example that demonstrates the problem. The goal is for recipe_updater_agent to run after refinement_loop exits, but it is never reached.

from google.adk.agents import LlmAgent, LoopAgent, SequentialAgent, BaseAgent from google.adk.tools.tool_context import ToolContext

--- Tool to exit the loop ---

def exit_loop(tool_context: ToolContext): """Signals that the iterative process should end.""" # This signal stops the loop, but also the parent SequentialAgents. tool_context.actions.escalate = True return {}

--- Dummy Agents for Demonstration ---

initial_analyzer_agent = LlmAgent(name="InitialAnalyzerAgent", instruction="Step 1: Analyze.") critic_agent_in_loop = LlmAgent(name="CriticAgent", instruction="Step 2a: Critique.") exit_checker_agent = LlmAgent(name="ExitCheckerAgent", tools=[exit_loop], instruction="Step 2b: Call exit_loop tool.") refiner_agent = LlmAgent(name="RefinerAgent", instruction="Step 2c: Refine.") recipe_updater_agent = LlmAgent(name="RecipeUpdaterAgent", instruction="Step 3: Update.")

--- Agent Hierarchy ---

The loop that should exit early

refinement_loop = LoopAgent( name="RefinementLoop", sub_agents=[ critic_agent_in_loop, exit_checker_agent, refiner_agent, ], max_iterations=5 )

A sub-pipeline that contains the loop

recipe_analyzer = SequentialAgent( name="RecipeAnalyzer", sub_agents=[ initial_analyzer_agent, refinement_loop ] )

The root agent that should run all steps in order

root_agent = SequentialAgent( name="Proofreading_Pipeline", sub_agents=[ recipe_analyzer, # This final agent is never reached because the escalate signal # from the loop halts this parent SequentialAgent. recipe_updater_agent, ] )

sanderbeirlaen avatar Jun 13 '25 11:06 sanderbeirlaen

instead of adding a separate loop for exit, in the refiner agent you can specify the exit condition, and for exit it should call a tool i.e,:

def exit_loop(tool_context: ToolContext):
    """Call this function ONLY when condition for exit is successful and no further refinement is needed."""
    print(f"  [Tool Call] exit_loop triggered by {tool_context.agent_name}")
    tool_context.actions.escalate = True
    return {}

exit_loop_tool = FunctionTool(func=exit_loop)

and add this as a tool to the refinement agent, it worked for me, and further i have the loop inside of a sequential agent which continues after this exit condition is triggered and doesn't stops.

akshatshaw avatar Jun 13 '25 18:06 akshatshaw

Okay so i have a little bit off an update on this: First of all the seq agent actually does run the problem is that it cannot get the context anymore since it might be corrupted. the issue is with there open telemetry library which they use for tracing or something. So when the escalate function is called the context gets probably not well handled. I'm currently trying to do it with a custom loop instead.

sanderbeirlaen avatar Jun 16 '25 04:06 sanderbeirlaen

instead of adding a separate loop for exit, in the refiner agent you can specify the exit condition, and for exit it should call a tool i.e,:

def exit_loop(tool_context: ToolContext):
    """Call this function ONLY when condition for exit is successful and no further refinement is needed."""
    print(f"  [Tool Call] exit_loop triggered by {tool_context.agent_name}")
    tool_context.actions.escalate = True
    return {}

exit_loop_tool = FunctionTool(func=exit_loop)

and add this as a tool to the refinement agent, it worked for me, and further i have the loop inside of a sequential agent which continues after this exit condition is triggered and doesn't stops.

The problem with this approach is that you can't use an outputschema with tools, otherwise I would've done it like that to and a little correction on my part it doesn't actually stop and break the seq agent. It just corrupts the context, its a bug in there opentelemetry library that they are using

sanderbeirlaen avatar Jun 16 '25 04:06 sanderbeirlaen

Hi @sanderbeirlaen and thanks to everyone who participated in this thread.

We're currently doing some housekeeping on our issue tracker. Given the rapid pace of development and the number of updates since this was last active, there's a good chance this issue has been resolved in a newer version. To help us keep our backlog focused on current issues, we are closing this as stale.

If you're still facing this problem, could you please update to the very latest version of the library and confirm the issue still exists? If it does, please comment here, and we will be happy to reopen this issue and investigate further.

Thanks for your contribution and understanding!

surajksharma07 avatar Oct 08 '25 09:10 surajksharma07