Skip to content

Commit 9231b68

Browse files
committed
fix(cli): load .env file before agent import validation in deploy
When using `adk deploy agent_engine --validate-agent-import`, the `_validate_agent_import` function imports the agent module without first loading `.env` files. This causes agents that depend on environment variables at import time (e.g. pydantic BaseSettings) to fail validation with errors like `ValidationError`. This fix calls `envs.load_dotenv_for_agent()` before the `importlib.import_module()` call, consistent with how `AgentLoader` already handles `.env` loading during normal agent loading. Fixes #4688
1 parent 36e76b9 commit 9231b68

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

src/google/adk/cli/cli_deploy.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
import click
2929
from packaging.version import parse
3030

31+
from .utils import envs
32+
3133
_IS_WINDOWS = os.name == 'nt'
3234
_GCLOUD_CMD = 'gcloud.cmd' if _IS_WINDOWS else 'gcloud'
3335
_LOCAL_STORAGE_FLAG_MIN_VERSION: Final[str] = '1.21.0'
@@ -509,6 +511,12 @@ def _validate_agent_import(
509511
# Add parent directory to path so imports work correctly
510512
if parent_dir not in sys.path:
511513
sys.path.insert(0, parent_dir)
514+
515+
# Load .env file before importing the agent module so that
516+
# environment-dependent code (e.g. pydantic BaseSettings) can resolve
517+
# variables during import.
518+
envs.load_dotenv_for_agent(module_name, parent_dir)
519+
512520
try:
513521
module = importlib.import_module(f'{module_name}.agent')
514522
except ImportError as e:

tests/unittests/cli/utils/test_cli_deploy.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from __future__ import annotations
1818

1919
import importlib
20+
import os
2021
from pathlib import Path
2122
import shutil
2223
import subprocess
@@ -654,3 +655,25 @@ def test_restores_sys_path(self, tmp_path: Path) -> None:
654655
)
655656

656657
assert sys.path == original_path
658+
659+
def test_loads_dotenv_before_import(self, tmp_path: Path) -> None:
660+
"""Should load .env file before importing agent module."""
661+
# Create agent.py that reads an env var at import time
662+
(tmp_path / "__init__.py").touch()
663+
(tmp_path / "agent.py").write_text(
664+
"import os\n"
665+
"val = os.environ.get('_ADK_TEST_DEPLOY_VAR')\n"
666+
"if val != 'from_dotenv':\n"
667+
" raise RuntimeError("
668+
"'_ADK_TEST_DEPLOY_VAR not loaded from .env')\n"
669+
"root_agent = 'ok'\n"
670+
)
671+
(tmp_path / ".env").write_text("_ADK_TEST_DEPLOY_VAR=from_dotenv\n")
672+
673+
# Should not raise because .env is loaded before import
674+
cli_deploy._validate_agent_import(
675+
str(tmp_path), "root_agent", is_config_agent=False
676+
)
677+
678+
# Clean up the env var
679+
os.environ.pop("_ADK_TEST_DEPLOY_VAR", None)

0 commit comments

Comments
 (0)