Skip to content

Commit aef54f8

Browse files
wuliang229copybara-github
authored andcommitted
feat(config): support loading from YAML config in CLI
The supported CLIs are: `adk web`, `adk run` and `adk api_server`. PiperOrigin-RevId: 781666724
1 parent ca396a3 commit aef54f8

3 files changed

Lines changed: 246 additions & 2 deletions

File tree

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
import os
18+
from pathlib import Path
19+
20+
import yaml
21+
22+
from ..utils.feature_decorator import working_in_progress
23+
from .agent_config import AgentConfig
24+
from .base_agent import BaseAgent
25+
from .llm_agent import LlmAgent
26+
from .llm_agent import LlmAgentConfig
27+
from .loop_agent import LoopAgent
28+
from .loop_agent import LoopAgentConfig
29+
30+
31+
@working_in_progress("from_config is not ready for use.")
32+
def from_config(config_path: str) -> BaseAgent:
33+
"""Build agent from a configfile path.
34+
35+
Args:
36+
config: the path to a YAML config file.
37+
38+
Returns:
39+
The created agent instance.
40+
41+
Raises:
42+
FileNotFoundError: If config file doesn't exist.
43+
ValidationError: If config file's content is invalid YAML.
44+
ValueError: If agent type is unsupported.
45+
"""
46+
abs_path = os.path.abspath(config_path)
47+
config = _load_config_from_path(abs_path)
48+
49+
if isinstance(config.root, LlmAgentConfig):
50+
return LlmAgent.from_config(config.root)
51+
elif isinstance(config.root, LoopAgentConfig):
52+
return LoopAgent.from_config(config.root)
53+
else:
54+
raise ValueError("Unsupported config type")
55+
56+
57+
@working_in_progress("_load_config_from_path is not ready for use.")
58+
def _load_config_from_path(config_path: str) -> AgentConfig:
59+
"""Load an agent's configuration from a YAML file.
60+
61+
Args:
62+
config_path: Path to the YAML config file. Both relative and absolute
63+
paths are accepted.
64+
65+
Returns:
66+
The loaded and validated AgentConfig object.
67+
68+
Raises:
69+
FileNotFoundError: If config file doesn't exist.
70+
ValidationError: If config file's content is invalid YAML.
71+
"""
72+
config_path = Path(config_path)
73+
74+
if not config_path.exists():
75+
raise FileNotFoundError(f"Config file not found: {config_path}")
76+
77+
with open(config_path, "r", encoding="utf-8") as f:
78+
config_data = yaml.safe_load(f)
79+
80+
return AgentConfig.model_validate(config_data)

‎src/google/adk/cli/utils/agent_loader.py‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,16 @@
1616

1717
import importlib
1818
import logging
19+
import os
1920
import sys
2021
from typing import Optional
2122

23+
from pydantic import ValidationError
24+
2225
from . import envs
26+
from ...agents import config_agent_utils
2327
from ...agents.base_agent import BaseAgent
28+
from ...utils.feature_decorator import working_in_progress
2429

2530
logger = logging.getLogger("google_adk." + __name__)
2631

