gadk_engine/workflow/nodes/
tool.rs1use std::any::Any;
19use std::collections::BTreeMap;
20use std::sync::Arc;
21
22use gadk_agent::{AgentError, Context, ContextDelta, EventStream, Tool};
23use gadk_genai::{Content, Part};
24use gadk_session::{Event, EventActions};
25use serde_json::{Map, Value, json};
26
27use crate::error::{WorkflowError, WorkflowErrorKind};
28use crate::tool::utils::CompiledSchema;
29use crate::workflow::route::go_quote;
30use crate::workflow::{BaseNode, Node, NodeConfig};
31
32struct ToolInner {
34 base: BaseNode,
35 tool: Arc<dyn Tool>,
36}
37
38pub struct ToolNode {
40 inner: Arc<ToolInner>,
41}
42
43impl ToolNode {
44 pub fn new(tool: Arc<dyn Tool>, cfg: NodeConfig) -> Result<Arc<ToolNode>, WorkflowError> {
47 Self::build("", tool, None, None, cfg)
48 }
49
50 pub fn named(
52 name: &str,
53 tool: Arc<dyn Tool>,
54 cfg: NodeConfig,
55 ) -> Result<Arc<ToolNode>, WorkflowError> {
56 Self::build(name, tool, None, None, cfg)
57 }
58
59 pub fn with_schemas(
61 tool: Arc<dyn Tool>,
62 input: Option<Value>,
63 output: Option<Value>,
64 cfg: NodeConfig,
65 ) -> Result<Arc<ToolNode>, WorkflowError> {
66 Self::build("", tool, input, output, cfg)
67 }
68
69 fn build(
71 name: &str,
72 tool: Arc<dyn Tool>,
73 input: Option<Value>,
74 output: Option<Value>,
75 cfg: NodeConfig,
76 ) -> Result<Arc<ToolNode>, WorkflowError> {
77 let name = if name.is_empty() {
78 tool.name().to_string()
79 } else {
80 name.to_string()
81 };
82 let input = input.unwrap_or_else(|| json!({}));
83 let output = output.unwrap_or_else(|| json!({}));
84 let err = |what: &str, e: String| {
85 WorkflowError::new(
86 WorkflowErrorKind::Other,
87 format!(
88 "resolving {what} schema for tool {}: {e}",
89 go_quote(tool.name())
90 ),
91 )
92 };
93 CompiledSchema::new(input.clone()).map_err(|e| err("input", e))?;
94 CompiledSchema::new(output.clone()).map_err(|e| err("output", e))?;
95 if tool.as_runnable().is_none() {
96 return Err(not_runnable(tool.name()));
97 }
98 let base =
99 BaseNode::with_schemas(&name, tool.description(), Some(input), Some(output), cfg)?;
100 Ok(Arc::new(ToolNode {
101 inner: Arc::new(ToolInner { base, tool }),
102 }))
103 }
104}
105
106fn not_runnable(tool_name: &str) -> WorkflowError {
109 WorkflowError::new(
110 WorkflowErrorKind::Other,
111 format!(
112 "tool {} (type dyn Tool) is not directly runnable in workflow node",
113 go_quote(tool_name)
114 ),
115 )
116}
117
118impl ToolInner {
119 async fn run_tool(&self, tool_ctx: Context, input: Value) -> Result<Value, AgentError> {
122 let input = match input {
123 Value::String(s) => match serde_json::from_str::<Map<String, Value>>(&s) {
124 Ok(m) => Value::Object(m),
125 Err(_) => Value::String(s),
126 },
127 v => v,
128 };
129 let name = self.tool.name();
130 let tool_input = self.base.validate_input(input).map_err(|e| {
131 AgentError::from(
132 WorkflowError::new(
133 e.kind(),
134 format!("converting input for tool {}: {e}", go_quote(name)),
135 )
136 .with_source(e.into()),
137 )
138 })?;
139 let Some(runnable) = self.tool.as_runnable() else {
140 return Err(not_runnable(name).into());
141 };
142 match runnable.run(tool_ctx, tool_input).await {
143 Ok(out) => Ok(Value::Object(out)),
144 Err(e) => {
145 let msg = format!("tool {} execution failed: {e}", go_quote(name));
146 Err(WorkflowError::new(WorkflowErrorKind::Other, msg)
147 .with_source(AgentError::Tool {
148 tool: name.to_string(),
149 source: e,
150 })
151 .into())
152 }
153 }
154 }
155
156 fn validate_output(&self, out: Value) -> Result<Value, WorkflowError> {
159 if self.base.output_schema().is_none() {
160 return Ok(out);
161 }
162 if let Ok(v) = self.base.validate_output(out.clone()) {
163 return Ok(v);
164 }
165 if let Some(inner) = out.as_object().and_then(|m| m.get("result"))
166 && let Ok(v) = self.base.validate_output(inner.clone())
167 {
168 return Ok(v);
169 }
170 self.base.validate_output(out)
171 }
172}
173
174impl Node for ToolNode {
175 fn name(&self) -> &str {
176 self.inner.base.name()
177 }
178 fn description(&self) -> &str {
179 self.inner.base.description()
180 }
181 fn config(&self) -> &NodeConfig {
182 self.inner.base.config()
183 }
184 fn input_schema(&self) -> Option<&Value> {
185 self.inner.base.input_schema()
186 }
187 fn output_schema(&self) -> Option<&Value> {
188 self.inner.base.output_schema()
189 }
190 fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
191 self.inner.base.validate_input(v)
192 }
193 fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
194 self.inner.validate_output(v)
195 }
196 fn run(&self, ctx: Context, input: Value) -> EventStream {
200 let inner = Arc::clone(&self.inner);
201 Box::pin(async_stream::stream! {
202 let actions = Arc::new(parking_lot::Mutex::new(EventActions {
203 state_delta: Some(Map::new()),
204 artifact_delta: Some(BTreeMap::new()),
205 ..EventActions::default()
206 }));
207 let tool_ctx = ctx.with_delta(ContextDelta {
209 function_call_id: Some(ctx.platform().new_uuid()),
210 actions: Some(Arc::clone(&actions)),
211 tool_confirmation: Some(None),
212 ..ContextDelta::default()
213 });
214 let output = match inner.run_tool(tool_ctx, input).await {
215 Ok(o) => o,
216 Err(e) => {
217 yield Err(e);
218 return;
219 }
220 };
221 let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
222 let mut acts = actions.lock().clone();
223 acts.compaction = None;
225 ev.actions = acts;
226 if let Value::String(s) = &output {
227 ev.response.content = Some(Content {
228 parts: vec![Part::from_text(s.clone())],
229 ..Content::default()
230 });
231 }
232 ev.output = Some(output);
233 yield Ok(ev);
234 })
235 }
236 fn as_any(&self) -> &dyn Any {
237 self
238 }
239}