gadk_engine/workflow/nodes/
agent.rs1use std::any::Any;
19use std::sync::Arc;
20
21use futures::StreamExt;
22use gadk_agent::{Agent, AgentError, Context, ContextDelta, EventStream, Mode};
23use gadk_genai::{Content, Schema};
24use gadk_session::{Event, EventActions, NodeInfo};
25use serde_json::{Map, Value, json};
26
27use crate::error::{WorkflowError, WorkflowErrorKind};
28use crate::llm::mode::{resolve_mode, with_bound_mode};
29use crate::llm::node_wrapper::run_llm_agent_as_node;
30use crate::llm::output_schema_binding::with_bound_output_schema;
31use crate::llm::processors::go_json_marshal;
32use crate::llm::state::reveal;
33use crate::workflow::base_node::compile_schema;
34use crate::workflow::model_output_schema::model_output_schema;
35use crate::workflow::route::go_quote;
36use crate::workflow::scheduler::message_text;
37use crate::workflow::{BaseNode, Node, NodeConfig};
38
39pub struct AgentNode {
41 pub(crate) base: BaseNode,
42 pub(crate) agent: Arc<dyn Agent>,
43 pub(crate) model_output_schema: Option<Schema>,
47}
48
49impl AgentNode {
50 pub fn new(agent: Arc<dyn Agent>, cfg: NodeConfig) -> Result<Arc<AgentNode>, WorkflowError> {
52 Self::with_schemas(agent, None, None, cfg)
53 }
54
55 pub fn with_schemas(
58 agent: Arc<dyn Agent>,
59 input: Option<Value>,
60 output: Option<Value>,
61 mut cfg: NodeConfig,
62 ) -> Result<Arc<AgentNode>, WorkflowError> {
63 let input = compile_schema(Some(input.unwrap_or_else(|| json!({})))).map_err(|e| {
64 WorkflowError::new(
65 WorkflowErrorKind::Other,
66 format!(
67 "resolving input schema for agent {}: {e}",
68 go_quote(agent.name())
69 ),
70 )
71 })?;
72 let output = output.unwrap_or_else(|| json!({}));
73 let model_output_schema = model_output_schema(Some(&output));
74 let output = compile_schema(Some(output)).map_err(|e| {
75 WorkflowError::new(
76 WorkflowErrorKind::Other,
77 format!(
78 "resolving output schema for agent {}: {e}",
79 go_quote(agent.name())
80 ),
81 )
82 })?;
83 cfg.emits_own_span = true;
85 let base = BaseNode::from_compiled(agent.name(), agent.description(), cfg, input, output);
86 Ok(Arc::new(AgentNode {
87 base,
88 agent,
89 model_output_schema,
90 }))
91 }
92
93 pub fn agent(&self) -> &Arc<dyn Agent> {
95 &self.agent
96 }
97}
98
99impl Node for AgentNode {
100 fn name(&self) -> &str {
101 self.base.name()
102 }
103 fn description(&self) -> &str {
104 self.base.description()
105 }
106 fn config(&self) -> &NodeConfig {
107 self.base.config()
108 }
109 fn input_schema(&self) -> Option<&Value> {
110 self.base.input_schema()
111 }
112 fn output_schema(&self) -> Option<&Value> {
113 self.base.output_schema()
114 }
115 fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
116 self.base.validate_input(v)
117 }
118 fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
119 self.base.validate_output(v)
120 }
121 fn run(&self, ctx: Context, input: Value) -> EventStream {
126 let agent = Arc::clone(self.agent());
127 let model_output_schema = self.model_output_schema.clone();
128 Box::pin(async_stream::stream! {
129 let user_content = match node_input_to_content(&input) {
130 Ok(c) => c,
131 Err(e) => {
132 yield Err(e);
133 return;
134 }
135 };
136 let declared_mode: Option<Mode> = reveal(agent.as_ref()).map(|s| s.cfg.mode);
137 let mut delta = ContextDelta {
140 agent: Some(Arc::clone(&agent)),
141 user_content: Some(user_content),
142 path: Some(String::new()),
143 run_id: Some(String::new()),
144 sub_scheduler: Some(None),
145 output_for_ancestors: Some(Vec::new()),
146 resumed_inputs: Some(Arc::new(Map::new())),
147 tool_confirmation: Some(None),
149 actions: Some(Arc::new(parking_lot::Mutex::new(EventActions::default()))),
150 fresh_end_flag: true,
151 ..ContextDelta::default()
152 };
153 if let Some(declared) = declared_mode {
154 let mode = resolve_mode(declared, Mode::SingleTurn);
157 let bound = with_bound_mode(ctx.as_invocation(), agent.name(), agent.agent_state(), mode);
158 let bound = with_bound_output_schema(
162 &bound,
163 agent.name(),
164 agent.agent_state(),
165 model_output_schema.clone(),
166 );
167 delta.bound_modes = Some(bound.bound_modes().clone());
168 }
169 let ex_ctx = ctx.with_delta(delta);
170 let mut events = if declared_mode.is_some() {
172 run_llm_agent_as_node(ex_ctx, Arc::clone(&agent), input)
173 } else {
174 agent.run(ex_ctx.as_invocation().clone())
175 };
176 let synthesize = declared_mode != Some(Mode::Task);
178 let scope = ctx.isolation_scope();
179 while let Some(item) = events.next().await {
180 let mut ev = match item {
181 Ok(ev) => ev,
182 Err(e) => {
183 yield Err(e);
184 return;
185 }
186 };
187 if synthesize && is_own_agent_event(&ev, agent.name()) {
190 synthesize_agent_output(&mut ev);
191 }
192 if !scope.is_empty() && ev.isolation_scope.is_empty() {
194 ev.isolation_scope = scope.clone();
195 }
196 yield Ok(ev);
197 }
198 })
199 }
200 fn as_any(&self) -> &dyn Any {
201 self
202 }
203}
204
205pub(crate) fn synthesize_agent_output(ev: &mut Event) {
209 if ev.output.is_some() || !ev.is_final_response() || !ev.long_running_tool_ids.is_empty() {
210 return;
211 }
212 if let Some(text) = message_text(ev) {
213 ev.output = Some(Value::String(text));
214 ev.node_info
215 .get_or_insert_with(NodeInfo::default)
216 .message_as_output = true;
217 }
218}
219
220pub(crate) fn is_own_agent_event(ev: &Event, node_agent_name: &str) -> bool {
222 ev.author.is_empty() || ev.author == node_agent_name
223}
224
225pub(crate) fn node_input_to_content(input: &Value) -> Result<Option<Content>, AgentError> {
230 match input {
231 Value::Null => Ok(None),
232 Value::String(s) => Ok(Some(Content::from_text(s.clone(), "user"))),
233 other => Ok(Some(Content::from_text(go_json_marshal(other), "user"))),
234 }
235}