Skip to main content

adk_graph/
workflow.rs

1//! Workflow schema types and loader for action node graph workflows.
2//!
3//! This module provides the `WorkflowSchema` type for serializing and deserializing
4//! graph workflows that include action nodes, and a builder that constructs a
5//! `GraphAgent` from a schema.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use adk_action::{ActionNodeConfig, SwitchNodeConfig, TriggerNodeConfig};
11use serde::{Deserialize, Serialize};
12
13use crate::action::ActionNodeExecutor;
14use crate::action::switch::evaluate_switch_conditions;
15use crate::edge::{END, EdgeTarget};
16use crate::error::{GraphError, Result};
17use crate::graph::StateGraph;
18use crate::node::Node;
19use crate::state::StateSchema;
20
21// ── WorkflowSchema types ──────────────────────────────────────────────
22
23/// An edge in the workflow graph, in the workflow JSON format.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct WorkflowEdge {
27    /// Source node ID.
28    pub from: String,
29    /// Target node ID.
30    pub to: String,
31    /// Optional condition ID that must be satisfied for this edge.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub condition: Option<String>,
34    /// Optional source port identifier.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub from_port: Option<String>,
37    /// Optional target port identifier.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub to_port: Option<String>,
40}
41
42/// A condition used by conditional edges in the workflow.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub struct WorkflowCondition {
46    /// Unique condition identifier.
47    pub id: String,
48    /// The condition expression to evaluate.
49    pub expression: String,
50    /// Optional human-readable description.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub description: Option<String>,
53}
54
55/// The serializable representation of a graph workflow including nodes, edges,
56/// conditions, and action node configurations.
57///
58/// This is the workflow JSON format that adk-graph loads and runs.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[serde(rename_all = "camelCase")]
61pub struct WorkflowSchema {
62    /// Edges connecting nodes in the graph.
63    pub edges: Vec<WorkflowEdge>,
64    /// Conditions referenced by conditional edges.
65    #[serde(default)]
66    pub conditions: Vec<WorkflowCondition>,
67    /// Action node configurations keyed by node ID.
68    #[serde(default)]
69    pub action_nodes: HashMap<String, ActionNodeConfig>,
70    /// Agent node IDs (LLM agent nodes registered externally).
71    #[serde(default)]
72    pub agent_nodes: Vec<String>,
73}
74
75impl WorkflowSchema {
76    /// Deserialize a `WorkflowSchema` from a JSON string.
77    pub fn from_json(json: &str) -> Result<Self> {
78        serde_json::from_str(json)
79            .map_err(|e| GraphError::InvalidGraph(format!("invalid workflow JSON: {e}")))
80    }
81
82    /// Build a `GraphAgent` from this workflow schema.
83    ///
84    /// 1. Creates a `StateGraph`
85    /// 2. Registers each action node via `ActionNodeExecutor`
86    /// 3. Registers edges (direct and conditional)
87    /// 4. Handles Switch nodes by auto-registering conditional edges
88    /// 5. Compiles and returns a `GraphAgent`
89    pub fn build_graph(&self, name: &str) -> Result<crate::agent::GraphAgent> {
90        let schema = StateSchema::simple(&["input", "output", "messages"]);
91        let mut graph = StateGraph::new(schema);
92
93        // Register action nodes
94        for (node_id, config) in &self.action_nodes {
95            let executor = ActionNodeExecutor::new(config.clone());
96            // Verify the executor's name matches the expected node_id
97            debug_assert_eq!(
98                executor.name(),
99                node_id,
100                "ActionNodeExecutor name must match node ID"
101            );
102            graph.nodes.insert(node_id.clone(), Arc::new(executor));
103        }
104
105        // Build a condition lookup map
106        let condition_map: HashMap<&str, &WorkflowCondition> =
107            self.conditions.iter().map(|c| (c.id.as_str(), c)).collect();
108
109        // Group edges by source to detect conditional routing
110        let mut conditional_groups: HashMap<String, Vec<&WorkflowEdge>> = HashMap::new();
111        let mut direct_edges: Vec<&WorkflowEdge> = Vec::new();
112
113        for edge in &self.edges {
114            if edge.condition.is_some() {
115                conditional_groups.entry(edge.from.clone()).or_default().push(edge);
116            } else {
117                direct_edges.push(edge);
118            }
119        }
120
121        // Register direct edges
122        for edge in &direct_edges {
123            graph = graph.add_edge(&edge.from, &edge.to);
124        }
125
126        // Register conditional edges from Switch nodes
127        for (node_id, config) in &self.action_nodes {
128            if let ActionNodeConfig::Switch(switch_config) = config {
129                graph = register_switch_conditional_edges(graph, node_id, switch_config);
130            }
131        }
132
133        // Register conditional edges from schema conditions
134        for (source, edges) in &conditional_groups {
135            // Skip if this source is a Switch node (already handled above)
136            if let Some(ActionNodeConfig::Switch(_)) = self.action_nodes.get(source) {
137                continue;
138            }
139
140            // Build targets map and router for condition-based edges
141            let mut targets_map: HashMap<String, EdgeTarget> = HashMap::new();
142            let mut condition_expressions: Vec<(String, String)> = Vec::new();
143
144            for edge in edges {
145                if let Some(cond_id) = &edge.condition {
146                    let target = if edge.to == END {
147                        EdgeTarget::End
148                    } else {
149                        EdgeTarget::Node(edge.to.clone())
150                    };
151                    targets_map.insert(edge.to.clone(), target);
152
153                    if let Some(cond) = condition_map.get(cond_id.as_str()) {
154                        condition_expressions.push((cond.expression.clone(), edge.to.clone()));
155                    }
156                }
157            }
158
159            let router_expressions = condition_expressions.clone();
160            let default_target = END.to_string();
161
162            let router = Arc::new(move |state: &crate::state::State| -> String {
163                for (expr, target) in &router_expressions {
164                    let resolved = adk_action::interpolate_variables(expr, state);
165                    let trimmed = resolved.trim().to_lowercase();
166                    if !trimmed.is_empty() && trimmed != "false" && trimmed != "0" {
167                        return target.clone();
168                    }
169                }
170                default_target.clone()
171            });
172
173            graph.edges.push(crate::edge::Edge::Conditional {
174                source: source.clone(),
175                router,
176                targets: targets_map,
177            });
178        }
179
180        let compiled = graph.compile()?;
181        Ok(crate::agent::GraphAgent::from_graph(name, compiled))
182    }
183
184    /// Extract trigger node configurations from the action nodes.
185    ///
186    /// Returns all `TriggerNodeConfig` entries found in the workflow.
187    pub fn trigger_configs(&self) -> Vec<TriggerNodeConfig> {
188        self.action_nodes
189            .values()
190            .filter_map(|config| {
191                if let ActionNodeConfig::Trigger(trigger) = config {
192                    Some(trigger.clone())
193                } else {
194                    None
195                }
196            })
197            .collect()
198    }
199
200    /// Build a `TriggerRuntime` from this workflow schema.
201    ///
202    /// Extracts trigger node configurations and constructs a `TriggerRuntime`
203    /// with the provided graph agent.
204    #[cfg(feature = "action-trigger")]
205    pub fn build_trigger_runtime(
206        &self,
207        graph: Arc<crate::agent::GraphAgent>,
208    ) -> crate::action::trigger_runtime::TriggerRuntime {
209        let triggers = self.trigger_configs();
210        crate::action::trigger_runtime::TriggerRuntime::new(graph, triggers)
211    }
212}
213
214/// Register conditional edges for a Switch node.
215///
216/// Creates a conditional edge from the switch node to each condition's output port,
217/// using the switch condition evaluation logic as the router.
218fn register_switch_conditional_edges(
219    mut graph: StateGraph,
220    node_id: &str,
221    switch_config: &SwitchNodeConfig,
222) -> StateGraph {
223    let conditions = switch_config.conditions.clone();
224    let eval_mode = switch_config.evaluation_mode.clone();
225    let default_branch = switch_config.default_branch.clone();
226
227    // Build targets map from conditions
228    let mut targets_map: HashMap<String, EdgeTarget> = HashMap::new();
229    for condition in &conditions {
230        targets_map
231            .insert(condition.output_port.clone(), EdgeTarget::Node(condition.output_port.clone()));
232    }
233    if let Some(ref default) = default_branch {
234        let target =
235            if default == END { EdgeTarget::End } else { EdgeTarget::Node(default.clone()) };
236        targets_map.insert(default.clone(), target);
237    }
238    // Always include END as a possible target
239    targets_map.insert(END.to_string(), EdgeTarget::End);
240
241    let router = Arc::new(move |state: &crate::state::State| -> String {
242        match evaluate_switch_conditions(&conditions, state, &eval_mode, default_branch.as_deref())
243        {
244            Ok(ports) => ports.into_iter().next().unwrap_or_else(|| END.to_string()),
245            Err(_) => END.to_string(),
246        }
247    });
248
249    graph.edges.push(crate::edge::Edge::Conditional {
250        source: node_id.to_string(),
251        router,
252        targets: targets_map,
253    });
254
255    graph
256}