Skip to main content

adk_graph/
agent.rs

1//! GraphAgent - ADK Agent integration for graph workflows
2//!
3//! Provides a builder pattern similar to LlmAgent and RealtimeAgent.
4
5use 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
25/// Type alias for callbacks
26pub 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
41/// Type alias for input mapper function
42pub type InputMapper = Arc<dyn Fn(&dyn InvocationContext) -> State + Send + Sync>;
43
44/// Type alias for output mapper function
45pub type OutputMapper = Arc<dyn Fn(&State) -> Vec<Event> + Send + Sync>;
46
47/// GraphAgent wraps a CompiledGraph as an ADK Agent
48pub struct GraphAgent {
49    name: String,
50    description: String,
51    graph: Arc<CompiledGraph>,
52    /// Map InvocationContext to graph input state
53    input_mapper: InputMapper,
54    /// Map graph output state to ADK Events
55    output_mapper: OutputMapper,
56    /// Before agent callback
57    before_callback: Option<BeforeAgentCallback>,
58    /// After agent callback
59    after_callback: Option<AfterAgentCallback>,
60}
61
62impl GraphAgent {
63    /// Create a new GraphAgent builder
64    pub fn builder(name: &str) -> GraphAgentBuilder {
65        GraphAgentBuilder::new(name)
66    }
67
68    /// Create directly from a compiled graph
69    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    /// Build a `GraphAgent` from a `WorkflowSchema`.
82    ///
83    /// Delegates to `schema.build_graph()` to construct the graph from the
84    /// workflow schema's action nodes, edges, and conditions.
85    #[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    /// Get the underlying compiled graph
94    pub fn graph(&self) -> &CompiledGraph {
95        &self.graph
96    }
97
98    /// Execute the graph directly (bypassing Agent trait)
99    pub async fn invoke(&self, input: State, config: ExecutionConfig) -> Result<State> {
100        self.graph.invoke(input, config).await
101    }
102
103    /// Stream execution
104    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        // Call before callback
201        if let Some(callback) = &self.before_callback {
202            callback(ctx.clone()).await?;
203        }
204
205        // Map context to input state
206        let input = (self.input_mapper)(ctx.as_ref());
207
208        // Create execution config from context, carrying the invocation so an
209        // `AgentNode` inside the graph presents this run's identity, services, and
210        // cancellation rather than a synthetic standalone context.
211        let config = ExecutionConfig::new(ctx.session_id()).with_parent_context(ctx.clone());
212
213        // Execute graph
214        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                        // Call after callback for each event
225                        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                    // The `Agent` trait yields events, so an interrupt cannot be
235                    // returned as an error without ending the invocation. Emit one
236                    // event carrying the structured pause so a caller can read the
237                    // node, the payload, and the checkpoint to resume from.
238                    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
263/// Default input mapper - extracts content from InvocationContext
264fn default_input_mapper(ctx: &dyn InvocationContext) -> State {
265    let mut state = State::new();
266
267    // Get user content
268    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    // Add session ID
277    state.insert("session_id".to_string(), json!(ctx.session_id()));
278
279    state
280}
281
282/// Default output mapper - creates events from state
283fn default_output_mapper(state: &State) -> Vec<Event> {
284    let mut events = Vec::new();
285
286    // Try to get output from common fields
287    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        // Return the full state as JSON
304        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
314/// Builder for GraphAgent
315pub 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    /// Create a new builder
339    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    /// Set description
364    pub fn description(mut self, desc: &str) -> Self {
365        self.description = desc.to_string();
366        self
367    }
368
369    /// Set state schema
370    pub fn state_schema(mut self, schema: StateSchema) -> Self {
371        self.schema = schema;
372        self
373    }
374
375    /// Add channels to state schema
376    pub fn channels(mut self, channels: &[&str]) -> Self {
377        self.schema = StateSchema::simple(channels);
378        self
379    }
380
381    /// Add a node
382    pub fn node<N: Node + 'static>(mut self, node: N) -> Self {
383        self.nodes.push(Arc::new(node));
384        self
385    }
386
387    /// Add a function as a node
388    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    /// Add a direct edge
398    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    /// Add a conditional edge
427    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    /// Set checkpointer
451    pub fn checkpointer<C: Checkpointer + 'static>(mut self, checkpointer: C) -> Self {
452        self.checkpointer = Some(Arc::new(checkpointer));
453        self
454    }
455
456    /// Set checkpointer with Arc
457    pub fn checkpointer_arc(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
458        self.checkpointer = Some(checkpointer);
459        self
460    }
461
462    /// Set nodes to interrupt before
463    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    /// Set nodes to interrupt after
469    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    /// Set recursion limit
475    /// Cap how many nodes execute concurrently within one super-step.
476    ///
477    /// See [`CompiledGraph::with_max_concurrency`](crate::graph::CompiledGraph::with_max_concurrency).
478    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    /// Set a timeout policy for a specific node.
489    ///
490    /// The policy is applied when the named node executes, enforcing
491    /// wall-clock and/or idle timeouts with the configured recovery action.
492    ///
493    /// # Example
494    ///
495    /// ```rust,ignore
496    /// use std::time::Duration;
497    /// use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
498    ///
499    /// let agent = GraphAgent::builder("my_graph")
500    ///     .node_timeout("slow_node", TimeoutPolicy {
501    ///         run_timeout: Some(Duration::from_secs(10)),
502    ///         idle_timeout: None,
503    ///         on_timeout: OnTimeout::Fail,
504    ///     })
505    ///     .build()?;
506    /// ```
507    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    /// Set a default timeout policy applied to all nodes without an explicit override.
513    ///
514    /// Nodes that have a per-node policy set via [`node_timeout`](Self::node_timeout)
515    /// will use their specific policy instead of this default.
516    ///
517    /// # Example
518    ///
519    /// ```rust,ignore
520    /// use std::time::Duration;
521    /// use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
522    ///
523    /// let agent = GraphAgent::builder("my_graph")
524    ///     .default_timeout(TimeoutPolicy {
525    ///         run_timeout: Some(Duration::from_secs(30)),
526    ///         idle_timeout: Some(Duration::from_secs(5)),
527    ///         on_timeout: OnTimeout::Skip,
528    ///     })
529    ///     .build()?;
530    /// ```
531    pub fn default_timeout(mut self, policy: TimeoutPolicy) -> Self {
532        self.default_timeout = Some(policy);
533        self
534    }
535
536    /// Add a deferred (fan-in barrier) node to the graph.
537    ///
538    /// A deferred node waits for all upstream parallel paths to complete before
539    /// executing. The provided function is wrapped as a [`FunctionNode`] and the
540    /// [`DeferredNodeConfig`] controls how upstream outputs are merged and how
541    /// long the node waits for all paths.
542    ///
543    /// # Arguments
544    ///
545    /// * `name` - The name of the deferred node.
546    /// * `func` - The async function to execute once all upstream paths complete.
547    /// * `config` - Configuration controlling merge strategy and fan-in timeout.
548    ///
549    /// # Example
550    ///
551    /// ```rust,ignore
552    /// use std::time::Duration;
553    /// use adk_graph::deferred::{DeferredNodeConfig, MergeStrategy};
554    /// use adk_graph::node::NodeOutput;
555    ///
556    /// let agent = GraphAgent::builder("scatter_gather")
557    ///     .deferred_node("aggregator", |_ctx| async {
558    ///         Ok(NodeOutput::new().with_update("status", serde_json::json!("merged")))
559    ///     }, DeferredNodeConfig {
560    ///         merge_strategy: MergeStrategy::Collect,
561    ///         fan_in_timeout: Some(Duration::from_secs(30)),
562    ///     })
563    ///     .build()?;
564    /// ```
565    /// Configure fan-in for a node already added with [`node`](Self::node).
566    ///
567    /// [`deferred_node`](Self::deferred_node) both adds and configures a node, so
568    /// a custom `Node` added through `node` had no way to set a merge strategy or
569    /// a fan-in timeout.
570    ///
571    /// A node reached by more than one unconditional edge is deferred
572    /// automatically; this overrides that default.
573    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    /// Set a cache policy for a specific node.
589    ///
590    /// When a node has a cache policy, its execution results are cached keyed
591    /// by a blake3 hash of the node name and input state. Subsequent executions
592    /// with identical inputs return the cached result without re-executing the
593    /// node.
594    ///
595    /// # Arguments
596    ///
597    /// * `name` — the name of the node to cache
598    /// * `policy` — the cache policy specifying backend and TTL
599    ///
600    /// # Example
601    ///
602    /// ```rust,ignore
603    /// use std::time::Duration;
604    /// use adk_graph::cache::{CacheBackend, NodeCachePolicy};
605    ///
606    /// let agent = GraphAgent::builder("cached_graph")
607    ///     .node_cache("expensive_node", NodeCachePolicy {
608    ///         backend: CacheBackend::InMemory { max_entries: 128 },
609    ///         ttl: Some(Duration::from_secs(300)),
610    ///     })
611    ///     .build()?;
612    /// ```
613    #[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    /// Set custom input mapper
620    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    /// Set custom output mapper
629    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    /// Set before agent callback
638    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    /// Set after agent callback
648    ///
649    /// Note: The callback receives a cloned Event to avoid lifetime issues.
650    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    /// Add an action node to the graph.
663    ///
664    /// Wraps the `ActionNodeConfig` in an `ActionNodeExecutor` and registers it
665    /// as a node. If the config is a `SwitchNodeConfig`, conditional edges are
666    /// also auto-registered from the switch conditions.
667    #[cfg(feature = "action")]
668    pub fn action_node(mut self, config: adk_action::ActionNodeConfig) -> Self {
669        use crate::action::ActionNodeExecutor;
670
671        // If this is a Switch node, register conditional edges
672        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    /// Build the GraphAgent
716    pub fn build(self) -> Result<GraphAgent> {
717        // Build the graph
718        let mut graph = StateGraph::new(self.schema);
719
720        // Add nodes
721        for node in self.nodes {
722            graph.nodes.insert(node.name().to_string(), node);
723        }
724
725        // Add edges
726        graph.edges = self.edges;
727
728        // Compile
729        let mut compiled = graph.compile()?;
730
731        // Configure
732        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        // Test direct invocation
780        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}