8000 fix: handle the case when agent loading error doesn't have msg attrib… · devevignesh/adk-python@c224626 · GitHub
[go: up one dir, main page]

Skip to content

Commit c224626

Browse files
seanzhougooglecopybara-github
authored andcommitted
fix: handle the case when agent loading error doesn't have msg attribute in agent loader
PiperOrigin-RevId: 767447874
1 parent 78bfce4 commit c224626

File tree

2 files changed

+54
-4
lines changed

2 files changed

+54
-4
lines changed

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,12 @@ def _load_from_module_or_package(
7676
e.msg = f"Fail to load '{agent_name}' module. " + e.msg
7777
raise e
7878
except Exception as e:
79-
e.msg = f"Fail to load '{agent_name}' module. " + e.msg
79+
if hasattr(e, "msg"):
80+
e.msg = f"Fail to load '{agent_name}' module. " + e.msg
81+
raise e
82+
e.args = (
83+
f"Fail to load '{agent_name}' module. {e.args[0] if e.args else ''}",
84+
) + e.args[1:]
8085
raise e
8186

8287
return None
@@ -110,7 +115,15 @@ def _load_from_submodule(self, agent_name: str) -> Optional[BaseAgent]:
110115
e.msg = f"Fail to load '{agent_name}.agent' module. " + e.msg
111116
raise e
112117
except Exception as e:
113-
e.msg = f"Fail to load '{agent_name}.agent' module. " + e.msg
118+
if hasattr(e, "msg"):
119+
e.msg = f"Fail to load '{agent_name}.agent' module. " + e.msg
120+
raise e
121+
e.args = (
122+
(
123+
f"Fail to load '{agent_name}.agent' module."
124+
f" {e.args[0] if e.args else ''}"
125+
),
126+
) + e.args[1:]
114127
raise e
115128

116129
return None

tests/unittests/cli/utils/test_agent_loader.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ def __init__(self):
351351
assert f"Fail to load '{agent_name}' module." in str(exc_info.value)
352352
assert "No module named 'non_existent_module'" in str(exc_info.value)
353353

354-
def test_agent_internal_import_error(self):
354+
def test_agent_internal_syntax_error(self):
355355
"""Test other import errors within an agent's code (e.g., SyntaxError)."""
356356
with tempfile.TemporaryDirectory() as temp_dir:
357357
temp_path = Path(temp_dir)
@@ -380,10 +380,47 @@ def __init__(self):
380380
) as exc_info: # Or potentially ImportError depending on Python version specifics with importlib
381381
loader.load_agent(agent_name)
382382

383-
assert f"Fail to load '{agent_name}' module." in str(exc_info.value)
383+
assert str(exc_info.value).startswith(
384+
f"Fail to load '{agent_name}' module."
385+
)
384386
# Check for part of the original SyntaxError message
385387
assert "invalid syntax" in str(exc_info.value).lower()
386388

389+
def test_agent_internal_name_error(self):
390+
"""Test other import errors within an agent's code (e.g., SyntaxError)."""
391+
with tempfile.TemporaryDirectory() as temp_dir:
392+
temp_path = Path(temp_dir)
393+
agent_name = "name_error_agent"
394+
395+
# Create agent with a syntax error (which leads to ImportError)
396+
agent_file = temp_path / f"{agent_name}.py"
397+
agent_file.write_text(dedent(f"""
398+
from google.adk.agents.base_agent import BaseAgent
399+
400+
# name is not defined
401+
print(non_existing_name)
402+
403+
class {agent_name.title()}Agent(BaseAgent):
404+
def __init__(self):
405+
super().__init__(name="{agent_name}")
406+
407+
root_agent = {agent_name.title()}Agent()
408+
"""))
409+
410+
loader = AgentLoader(str(temp_path))
411+
# SyntaxError is a subclass of Exception, and importlib might wrap it
412+
# The loader is expected to prepend its message and re-raise.
413+
with pytest.raises(
414+
NameError
415+
) as exc_info: # Or potentially ImportError depending on Python version specifics with importlib
416+
loader.load_agent(agent_name)
417+
418+
assert str(exc_info.value).startswith(
419+
f"Fail to load '{agent_name}' module."
420+
)
421+
# Check for part of the original SyntaxError message
422+
assert "is not defined" in str(exc_info.value).lower()
423+
387424
def test_sys_path_modification(self):
388425 3F4C
"""Test that agents_dir is added to sys.path correctly."""
389426
with tempfile.TemporaryDirectory() as temp_dir:

0 commit comments

Comments
 (0)
0