Skip to main content

gemini_adk_rs/
agent_config.rs

1//! YAML/TOML agent configuration — define agents without code.
2//!
3//! Mirrors upstream ADK's `root_agent.yaml` format. Agents can be defined
4//! declaratively and loaded at runtime by the CLI or API server.
5
6use std::collections::HashMap;
7use std::path::Path;
8
9use serde::{Deserialize, Serialize};
10
11/// Declarative agent configuration — loadable from YAML or TOML.
12///
13/// # Example YAML
14///
15/// ```yaml
16/// name: weather_agent
17/// model: gemini-2.0-flash
18/// instruction: "You are a helpful weather assistant."
19/// description: "Provides weather information for cities."
20/// tools:
21///   - name: get_weather
22///     description: "Get weather for a city"
23///   - builtin: google_search
24/// sub_agents:
25///   - name: forecast_agent
26///     model: gemini-2.0-flash
27///     instruction: "Provide 5-day forecasts."
28/// output_key: weather_result
29/// ```
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct AgentConfig {
32    /// Agent name (required).
33    pub name: String,
34
35    /// Model identifier (e.g., "gemini-2.0-flash", "gemini-2.5-pro").
36    #[serde(default)]
37    pub model: Option<String>,
38
39    /// System instruction for the agent.
40    #[serde(default)]
41    pub instruction: Option<String>,
42
43    /// Human-readable description of what this agent does.
44    #[serde(default)]
45    pub description: Option<String>,
46
47    /// Tool declarations.
48    #[serde(default)]
49    pub tools: Vec<ToolConfig>,
50
51    /// Sub-agent configurations (for multi-agent hierarchies).
52    #[serde(default)]
53    pub sub_agents: Vec<AgentConfig>,
54
55    /// Temperature for generation (0.0 - 2.0).
56    #[serde(default)]
57    pub temperature: Option<f32>,
58
59    /// Maximum output tokens.
60    #[serde(default)]
61    pub max_output_tokens: Option<u32>,
62
63    /// Thinking budget (Google AI only).
64    #[serde(default)]
65    pub thinking_budget: Option<u32>,
66
67    /// State key to auto-save the agent's final response into.
68    #[serde(default)]
69    pub output_key: Option<String>,
70
71    /// JSON Schema for structured output.
72    #[serde(default)]
73    pub output_schema: Option<serde_json::Value>,
74
75    /// Maximum number of LLM calls per invocation (safety limit).
76    #[serde(default)]
77    pub max_llm_calls: Option<u32>,
78
79    /// Agent type: "llm" (default), "sequential", "parallel", "loop".
80    #[serde(default = "default_agent_type")]
81    pub agent_type: String,
82
83    /// For loop agents: maximum iterations.
84    #[serde(default)]
85    pub max_iterations: Option<u32>,
86
87    /// Custom metadata (passed through to state or callbacks).
88    #[serde(default)]
89    pub metadata: HashMap<String, serde_json::Value>,
90
91    /// Voice configuration for live agents.
92    #[serde(default)]
93    pub voice: Option<String>,
94
95    /// Greeting message (model speaks first on connect).
96    #[serde(default)]
97    pub greeting: Option<String>,
98
99    /// Whether to enable transcription.
100    #[serde(default)]
101    pub transcription: Option<bool>,
102
103    /// Whether to enable A2A protocol endpoint.
104    #[serde(default)]
105    pub a2a: Option<bool>,
106
107    /// Environment variables to set when loading this agent.
108    #[serde(default)]
109    pub env: HashMap<String, String>,
110}
111
112/// The agent type when a config does not name one: `"llm"`.
113///
114/// Also the serde default for `agent_type` in the server's agent entries.
115pub fn default_agent_type() -> String {
116    "llm".to_string()
117}
118
119/// Tool configuration within an agent config.
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct ToolConfig {
122    /// Tool name (for custom tools).
123    #[serde(default)]
124    pub name: Option<String>,
125
126    /// Tool description.
127    #[serde(default)]
128    pub description: Option<String>,
129
130    /// Built-in tool type (e.g., "google_search", "code_execution", "url_context").
131    #[serde(default)]
132    pub builtin: Option<String>,
133
134    /// JSON Schema for the tool's parameters.
135    #[serde(default)]
136    pub parameters: Option<serde_json::Value>,
137}
138
139/// Errors from agent config operations.
140#[derive(Debug, thiserror::Error)]
141pub enum AgentConfigError {
142    /// Failed to read the config file.
143    #[error("IO error: {0}")]
144    Io(#[from] std::io::Error),
145
146    /// Failed to parse YAML.
147    #[error("YAML parse error: {0}")]
148    Yaml(String),
149
150    /// Failed to parse TOML.
151    #[error("TOML parse error: {0}")]
152    Toml(String),
153
154    /// Failed to parse JSON.
155    #[error("JSON parse error: {0}")]
156    Json(#[from] serde_json::Error),
157
158    /// Invalid configuration.
159    #[error("Invalid config: {0}")]
160    Invalid(String),
161}
162
163impl AgentConfig {
164    /// Load agent config from a YAML file.
165    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    /// Parse agent config from a YAML string.
171    pub fn from_yaml(yaml: &str) -> Result<Self, AgentConfigError> {
172        serde_json::from_value(
173            serde_json::to_value(
174                // Use serde_json roundtrip since we don't want to add serde_yaml dep.
175                // In practice, the CLI crate will parse YAML and pass the Value.
176                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    /// Parse agent config from a JSON string.
185    pub fn from_json(json: &str) -> Result<Self, AgentConfigError> {
186        Ok(serde_json::from_str(json)?)
187    }
188
189    /// Parse agent config from a JSON value.
190    pub fn from_value(value: serde_json::Value) -> Result<Self, AgentConfigError> {
191        Ok(serde_json::from_value(value)?)
192    }
193
194    /// Validate the configuration.
195    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        // Validate sub-agents recursively.
207        for sub in &self.sub_agents {
208            sub.validate()?;
209        }
210        Ok(())
211    }
212
213    /// Check if this is a built-in tool reference.
214    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    /// Check if this is a workflow agent (non-LLM).
222    pub fn is_workflow(&self) -> bool {
223        matches!(self.agent_type.as_str(), "sequential" | "parallel" | "loop")
224    }
225}
226
227/// Discover agent configurations in a directory.
228///
229/// Scans for files named `agent.yaml`, `agent.json`, `agent.toml`,
230/// `root_agent.yaml`, or `root_agent.json`.
231pub 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                // TOML parsing delegated to CLI crate which has the toml dep
243                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    // Also scan subdirectories for agent configs.
257    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}