gemini_adk_rs/orchestration/
mod.rs1use std::future::Future;
20use std::sync::Arc;
21
22use serde_json::Value;
23
24use crate::AsyncSourceFn;
25use crate::error::AgentError;
26use crate::llm::{BaseLlm, LlmRequest};
27use crate::state::State;
28use crate::text::TextAgent;
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum AgentMode {
33 Call,
36 Dispatch,
38 Background,
41}
42
43pub fn result_key(name: &str) -> String {
45 format!("{name}:result")
46}
47
48pub fn error_key(name: &str) -> String {
50 format!("{name}:error")
51}
52
53pub fn provenance(state: &State, key: &str) -> Option<String> {
56 state
57 .get::<serde_json::Value>(&format!("state_meta:{key}"))
58 .and_then(|m| m.get("source").and_then(|s| s.as_str().map(String::from)))
59}
60
61pub async fn call_agent(
68 name: &str,
69 agent: Arc<dyn TextAgent>,
70 state: &State,
71) -> Result<String, AgentError> {
72 let result = agent.run(state).await;
73 match &result {
74 Ok(r) => {
75 let key = result_key(name);
76 let _ = state.set(
77 format!("state_meta:{key}"),
78 serde_json::json!({ "source": "agent", "resolver": name }),
79 );
80 let _ = state.set(key, r);
81 }
82 Err(e) => {
83 let _ = state.set(error_key(name), e.to_string());
84 }
85 }
86 result
87}
88
89enum Source {
90 Agent(Arc<dyn TextAgent>),
92 Fetch(AsyncSourceFn),
95 Llm {
97 llm: Arc<dyn BaseLlm>,
99 prompt: String,
101 },
102}
103
104fn interpolate(template: &str, state: &State) -> String {
106 crate::utils::text::interpolate_with(template, |key| state.get::<serde_json::Value>(key))
107}
108
109pub struct Resolver {
121 name: String,
122 source: Source,
123}
124
125impl Resolver {
126 pub fn agent(name: impl Into<String>, agent: Arc<dyn TextAgent>) -> Self {
128 Self {
129 name: name.into(),
130 source: Source::Agent(agent),
131 }
132 }
133
134 pub fn fetch<F, Fut>(name: impl Into<String>, f: F) -> Self
138 where
139 F: Fn(State) -> Fut + Send + Sync + 'static,
140 Fut: Future<Output = Result<Value, String>> + Send + 'static,
141 {
142 let f = Arc::new(f);
143 Self {
144 name: name.into(),
145 source: Source::Fetch(Arc::new(move |state| {
146 let f = f.clone();
147 Box::pin(async move { f(state).await })
148 })),
149 }
150 }
151
152 pub fn llm(name: impl Into<String>, llm: Arc<dyn BaseLlm>, prompt: impl Into<String>) -> Self {
155 Self {
156 name: name.into(),
157 source: Source::Llm {
158 llm,
159 prompt: prompt.into(),
160 },
161 }
162 }
163
164 pub fn name(&self) -> &str {
166 &self.name
167 }
168
169 fn source_kind(&self) -> &'static str {
171 match &self.source {
172 Source::Agent(_) => "agent",
173 Source::Fetch(_) => "fetch",
174 Source::Llm { .. } => "llm",
175 }
176 }
177
178 pub async fn resolve(&self, state: &State) -> Result<Value, String> {
182 let outcome = match &self.source {
183 Source::Agent(a) => a
184 .run(state)
185 .await
186 .map(Value::from)
187 .map_err(|e| e.to_string()),
188 Source::Fetch(f) => f(state.clone()).await,
189 Source::Llm { llm, prompt } => {
190 let rendered = interpolate(prompt, state);
191 llm.generate(LlmRequest::from_text(rendered))
192 .await
193 .map(|r| Value::from(r.text()))
194 .map_err(|e| e.to_string())
195 }
196 };
197 match &outcome {
198 Ok(v) => {
199 let key = result_key(&self.name);
200 let _ = state.set(
201 format!("state_meta:{key}"),
202 serde_json::json!({ "source": self.source_kind(), "resolver": self.name }),
203 );
204 let _ = state.set(key, v.clone());
205 }
206 Err(e) => {
207 let _ = state.set(error_key(&self.name), e);
208 }
209 }
210 outcome
211 }
212
213 pub fn dispatch(self, state: State) {
217 tokio::spawn(async move {
218 let _ = self.resolve(&state).await;
219 });
220 }
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226 use async_trait::async_trait;
227 use serde_json::json;
228
229 struct Echo(&'static str);
230 #[async_trait]
231 impl TextAgent for Echo {
232 fn name(&self) -> &str {
233 "echo"
234 }
235 async fn run(&self, _state: &State) -> Result<String, AgentError> {
236 Ok(self.0.to_string())
237 }
238 }
239
240 struct Boom;
241 #[async_trait]
242 impl TextAgent for Boom {
243 fn name(&self) -> &str {
244 "boom"
245 }
246 async fn run(&self, _state: &State) -> Result<String, AgentError> {
247 Err(AgentError::Other("kaboom".into()))
248 }
249 }
250
251 #[tokio::test]
252 async fn call_writes_result_to_state() {
253 let state = State::new();
254 let out = call_agent("verify", Arc::new(Echo("ok-123")), &state)
255 .await
256 .unwrap();
257 assert_eq!(out, "ok-123");
258 assert_eq!(
259 state.get::<String>("verify:result").as_deref(),
260 Some("ok-123")
261 );
262 }
263
264 #[tokio::test]
265 async fn call_writes_error_to_state() {
266 let state = State::new();
267 let r = call_agent("verify", Arc::new(Boom), &state).await;
268 assert!(r.is_err());
269 assert!(state.contains("verify:error"));
270 assert!(!state.contains("verify:result"));
271 }
272
273 #[tokio::test]
274 async fn resolver_fetch_binds_state_and_writes_result() {
275 let state = State::new();
276 let _ = state.set("slot", "afternoon");
277 let r = Resolver::fetch("availability", |s: State| async move {
278 let slot = s.get::<String>("slot").unwrap_or_default();
280 Ok(json!({ "open": slot == "afternoon" }))
281 });
282 let out = r.resolve(&state).await.unwrap();
283 assert_eq!(out, json!({ "open": true }));
284 assert_eq!(
285 state.get::<Value>("availability:result"),
286 Some(json!({ "open": true }))
287 );
288 assert_eq!(
290 provenance(&state, "availability:result").as_deref(),
291 Some("fetch")
292 );
293 }
294
295 #[tokio::test]
296 async fn resolver_agent_uses_result_convention() {
297 let state = State::new();
298 Resolver::agent("verify", Arc::new(Echo("ok-9")))
300 .resolve(&state)
301 .await
302 .unwrap();
303 assert_eq!(
304 state.get::<String>("verify:result").as_deref(),
305 Some("ok-9")
306 );
307 }
308
309 #[tokio::test]
310 async fn resolver_fetch_records_error() {
311 let state = State::new();
312 let r = Resolver::fetch("lookup", |_s: State| async move {
313 Err::<Value, String>("upstream 503".into())
314 });
315 assert!(r.resolve(&state).await.is_err());
316 assert_eq!(
317 state.get::<String>("lookup:error").as_deref(),
318 Some("upstream 503")
319 );
320 assert!(!state.contains("lookup:result"));
321 }
322
323 #[tokio::test]
324 async fn resolver_llm_interpolates_prompt_and_stores_text() {
325 use crate::llm::MockLlm;
326
327 let state = State::new();
329 let _ = state.set("topic", "billing");
330 let out = Resolver::llm(
331 "summary",
332 Arc::new(MockLlm::echo()),
333 "Summarize the {topic} issue",
334 )
335 .resolve(&state)
336 .await
337 .unwrap();
338 assert_eq!(out, json!("Summarize the billing issue"));
339 assert_eq!(
340 state.get::<String>("summary:result").as_deref(),
341 Some("Summarize the billing issue")
342 );
343 }
344
345 #[tokio::test]
346 async fn resolver_dispatch_runs_detached() {
347 let state = State::new();
348 Resolver::fetch("ping", |_s: State| async move { Ok(json!("pong")) })
349 .dispatch(state.clone());
350 for _ in 0..100 {
352 if state.contains("ping:result") {
353 break;
354 }
355 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
356 }
357 assert_eq!(state.get::<String>("ping:result").as_deref(), Some("pong"));
358 }
359}