diff --git a/src/google/adk/utils/yaml_utils.py b/src/google/adk/utils/yaml_utils.py index ab1a8f4e..0598927d 100644 --- a/src/google/adk/utils/yaml_utils.py +++ b/src/google/adk/utils/yaml_utils.py @@ -43,9 +43,16 @@ def dump_pydantic_to_yaml( file_path = Path(file_path) file_path.parent.mkdir(parents=True, exist_ok=True) - # Create a custom dumper class class _MultilineDumper(yaml.SafeDumper): - pass + + def increase_indent(self, flow=False, indentless=False): + """Override to force consistent indentation for sequences in mappings. + + By default, PyYAML uses indentless=True for sequences that are values + in mappings, creating flush-left alignment. This override forces proper + indentation for all sequences regardless of context. + """ + return super(_MultilineDumper, self).increase_indent(flow, False) def multiline_str_representer(dumper, data): if '\n' in data: diff --git a/tests/unittests/utils/test_yaml_utils.py b/tests/unittests/utils/test_yaml_utils.py index 0c756ae2..93a4be7a 100644 --- a/tests/unittests/utils/test_yaml_utils.py +++ b/tests/unittests/utils/test_yaml_utils.py @@ -30,6 +30,7 @@ class SimpleModel(BaseModel): active: bool finish_reason: Optional[types.FinishReason] = None multiline_text: Optional[str] = None + items: Optional[list[str]] = None def test_yaml_file_generation(tmp_path: Path): @@ -77,3 +78,48 @@ multiline_text: |- and should be formatted with pipe style name: Test """ + + +def test_list_indentation(tmp_path: Path): + """Test that lists in mappings are properly indented.""" + model = SimpleModel( + name="Test", + age=25, + active=True, + items=["item1", "item2", "item3"], + ) + yaml_file = tmp_path / "test.yaml" + + dump_pydantic_to_yaml(model, yaml_file) + + expected = """\ +active: true +age: 25 +items: + - item1 + - item2 + - item3 +name: Test +""" + assert yaml_file.read_text(encoding="utf-8") == expected + + +def test_empty_list_formatting(tmp_path: Path): + """Test that empty lists are formatted properly.""" + model = SimpleModel( + name="Test", + age=25, + active=True, + items=[], + ) + yaml_file = tmp_path / "test.yaml" + + dump_pydantic_to_yaml(model, yaml_file) + + expected = """\ +active: true +age: 25 +items: [] +name: Test +""" + assert yaml_file.read_text(encoding="utf-8") == expected