@@ -34,6 +39,8 @@ class AgentLoader:
3439
agents_dir/{agent_name}.py (with root_agent defined in the module)
3540
c) {agent_name} as a package name
3641
agents_dir/{agent_name}/__init__.py (with root_agent in the package)
42+
d) {agent_name} as a YAML config folder:
43+
agents_dir/{agent_name}/root_agent.yaml defines the root agent
3744
3845
"""
3946

@@ -128,6 +135,29 @@ def _load_from_submodule(self, agent_name: str) -> Optional[BaseAgent]:
128135

129136
return None
130137

138+
@working_in_progress("_load_from_yaml_config is not ready for use.")
139+
def _load_from_yaml_config(self, agent_name: str) -> Optional[BaseAgent]:
140+
# Load from the config file at agents_dir/{agent_name}/root_agent.yaml
141+
config_path = os.path.join(self.agents_dir, agent_name, "root_agent.yaml")
142+
try:
143+
agent = config_agent_utils.from_config(config_path)
144+
logger.info("Loaded root agent for %s from %s", agent_name, config_path)
145+
return agent
146+
except FileNotFoundError:
147+
logger.debug("Config file %s not found.", config_path)
148+
return None
149+
except ValidationError as e:
150+
logger.error("Config file %s is invalid YAML.", config_path)
151+
raise e
152+
except Exception as e:
153+
if hasattr(e, "msg"):
154+
e.msg = f"Fail to load '{config_path}' config. " + e.msg
155+
raise e
156+
e.args = (
157+
f"Fail to load '{config_path}' config. {e.args[0] if e.args else ''}",
158+
) + e.args[1:]
159+
raise e
160+
131161
def _perform_load(self, agent_name: str) -> BaseAgent:
132162
"""Internal logic to load an agent"""
133163
# Add self.agents_dir to sys.path
@@ -145,10 +175,14 @@ def _perform_load(self, agent_name: str) -> BaseAgent:
145175
if root_agent := self._load_from_submodule(agent_name):
146176
return root_agent
147177

178+
if root_agent := self._load_from_yaml_config(agent_name):
179+
return root_agent
180+
148181
# If no root_agent was found by any pattern
149182
raise ValueError(
150183
f"No root_agent found for '{agent_name}'. Searched in"
151-
f" '{agent_name}.agent.root_agent', '{agent_name}.root_agent'."
184+
f" '{agent_name}.agent.root_agent', '{agent_name}.root_agent' and"
185+
f" '{agent_name}/root_agent.yaml'."
152186
f" Ensure '{self.agents_dir}/{agent_name}' is structured correctly,"
153187
" an .env file can be loaded if present, and a root_agent is"
154188
" exposed."

‎tests/unittests/cli/utils/test_agent_loader.py‎

Lines changed: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from textwrap import dedent
2020

2121
from google.adk.cli.utils.agent_loader import AgentLoader
22+
from pydantic import ValidationError
2223
import pytest
2324

2425

@@ -30,6 +31,8 @@ def cleanup_sys_path(self):
3031
"""Ensure sys.path is restored after each test."""
3132
original_path = sys.path.copy()
3233
original_env = os.environ.copy()
34+
# Enable WIP features for YAML agent loading tests
35+
os.environ["ADK_ALLOW_WIP_FEATURES"] = "true"
3336
yield
3437
sys.path[:] = original_path
3538
# Restore environment variables
@@ -292,7 +295,8 @@ def test_agent_not_found_error(self):
292295
expected_msg_part_1 = "No root_agent found for 'nonexistent_agent'."
293296
expected_msg_part_2 = (
294297
"Searched in 'nonexistent_agent.agent.root_agent',"
295-
" 'nonexistent_agent.root_agent'."
298+
" 'nonexistent_agent.root_agent' and"
299+
" 'nonexistent_agent/root_agent.yaml'."
296300
)
297301
expected_msg_part_3 = (
298302
f"Ensure '{agents_dir}/nonexistent_agent' is structured correctly"
@@ -443,3 +447,129 @@ def test_sys_path_modification(self):
443447
# Now assert path was added
444448
assert str(temp_path) in sys.path
445449
assert agent.name == "path_agent"
450+
451+
def create_yaml_agent_structure(
452+
self, temp_dir: Path, agent_name: str, yaml_content: str
453+
):
454+
"""Create an agent structure with YAML configuration.
455+
456+
Args:
457+
temp_dir: The temporary directory to create the agent in
458+
agent_name: Name of the agent
459+
yaml_content: YAML content for the root_agent.yaml file
460+
"""
461+
agent_dir = temp_dir / agent_name
462+
agent_dir.mkdir()
463+
464+
# Create root_agent.yaml file
465+
yaml_file = agent_dir / "root_agent.yaml"
466+
yaml_file.write_text(yaml_content)
467+
468+
def test_load_agent_from_yaml_config(self):
469+
"""Test loading an agent from YAML configuration."""
470+
with tempfile.TemporaryDirectory() as temp_dir:
471+
temp_path = Path(temp_dir)
472+
agent_name = "yaml_agent"
473+
474+
# Create YAML configuration
475+
yaml_content = dedent("""
476+
agent_class: LlmAgent
477+
name: yaml_test_agent
478+
model: gemini-2.0-flash
479+
instruction: You are a test agent loaded from YAML configuration.
480+
description: A test agent created from YAML config
481+
""")
482+
483+
self.create_yaml_agent_structure(temp_path, agent_name, yaml_content)
484+
485+
# Load the agent
486+
loader = AgentLoader(str(temp_path))
487+
agent = loader.load_agent(agent_name)
488+
489+
# Assert agent was loaded correctly
490+
assert agent.name == "yaml_test_agent"
491+
# Check if it's an LlmAgent before accessing model and instruction
492+
from google.adk.agents.llm_agent import LlmAgent
493+
494+
if isinstance(agent, LlmAgent):
495+
assert agent.model == "gemini-2.0-flash"
496+
# Handle instruction which can be string or InstructionProvider
497+
instruction_text = str(agent.instruction)
498+
assert "test agent loaded from YAML" in instruction_text
499+
500+
def test_yaml_agent_caching_returns_same_instance(self):
501+
"""Test that loading the same YAML agent twice returns the same instance."""
502+
with tempfile.TemporaryDirectory() as temp_dir:
503+
temp_path = Path(temp_dir)
504+
agent_name = "cached_yaml_agent"
505+
506+
# Create YAML configuration
507+
yaml_content = dedent("""
508+
agent_class: LlmAgent
509+
name: cached_yaml_test_agent
510+
model: gemini-2.0-flash
511+
instruction: You are a cached test agent.
512+
""")
513+
514+
self.create_yaml_agent_structure(temp_path, agent_name, yaml_content)
515+
516+
# Load the agent twice
517+
loader = AgentLoader(str(temp_path))
518+
agent1 = loader.load_agent(agent_name)
519+
agent2 = loader.load_agent(agent_name)
520+
521+
# Assert same instance is returned
522+
assert agent1 is agent2
523+
assert agent1.name == agent2.name
524+
525+
def test_yaml_agent_not_found_error(self):
526+
"""Test that appropriate error is raised when YAML agent is not found."""
527+
with tempfile.TemporaryDirectory() as temp_dir:
528+
loader = AgentLoader(temp_dir)
529+
agents_dir = temp_dir # For use in the expected message string
530+
531+
# Try to load non-existent YAML agent
532+
with pytest.raises(ValueError) as exc_info:
533+
loader.load_agent("nonexistent_yaml_agent")
534+
535+
expected_msg_part_1 = "No root_agent found for 'nonexistent_yaml_agent'."
536+
expected_msg_part_2 = (
537+
"Searched in 'nonexistent_yaml_agent.agent.root_agent',"
538+
" 'nonexistent_yaml_agent.root_agent' and"
539+
" 'nonexistent_yaml_agent/root_agent.yaml'."
540+
)
541+
expected_msg_part_3 = (
542+
f"Ensure '{agents_dir}/nonexistent_yaml_agent' is structured"
543+
" correctly"
544+
)
545+
546+
assert expected_msg_part_1 in str(exc_info.value)
547+
assert expected_msg_part_2 in str(exc_info.value)
548+
assert expected_msg_part_3 in str(exc_info.value)
549+
550+
def test_yaml_agent_invalid_yaml_error(self):
551+
"""Test that appropriate error is raised when YAML is invalid."""
552+
with tempfile.TemporaryDirectory() as temp_dir:
553+
temp_path = Path(temp_dir)
554+
agent_name = "invalid_yaml_agent"
555+
556+
# Create invalid YAML content with wrong field name
557+
invalid_yaml_content = dedent("""
558+
agent_type: LlmAgent
559+
name: invalid_yaml_test_agent
560+
model: gemini-2.0-flash
561+
instruction: You are a test agent with invalid YAML
562+
""")
563+
564+
self.create_yaml_agent_structure(
565+
temp_path, agent_name, invalid_yaml_content
566+
)
567+
568+
loader = AgentLoader(str(temp_path))
569+
570+
# Try to load agent with invalid YAML
571+
with pytest.raises(ValidationError) as exc_info:
572+
loader.load_agent(agent_name)
573+
574+
# Should raise some form of YAML parsing error
575+
assert "Extra inputs are not permitted" in str(exc_info.value)

0 commit comments

Comments
 (0)