Skip to main content

gadk_engine/agents/
loop_agent.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! A loop agent: runs its sub-agents in sequence repeatedly.
17
18use std::sync::Arc;
19
20use futures::StreamExt;
21use gadk_agent::{
22    Agent, AgentConfig, AgentError, AgentState, AgentType, EventStream, InvocationContext,
23};
24
25use crate::agents::graph_resume::graph_resume_indexes;
26
27/// The configuration of a loop agent.
28#[derive(Clone, Default)]
29pub struct LoopAgentConfig {
30    /// Basic agent setup; `run` must be `None`.
31    pub agent: AgentConfig,
32    /// With 0 the loop runs indefinitely or until a sub-agent escalates. A sub-agent error ends
33    /// the loop regardless. The context is checked before each pass, and if it is cancelled the
34    /// loop ends with the context's error. A loop agent with no sub-agents returns immediately
35    /// without yielding any event or error.
36    pub max_iterations: u32,
37}
38
39/// An agent that runs its sub-agents in sequence repeatedly, for `max_iterations` passes or until
40/// a sub-agent escalates. Use it for repetition or iterative refinement, such as revising code.
41pub fn new(cfg: LoopAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
42    if cfg.agent.run.is_some() {
43        return Err(AgentError::Config(
44            "LoopAgent doesn't allow custom Run implementations".into(),
45        ));
46    }
47    let max = cfg.max_iterations;
48    let mut agent_cfg = cfg.agent.clone();
49    agent_cfg.run = Some(Arc::new(move |ctx: InvocationContext| run(ctx, max)));
50    gadk_agent::new_with_state(
51        agent_cfg,
52        AgentState {
53            agent_type: AgentType::LoopAgent,
54            config: Some(Arc::new(cfg)),
55            on_before_agent_callback_event: None,
56            live: None,
57        },
58    )
59    .map_err(|e| AgentError::Config(format!("failed to create base agent: {e}")))
60}
61
62/// Runs the passes of the loop agent.
63fn run(ctx: InvocationContext, max_iterations: u32) -> EventStream {
64    Box::pin(async_stream::stream! {
65        let subs: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
66        // Without sub-agents there is nothing to run, escalate or fail: return at once in both
67        // the bounded and unbounded case, as adk-python does.
68        if subs.is_empty() {
69            return;
70        }
71        // Only the first pass narrows to the sub-agent holding the lowest-indexed caller; later
72        // passes run every sub-agent under a context marked done, so nothing beneath narrows
73        // again.
74        let mut pass_subs: &[Arc<dyn Agent>] = &subs;
75        if let Some(&first) = graph_resume_indexes(&ctx).as_ref().and_then(|ix| ix.first()) {
76            pass_subs = &subs[first..];
77        }
78        let mut pass_ctx = ctx.clone();
79        let mut count = max_iterations;
80        loop {
81            // A pass can yield no events (for example when every sub-agent is empty), so the
82            // consumer never gets a chance to stop the loop: stop on cancellation here.
83            if ctx.cancellation_token().is_cancelled() {
84                yield Err(AgentError::Cancelled);
85                return;
86            }
87            // An all-empty pass awaits nothing pending; give the runtime a turn so a cancellation
88            // can land.
89            tokio::task::yield_now().await;
90            let mut should_exit = false;
91            for sub in pass_subs {
92                let mut s = sub.run(pass_ctx.clone());
93                while let Some(item) = s.next().await {
94                    match item {
95                        // A failed sub-agent ends the loop, as in adk-python: retrying it would
96                        // repeat the same failure, forever without max_iterations.
97                        Err(e) => {
98                            yield Err(e);
99                            return;
100                        }
101                        Ok(ev) => {
102                            let escalate = ev.actions.escalate;
103                            yield Ok(ev);
104                            if escalate {
105                                should_exit = true;
106                            }
107                        }
108                    }
109                }
110                // Escalation ends the loop once the escalating sub-agent has finished.
111                if should_exit {
112                    return;
113                }
114            }
115            pass_subs = &subs;
116            pass_ctx = ctx.with_graph_resume_done();
117            if count > 0 {
118                count -= 1;
119                if count == 0 {
120                    return;
121                }
122            }
123        }
124    })
125}