gadk_engine/workflow/
base_node.rs1use std::sync::Arc;
19
20use gadk_agent::AgentError;
21use gadk_session::Event;
22use serde_json::Value;
23
24use crate::error::{WorkflowError, WorkflowErrorKind};
25use crate::tool::utils::CompiledSchema;
26use crate::workflow::route::go_quote;
27use crate::workflow::validation::default_validate_input;
28use crate::workflow::{Node, NodeConfig};
29
30#[derive(Clone)]
33pub struct BaseNode {
34 name: String,
35 description: String,
36 config: NodeConfig,
37 input: Option<Arc<CompiledSchema>>,
38 output: Option<Arc<CompiledSchema>>,
39}
40
41pub(crate) fn compile_schema(schema: Option<Value>) -> Result<Option<Arc<CompiledSchema>>, String> {
43 match schema {
44 None => Ok(None),
45 Some(v) => CompiledSchema::new(v).map(|c| Some(Arc::new(c))),
46 }
47}
48
49impl BaseNode {
50 pub(crate) fn from_compiled(
52 name: &str,
53 description: &str,
54 cfg: NodeConfig,
55 input: Option<Arc<CompiledSchema>>,
56 output: Option<Arc<CompiledSchema>>,
57 ) -> Self {
58 Self {
59 name: name.to_owned(),
60 description: description.to_owned(),
61 config: cfg,
62 input,
63 output,
64 }
65 }
66
67 pub fn with_schemas(
70 name: &str,
71 description: &str,
72 input: Option<Value>,
73 output: Option<Value>,
74 cfg: NodeConfig,
75 ) -> Result<Self, WorkflowError> {
76 let input = compile_schema(input).map_err(|e| {
77 WorkflowError::new(
78 WorkflowErrorKind::Other,
79 format!("resolving input schema for node {}: {e}", go_quote(name)),
80 )
81 })?;
82 let output = compile_schema(output).map_err(|e| {
83 WorkflowError::new(
84 WorkflowErrorKind::Other,
85 format!("resolving output schema for node {}: {e}", go_quote(name)),
86 )
87 })?;
88 Ok(Self::from_compiled(name, description, cfg, input, output))
89 }
90
91 pub fn new(name: &str, description: &str, cfg: NodeConfig) -> Self {
93 Self::from_compiled(name, description, cfg, None, None)
94 }
95
96 pub fn name(&self) -> &str {
98 &self.name
99 }
100
101 pub fn description(&self) -> &str {
103 &self.description
104 }
105
106 pub fn config(&self) -> &NodeConfig {
108 &self.config
109 }
110
111 pub fn input_schema(&self) -> Option<&Value> {
113 self.input.as_deref().map(CompiledSchema::schema)
114 }
115
116 pub fn output_schema(&self) -> Option<&Value> {
118 self.output.as_deref().map(CompiledSchema::schema)
119 }
120
121 pub(crate) fn input_compiled(&self) -> Option<&CompiledSchema> {
123 self.input.as_deref()
124 }
125
126 pub(crate) fn output_compiled(&self) -> Option<&CompiledSchema> {
128 self.output.as_deref()
129 }
130
131 pub fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
134 default_validate_input(v, self.input_compiled())
135 .map_err(|m| WorkflowError::new(WorkflowErrorKind::InputValidation, m))
136 }
137
138 pub fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
141 default_validate_output(v, self.output_compiled())
142 .map_err(|m| WorkflowError::new(WorkflowErrorKind::OutputValidation, m))
143 }
144}
145
146pub(crate) fn default_validate_output(
150 out: Value,
151 schema: Option<&CompiledSchema>,
152) -> Result<Value, String> {
153 let Some(schema) = schema else { return Ok(out) };
154 if out.is_null() {
155 return Ok(out);
156 }
157 let err = match schema.validate(&out) {
158 Ok(()) => return Ok(out),
159 Err(e) => e,
160 };
161 if let Value::String(text) = &out
162 && let Some(v) = project_text_onto_schema(text, schema)
163 {
164 return Ok(v);
165 }
166 Err(err)
167}
168
169#[cfg(test)]
174pub(crate) fn default_validate_content_output(
175 content: &gadk_genai::Content,
176 schema: Option<&CompiledSchema>,
177) -> Result<Value, String> {
178 let v = serde_json::to_value(content).map_err(|e| e.to_string())?;
179 let Some(schema) = schema else { return Ok(v) };
180 let err = match schema.validate(&v) {
181 Ok(()) => return Ok(v),
182 Err(e) => e,
183 };
184 let text: String = content
185 .parts
186 .iter()
187 .filter(|p| !p.text.is_empty() && !p.thought)
188 .map(|p| p.text.as_str())
189 .collect();
190 project_text_onto_schema(&text, schema).ok_or(err)
191}
192
193fn project_text_onto_schema(s: &str, schema: &CompiledSchema) -> Option<Value> {
197 if root_schema_is_string(schema) {
198 let v = Value::String(s.to_owned());
199 return schema.validate(&v).ok().map(|()| v);
200 }
201 if s.trim().is_empty() {
202 return None;
203 }
204 let parsed: Value = serde_json::from_str(s).ok()?;
205 schema.validate(&parsed).ok().map(|()| parsed)
206}
207
208fn root_schema_is_string(schema: &CompiledSchema) -> bool {
210 match schema.schema().get("type") {
211 Some(Value::String(t)) => t == "string",
212 Some(Value::Array(ts)) => ts.iter().any(|t| t == "string"),
213 _ => false,
214 }
215}
216
217pub(crate) fn validate_and_stamp_output(
221 n: &dyn Node,
222 out: Value,
223 ev: &mut Event,
224) -> Result<Value, AgentError> {
225 let validated = n.validate_output(out).map_err(|e| {
226 let msg = format!(
227 "{}: output validation failed for node {}: {}",
228 WorkflowError::sentinel_text(WorkflowErrorKind::NodeFailed),
229 go_quote(n.name()),
230 e
231 );
232 AgentError::from(
233 WorkflowError::new(WorkflowErrorKind::OutputValidation, msg).with_source(e.into()),
234 )
235 })?;
236 if ev.output.is_some() {
237 ev.output = Some(validated.clone());
238 }
239 Ok(validated)
240}