-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathtest_agent_config.py
More file actions
509 lines (438 loc) · 15.4 KB
/
test_agent_config.py
File metadata and controls
509 lines (438 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ntpath
import os
from pathlib import Path
from textwrap import dedent
from typing import Literal
from typing import Type
from unittest import mock
from google.adk.agents import config_agent_utils
from google.adk.agents.agent_config import AgentConfig
from google.adk.agents.base_agent import BaseAgent
from google.adk.agents.base_agent_config import BaseAgentConfig
from google.adk.agents.common_configs import AgentRefConfig
from google.adk.agents.llm_agent import LlmAgent
from google.adk.agents.loop_agent import LoopAgent
from google.adk.agents.parallel_agent import ParallelAgent
from google.adk.agents.sequential_agent import SequentialAgent
from google.adk.models.lite_llm import LiteLlm
import pytest
import yaml
def test_agent_config_discriminator_default_is_llm_agent(tmp_path: Path):
yaml_content = """\
name: search_agent
model: gemini-2.5-flash
description: a sample description
instruction: a fake instruction
tools:
- name: google_search
"""
config_file = tmp_path / "test_config.yaml"
config_file.write_text(yaml_content)
config = AgentConfig.model_validate(yaml.safe_load(yaml_content))
agent = config_agent_utils.from_config(str(config_file))
assert isinstance(agent, LlmAgent)
assert config.root.agent_class == "LlmAgent"
@pytest.mark.parametrize(
"agent_class_value",
[
"LlmAgent",
"google.adk.agents.LlmAgent",
"google.adk.agents.llm_agent.LlmAgent",
],
)
def test_agent_config_discriminator_llm_agent(
agent_class_value: str, tmp_path: Path
):
yaml_content = f"""\
agent_class: {agent_class_value}
name: search_agent
model: gemini-2.5-flash
description: a sample description
instruction: a fake instruction
tools:
- name: google_search
"""
config_file = tmp_path / "test_config.yaml"
config_file.write_text(yaml_content)
config = AgentConfig.model_validate(yaml.safe_load(yaml_content))
agent = config_agent_utils.from_config(str(config_file))
assert isinstance(agent, LlmAgent)
assert config.root.agent_class == agent_class_value
@pytest.mark.parametrize(
"agent_class_value",
[
"LoopAgent",
"google.adk.agents.LoopAgent",
"google.adk.agents.loop_agent.LoopAgent",
],
)
def test_agent_config_discriminator_loop_agent(
agent_class_value: str, tmp_path: Path
):
yaml_content = f"""\
agent_class: {agent_class_value}
name: CodePipelineAgent
description: Executes a sequence of code writing, reviewing, and refactoring.
sub_agents: []
"""
config_file = tmp_path / "test_config.yaml"
config_file.write_text(yaml_content)
config = AgentConfig.model_validate(yaml.safe_load(yaml_content))
agent = config_agent_utils.from_config(str(config_file))
assert isinstance(agent, LoopAgent)
assert config.root.agent_class == agent_class_value
@pytest.mark.parametrize(
"agent_class_value",
[
"ParallelAgent",
"google.adk.agents.ParallelAgent",
"google.adk.agents.parallel_agent.ParallelAgent",
],
)
def test_agent_config_discriminator_parallel_agent(
agent_class_value: str, tmp_path: Path
):
yaml_content = f"""\
agent_class: {agent_class_value}
name: CodePipelineAgent
description: Executes a sequence of code writing, reviewing, and refactoring.
sub_agents: []
"""
config_file = tmp_path / "test_config.yaml"
config_file.write_text(yaml_content)
config = AgentConfig.model_validate(yaml.safe_load(yaml_content))
agent = config_agent_utils.from_config(str(config_file))
assert isinstance(agent, ParallelAgent)
assert config.root.agent_class == agent_class_value
@pytest.mark.parametrize(
"agent_class_value",
[
"SequentialAgent",
"google.adk.agents.SequentialAgent",
"google.adk.agents.sequential_agent.SequentialAgent",
],
)
def test_agent_config_discriminator_sequential_agent(
agent_class_value: str, tmp_path: Path
):
yaml_content = f"""\
agent_class: {agent_class_value}
name: CodePipelineAgent
description: Executes a sequence of code writing, reviewing, and refactoring.
sub_agents: []
"""
config_file = tmp_path / "test_config.yaml"
config_file.write_text(yaml_content)
config = AgentConfig.model_validate(yaml.safe_load(yaml_content))
agent = config_agent_utils.from_config(str(config_file))
assert isinstance(agent, SequentialAgent)
assert config.root.agent_class == agent_class_value
@pytest.mark.parametrize(
("agent_class_value", "expected_agent_type"),
[
("LoopAgent", LoopAgent),
("google.adk.agents.LoopAgent", LoopAgent),
("google.adk.agents.loop_agent.LoopAgent", LoopAgent),
("ParallelAgent", ParallelAgent),
("google.adk.agents.ParallelAgent", ParallelAgent),
("google.adk.agents.parallel_agent.ParallelAgent", ParallelAgent),
("SequentialAgent", SequentialAgent),
("google.adk.agents.SequentialAgent", SequentialAgent),
("google.adk.agents.sequential_agent.SequentialAgent", SequentialAgent),
],
)
def test_agent_config_discriminator_with_sub_agents(
agent_class_value: str, expected_agent_type: Type[BaseAgent], tmp_path: Path
):
# Create sub-agent config files
sub_agent_dir = tmp_path / "sub_agents"
sub_agent_dir.mkdir()
sub_agent_config = """\
name: sub_agent_{index}
model: gemini-2.5-flash
description: a sub agent
instruction: sub agent instruction
"""
(sub_agent_dir / "sub_agent1.yaml").write_text(
sub_agent_config.format(index=1)
)
(sub_agent_dir / "sub_agent2.yaml").write_text(
sub_agent_config.format(index=2)
)
yaml_content = f"""\
agent_class: {agent_class_value}
name: main_agent
description: main agent with sub agents
sub_agents:
- config_path: sub_agents/sub_agent1.yaml
- config_path: sub_agents/sub_agent2.yaml
"""
config_file = tmp_path / "test_config.yaml"
config_file.write_text(yaml_content)
config = AgentConfig.model_validate(yaml.safe_load(yaml_content))
agent = config_agent_utils.from_config(str(config_file))
assert isinstance(agent, expected_agent_type)
assert config.root.agent_class == agent_class_value
@pytest.mark.parametrize(
("agent_class_value", "expected_agent_type"),
[
("LlmAgent", LlmAgent),
("google.adk.agents.LlmAgent", LlmAgent),
("google.adk.agents.llm_agent.LlmAgent", LlmAgent),
],
)
def test_agent_config_discriminator_llm_agent_with_sub_agents(
agent_class_value: str, expected_agent_type: Type[BaseAgent], tmp_path: Path
):
# Create sub-agent config files
sub_agent_dir = tmp_path / "sub_agents"
sub_agent_dir.mkdir()
sub_agent_config = """\
name: sub_agent_{index}
model: gemini-2.5-flash
description: a sub agent
instruction: sub agent instruction
"""
(sub_agent_dir / "sub_agent1.yaml").write_text(
sub_agent_config.format(index=1)
)
(sub_agent_dir / "sub_agent2.yaml").write_text(
sub_agent_config.format(index=2)
)
yaml_content = f"""\
agent_class: {agent_class_value}
name: main_agent
model: gemini-2.5-flash
description: main agent with sub agents
instruction: main agent instruction
sub_agents:
- config_path: sub_agents/sub_agent1.yaml
- config_path: sub_agents/sub_agent2.yaml
"""
config_file = tmp_path / "test_config.yaml"
config_file.write_text(yaml_content)
config = AgentConfig.model_validate(yaml.safe_load(yaml_content))
agent = config_agent_utils.from_config(str(config_file))
assert isinstance(agent, expected_agent_type)
assert config.root.agent_class == agent_class_value
def test_agent_config_litellm_model_with_custom_args(tmp_path: Path):
yaml_content = """\
name: managed_api_agent
description: Agent using LiteLLM managed endpoint
instruction: Respond concisely.
model_code:
name: google.adk.models.lite_llm.LiteLlm
args:
- name: model
value: kimi/k2
- name: api_base
value: https://proxy.litellm.ai/v1
"""
config_file = tmp_path / "litellm_agent.yaml"
config_file.write_text(yaml_content)
agent = config_agent_utils.from_config(str(config_file), trusted=True)
assert isinstance(agent, LlmAgent)
assert isinstance(agent.model, LiteLlm)
assert agent.model.model == "kimi/k2"
assert agent.model._additional_args.get("api_base") == (
"https://proxy.litellm.ai/v1"
)
def test_agent_config_legacy_model_mapping_still_supported(tmp_path: Path):
yaml_content = """\
name: managed_api_agent
description: Agent using LiteLLM managed endpoint
instruction: Respond concisely.
model:
name: google.adk.models.lite_llm.LiteLlm
args:
- name: model
value: kimi/k2
"""
config_file = tmp_path / "legacy_litellm_agent.yaml"
config_file.write_text(yaml_content)
agent = config_agent_utils.from_config(str(config_file), trusted=True)
assert isinstance(agent, LlmAgent)
assert isinstance(agent.model, LiteLlm)
assert agent.model.model == "kimi/k2"
def test_agent_config_discriminator_custom_agent():
class MyCustomAgentConfig(BaseAgentConfig):
agent_class: Literal["mylib.agents.MyCustomAgent"] = (
"mylib.agents.MyCustomAgent"
)
other_field: str
yaml_content = """\
agent_class: mylib.agents.MyCustomAgent
name: CodePipelineAgent
description: Executes a sequence of code writing, reviewing, and refactoring.
other_field: other value
"""
config_data = yaml.safe_load(yaml_content)
config = AgentConfig.model_validate(config_data)
# pylint: disable=unidiomatic-typecheck Needs exact class matching.
assert type(config.root) is BaseAgentConfig
assert config.root.agent_class == "mylib.agents.MyCustomAgent"
assert config.root.model_extra == {"other_field": "other value"}
my_custom_config = MyCustomAgentConfig.model_validate(
config.root.model_dump()
)
assert my_custom_config.other_field == "other value"
@pytest.mark.parametrize(
("config_rel_path", "child_rel_path", "child_name", "instruction"),
[
(
Path("main.yaml"),
Path("sub_agents/child.yaml"),
"child_agent",
"I am a child agent",
),
(
Path("level1/level2/nested_main.yaml"),
Path("sub/nested_child.yaml"),
"nested_child",
"I am nested",
),
],
)
def test_resolve_agent_reference_resolves_relative_paths(
config_rel_path: Path,
child_rel_path: Path,
child_name: str,
instruction: str,
tmp_path: Path,
):
"""Verify resolve_agent_reference resolves relative sub-agent paths."""
config_file = tmp_path / config_rel_path
config_file.parent.mkdir(parents=True, exist_ok=True)
child_config_path = config_file.parent / child_rel_path
child_config_path.parent.mkdir(parents=True, exist_ok=True)
child_config_path.write_text(dedent(f"""
agent_class: LlmAgent
name: {child_name}
model: gemini-2.5-flash
instruction: {instruction}
""").lstrip())
config_file.write_text(dedent(f"""
agent_class: LlmAgent
name: main_agent
model: gemini-2.5-flash
instruction: I am the main agent
sub_agents:
- config_path: {child_rel_path.as_posix()}
""").lstrip())
ref_config = AgentRefConfig(config_path=child_rel_path.as_posix())
agent = config_agent_utils.resolve_agent_reference(
ref_config, str(config_file)
)
assert agent.name == child_name
config_dir = os.path.dirname(str(config_file.resolve()))
assert config_dir == str(config_file.parent.resolve())
expected_child_path = os.path.join(config_dir, *child_rel_path.parts)
assert os.path.exists(expected_child_path)
def test_resolve_agent_reference_uses_windows_dirname():
"""Ensure Windows-style config references resolve via os.path.dirname."""
ref_config = AgentRefConfig(config_path="sub\\child.yaml")
recorded: dict[str, str] = {}
def fake_from_config(path: str):
recorded["path"] = path
return "sentinel"
with (
mock.patch.object(
config_agent_utils,
"from_config",
autospec=True,
side_effect=fake_from_config,
),
mock.patch.object(config_agent_utils.os, "path", ntpath),
):
referencing = r"C:\workspace\agents\main.yaml"
result = config_agent_utils.resolve_agent_reference(ref_config, referencing)
expected_path = ntpath.join(
ntpath.dirname(referencing), ref_config.config_path
)
assert result == "sentinel"
assert recorded["path"] == expected_path
def test_load_config_from_path_blocks_args_when_enforced(tmp_path):
"""Verify _load_config_from_path blocks 'args' when enforcement is enabled."""
config_file = tmp_path / "malicious.yaml"
config_file.write_text("""
name: malicious_agent
tools:
- name: some_tool
args:
cmd: "rm -rf /"
""")
config_agent_utils._set_enforce_denylist(True)
try:
with pytest.raises(ValueError) as exc_info:
config_agent_utils._load_config_from_path(str(config_file))
assert "Blocked key 'args' found" in str(exc_info.value)
finally:
config_agent_utils._set_enforce_denylist(False)
def test_from_config_blocks_args_by_default(tmp_path: Path):
"""Default from_config() rejects YAML containing an 'args' key."""
config_file = tmp_path / "with_args.yaml"
config_file.write_text(
"agent_class: LlmAgent\n"
"name: agent_with_args\n"
'instruction: "."\n'
"model_code:\n"
" name: google.adk.models.lite_llm.LiteLlm\n"
" args:\n"
" - name: model\n"
" value: kimi/k2\n"
)
with pytest.raises(ValueError) as exc_info:
config_agent_utils.from_config(str(config_file))
assert "Blocked key 'args' found" in str(exc_info.value)
def test_from_config_allows_args_when_trusted(tmp_path: Path):
"""from_config(..., trusted=True) accepts YAML containing an 'args' key."""
config_file = tmp_path / "with_args.yaml"
config_file.write_text(
"agent_class: LlmAgent\n"
"name: agent_with_args\n"
'instruction: "."\n'
"model_code:\n"
" name: google.adk.models.lite_llm.LiteLlm\n"
" args:\n"
" - name: model\n"
" value: kimi/k2\n"
)
agent = config_agent_utils.from_config(str(config_file), trusted=True)
assert isinstance(agent, LlmAgent)
assert isinstance(agent.model, LiteLlm)
assert agent.model.model == "kimi/k2"
def test_from_config_default_blocks_os_system_in_output_schema(tmp_path: Path):
"""Default from_config() blocks the output_schema CodeConfig.args RCE sink.
Without the denylist, output_schema.name=os.system with a single args entry
would invoke os.system at agent load. The default trusted=False path
rejects the YAML before resolve_code_reference is reached.
"""
marker = tmp_path / "rce_marker"
config_file = tmp_path / "exploit.yaml"
config_file.write_text(
"agent_class: LlmAgent\n"
"name: exploit_agent\n"
'instruction: "."\n'
'model: "gemini-2.5-flash"\n'
"output_schema:\n"
" name: os.system\n"
" args:\n"
f" - value: 'touch {marker.as_posix()}'\n"
)
with pytest.raises(ValueError) as exc_info:
config_agent_utils.from_config(str(config_file))
assert "Blocked key 'args' found" in str(exc_info.value)
assert not marker.exists()