1use crate::checkpoint::Checkpointer;
6use crate::deferred::DeferredNodeConfig;
7use crate::edge::{END, Edge, EdgeTarget, START};
8use crate::error::{GraphError, Result};
9use crate::graph::{CompiledGraph, StateGraph};
10use crate::node::{ExecutionConfig, FunctionNode, Node, NodeContext, NodeOutput};
11use crate::state::{State, StateSchema};
12use crate::stream::{StreamEvent, StreamMode};
13use crate::timeout::TimeoutPolicy;
14use adk_core::{
15 Agent, AgentCapabilities, AgentRelationshipKind, AgentTopology, AgentTopologyMember,
16 AgentTopologyRelationship, Content, Event, EventStream, InvocationContext,
17};
18use async_trait::async_trait;
19use serde_json::json;
20use std::collections::HashMap;
21use std::future::Future;
22use std::pin::Pin;
23use std::sync::Arc;
24
25pub type BeforeAgentCallback = Arc<
27 dyn Fn(Arc<dyn InvocationContext>) -> Pin<Box<dyn Future<Output = adk_core::Result<()>> + Send>>
28 + Send
29 + Sync,
30>;
31
32pub type AfterAgentCallback = Arc<
33 dyn Fn(
34 Arc<dyn InvocationContext>,
35 Event,
36 ) -> Pin<Box<dyn Future<Output = adk_core::Result<()>> + Send>>
37 + Send
38 + Sync,
39>;
40
41pub type InputMapper = Arc<dyn Fn(&dyn InvocationContext) -> State + Send + Sync>;
43
44pub type OutputMapper = Arc<dyn Fn(&State) -> Vec<Event> + Send + Sync>;
46
47pub struct GraphAgent {
49 name: String,
50 description: String,
51 graph: Arc<CompiledGraph>,
52 input_mapper: InputMapper,
54 output_mapper: OutputMapper,
56 before_callback: Option<BeforeAgentCallback>,
58 after_callback: Option<AfterAgentCallback>,
60}
61
62impl GraphAgent {
63 pub fn builder(name: &str) -> GraphAgentBuilder {
65 GraphAgentBuilder::new(name)
66 }
67
68 pub fn from_graph(name: &str, graph: CompiledGraph) -> Self {
70 Self {
71 name: name.to_string(),
72 description: String::new(),
73 graph: Arc::new(graph),
74 input_mapper: Arc::new(default_input_mapper),
75 output_mapper: Arc::new(default_output_mapper),
76 before_callback: None,
77 after_callback: None,
78 }
79 }
80
81 #[cfg(feature = "action")]
86 pub fn from_workflow_schema(
87 name: &str,
88 schema: &crate::workflow::WorkflowSchema,
89 ) -> Result<Self> {
90 schema.build_graph(name)
91 }
92
93 pub fn graph(&self) -> &CompiledGraph {
95 &self.graph
96 }
97
98 pub async fn invoke(&self, input: State, config: ExecutionConfig) -> Result<State> {
100 self.graph.invoke(input, config).await
101 }
102
103 pub fn stream(
105 &self,
106 input: State,
107 config: ExecutionConfig,
108 mode: StreamMode,
109 ) -> impl futures::Stream<Item = Result<StreamEvent>> + '_ {
110 self.graph.stream(input, config, mode)
111 }
112}
113
114#[async_trait]
115impl Agent for GraphAgent {
116 fn name(&self) -> &str {
117 &self.name
118 }
119
120 fn description(&self) -> &str {
121 &self.description
122 }
123
124 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
125 &[]
126 }
127
128 fn supports_agent_transfer(&self) -> bool {
129 false
130 }
131
132 fn capabilities(&self) -> AgentCapabilities {
133 AgentCapabilities {
134 checkpoint_resume: self.graph.has_checkpointer(),
135 shared_state: true,
136 invocation_metadata: true,
137 ..AgentCapabilities::default()
138 }
139 }
140
141 fn topology(&self) -> Option<AgentTopology> {
142 let mut nodes = self.graph.nodes.values().collect::<Vec<_>>();
143 nodes.sort_by_key(|node| node.name().to_string());
144 let mut members = vec![AgentTopologyMember {
145 name: self.name.clone(),
146 description: self.description.clone(),
147 coordinator: true,
148 capabilities: self.capabilities(),
149 }];
150 members.extend(nodes.into_iter().map(|node| AgentTopologyMember {
151 name: node.name().to_string(),
152 description: node.description().to_string(),
153 coordinator: false,
154 capabilities: node.capabilities(),
155 }));
156
157 let mut relationships = self
158 .graph
159 .get_entry_nodes()
160 .into_iter()
161 .map(|entry| AgentTopologyRelationship {
162 from: self.name.clone(),
163 to: entry,
164 kind: AgentRelationshipKind::Flow,
165 })
166 .collect::<Vec<_>>();
167 for edge in &self.graph.edges {
168 match edge {
169 Edge::Direct { source, target: EdgeTarget::Node(target) } => {
170 relationships.push(AgentTopologyRelationship {
171 from: source.clone(),
172 to: target.clone(),
173 kind: AgentRelationshipKind::Flow,
174 });
175 }
176 Edge::Conditional { source, targets, .. } => {
177 relationships.extend(targets.values().filter_map(|target| {
178 target.node_name().map(|target| AgentTopologyRelationship {
179 from: source.clone(),
180 to: target.to_string(),
181 kind: AgentRelationshipKind::Flow,
182 })
183 }));
184 }
185 Edge::Direct { target: EdgeTarget::End, .. } | Edge::Entry { .. } => {}
186 }
187 }
188 relationships.sort_by(|left, right| (&left.from, &left.to).cmp(&(&right.from, &right.to)));
189 relationships.dedup_by(|left, right| left.from == right.from && left.to == right.to);
190
191 Some(AgentTopology {
192 root: self.name.clone(),
193 coordinator: self.name.clone(),
194 members,
195 relationships,
196 })
197 }
198
199 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> adk_core::Result<EventStream> {
200 if let Some(callback) = &self.before_callback {
202 callback(ctx.clone()).await?;
203 }
204
205 let input = (self.input_mapper)(ctx.as_ref());
207
208 let config = ExecutionConfig::new(ctx.session_id()).with_parent_context(ctx.clone());
212
213 let graph = self.graph.clone();
215 let output_mapper = self.output_mapper.clone();
216 let after_callback = self.after_callback.clone();
217 let ctx_clone = ctx.clone();
218
219 let stream = async_stream::stream! {
220 match graph.invoke(input, config).await {
221 Ok(state) => {
222 let events = output_mapper(&state);
223 for event in events {
224 if let Some(callback) = &after_callback
226 && let Err(e) = callback(ctx_clone.clone(), event.clone()).await {
227 yield Err(e);
228 return;
229 }
230 yield Ok(event);
231 }
232 }
233 Err(GraphError::Interrupted(interrupt)) => {
234 let payload = crate::interrupt::GraphInterruptPayload::new(
239 &interrupt.interrupt,
240 &interrupt.thread_id,
241 &interrupt.checkpoint_id,
242 );
243 let mut event = Event::new("graph_interrupted");
244 event.set_content(
245 Content::new("assistant").with_text(interrupt.interrupt.to_string()),
246 );
247 event.provider_metadata.insert(
248 crate::interrupt::INTERRUPT_METADATA_KEY.to_string(),
249 payload.to_metadata_value(),
250 );
251 yield Ok(event);
252 }
253 Err(e) => {
254 yield Err(adk_core::AdkError::agent(e.to_string()));
255 }
256 }
257 };
258
259 Ok(Box::pin(stream))
260 }
261}
262
263fn default_input_mapper(ctx: &dyn InvocationContext) -> State {
265 let mut state = State::new();
266
267 let content = ctx.user_content();
269 let text: String = content.parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join("\n");
270
271 if !text.is_empty() {
272 state.insert("input".to_string(), json!(text));
273 state.insert("messages".to_string(), json!([{"role": "user", "content": text}]));
274 }
275
276 state.insert("session_id".to_string(), json!(ctx.session_id()));
278
279 state
280}
281
282fn default_output_mapper(state: &State) -> Vec<Event> {
284 let mut events = Vec::new();
285
286 let output_text = state
288 .get("output")
289 .and_then(|v| v.as_str())
290 .or_else(|| state.get("result").and_then(|v| v.as_str()))
291 .or_else(|| {
292 state
293 .get("messages")
294 .and_then(|v| v.as_array())
295 .and_then(|arr| arr.last())
296 .and_then(|msg| msg.get("content"))
297 .and_then(|c| c.as_str())
298 });
299
300 let text = if let Some(text) = output_text {
301 text.to_string()
302 } else {
303 serde_json::to_string_pretty(state).unwrap_or_default()
305 };
306
307 let mut event = Event::new("graph_output");
308 event.set_content(Content::new("assistant").with_text(&text));
309 events.push(event);
310
311 events
312}
313
314pub struct GraphAgentBuilder {
316 name: String,
317 description: String,
318 schema: StateSchema,
319 nodes: Vec<Arc<dyn Node>>,
320 edges: Vec<Edge>,
321 checkpointer: Option<Arc<dyn Checkpointer>>,
322 interrupt_before: Vec<String>,
323 interrupt_after: Vec<String>,
324 recursion_limit: usize,
325 max_concurrency: Option<usize>,
326 input_mapper: Option<InputMapper>,
327 output_mapper: Option<OutputMapper>,
328 before_callback: Option<BeforeAgentCallback>,
329 after_callback: Option<AfterAgentCallback>,
330 timeout_policies: HashMap<String, TimeoutPolicy>,
331 default_timeout: Option<TimeoutPolicy>,
332 deferred_configs: HashMap<String, DeferredNodeConfig>,
333 #[cfg(feature = "node-cache")]
334 cache_policies: HashMap<String, crate::cache::NodeCachePolicy>,
335}
336
337impl GraphAgentBuilder {
338 pub fn new(name: &str) -> Self {
340 Self {
341 name: name.to_string(),
342 description: String::new(),
343 schema: StateSchema::simple(&["input", "output", "messages"]),
344 nodes: vec![],
345 edges: vec![],
346 checkpointer: None,
347 interrupt_before: vec![],
348 interrupt_after: vec![],
349 recursion_limit: 100,
350 max_concurrency: None,
351 input_mapper: None,
352 output_mapper: None,
353 before_callback: None,
354 after_callback: None,
355 timeout_policies: HashMap::new(),
356 default_timeout: None,
357 deferred_configs: HashMap::new(),
358 #[cfg(feature = "node-cache")]
359 cache_policies: HashMap::new(),
360 }
361 }
362
363 pub fn description(mut self, desc: &str) -> Self {
365 self.description = desc.to_string();
366 self
367 }
368
369 pub fn state_schema(mut self, schema: StateSchema) -> Self {
371 self.schema = schema;
372 self
373 }
374
375 pub fn channels(mut self, channels: &[&str]) -> Self {
377 self.schema = StateSchema::simple(channels);
378 self
379 }
380
381 pub fn node<N: Node + 'static>(mut self, node: N) -> Self {
383 self.nodes.push(Arc::new(node));
384 self
385 }
386
387 pub fn node_fn<F, Fut>(mut self, name: &str, func: F) -> Self
389 where
390 F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
391 Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
392 {
393 self.nodes.push(Arc::new(FunctionNode::new(name, func)));
394 self
395 }
396
397 pub fn edge(mut self, source: &str, target: &str) -> Self {
399 let target =
400 if target == END { EdgeTarget::End } else { EdgeTarget::Node(target.to_string()) };
401
402 if source == START {
403 let entry_idx = self.edges.iter().position(|e| matches!(e, Edge::Entry { .. }));
404 match entry_idx {
405 Some(idx) => {
406 if let Edge::Entry { targets } = &mut self.edges[idx]
407 && let EdgeTarget::Node(node) = &target
408 && !targets.contains(node)
409 {
410 targets.push(node.clone());
411 }
412 }
413 None => {
414 if let EdgeTarget::Node(node) = target {
415 self.edges.push(Edge::Entry { targets: vec![node] });
416 }
417 }
418 }
419 } else {
420 self.edges.push(Edge::Direct { source: source.to_string(), target });
421 }
422
423 self
424 }
425
426 pub fn conditional_edge<F, I>(mut self, source: &str, router: F, targets: I) -> Self
428 where
429 F: Fn(&State) -> String + Send + Sync + 'static,
430 I: IntoIterator<Item = (&'static str, &'static str)>,
431 {
432 let targets_map: HashMap<String, EdgeTarget> = targets
433 .into_iter()
434 .map(|(k, v)| {
435 let target =
436 if v == END { EdgeTarget::End } else { EdgeTarget::Node(v.to_string()) };
437 (k.to_string(), target)
438 })
439 .collect();
440
441 self.edges.push(Edge::Conditional {
442 source: source.to_string(),
443 router: Arc::new(router),
444 targets: targets_map,
445 });
446
447 self
448 }
449
450 pub fn checkpointer<C: Checkpointer + 'static>(mut self, checkpointer: C) -> Self {
452 self.checkpointer = Some(Arc::new(checkpointer));
453 self
454 }
455
456 pub fn checkpointer_arc(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
458 self.checkpointer = Some(checkpointer);
459 self
460 }
461
462 pub fn interrupt_before(mut self, nodes: &[&str]) -> Self {
464 self.interrupt_before = nodes.iter().map(|s| s.to_string()).collect();
465 self
466 }
467
468 pub fn interrupt_after(mut self, nodes: &[&str]) -> Self {
470 self.interrupt_after = nodes.iter().map(|s| s.to_string()).collect();
471 self
472 }
473
474 pub fn max_concurrency(mut self, limit: usize) -> Self {
479 self.max_concurrency = Some(limit.max(1));
480 self
481 }
482
483 pub fn recursion_limit(mut self, limit: usize) -> Self {
484 self.recursion_limit = limit;
485 self
486 }
487
488 pub fn node_timeout(mut self, node_name: &str, policy: TimeoutPolicy) -> Self {
508 self.timeout_policies.insert(node_name.to_string(), policy);
509 self
510 }
511
512 pub fn default_timeout(mut self, policy: TimeoutPolicy) -> Self {
532 self.default_timeout = Some(policy);
533 self
534 }
535
536 pub fn mark_deferred(mut self, name: &str, config: DeferredNodeConfig) -> Self {
574 self.deferred_configs.insert(name.to_string(), config);
575 self
576 }
577
578 pub fn deferred_node<F, Fut>(mut self, name: &str, func: F, config: DeferredNodeConfig) -> Self
579 where
580 F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
581 Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
582 {
583 self.nodes.push(Arc::new(FunctionNode::new(name, func)));
584 self.deferred_configs.insert(name.to_string(), config);
585 self
586 }
587
588 #[cfg(feature = "node-cache")]
614 pub fn node_cache(mut self, name: &str, policy: crate::cache::NodeCachePolicy) -> Self {
615 self.cache_policies.insert(name.to_string(), policy);
616 self
617 }
618
619 pub fn input_mapper<F>(mut self, mapper: F) -> Self
621 where
622 F: Fn(&dyn InvocationContext) -> State + Send + Sync + 'static,
623 {
624 self.input_mapper = Some(Arc::new(mapper));
625 self
626 }
627
628 pub fn output_mapper<F>(mut self, mapper: F) -> Self
630 where
631 F: Fn(&State) -> Vec<Event> + Send + Sync + 'static,
632 {
633 self.output_mapper = Some(Arc::new(mapper));
634 self
635 }
636
637 pub fn before_agent_callback<F, Fut>(mut self, callback: F) -> Self
639 where
640 F: Fn(Arc<dyn InvocationContext>) -> Fut + Send + Sync + 'static,
641 Fut: Future<Output = adk_core::Result<()>> + Send + 'static,
642 {
643 self.before_callback = Some(Arc::new(move |ctx| Box::pin(callback(ctx))));
644 self
645 }
646
647 pub fn after_agent_callback<F, Fut>(mut self, callback: F) -> Self
651 where
652 F: Fn(Arc<dyn InvocationContext>, Event) -> Fut + Send + Sync + 'static,
653 Fut: Future<Output = adk_core::Result<()>> + Send + 'static,
654 {
655 self.after_callback = Some(Arc::new(move |ctx, event| {
656 let event_clone = event.clone();
657 Box::pin(callback(ctx, event_clone))
658 }));
659 self
660 }
661
662 #[cfg(feature = "action")]
668 pub fn action_node(mut self, config: adk_action::ActionNodeConfig) -> Self {
669 use crate::action::ActionNodeExecutor;
670
671 if let adk_action::ActionNodeConfig::Switch(ref switch_config) = config {
673 let conditions = switch_config.conditions.clone();
674 let eval_mode = switch_config.evaluation_mode.clone();
675 let default_branch = switch_config.default_branch.clone();
676 let source = config.standard().id.clone();
677
678 let mut targets_map: HashMap<String, EdgeTarget> = HashMap::new();
679 for condition in &conditions {
680 targets_map.insert(
681 condition.output_port.clone(),
682 EdgeTarget::Node(condition.output_port.clone()),
683 );
684 }
685 if let Some(ref default) = default_branch {
686 let target = if default == END {
687 EdgeTarget::End
688 } else {
689 EdgeTarget::Node(default.clone())
690 };
691 targets_map.insert(default.clone(), target);
692 }
693 targets_map.insert(END.to_string(), EdgeTarget::End);
694
695 let router = Arc::new(move |state: &State| -> String {
696 match crate::action::switch::evaluate_switch_conditions(
697 &conditions,
698 state,
699 &eval_mode,
700 default_branch.as_deref(),
701 ) {
702 Ok(ports) => ports.into_iter().next().unwrap_or_else(|| END.to_string()),
703 Err(_) => END.to_string(),
704 }
705 });
706
707 self.edges.push(Edge::Conditional { source, router, targets: targets_map });
708 }
709
710 let executor = ActionNodeExecutor::new(config);
711 self.nodes.push(Arc::new(executor));
712 self
713 }
714
715 pub fn build(self) -> Result<GraphAgent> {
717 let mut graph = StateGraph::new(self.schema);
719
720 for node in self.nodes {
722 graph.nodes.insert(node.name().to_string(), node);
723 }
724
725 graph.edges = self.edges;
727
728 let mut compiled = graph.compile()?;
730
731 if let Some(cp) = self.checkpointer {
733 compiled.checkpointer = Some(cp);
734 }
735 compiled.interrupt_before = self.interrupt_before.into_iter().collect();
736 compiled.interrupt_after = self.interrupt_after.into_iter().collect();
737 compiled.recursion_limit = self.recursion_limit;
738 compiled.max_concurrency = self.max_concurrency;
739 compiled.timeout_policies = self.timeout_policies;
740 compiled.default_timeout = self.default_timeout;
741 compiled.deferred_configs = self.deferred_configs;
742
743 #[cfg(feature = "node-cache")]
744 {
745 compiled.cache_policies = self.cache_policies;
746 }
747
748 Ok(GraphAgent {
749 name: self.name,
750 description: self.description,
751 graph: Arc::new(compiled),
752 input_mapper: self.input_mapper.unwrap_or(Arc::new(default_input_mapper)),
753 output_mapper: self.output_mapper.unwrap_or(Arc::new(default_output_mapper)),
754 before_callback: self.before_callback,
755 after_callback: self.after_callback,
756 })
757 }
758}
759
760#[cfg(test)]
761mod tests {
762 use super::*;
763 use serde_json::json;
764
765 #[tokio::test]
766 async fn test_graph_agent_builder() {
767 let agent = GraphAgent::builder("test")
768 .description("Test agent")
769 .channels(&["value"])
770 .node_fn("set", |_ctx| async { Ok(NodeOutput::new().with_update("value", json!(42))) })
771 .edge(START, "set")
772 .edge("set", END)
773 .build()
774 .unwrap();
775
776 assert_eq!(agent.name(), "test");
777 assert_eq!(agent.description(), "Test agent");
778
779 let result = agent.invoke(State::new(), ExecutionConfig::new("test")).await.unwrap();
781
782 assert_eq!(result.get("value"), Some(&json!(42)));
783
784 let topology = agent.topology().expect("graph topology");
785 assert_eq!(topology.root, "test");
786 assert_eq!(topology.coordinator, "test");
787 assert_eq!(topology.members.len(), 2);
788 assert_eq!(topology.relationships.len(), 1);
789 assert_eq!(topology.relationships[0].from, "test");
790 assert_eq!(topology.relationships[0].to, "set");
791 assert_eq!(topology.relationships[0].kind, AgentRelationshipKind::Flow);
792 }
793}