Skip to main content

adk_graph/definition/
build.rs

1//! Compiles a [`WorkflowDefinition`] into a graph.
2
3use std::collections::{BTreeMap, HashMap};
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7
8use adk_action::{ActionNodeConfig, ExpressionMode, get_nested_value, interpolate_variables};
9use adk_core::{Agent, Llm, Tool};
10use serde_json::{Map, Value, json};
11
12use super::WorkflowError;
13use super::types::{
14    CheckpointStore, Condition, EdgeDefinition, EdgeSpec, LlmDefinition, NodeDefinition,
15    ReducerKind, WorkflowDefinition,
16};
17use super::validate::{END_ID, START_ID};
18use crate::action::ActionNodeExecutor;
19use crate::agent::GraphAgent;
20use crate::checkpoint::{Checkpointer, MemoryCheckpointer};
21use crate::edge::{Edge, EdgeTarget};
22use crate::graph::{CompiledGraph, StateGraph};
23use crate::node::{AgentNode, FunctionNode, Node, NodeContext, NodeOutput};
24use crate::retry::RetryPolicy;
25use crate::state::{Reducer, State, StateSchema};
26
27/// A function node a workflow names with `function:`.
28pub type FunctionNodeFn = Arc<
29    dyn Fn(NodeContext) -> Pin<Box<dyn Future<Output = crate::Result<NodeOutput>> + Send>>
30        + Send
31        + Sync,
32>;
33
34/// Resolves a `provider/model` reference, such as `anthropic/claude-haiku-5-5`, to a model.
35pub type ModelResolver = Arc<dyn Fn(&str) -> adk_core::Result<Arc<dyn Llm>> + Send + Sync>;
36
37/// What a workflow's names refer to: agents, models, tools and functions, registered by name.
38///
39/// # Example
40///
41/// ```rust,no_run
42/// use std::sync::Arc;
43/// use adk_core::{Agent, Llm};
44/// use adk_graph::definition::{WorkflowDefinition, WorkflowRegistry};
45///
46/// # async fn run(researcher: Arc<dyn Agent>, haiku: Arc<dyn Llm>) -> Result<(), Box<dyn std::error::Error>> {
47/// let registry = WorkflowRegistry::new()
48///     .agent(researcher)
49///     .model("anthropic/claude-haiku-5-5", haiku);
50/// let graph = WorkflowDefinition::from_file("workflow.yaml")?.build(&registry).await?;
51/// # let _ = graph;
52/// # Ok(())
53/// # }
54/// ```
55#[derive(Clone, Default)]
56pub struct WorkflowRegistry {
57    agents: BTreeMap<String, Arc<dyn Agent>>,
58    models: BTreeMap<String, Arc<dyn Llm>>,
59    tools: BTreeMap<String, Arc<dyn Tool>>,
60    functions: BTreeMap<String, FunctionNodeFn>,
61    model_resolver: Option<ModelResolver>,
62    checkpointer: Option<Arc<dyn Checkpointer>>,
63}
64
65impl std::fmt::Debug for WorkflowRegistry {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        f.debug_struct("WorkflowRegistry")
68            .field("agents", &self.agents.keys().collect::<Vec<_>>())
69            .field("models", &self.models.keys().collect::<Vec<_>>())
70            .field("tools", &self.tools.keys().collect::<Vec<_>>())
71            .field("functions", &self.functions.keys().collect::<Vec<_>>())
72            .field("model_resolver", &self.model_resolver.is_some())
73            .field("checkpointer", &self.checkpointer.is_some())
74            .finish()
75    }
76}
77
78impl WorkflowRegistry {
79    /// An empty registry.
80    pub fn new() -> Self {
81        Self::default()
82    }
83
84    /// Registers `agent` under its name, for `agent:` nodes.
85    #[must_use]
86    pub fn agent(mut self, agent: Arc<dyn Agent>) -> Self {
87        self.agents.insert(agent.name().to_string(), agent);
88        self
89    }
90
91    /// Registers `model` under `name`, for `llm.model` references and `models` aliases.
92    #[must_use]
93    pub fn model(mut self, name: impl Into<String>, model: Arc<dyn Llm>) -> Self {
94        self.models.insert(name.into(), model);
95        self
96    }
97
98    /// Resolves model references no registered model answers, such as
99    /// `anthropic/claude-haiku-5-5`.
100    #[must_use]
101    pub fn model_resolver<F>(mut self, resolver: F) -> Self
102    where
103        F: Fn(&str) -> adk_core::Result<Arc<dyn Llm>> + Send + Sync + 'static,
104    {
105        self.model_resolver = Some(Arc::new(resolver));
106        self
107    }
108
109    /// Registers `tool` under its name, for `llm.tools`.
110    #[must_use]
111    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
112        self.tools.insert(tool.name().to_string(), tool);
113        self
114    }
115
116    /// Registers a function node under `name`, for `function:` nodes.
117    #[must_use]
118    pub fn function<F, Fut>(mut self, name: impl Into<String>, function: F) -> Self
119    where
120        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
121        Fut: Future<Output = crate::Result<NodeOutput>> + Send + 'static,
122    {
123        self.functions.insert(name.into(), Arc::new(move |ctx| Box::pin(function(ctx))));
124        self
125    }
126
127    /// Keeps checkpoints in `checkpointer`, in place of the store the workflow names.
128    #[must_use]
129    pub fn checkpointer(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
130        self.checkpointer = Some(checkpointer);
131        self
132    }
133
134    fn resolve_model(
135        &self,
136        workflow: &WorkflowDefinition,
137        name: &str,
138    ) -> Result<Arc<dyn Llm>, String> {
139        let reference = workflow.models.get(name).map_or(name, String::as_str);
140        if let Some(model) = self.models.get(reference).or_else(|| self.models.get(name)) {
141            return Ok(Arc::clone(model));
142        }
143        match &self.model_resolver {
144            Some(resolve) => resolve(reference)
145                .map_err(|error| format!("cannot resolve model '{reference}': {}", error.message)),
146            None => Err(format!(
147                "no model '{reference}' is registered and the registry has no model resolver; \
148                 register it with WorkflowRegistry::model or set a model_resolver"
149            )),
150        }
151    }
152}
153
154fn graph_id(id: &str) -> &str {
155    match id {
156        START_ID => crate::START,
157        END_ID => crate::END,
158        other => other,
159    }
160}
161
162impl WorkflowDefinition {
163    /// Compiles the workflow into a graph with its checkpointer, interrupts, recursion limit
164    /// and retries.
165    ///
166    /// # Errors
167    ///
168    /// Returns every validation issue, and every name the registry cannot resolve (an agent,
169    /// model, tool or function), each with its path and location.
170    pub async fn build(&self, registry: &WorkflowRegistry) -> Result<CompiledGraph, WorkflowError> {
171        self.validate()?;
172        let mut issues: Vec<(String, String)> = Vec::new();
173        let mut graph = StateGraph::new(self.state_schema());
174
175        for (id, node) in &self.nodes {
176            match self.node(id, node, registry) {
177                Ok(built) => {
178                    graph.nodes.insert(id.clone(), built);
179                }
180                Err(issue) => issues.push(issue),
181            }
182        }
183        if !issues.is_empty() {
184            return Err(self.source.error(issues));
185        }
186
187        for edge in &self.edges {
188            graph = match edge {
189                EdgeDefinition::Chain(ids) => ids.windows(2).fold(graph, |graph, pair| {
190                    graph.add_edge(graph_id(&pair[0]), graph_id(&pair[1]))
191                }),
192                EdgeDefinition::Edge(spec) => add_spec(graph, spec),
193            };
194        }
195
196        let mut compiled = graph
197            .compile()
198            .map_err(|error| self.source.error(vec![(String::new(), error.to_string())]))?;
199
200        let checkpointer = match &registry.checkpointer {
201            Some(checkpointer) => Some(Arc::clone(checkpointer)),
202            None => self.store().await?,
203        };
204        if let Some(checkpointer) = checkpointer {
205            compiled = compiled.with_checkpointer_arc(checkpointer);
206        }
207        if !self.interrupt_before.is_empty() {
208            let nodes: Vec<&str> = self.interrupt_before.iter().map(String::as_str).collect();
209            compiled = compiled.with_interrupt_before(&nodes);
210        }
211        if !self.interrupt_after.is_empty() {
212            let nodes: Vec<&str> = self.interrupt_after.iter().map(String::as_str).collect();
213            compiled = compiled.with_interrupt_after(&nodes);
214        }
215        if let Some(limit) = self.recursion_limit {
216            compiled = compiled.with_recursion_limit(limit);
217        }
218        for (id, node) in &self.nodes {
219            if let Some(attempts) = node.max_attempts.filter(|attempts| *attempts > 1) {
220                compiled = compiled.with_node_retry(id, RetryPolicy::new(attempts));
221            }
222        }
223        Ok(compiled)
224    }
225
226    /// Compiles the workflow into a [`GraphAgent`] named after it, which a `Runner` can run;
227    /// each turn of a paused thread resumes it with the turn's text.
228    ///
229    /// # Errors
230    ///
231    /// Returns the issues [`build`](Self::build) returns.
232    pub async fn build_agent(
233        &self,
234        registry: &WorkflowRegistry,
235    ) -> Result<GraphAgent, WorkflowError> {
236        Ok(GraphAgent::from_graph(&self.name, self.build(registry).await?))
237    }
238
239    fn state_schema(&self) -> StateSchema {
240        let mut builder = StateSchema::builder().list_channel("messages");
241        for (name, channel) in &self.state {
242            let reducer = match channel.reducer {
243                ReducerKind::Overwrite => Reducer::Overwrite,
244                ReducerKind::Append => Reducer::Append,
245                ReducerKind::Sum => Reducer::Sum,
246            };
247            builder = builder.channel_with_reducer(name, reducer);
248        }
249        let mut schema = builder.build();
250        for (name, channel) in &self.state {
251            if let Some(default) = &channel.default
252                && let Some(declared) = schema.channels.get_mut(name)
253            {
254                declared.default = Some(default.clone());
255            }
256        }
257        schema
258    }
259
260    async fn store(&self) -> Result<Option<Arc<dyn Checkpointer>>, WorkflowError> {
261        match self.checkpoint.store {
262            CheckpointStore::Memory => Ok(Some(Arc::new(MemoryCheckpointer::new()))),
263            CheckpointStore::None => Ok(None),
264            CheckpointStore::Sqlite => self.sqlite_store().await,
265        }
266    }
267
268    #[cfg(feature = "sqlite")]
269    async fn sqlite_store(&self) -> Result<Option<Arc<dyn Checkpointer>>, WorkflowError> {
270        let path = self.checkpoint.path.as_deref().unwrap_or_default();
271        let path = match &self.source.base_dir {
272            Some(dir) if !std::path::Path::new(path).is_absolute() => dir.join(path),
273            _ => std::path::PathBuf::from(path),
274        };
275        let url = format!("sqlite://{}?mode=rwc", path.display());
276        let checkpointer =
277            crate::checkpoint::SqliteCheckpointer::new(&url).await.map_err(|error| {
278                self.source.error(vec![(
279                    "checkpoint.path".into(),
280                    format!("cannot open the SQLite checkpoint database: {error}"),
281                )])
282            })?;
283        Ok(Some(Arc::new(checkpointer)))
284    }
285
286    #[cfg(not(feature = "sqlite"))]
287    async fn sqlite_store(&self) -> Result<Option<Arc<dyn Checkpointer>>, WorkflowError> {
288        Err(self.source.error(vec![(
289            "checkpoint.store".into(),
290            "the `sqlite` store needs adk-graph's `sqlite` feature; rebuild with it, or register \
291             a checkpointer with WorkflowRegistry::checkpointer"
292                .into(),
293        )]))
294    }
295
296    fn node(
297        &self,
298        id: &str,
299        node: &NodeDefinition,
300        registry: &WorkflowRegistry,
301    ) -> Result<Arc<dyn Node>, (String, String)> {
302        let path = format!("nodes.{id}");
303        if let Some(name) = &node.agent {
304            let agent = registry.agents.get(name).cloned().ok_or_else(|| {
305                let known: Vec<&str> = registry.agents.keys().map(String::as_str).collect();
306                (
307                    format!("{path}.agent"),
308                    format!(
309                        "no agent named '{name}' is registered; registered agents: {}",
310                        if known.is_empty() { "none".to_string() } else { known.join(", ") }
311                    ),
312                )
313            })?;
314            return Ok(Arc::new(agent_node(id, agent, node)));
315        }
316        if let Some(llm) = &node.llm {
317            let agent = self
318                .llm_agent(id, llm, registry)
319                .map_err(|(field, message)| (format!("{path}.llm{field}"), message))?;
320            return Ok(Arc::new(agent_node(id, agent, node)));
321        }
322        if let Some(name) = &node.function {
323            let function = registry.functions.get(name).cloned().ok_or_else(|| {
324                (format!("{path}.function"), format!("no function named '{name}' is registered"))
325            })?;
326            return Ok(Arc::new(FunctionNode::new(id, move |ctx| function(ctx))));
327        }
328        if let Some(values) = &node.set {
329            let values = Arc::new(values.clone());
330            return Ok(Arc::new(FunctionNode::new(id, move |ctx| {
331                let values = Arc::clone(&values);
332                async move {
333                    let mut output = NodeOutput::new();
334                    for (key, value) in values.iter() {
335                        output = output.with_update(key, interpolate_value(value, &ctx.state));
336                    }
337                    Ok(output)
338                }
339            })));
340        }
341        if let Some(action) = &node.action {
342            let config = action_config(id, action, node.output_key.as_deref())
343                .map_err(|message| (format!("{path}.action"), message))?;
344            return Ok(Arc::new(ActionNodeExecutor::new(config)));
345        }
346        if let Some(interrupt) = &node.interrupt {
347            let message = interrupt.message.clone();
348            let schema = interrupt.response_schema.clone();
349            let key = node.output_key.clone().unwrap_or_else(|| id.to_string());
350            return Ok(Arc::new(FunctionNode::new(id, move |ctx| {
351                let (message, schema, key) = (message.clone(), schema.clone(), key.clone());
352                async move {
353                    if let Some(answer) = ctx.resume_value() {
354                        return Ok(NodeOutput::new().with_update(&key, answer.clone()));
355                    }
356                    let output =
357                        NodeOutput::interrupt(&interpolate_variables(&message, &ctx.state));
358                    Ok(match schema {
359                        Some(schema) => output.with_response_schema(schema),
360                        None => output,
361                    })
362                }
363            })));
364        }
365        Err((path, "the node has no kind".into()))
366    }
367
368    fn llm_agent(
369        &self,
370        id: &str,
371        llm: &LlmDefinition,
372        registry: &WorkflowRegistry,
373    ) -> Result<Arc<dyn Agent>, (String, String)> {
374        let model = registry
375            .resolve_model(self, &llm.model)
376            .map_err(|message| (".model".into(), message))?;
377        let mut builder = adk_agent::LlmAgentBuilder::new(id).model(model);
378        if let Some(instruction) = &llm.instruction {
379            builder = builder.instruction(instruction);
380        }
381        if let Some(description) = &llm.description {
382            builder = builder.description(description);
383        }
384        for (index, name) in llm.tools.iter().enumerate() {
385            let tool = registry.tools.get(name).cloned().ok_or_else(|| {
386                (format!(".tools[{index}]"), format!("no tool named '{name}' is registered"))
387            })?;
388            builder = builder.tool(tool);
389        }
390        let agent = builder.build().map_err(|error| (String::new(), error.message))?;
391        Ok(Arc::new(agent))
392    }
393}
394
395/// An agent node named `id`, whose input and output follow the node's `input` and `output_key`.
396fn agent_node(id: &str, agent: Arc<dyn Agent>, node: &NodeDefinition) -> AgentNode {
397    let mut built = AgentNode::new(agent).with_name(id);
398    if let Some(template) = node.input.clone() {
399        built = built.with_input_mapper(move |state| {
400            adk_core::Content::new("user").with_text(interpolate_variables(&template, state))
401        });
402    }
403    let key = node.output_key.clone();
404    built.with_output_mapper(move |events| {
405        let responses = response_texts(events);
406        let mut updates = HashMap::new();
407        if let Some(key) = &key {
408            updates.insert(key.clone(), json!(responses.last().cloned().unwrap_or_default()));
409        }
410        if !responses.is_empty() {
411            let messages: Vec<Value> = responses
412                .into_iter()
413                .map(|text| json!({ "role": "assistant", "content": text }))
414                .collect();
415            updates.insert("messages".to_string(), Value::Array(messages));
416        }
417        updates
418    })
419}
420
421/// The text of each model response in `events`, with a streamed response's deltas joined.
422fn response_texts(events: &[adk_core::Event]) -> Vec<String> {
423    let mut deltas = adk_core::EventTextDeltas::default();
424    let mut responses: Vec<(String, String)> = Vec::new();
425    for event in events {
426        let shown = deltas.push(event);
427        let text: String = shown
428            .content()
429            .map(|content| content.parts.iter().filter_map(adk_core::Part::text).collect())
430            .unwrap_or_default();
431        if text.is_empty() {
432            continue;
433        }
434        match responses.last_mut() {
435            Some((id, joined)) if *id == event.id => joined.push_str(&text),
436            _ => responses.push((event.id.clone(), text)),
437        }
438    }
439    responses.into_iter().map(|(_, text)| text).collect()
440}
441
442fn add_spec(mut graph: StateGraph, spec: &EdgeSpec) -> StateGraph {
443    let source = graph_id(&spec.from).to_string();
444    if let Some(to) = &spec.to {
445        for target in to.ids() {
446            graph = graph.add_edge(&source, graph_id(target));
447        }
448        return graph;
449    }
450    let default = graph_id(spec.default.as_deref().unwrap_or(END_ID)).to_string();
451    let mut targets: HashMap<String, EdgeTarget> = HashMap::new();
452    targets.insert(default.clone(), EdgeTarget::from(default.as_str()));
453    let router: crate::edge::RouterFn = if let Some(field) = &spec.switch {
454        let cases: Vec<(String, String)> = spec
455            .cases
456            .iter()
457            .map(|(value, target)| (value.trim().to_string(), graph_id(target).to_string()))
458            .collect();
459        for (_, target) in &cases {
460            targets.insert(target.clone(), EdgeTarget::from(target.as_str()));
461        }
462        let field = field.clone();
463        Arc::new(move |state: &State| {
464            let value = get_nested_value(state, &field).map(value_text).unwrap_or_default();
465            let value = value.trim();
466            cases
467                .iter()
468                .find(|(case, _)| case == value)
469                .map_or_else(|| default.clone(), |(_, target)| target.clone())
470        })
471    } else {
472        let routes: Vec<(Condition, String)> = spec
473            .routes
474            .iter()
475            .map(|route| (route.when.clone(), graph_id(&route.to).to_string()))
476            .collect();
477        for (_, target) in &routes {
478            targets.insert(target.clone(), EdgeTarget::from(target.as_str()));
479        }
480        Arc::new(move |state: &State| {
481            routes
482                .iter()
483                .find(|(condition, _)| holds(condition, state))
484                .map_or_else(|| default.clone(), |(_, target)| target.clone())
485        })
486    };
487    graph.edges.push(Edge::Conditional { source, router, targets });
488    graph
489}
490
491/// Whether `condition` holds over `state`, with `adk-action`'s switch operators.
492pub(crate) fn holds(condition: &Condition, state: &State) -> bool {
493    if let Some(all) = &condition.all {
494        return all.iter().all(|inner| holds(inner, state));
495    }
496    if let Some(any) = &condition.any {
497        return any.iter().any(|inner| holds(inner, state));
498    }
499    if let Some(inner) = &condition.not {
500        return !holds(inner, state);
501    }
502    let (Some(field), Some(op)) = (&condition.field, condition.op) else {
503        return false;
504    };
505    let value = match &condition.value {
506        Some(Value::Array(items)) => items.iter().map(value_text).collect::<Vec<_>>().join(","),
507        Some(value) => value_text(value),
508        None => String::new(),
509    };
510    let expression =
511        ExpressionMode { field: field.clone(), operator: op.action_name().to_string(), value };
512    crate::action::switch::evaluate_condition(&expression, state)
513}
514
515fn value_text(value: &Value) -> String {
516    match value {
517        Value::String(text) => text.clone(),
518        Value::Null => String::new(),
519        other => other.to_string(),
520    }
521}
522
523/// A `set` value with each string's `{{key}}` templates filled from state.
524fn interpolate_value(value: &Value, state: &State) -> Value {
525    match value {
526        Value::String(template) => Value::String(interpolate_variables(template, state)),
527        Value::Array(items) => {
528            Value::Array(items.iter().map(|item| interpolate_value(item, state)).collect())
529        }
530        Value::Object(fields) => Value::Object(
531            fields
532                .iter()
533                .map(|(key, item)| (key.clone(), interpolate_value(item, state)))
534                .collect(),
535        ),
536        other => other.clone(),
537    }
538}
539
540/// The `adk-action` config of an `action:` node, with the standard properties it leaves out
541/// taken from the node: its id and name, stop-on-error, tracing off, a 30 s timeout, and the
542/// node's `output_key` (else its id) as the output key.
543pub(crate) fn action_config(
544    id: &str,
545    action: &Value,
546    output_key: Option<&str>,
547) -> Result<ActionNodeConfig, String> {
548    let Value::Object(fields) = action else {
549        return Err("an action is a mapping with a `type`, such as `type: transform`".into());
550    };
551    if let Some(given) = fields.get("id").and_then(Value::as_str)
552        && given != id
553    {
554        return Err(format!("the action's id '{given}' differs from its node id '{id}'; omit it"));
555    }
556    let mut fields: Map<String, Value> = fields.clone();
557    let defaults = [
558        ("id", json!(id)),
559        ("name", json!(id)),
560        ("errorHandling", json!({ "mode": "stop" })),
561        ("tracing", json!({ "enabled": false, "logLevel": "none" })),
562        ("callbacks", json!({})),
563        ("execution", json!({ "timeout": 30_000 })),
564        ("mapping", json!({ "outputKey": output_key.unwrap_or(id) })),
565    ];
566    for (key, value) in defaults {
567        fields.entry(key).or_insert(value);
568    }
569    serde_json::from_value(Value::Object(fields))
570        .map_err(|error| format!("not a valid action: {error}"))
571}
572
573#[cfg(test)]
574mod tests {
575    use super::*;
576    use adk_core::{Content, Event};
577
578    fn chunk(id: &str, text: &str, partial: bool) -> Event {
579        let mut event = Event::new("invocation");
580        event.id = id.to_string();
581        event.llm_response.partial = partial;
582        event.set_content(Content::new("model").with_text(text));
583        event
584    }
585
586    #[test]
587    fn a_streamed_response_is_one_text() {
588        let mut terminal = chunk("r1", "Your refund is approved.", false);
589        terminal.llm_response.provider_metadata = Some(json!({ "content_complete": true }));
590        let events = [
591            chunk("r1", "Your refund", true),
592            chunk("r1", " is approved", true),
593            chunk("r1", ".", true),
594            terminal,
595            chunk("r2", "Anything else?", false),
596        ];
597        assert_eq!(response_texts(&events), ["Your refund is approved.", "Anything else?"]);
598    }
599}