-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtemplate.py
More file actions
1982 lines (1711 loc) · 80.8 KB
/
template.py
File metadata and controls
1982 lines (1711 loc) · 80.8 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2025 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 json
import logging
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from datetime import datetime
from typing import Any
if sys.version_info >= (3, 11):
from datetime import UTC
else:
from datetime import timezone
UTC = timezone.utc # noqa: UP017 - Required for Python 3.10 compatibility
import yaml
from cookiecutter.main import cookiecutter
from rich.console import Console
from rich.prompt import Confirm, IntPrompt, Prompt
from agent_starter_pack.cli.utils.version import get_current_version
from .datastores import DATASTORES
from .remote_template import (
get_base_template_name,
render_and_merge_makefiles,
)
# =============================================================================
# Agent Name Aliases (Backwards Compatibility)
# =============================================================================
# Maps legacy agent names to their current names.
# This allows users to continue using old names like `--agent adk_base`
# and for remote templates to reference `base_template: adk_base`.
# =============================================================================
AGENT_ALIASES: dict[str, str] = {
"adk_base": "adk",
"langgraph_base": "langgraph",
"custom": "langgraph",
"custom_a2a": "langgraph",
"adk_a2a_base": "adk_a2a",
"adk_base_go": "adk_go",
}
def resolve_agent_alias(name: str | None) -> str | None:
"""Resolve legacy agent name to current name.
Args:
name: Agent name (possibly a legacy alias)
Returns:
Current agent name, or original if not an alias
"""
if name is None:
return None
resolved = AGENT_ALIASES.get(name, name)
if resolved != name:
logging.info(f"Agent '{name}' has been renamed to '{resolved}'")
return resolved
# =============================================================================
# Conditional Files Configuration
# =============================================================================
# Maps file/directory paths to their inclusion conditions.
# Files are stored with simple names and deleted if condition is False.
# This replaces Jinja2 conditionals in filenames for Windows compatibility.
#
# Format: "relative/path/to/file_or_dir": lambda config: bool_condition
# The config dict contains: agent_name, cicd_runner, is_adk, is_adk_live, is_a2a
# =============================================================================
# Helper: exclude service.tf only for adk_live + agent_engine combination
_exclude_adk_live_agent_engine = lambda c: not (
c.get("agent_name") == "adk_live" and c.get("deployment_target") == "agent_engine"
)
CONDITIONAL_FILES = {
# CI/CD runner conditional files (base_template)
".cloudbuild": lambda c: c.get("cicd_runner") == "google_cloud_build",
".github": lambda c: c.get("cicd_runner") == "github_actions",
"deployment/terraform/build_triggers.tf": (
lambda c: c.get("cicd_runner") == "google_cloud_build"
),
"deployment/terraform/wif.tf": (lambda c: c.get("cicd_runner") == "github_actions"),
# Agent-specific conditional files (uses agent_directory placeholder)
"{agent_directory}/app_utils/gcs.py": (lambda c: c.get("agent_name") == "adk_live"),
"{agent_directory}/app_utils/executor": (
lambda c: c.get("is_a2a") and c.get("agent_name") == "langgraph"
),
"{agent_directory}/app_utils/converters": (
lambda c: c.get("is_a2a") and c.get("agent_name") == "langgraph"
),
# Agent Engine deployment target conditionals
"{agent_directory}/app_utils/expose_app.py": lambda c: c.get("is_adk_live"),
"tests/helpers.py": lambda c: c.get("is_a2a"),
"deployment/terraform/service.tf": _exclude_adk_live_agent_engine,
"deployment/terraform/dev/service.tf": _exclude_adk_live_agent_engine,
}
def apply_conditional_files(
project_path: pathlib.Path,
config: dict[str, Any],
agent_directory: str = "app",
) -> None:
"""Apply conditional file logic by deleting files that don't match conditions.
This function checks each conditional file against its condition and either
keeps the file (condition True) or renames it to unused_* (condition False)
so it gets cleaned up by the existing unused file cleanup logic.
Args:
project_path: Path to the generated project directory
config: Configuration dict with keys: agent_name, cicd_runner,
is_adk, is_adk_live, is_a2a
agent_directory: Name of the agent directory (replaces {agent_directory} placeholder)
"""
for rel_path_template, condition_fn in CONDITIONAL_FILES.items():
# Replace {agent_directory} placeholder
rel_path = rel_path_template.replace("{agent_directory}", agent_directory)
file_path = project_path / rel_path
if not file_path.exists():
continue
should_include = condition_fn(config)
if not should_include:
# Rename to unused_* so existing cleanup logic handles it
parent = file_path.parent
name = file_path.name
unused_path = parent / f"unused_{name}"
logging.debug(
f"Conditional file '{rel_path}' condition False, "
f"renaming to {unused_path.name}"
)
if unused_path.exists():
if unused_path.is_dir():
shutil.rmtree(unused_path)
else:
unused_path.unlink()
file_path.rename(unused_path)
else:
logging.debug(f"Conditional file '{rel_path}' condition True, keeping")
def add_base_template_dependencies_interactively(
project_path: pathlib.Path,
base_dependencies: list[str],
base_template_name: str,
auto_approve: bool = False,
) -> bool:
"""Interactively add base template dependencies using uv add.
Args:
project_path: Path to the project directory
base_dependencies: List of dependencies from base template's extra_dependencies
base_template_name: Name of the base template being used
auto_approve: Whether to skip confirmation and auto-install
Returns:
True if dependencies were added successfully, False otherwise
"""
if not base_dependencies:
return True
console = Console()
# Construct dependency string once for reuse
deps_str = " ".join(f"'{dep}'" for dep in base_dependencies)
# Show what dependencies will be added
console.print(
f"\n✓ Base template override: Using '{base_template_name}' as foundation",
style="bold cyan",
)
console.print(" This requires adding the following dependencies:", style="white")
for dep in base_dependencies:
console.print(f" • {dep}", style="yellow")
# Ask for confirmation unless auto-approve
should_add = True
if not auto_approve:
should_add = Confirm.ask(
"\n? Add these dependencies automatically?", default=True
)
if not should_add:
console.print("\n⚠️ Skipped dependency installation.", style="yellow")
console.print(" To add them manually later, run:", style="dim")
console.print(f" cd {project_path.name}", style="dim")
console.print(f" uv add {deps_str}\n", style="dim")
return False
# Run uv add
try:
if auto_approve:
console.print(
f"✓ Auto-installing dependencies: {', '.join(base_dependencies)}",
style="bold cyan",
)
else:
console.print(f"\n✓ Running: uv add {deps_str}", style="bold cyan")
# Run uv add in the project directory
cmd = ["uv", "add", *base_dependencies]
result = subprocess.run(
cmd,
cwd=project_path,
capture_output=True,
text=True,
check=True,
)
# Show success message
if not auto_approve:
# Show a summary line from uv output
output_lines = result.stderr.strip().split("\n")
for line in output_lines:
if "Resolved" in line or "Installed" in line:
console.print(f" {line}", style="dim")
break
console.print("✓ Dependencies added successfully\n", style="bold green")
return True
except subprocess.CalledProcessError as e:
console.print(
f"\n✗ Failed to add dependencies: {e.stderr.strip()}", style="bold red"
)
console.print(" You can add them manually:", style="yellow")
console.print(f" cd {project_path.name}", style="dim")
console.print(f" uv add {deps_str}\n", style="dim")
return False
except FileNotFoundError:
console.print(
"\n✗ uv command not found. Please install uv first.", style="bold red"
)
console.print(" Install from: https://docs.astral.sh/uv/", style="dim")
console.print("\n To add dependencies manually:", style="yellow")
console.print(f" cd {project_path.name}", style="dim")
console.print(f" uv add {deps_str}\n", style="dim")
return False
def validate_agent_directory_name(agent_dir: str, allow_dot: bool = False) -> None:
"""Validate that an agent directory name is a valid Python identifier.
Args:
agent_dir: The agent directory name to validate
allow_dot: If True, allows "." as a special value indicating flat structure
Raises:
ValueError: If the agent directory name is not a valid Python identifier
Note:
The special value "." indicates flat structure - agent code is in the
template root. When "." is used, the target directory name will be
derived from the template folder name.
"""
if agent_dir == ".":
if allow_dot:
return # "." is valid when explicitly allowed (will be resolved later)
raise ValueError(
"Agent directory '.' is not valid in this context. "
"Use '.' only to indicate flat structure templates."
)
if "-" in agent_dir:
raise ValueError(
f"Agent directory '{agent_dir}' contains hyphens (-) which are not allowed. "
"Agent directories must be valid Python identifiers since they're used as module names. "
"Please use underscores (_) or lowercase letters instead."
)
if not agent_dir.replace("_", "a").isidentifier():
raise ValueError(
f"Agent directory '{agent_dir}' is not a valid Python identifier. "
"Agent directories must be valid Python identifiers since they're used as module names. "
"Please use only lowercase letters, numbers, and underscores, and don't start with a number."
)
@dataclass
class TemplateConfig:
name: str
description: str
settings: dict[str, bool | list[str]]
@classmethod
def from_file(cls, config_path: pathlib.Path) -> "TemplateConfig":
"""Load template config from file with validation"""
try:
with open(config_path, encoding="utf-8") as f:
data = yaml.safe_load(f)
if not isinstance(data, dict):
raise ValueError(f"Invalid template config format in {config_path}")
required_fields = ["name", "description", "settings"]
missing_fields = [f for f in required_fields if f not in data]
if missing_fields:
raise ValueError(
f"Missing required fields in template config: {missing_fields}"
)
return cls(
name=data["name"],
description=data["description"],
settings=data["settings"],
)
except yaml.YAMLError as err:
raise ValueError(f"Invalid YAML in template config: {err}") from err
except Exception as err:
raise ValueError(f"Error loading template config: {err}") from err
def get_overwrite_folders(agent_directory: str) -> list[str]:
"""Get folders to overwrite with configurable agent directory."""
return [agent_directory, "frontend", "tests", "notebooks"]
TEMPLATE_CONFIG_FILE = "templateconfig.yaml"
DEPLOYMENT_TARGETS = ["cloud_run", "agent_engine"]
SUPPORTED_LANGUAGES = ["python", "go"]
DEFAULT_FRONTEND = "None"
def get_available_agents(deployment_target: str | None = None) -> dict:
"""Dynamically load available agents from the agents directory.
Returns agents grouped by language and framework for display purposes.
Each agent dict includes: name, description, language, framework.
Args:
deployment_target: Optional deployment target to filter agents
"""
# Define display order for agents within each group
PRIORITY_ORDER = {
"adk": 0,
"adk_a2a": 1,
"adk_live": 2,
"agentic_rag": 3,
"langgraph": 0,
"adk_go": 0,
}
agents_list = []
agents_dir = pathlib.Path(__file__).parent.parent.parent / "agents"
for agent_dir in agents_dir.iterdir():
if agent_dir.is_dir() and not agent_dir.name.startswith("__"):
template_config_path = agent_dir / ".template" / "templateconfig.yaml"
if template_config_path.exists():
try:
with open(template_config_path, encoding="utf-8") as f:
config = yaml.safe_load(f)
agent_name = agent_dir.name
settings = config.get("settings", {})
# Skip if deployment target specified and agent doesn't support it
if deployment_target:
targets = settings.get("deployment_targets", [])
if isinstance(targets, str):
targets = [targets]
if deployment_target not in targets:
continue
# Determine language (default to python)
language = settings.get("language", "python")
# Determine framework from tags
tags = settings.get("tags", [])
if "langgraph" in tags:
framework = "langgraph"
elif "adk" in tags:
framework = "adk"
else:
framework = "other"
description = config.get("description", "No description available")
display_name = config.get("display_name", agent_name)
priority = PRIORITY_ORDER.get(agent_name, 100)
agent_info = {
"name": agent_name,
"display_name": display_name,
"description": description,
"language": language,
"framework": framework,
"priority": priority,
}
agents_list.append(agent_info)
except Exception as e:
logging.warning(f"Could not load agent from {agent_dir}: {e}")
# Define group order: Python ADK, Python LangGraph, Go ADK, Other
GROUP_ORDER = {
("python", "adk"): 0,
("python", "langgraph"): 1,
("go", "adk"): 2,
}
def sort_key(agent: dict) -> tuple:
group = (agent["language"], agent["framework"])
group_order = GROUP_ORDER.get(group, 99)
return (group_order, agent["priority"], agent["name"])
agents_list.sort(key=sort_key)
# Convert to numbered dictionary starting from 1
agents = {i + 1: agent for i, agent in enumerate(agents_list)}
return agents
def load_template_config(template_dir: pathlib.Path) -> dict[str, Any]:
"""Read .templateconfig.yaml file to get agent configuration."""
config_file = template_dir / TEMPLATE_CONFIG_FILE
if not config_file.exists():
return {}
try:
with open(config_file, encoding="utf-8") as f:
config = yaml.safe_load(f)
return config if config else {}
except Exception as e:
logging.error(f"Error loading template config: {e}")
return {}
def get_agent_language(
agent_name: str, remote_config: dict[str, Any] | None = None
) -> str:
"""Get the programming language for the selected agent.
Args:
agent_name: Name of the agent
remote_config: Optional remote template configuration
Returns:
Language string ('python' or 'go'), defaults to 'python'
"""
if remote_config:
config = remote_config
else:
template_path = (
pathlib.Path(__file__).parent.parent.parent
/ "agents"
/ agent_name
/ ".template"
)
config = load_template_config(template_path)
if not config:
return "python"
language = config.get("settings", {}).get("language", "python")
if language not in SUPPORTED_LANGUAGES:
logging.warning(
f"Unsupported language '{language}' for agent {agent_name}, defaulting to python"
)
return "python"
return language
def get_deployment_targets(
agent_name: str, remote_config: dict[str, Any] | None = None
) -> list:
"""Get available deployment targets for the selected agent."""
if remote_config:
config = remote_config
else:
template_path = (
pathlib.Path(__file__).parent.parent.parent
/ "agents"
/ agent_name
/ ".template"
)
config = load_template_config(template_path)
if not config:
return []
targets = config.get("settings", {}).get("deployment_targets", [])
return targets if isinstance(targets, list) else [targets]
def prompt_deployment_target(
agent_name: str, remote_config: dict[str, Any] | None = None
) -> str:
"""Ask user to select a deployment target for the agent."""
targets = get_deployment_targets(agent_name, remote_config=remote_config)
# Define deployment target friendly names and descriptions
TARGET_INFO = {
"agent_engine": {
"display_name": "agent_engine",
"description": "Vertex AI managed platform",
},
"cloud_run": {
"display_name": "cloud_run",
"description": "GCP serverless containers",
},
}
if not targets:
return ""
console = Console()
console.print("\n> Please select a deployment target:")
console.print("\n [bold cyan]☁️ Deployment Targets[/]")
for idx, target in enumerate(targets, 1):
info = TARGET_INFO.get(target, {})
display_name = info.get("display_name", target)
description = info.get("description", "")
name_padded = display_name.ljust(14)
console.print(f" {idx}. [bold]{name_padded}[/] [dim]{description}[/]")
choice = IntPrompt.ask(
"\nEnter the number of your deployment target choice",
default=1,
show_default=True,
)
return targets[choice - 1]
def prompt_session_type_selection() -> str:
"""Ask user to select a session type for Cloud Run deployment."""
console = Console()
session_types = {
"in_memory": {
"display_name": "in_memory",
"description": "Stateless, data in memory",
},
"cloud_sql": {
"display_name": "cloud_sql",
"description": "PostgreSQL persistence",
},
"agent_engine": {
"display_name": "agent_engine",
"description": "Managed session service",
},
}
console.print("\n> Please select a session type:")
console.print("\n [bold cyan]💾 Session Types[/]")
for idx, (_key, info) in enumerate(session_types.items(), 1):
name_padded = info["display_name"].ljust(14)
console.print(
f" {idx}. [bold]{name_padded}[/] [dim]{info['description']}[/]"
)
choice = IntPrompt.ask(
"\nEnter the number of your session type choice",
default=1,
show_default=True,
)
return list(session_types.keys())[choice - 1]
def _display_datastore_menu(console: Console) -> str:
"""Display the datastore selection menu and return the selected type."""
console.print("\n> Please select a datastore:")
console.print("\n [bold cyan]🗄️ Datastores[/]")
for i, (key, info) in enumerate(DATASTORES.items(), 1):
name_padded = key.ljust(24)
console.print(f" {i}. [bold]{name_padded}[/] [dim]{info['name']}[/]")
choice = Prompt.ask(
"\nEnter the number of your choice",
choices=[str(i) for i in range(1, len(DATASTORES) + 1)],
default="1",
)
return list(DATASTORES.keys())[int(choice) - 1]
def prompt_datastore_selection(
agent_name: str, from_cli_flag: bool = False
) -> str | None:
"""Ask user to select a datastore type if the agent supports data ingestion.
Args:
agent_name: Name of the agent
from_cli_flag: Whether this is being called due to explicit --include-data-ingestion flag
"""
console = Console()
# If this is from CLI flag, skip the "would you like to include" prompt
if from_cli_flag:
return _display_datastore_menu(console)
# Otherwise, proceed with normal flow
template_path = (
pathlib.Path(__file__).parent.parent.parent
/ "agents"
/ agent_name
/ ".template"
)
config = load_template_config(template_path)
if config:
# If requires_data_ingestion is true, prompt for datastore type without asking if they want it
if config.get("settings", {}).get("requires_data_ingestion"):
console.print("\n> This agent includes a data ingestion pipeline.")
return _display_datastore_menu(console)
# Only prompt if the agent has optional data ingestion support
if "requires_data_ingestion" in config.get("settings", {}):
include = (
Prompt.ask(
"\n> This agent supports data ingestion. Would you like to include a data pipeline?",
choices=["y", "n"],
default="n",
).lower()
== "y"
)
if include:
return _display_datastore_menu(console)
# If we get here, we need to prompt for datastore selection for explicit --include-data-ingestion flag
return _display_datastore_menu(console)
def prompt_cicd_runner_selection() -> str:
"""Ask user to select a CI/CD runner."""
console = Console()
cicd_runners = {
"skip": {
"display_name": "simple",
"description": "No CI/CD, add later with 'enhance'",
},
"google_cloud_build": {
"display_name": "google_cloud_build",
"description": "Fully managed, GCP-integrated",
},
"github_actions": {
"display_name": "github_actions",
"description": "Workload identity federation",
},
}
console.print("\n> Please select a CI/CD runner:")
console.print("\n [bold cyan]🔧 CI/CD Options[/]")
for idx, (_key, info) in enumerate(cicd_runners.items(), 1):
name_padded = info["display_name"].ljust(20)
console.print(
f" {idx}. [bold]{name_padded}[/] [dim]{info['description']}[/]"
)
choice = IntPrompt.ask(
"\nEnter the number of your CI/CD runner choice",
default=1,
show_default=True,
)
return list(cicd_runners.keys())[choice - 1]
def get_template_path(agent_name: str, debug: bool = False) -> pathlib.Path:
"""Get the absolute path to the agent template directory."""
current_dir = pathlib.Path(__file__).parent.parent.parent
template_path = current_dir / "agents" / agent_name / ".template"
if debug:
logging.debug(f"Looking for template in: {template_path}")
logging.debug(f"Template exists: {template_path.exists()}")
if template_path.exists():
logging.debug(f"Template contents: {list(template_path.iterdir())}")
if not template_path.exists():
raise ValueError(f"Template directory not found at {template_path}")
return template_path
def copy_data_ingestion_files(
project_template: pathlib.Path, datastore_type: str
) -> None:
"""Copy data processing files to the project template for cookiecutter templating.
Args:
project_template: Path to the project template directory
datastore_type: Type of datastore to use for data ingestion
"""
data_ingestion_src = pathlib.Path(__file__).parent.parent.parent / "data_ingestion"
data_ingestion_dst = project_template / "data_ingestion"
if data_ingestion_src.exists():
logging.debug(
f"Copying data processing files from {data_ingestion_src} to {data_ingestion_dst}"
)
copy_files(data_ingestion_src, data_ingestion_dst, overwrite=True)
logging.debug(f"Data ingestion files prepared for datastore: {datastore_type}")
else:
logging.warning(
f"Data processing source directory not found at {data_ingestion_src}"
)
def _extract_agent_garden_labels(
agent_garden: bool,
remote_spec: Any | None,
remote_template_path: pathlib.Path | None,
) -> tuple[str | None, str | None]:
"""Extract agent sample ID and publisher for Agent Garden labeling.
This function supports two mechanisms for extracting label information:
1. From remote_spec metadata (for ADK samples)
2. Fallback to pyproject.toml parsing (for version-locked templates)
Args:
agent_garden: Whether this deployment is from Agent Garden
remote_spec: Remote template spec with ADK samples metadata
remote_template_path: Path to remote template directory
Returns:
Tuple of (agent_sample_id, agent_sample_publisher) or (None, None) if no labels found
"""
if not agent_garden:
return None, None
agent_sample_id = None
agent_sample_publisher = None
# Handle remote specs with ADK samples metadata
if (
remote_spec
and hasattr(remote_spec, "is_adk_samples")
and remote_spec.is_adk_samples
):
# For ADK samples, template_path is like "python/agents/sample-name"
agent_sample_id = pathlib.Path(remote_spec.template_path).name
# For ADK samples, publisher is always "google"
agent_sample_publisher = "google"
logging.debug(f"Detected ADK sample from remote_spec: {agent_sample_id}")
return agent_sample_id, agent_sample_publisher
# Fallback: Detect ADK samples from pyproject.toml (for version-locked templates)
if remote_template_path:
pyproject_path = remote_template_path / "pyproject.toml"
if pyproject_path.exists():
try:
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
with open(pyproject_path, "rb") as toml_file:
pyproject_data = tomllib.load(toml_file)
# Extract project name from pyproject.toml
project_name_from_toml = pyproject_data.get("project", {}).get("name")
if project_name_from_toml:
agent_sample_id = project_name_from_toml
agent_sample_publisher = "google" # ADK samples are from Google
logging.debug(
f"Detected ADK sample from pyproject.toml: {agent_sample_id}"
)
except Exception as e:
logging.debug(f"Failed to read pyproject.toml: {e}")
return agent_sample_id, agent_sample_publisher
def _inject_app_object_if_missing(
agent_py_path: pathlib.Path, agent_directory: str, console: Console
) -> None:
"""Inject app object into agent.py if missing (backward compatibility for ADK).
Args:
agent_py_path: Path to the agent.py file
agent_directory: Name of the agent directory for logging
console: Rich console for user feedback
"""
try:
content = agent_py_path.read_text(encoding="utf-8")
# Check for app object (assignment, function definition, or import)
app_patterns = [
r"^\s*app\s*=", # assignment: app = ...
r"^\s*def\s+app\(", # function: def app(...)
r"from\s+.*\s+import\s+.*\bapp\b", # import: from ... import app
]
has_app = any(
re.search(pattern, content, re.MULTILINE) for pattern in app_patterns
)
if not has_app:
console.print(
f"ℹ️ Adding 'app' object to [cyan]{agent_directory}/agent.py[/cyan] for backward compatibility",
style="dim",
)
# Add import and app object at the end of the file
content = content.rstrip()
if "from google.adk.apps import App" not in content:
content += "\n\nfrom google.adk.apps import App\n"
content += f'\napp = App(root_agent=root_agent, name="{agent_directory}")\n'
# Write the modified content back
agent_py_path.write_text(content, encoding="utf-8")
except Exception as e:
logging.warning(
f"Could not inject app object into {agent_directory}/agent.py: {type(e).__name__}: {e}"
)
def _generate_yaml_agent_shim(
agent_py_path: pathlib.Path,
agent_directory: str,
console: Console,
force: bool = False,
) -> None:
"""Generate agent.py shim for YAML config agents.
When a root_agent.yaml is detected, this function generates an agent.py
that loads the YAML config and exposes the root_agent and app objects
required by the deployment pipeline.
Args:
agent_py_path: Path where agent.py should be created/updated
agent_directory: Name of the agent directory for logging
console: Rich console for user feedback
force: If True, overwrite existing agent.py even if it has root_agent defined.
Used when the user explicitly has a root_agent.yaml.
"""
root_agent_yaml = agent_py_path.parent / "root_agent.yaml"
if not root_agent_yaml.exists():
return
# Check if agent.py already exists and has root_agent defined
if agent_py_path.exists() and not force:
try:
content = agent_py_path.read_text(encoding="utf-8")
if re.search(r"^\s*root_agent\s*=", content, re.MULTILINE):
logging.debug(
f"{agent_directory}/agent.py already has root_agent defined"
)
return
except Exception as e:
logging.warning(f"Could not read existing agent.py: {e}")
console.print(
f"ℹ️ Generating [cyan]{agent_directory}/agent.py[/cyan] shim for YAML config agent",
style="dim",
)
shim_content = f'''"""Agent module that loads the YAML config agent.
This file is auto-generated to provide compatibility with the deployment pipeline.
Edit root_agent.yaml to modify your agent configuration.
"""
from pathlib import Path
from google.adk.agents import config_agent_utils
from google.adk.apps import App
_AGENT_DIR = Path(__file__).parent
root_agent = config_agent_utils.from_config(str(_AGENT_DIR / "root_agent.yaml"))
app = App(root_agent=root_agent, name="{agent_directory}")
'''
try:
agent_py_path.write_text(shim_content, encoding="utf-8")
logging.debug(f"Generated YAML agent shim at {agent_py_path}")
except Exception as e:
logging.warning(
f"Could not generate YAML agent shim at {agent_py_path}: {type(e).__name__}: {e}"
)
def process_template(
agent_name: str,
template_dir: pathlib.Path,
project_name: str,
deployment_target: str | None = None,
cicd_runner: str | None = None,
include_data_ingestion: bool = False,
datastore: str | None = None,
session_type: str | None = None,
output_dir: pathlib.Path | None = None,
remote_template_path: pathlib.Path | None = None,
remote_config: dict[str, Any] | None = None,
in_folder: bool = False,
cli_overrides: dict[str, Any] | None = None,
agent_garden: bool = False,
remote_spec: Any | None = None,
google_api_key: str | None = None,
google_cloud_project: str | None = None,
) -> None:
"""Process the template directory and create a new project.
Args:
agent_name: Name of the agent template to use
template_dir: Directory containing the template files
project_name: Name of the project to create
deployment_target: Optional deployment target (agent_engine or cloud_run)
cicd_runner: Optional CI/CD runner to use
include_data_ingestion: Whether to include data pipeline components
datastore: Optional datastore type for data ingestion
session_type: Optional session type for cloud_run deployment
output_dir: Optional output directory path, defaults to current directory
remote_template_path: Optional path to remote template for overlay
remote_config: Optional remote template configuration
in_folder: Whether to template directly into the output directory instead of creating a subdirectory
cli_overrides: Optional CLI override values that should take precedence over template config
agent_garden: Whether this deployment is from Agent Garden
google_api_key: Optional Google AI Studio API key to generate .env file
google_cloud_project: Optional GCP project ID to populate .env file
"""
logging.debug(f"Processing template from {template_dir}")
logging.debug(f"Project name: {project_name}")
logging.debug(f"Include pipeline: {datastore}")
logging.debug(f"Output directory: {output_dir}")
# Create console for user feedback
console = Console()
def get_agent_directory(
template_config: dict[str, Any], cli_overrides: dict[str, Any] | None = None
) -> str:
"""Get agent directory with CLI override support.
Handles the special case where agent_directory is "." (flat structure),
deriving the target directory name from the remote template folder name.
"""
agent_dir = None
if (
cli_overrides
and "settings" in cli_overrides
and "agent_directory" in cli_overrides["settings"]
):
agent_dir = cli_overrides["settings"]["agent_directory"]
else:
agent_dir = template_config.get("settings", {}).get(
"agent_directory", "app"
)
# Handle "." (flat structure) - derive target from folder name
if agent_dir == ".":
if remote_template_path:
# Derive from remote template folder name
folder_name = remote_template_path.name.replace("-", "_")
logging.debug(
f"Flat structure (-dir .): deriving target '{folder_name}' from folder name"
)
agent_dir = folder_name
else:
# Fallback to "app" for non-remote templates
logging.debug("Flat structure (-dir .): using 'app' as fallback")
agent_dir = "app"
# Validate agent directory is a valid Python identifier
validate_agent_directory_name(agent_dir)
return agent_dir
# Handle remote vs local templates
is_remote = remote_template_path is not None
if is_remote:
# For remote templates, determine the base template
base_template_name = get_base_template_name(remote_config or {})
agent_path = (
pathlib.Path(__file__).parent.parent.parent / "agents" / base_template_name
)
logging.debug(f"Remote template using base: {base_template_name}")
elif cli_overrides and cli_overrides.get("base_template"):