1use std::collections::HashMap;
7use std::path::Path;
8
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct AgentConfig {
32 pub name: String,
34
35 #[serde(default)]
37 pub model: Option<String>,
38
39 #[serde(default)]
41 pub instruction: Option<String>,
42
43 #[serde(default)]
45 pub description: Option<String>,
46
47 #[serde(default)]
49 pub tools: Vec<ToolConfig>,
50
51 #[serde(default)]
53 pub sub_agents: Vec<AgentConfig>,
54
55 #[serde(default)]
57 pub temperature: Option<f32>,
58
59 #[serde(default)]
61 pub max_output_tokens: Option<u32>,
62
63 #[serde(default)]
65 pub thinking_budget: Option<u32>,
66
67 #[serde(default)]
69 pub output_key: Option<String>,
70
71 #[serde(default)]
73 pub output_schema: Option<serde_json::Value>,
74
75 #[serde(default)]
77 pub max_llm_calls: Option<u32>,
78
79 #[serde(default = "default_agent_type")]
81 pub agent_type: String,
82
83 #[serde(default)]
85 pub max_iterations: Option<u32>,
86
87 #[serde(default)]
89 pub metadata: HashMap<String, serde_json::Value>,
90
91 #[serde(default)]
93 pub voice: Option<String>,
94
95 #[serde(default)]
97 pub greeting: Option<String>,
98
99 #[serde(default)]
101 pub transcription: Option<bool>,
102
103 #[serde(default)]
105 pub a2a: Option<bool>,
106
107 #[serde(default)]
109 pub env: HashMap<String, String>,
110}
111
112pub fn default_agent_type() -> String {
116 "llm".to_string()
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct ToolConfig {
122 #[serde(default)]
124 pub name: Option<String>,
125
126 #[serde(default)]
128 pub description: Option<String>,
129
130 #[serde(default)]
132 pub builtin: Option<String>,
133
134 #[serde(default)]
136 pub parameters: Option<serde_json::Value>,
137}
138
139#[derive(Debug, thiserror::Error)]
141pub enum AgentConfigError {
142 #[error("IO error: {0}")]
144 Io(#[from] std::io::Error),
145
146 #[error("YAML parse error: {0}")]
148 Yaml(String),
149
150 #[error("TOML parse error: {0}")]
152 Toml(String),
153
154 #[error("JSON parse error: {0}")]
156 Json(#[from] serde_json::Error),
157
158 #[error("Invalid config: {0}")]
160 Invalid(String),
161}
162
163impl AgentConfig {
164 pub fn from_yaml_file(path: &Path) -> Result<Self, AgentConfigError> {
166 let content = std::fs::read_to_string(path)?;
167 Self::from_yaml(&content)
168 }
169
170 pub fn from_yaml(yaml: &str) -> Result<Self, AgentConfigError> {
172 serde_json::from_value(
173 serde_json::to_value(
174 serde_json::from_str::<serde_json::Value>(yaml)
177 .map_err(|e| AgentConfigError::Yaml(e.to_string()))?,
178 )
179 .map_err(|e| AgentConfigError::Yaml(e.to_string()))?,
180 )
181 .map_err(|e| AgentConfigError::Yaml(e.to_string()))
182 }
183
184 pub fn from_json(json: &str) -> Result<Self, AgentConfigError> {
186 Ok(serde_json::from_str(json)?)
187 }
188
189 pub fn from_value(value: serde_json::Value) -> Result<Self, AgentConfigError> {
191 Ok(serde_json::from_value(value)?)
192 }
193
194 pub fn validate(&self) -> Result<(), AgentConfigError> {
196 if self.name.is_empty() {
197 return Err(AgentConfigError::Invalid("Agent name is required".into()));
198 }
199 if let Some(temp) = self.temperature
200 && !(0.0..=2.0).contains(&temp)
201 {
202 return Err(AgentConfigError::Invalid(format!(
203 "Temperature must be 0.0-2.0, got {temp}"
204 )));
205 }
206 for sub in &self.sub_agents {
208 sub.validate()?;
209 }
210 Ok(())
211 }
212
213 pub fn builtin_tools(&self) -> Vec<&str> {
215 self.tools
216 .iter()
217 .filter_map(|t| t.builtin.as_deref())
218 .collect()
219 }
220
221 pub fn is_workflow(&self) -> bool {
223 matches!(self.agent_type.as_str(), "sequential" | "parallel" | "loop")
224 }
225}
226
227pub fn discover_agent_configs(dir: &Path) -> Result<Vec<AgentConfig>, AgentConfigError> {
232 let candidates = ["agent.json", "root_agent.json", "agent.toml"];
233
234 let mut configs = Vec::new();
235 for candidate in &candidates {
236 let path = dir.join(candidate);
237 if path.exists() {
238 let content = std::fs::read_to_string(&path)?;
239 let config: AgentConfig = if candidate.ends_with(".json") {
240 serde_json::from_str(&content)?
241 } else if candidate.ends_with(".toml") {
242 return Err(AgentConfigError::Toml(
244 "TOML parsing requires the gemini-adk-cli-rs crate".into(),
245 ));
246 } else {
247 return Err(AgentConfigError::Yaml(
248 "YAML parsing requires the gemini-adk-cli-rs crate".into(),
249 ));
250 };
251 config.validate()?;
252 configs.push(config);
253 }
254 }
255
256 if let Ok(entries) = std::fs::read_dir(dir) {
258 for entry in entries.flatten() {
259 let path = entry.path();
260 if path.is_dir()
261 && let Ok(sub_configs) = discover_agent_configs(&path)
262 {
263 configs.extend(sub_configs);
264 }
265 }
266 }
267
268 Ok(configs)
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274
275 #[test]
276 fn parse_minimal_json_config() {
277 let json = r#"{"name": "test_agent"}"#;
278 let config = AgentConfig::from_json(json).unwrap();
279 assert_eq!(config.name, "test_agent");
280 assert_eq!(config.agent_type, "llm");
281 assert!(config.model.is_none());
282 assert!(config.tools.is_empty());
283 }
284
285 #[test]
286 fn parse_full_json_config() {
287 let json = r#"{
288 "name": "weather_agent",
289 "model": "gemini-2.0-flash",
290 "instruction": "You are a weather assistant.",
291 "description": "Gets weather info",
292 "temperature": 0.3,
293 "max_output_tokens": 1024,
294 "output_key": "weather_result",
295 "max_llm_calls": 10,
296 "tools": [
297 {"name": "get_weather", "description": "Get weather for a city"},
298 {"builtin": "google_search"}
299 ],
300 "sub_agents": [
301 {"name": "forecast", "instruction": "Give forecasts"}
302 ]
303 }"#;
304 let config = AgentConfig::from_json(json).unwrap();
305 assert_eq!(config.name, "weather_agent");
306 assert_eq!(config.model.as_deref(), Some("gemini-2.0-flash"));
307 assert_eq!(config.temperature, Some(0.3));
308 assert_eq!(config.output_key.as_deref(), Some("weather_result"));
309 assert_eq!(config.max_llm_calls, Some(10));
310 assert_eq!(config.tools.len(), 2);
311 assert_eq!(config.sub_agents.len(), 1);
312 assert_eq!(config.builtin_tools(), vec!["google_search"]);
313 }
314
315 #[test]
316 fn validate_empty_name_fails() {
317 let config = AgentConfig::from_json(r#"{"name": ""}"#).unwrap();
318 assert!(config.validate().is_err());
319 }
320
321 #[test]
322 fn validate_bad_temperature_fails() {
323 let config = AgentConfig::from_json(r#"{"name": "test", "temperature": 3.0}"#).unwrap();
324 assert!(config.validate().is_err());
325 }
326
327 #[test]
328 fn validate_good_config_passes() {
329 let config = AgentConfig::from_json(r#"{"name": "test", "temperature": 0.7}"#).unwrap();
330 assert!(config.validate().is_ok());
331 }
332
333 #[test]
334 fn is_workflow_detection() {
335 let sequential =
336 AgentConfig::from_json(r#"{"name": "seq", "agent_type": "sequential"}"#).unwrap();
337 assert!(sequential.is_workflow());
338
339 let llm = AgentConfig::from_json(r#"{"name": "llm"}"#).unwrap();
340 assert!(!llm.is_workflow());
341 }
342
343 #[test]
344 fn tool_config_variants() {
345 let custom = ToolConfig {
346 name: Some("my_tool".into()),
347 description: Some("Does stuff".into()),
348 builtin: None,
349 parameters: Some(serde_json::json!({"type": "object"})),
350 };
351 assert!(custom.name.is_some());
352 assert!(custom.builtin.is_none());
353
354 let builtin = ToolConfig {
355 name: None,
356 description: None,
357 builtin: Some("google_search".into()),
358 parameters: None,
359 };
360 assert!(builtin.builtin.is_some());
361 }
362}