gadk_engine/agents/
sequential_agent.rs1use std::any::Any;
19use std::collections::HashSet;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use futures::StreamExt;
24use gadk_agent::{
25 Agent, AgentConfig, AgentError, AgentState, AgentType, Context, ContextDelta, EventStream,
26 InvocationContext, LiveAgent, LiveRequest, LiveSession, Tool, ToolError,
27};
28use schemars::JsonSchema;
29use serde::{Deserialize, Serialize};
30
31use crate::agents::graph_resume::graph_resume_indexes;
32use crate::llm::state::reveal;
33use crate::runner::wrap;
34use crate::tool::{FunctionTool, FunctionToolConfig};
35
36#[derive(Clone, Default)]
38pub struct SequentialAgentConfig {
39 pub agent: AgentConfig,
41}
42
43pub fn new(cfg: SequentialAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
46 if cfg.agent.run.is_some() {
47 return Err(AgentError::Config(
48 "SequentialAgent doesn't allow custom Run implementations".into(),
49 ));
50 }
51 let mut agent_cfg = cfg.agent.clone();
52 agent_cfg.run = Some(Arc::new(run));
53 gadk_agent::new_with_state(
54 agent_cfg,
55 AgentState {
56 agent_type: AgentType::SequentialAgent,
57 config: Some(Arc::new(cfg)),
58 on_before_agent_callback_event: None,
59 live: Some(Arc::new(SequentialLive)),
61 },
62 )
63 .map_err(|e| AgentError::Config(format!("failed to create base agent: {e}")))
64}
65
66fn run(ctx: InvocationContext) -> EventStream {
68 Box::pin(async_stream::stream! {
69 let mut subs: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
70 if let Some(&first) = graph_resume_indexes(&ctx).as_ref().and_then(|ix| ix.first()) {
73 subs.drain(..first);
74 }
75 for sub in subs {
76 let mut s = sub.run(ctx.clone());
77 while let Some(item) = s.next().await {
78 let failed = item.is_err();
81 yield item;
82 if failed {
83 return;
84 }
85 }
86 }
87 })
88}
89
90const TASK_COMPLETED_NAME: &str = "task_completed";
92const TASK_COMPLETED_DESCRIPTION: &str =
94 "Signals that the agent has successfully completed the user's question or task.";
95pub(crate) const TASK_COMPLETED_INSTRUCTION_SUFFIX: &str = "\nIf you finished the user's request according to its description, call the task_completed function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.";
97
98#[derive(Deserialize, JsonSchema)]
101struct TaskCompletedArgs {}
102
103#[derive(Serialize, JsonSchema)]
105struct TaskCompletedResults {
106 result: String,
107}
108
109fn task_completed_tool() -> Result<Arc<dyn Tool>, ToolError> {
112 FunctionTool::new(
113 FunctionToolConfig::new(TASK_COMPLETED_NAME, TASK_COMPLETED_DESCRIPTION),
114 |_ctx: Context, _args: TaskCompletedArgs| async move {
115 Ok::<_, ToolError>(TaskCompletedResults {
116 result: "Task completion signaled.".into(),
117 })
118 },
119 )
120}
121
122fn inject_sub_agents(
127 agents: &[Arc<dyn Agent>],
128 tool: &Arc<dyn Tool>,
129 visited: &mut HashSet<usize>,
130) {
131 for sub in agents {
132 if !visited.insert(Arc::as_ptr(sub).cast::<()>() as usize) {
133 continue;
134 }
135 if let Some(state) = reveal(&**sub) {
136 state.live_injection.do_once(|| {
139 let has_completion_tool = state
140 .tools
141 .read()
142 .iter()
143 .any(|t| t.name() == TASK_COMPLETED_NAME);
144 if has_completion_tool {
145 return;
146 }
147 state.tools.write().push(Arc::clone(tool));
148 state
149 .instruction_suffix
150 .write()
151 .push_str(TASK_COMPLETED_INSTRUCTION_SUFFIX);
152 });
153 } else if sub.as_live().is_some() && !sub.sub_agents().is_empty() {
154 inject_sub_agents(sub.sub_agents(), tool, visited);
155 }
156 }
157}
158
159#[derive(Default)]
166pub(crate) struct SequentialLiveSession {
167 state: parking_lot::Mutex<(Option<Arc<dyn LiveSession>>, bool)>,
169}
170
171impl SequentialLiveSession {
172 fn set_active(&self, sess: Arc<dyn LiveSession>) {
174 self.state.lock().0 = Some(sess);
175 }
176}
177
178#[async_trait]
179impl LiveSession for SequentialLiveSession {
180 async fn send(&self, req: LiveRequest) -> Result<(), AgentError> {
183 let active = {
184 let g = self.state.lock();
185 if g.1 {
186 return Err(AgentError::other("session is closed"));
187 }
188 match &g.0 {
189 Some(s) => Arc::clone(s),
190 None => return Err(AgentError::other("no active sub-agent live session")),
191 }
192 };
193 active.send(req).await
194 }
195
196 async fn close(&self) -> Result<(), AgentError> {
198 let active = {
199 let mut g = self.state.lock();
200 g.1 = true;
201 g.0.clone()
202 };
203 match active {
204 Some(s) => s.close().await,
205 None => Ok(()),
206 }
207 }
208
209 fn as_any(&self) -> &dyn Any {
210 self
211 }
212}
213
214struct CloseOnDrop(Option<Arc<dyn LiveSession>>);
217
218impl CloseOnDrop {
219 async fn close(mut self) {
220 if let Some(s) = self.0.take()
221 && let Err(e) = s.close().await
222 {
223 tracing::warn!("error closing sub-session: {e}");
224 }
225 }
226}
227
228impl Drop for CloseOnDrop {
229 fn drop(&mut self) {
230 let Some(s) = self.0.take() else {
231 return;
232 };
233 if let Ok(h) = tokio::runtime::Handle::try_current() {
234 h.spawn(async move {
235 if let Err(e) = s.close().await {
236 tracing::warn!("error closing sub-session: {e}");
237 }
238 });
239 }
240 }
241}
242
243pub(crate) struct SequentialLive;
246
247#[async_trait]
248impl LiveAgent for SequentialLive {
249 async fn run_live(
263 &self,
264 ctx: InvocationContext,
265 ) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
266 let sub_agents: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
267 if sub_agents.is_empty() {
268 return Err(AgentError::other("sequential agent has no sub-agents"));
269 }
270 let tool =
271 task_completed_tool().map_err(|e| wrap("failed to create task_completed tool", e))?;
272 inject_sub_agents(&sub_agents, &tool, &mut HashSet::new());
273
274 let seq_sess = Arc::new(SequentialLiveSession::default());
275 let stream = sequential_live_stream(ctx, sub_agents, Arc::clone(&seq_sess));
276 Ok((seq_sess, stream))
277 }
278}
279
280fn sequential_live_stream(
283 ctx: InvocationContext,
284 sub_agents: Vec<Arc<dyn Agent>>,
285 seq_sess: Arc<SequentialLiveSession>,
286) -> EventStream {
287 Box::pin(async_stream::stream! {
288 for sub in sub_agents {
289 let Some(live) = sub.as_live() else {
290 yield Err(AgentError::other(format!(
291 "sub-agent {} does not support Live Run",
292 sub.name()
293 )));
294 return;
295 };
296 let sub_ctx = ctx.with_delta(ContextDelta {
297 agent: Some(Arc::clone(&sub)),
298 ..Default::default()
299 });
300 let (sub_sess, mut inner) = match live.run_live(sub_ctx).await {
301 Ok(v) => v,
302 Err(e) => {
303 yield Err(wrap(format!("sub-agent {} live run failed", sub.name()), e));
304 return;
305 }
306 };
307 seq_sess.set_active(Arc::clone(&sub_sess));
308 let guard = CloseOnDrop(Some(sub_sess));
310 while let Some(item) = inner.next().await {
311 let failed = item.is_err();
314 yield item;
315 if failed {
316 guard.close().await;
317 return;
318 }
319 }
320 guard.close().await;
321 }
322 })
323}