adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

[Reasoning Engine] ModuleNotFoundError - During ADK Agent deployment despite correct packaging

Open reyolivo opened this issue 1 year ago • 1 comments

Component: Vertex AI Reasoning Engines, Google ADK

Description: We are encountering a persistent “ModuleNotFoundError” (No module named 'src') when deploying an ADK Agent to Agent Engine. This error occurs during the remote unpickling process, suggesting the remote environment cannot locate our project's modules.

The application and all multi-agent interactions work correctly when tested locally, including when served via the adk web command. This indicates the issue is specific to the remote deployment and unpickling process on Vertex AI, not an issue with the agent logic itself.

We have followed standard Python packaging practices using a src layout with Poetry, but the issue remains. We have attempted solutions using both absolute and relative imports, as well as explicitly including the project's packaged .whl file in the extra_packages argument of the deployment function. None of these approaches have resolved the error.

Error Message: The deployment fails with the following traceback from the Vertex AI logs:

ERROR:    Pickle load failed: Missing module. Service terminating. A required module, present when the agent object was pickled locally, is missing in the remote environment. Please ensure all necessary dependencies used by the agent object are included in `extra_packages` or `requirements.txt`, or remove unused but imported dependencies in the agent object. Traceback: Traceback (most recent call last):
  File "/code/app/api/factory/python_file_api_builder.py", line 893, in create_apis
    obj = utils.get_object(python_file_name)
  File "/code/app/api/factory/utils.py", line 154, in get_object
    obj = get_local_object(obj_filename)
  File "/code/app/api/factory/utils.py", line 173, in get_local_object
    return cloudpickle.loads(f.read())
ModuleNotFoundError: No module named 'src'

Project Structure: Our project uses a standard src layout with a multi-agent structure. The workflow_agent is the main entry point and it imports other specialized agents. . ├── poetry.lock ├── pyproject.toml ├── dist/ │ └── my_project-0.1.0-py3-none-any.whl └── src/ ├── init.py └── agent_suite/ ├── init.py ├── agents/ │ ├── init.py │ ├── workflow_agent/ # Main agent being deployed │ │ ├── init.py │ │ └── agent.py │ ├── specialty_agent_one/ # Imported by workflow_agent │ │ ├── init.py │ │ └── agent.py │ └── specialty_agent_two/ # Imported by workflow_agent │ ├── init.py │ └── agent.py └── deployment/ ├── init.py └── deploymentManagement.py

Workflow Agent Code Example: This is the ~pseudo-code for the workflow_agent that is being deployed. Note how it is composed of several sub-agents and dispatches tasks to other imported specialty agents.

# In src/agent_suite/agents/workflow_agent/agent.py

from google.adk.agents import LlmAgent, SequentialAgent, LoopAgent
from google.adk.tools.agent_tool import AgentTool
from google.genai.types import GenerateContentConfig
from google.genai import types as genai_types
from google.adk.planners import BuiltInPlanner

# Imports for other agents and tools (using relative imports)
from ..specialty_agent_one.agent import root_agent as specialty_agent_one
from ..specialty_agent_two.agent import root_agent as specialty_agent_two
from ..specialty_agent_three.agent import root_agent as specialty_agent_three
from ..specialty_agent_four.agent import root_agent as specialty_agent_four
from ..specialty_agent_five.agent import root_agent as specialty_agent_five
from ...tools.responseTools import finalize_response_tool
from ...common.utils import agentSetupUtils

# Assume llmConfig and envType are loaded

# --- Agent Definitions ---

categorization_agent_name = "categorization_agent"
categorization_agent = LlmAgent(
    name=categorization_agent_name,
    model=llmConfig[categorization_agent_name][envType]['model'],
    disallow_transfer_to_parent=True,
    instruction=agentSetupUtils.getSystemInstructionsForAgent(llmConfig, categorization_agent_name, False, False, envType),
    description=llmConfig[categorization_agent_name]['default']['description'],
    generate_content_config=GenerateContentConfig(temperature=llmConfig[categorization_agent_name][envType]['temperature']),
    output_key="categoryOutput"
)

dispatch_agent_name = "dispatch_agent"
dispatch_agent = LlmAgent(
    name=dispatch_agent_name,
    model=llmConfig[dispatch_agent_name][envType]['model'],
    instruction=agentSetupUtils.getSystemInstructionsForAgent(llmConfig, dispatch_agent_name, True, False, envType),
    description=llmConfig[dispatch_agent_name]['default']['description'],
    disallow_transfer_to_parent=True,
    tools=[AgentTool(specialty_agent_one), 
           AgentTool(specialty_agent_two), 
           AgentTool(specialty_agent_three), 
           AgentTool(specialty_agent_four),
           AgentTool(specialty_agent_five)],
    generate_content_config=GenerateContentConfig(temperature=llmConfig[dispatch_agent_name][envType]['temperature']),
    output_key="responseOutput"
)

validation_agent_name = "validation_agent"
validation_agent = LlmAgent(
    name=validation_agent_name,
    model=llmConfig[validation_agent_name][envType]['model'],
    disallow_transfer_to_parent=True,
    instruction=agentSetupUtils.getSystemInstructionsForAgent(llmConfig, validation_agent_name, True, True, envType),
    description=llmConfig[validation_agent_name]['default']['description'],
    generate_content_config=GenerateContentConfig(temperature=llmConfig[validation_agent_name][envType]['temperature']),
    output_key="validatedOutput"
)

final_response_agent_name = "final_response_agent"
final_response_agent = LlmAgent(
    name=final_response_agent_name,
    model=llmConfig[final_response_agent_name][envType]['model'],
    planner=BuiltInPlanner(
        thinking_config=genai_types.ThinkingConfig(include_thoughts=True)
    ),
    instruction=agentSetupUtils.getSystemInstructionsForAgent(llmConfig, final_response_agent_name, True, True, envType),
    description=llmConfig[final_response_agent_name]['default']['description'],
    generate_content_config=GenerateContentConfig(temperature=llmConfig[validation_agent_name][envType]['temperature']),
    tools=[finalize_response_tool],
    output_key="exitOutput"
)

processing_loop_agent_name = "processing_loop_agent"
processing_loop_agent = LoopAgent(
    name=processing_loop_agent_name,
    max_iterations=3,
    sub_agents=[dispatch_agent, validation_agent, final_response_agent]
)

root_agent_name="workflow_agent"
root_agent = SequentialAgent(
    name=root_agent_name,
    description=llmConfig[root_agent_name]['default']['description'],
    sub_agents=[categorization_agent, processing_loop_agent]
)

Deployment Code:

# From src/agent_suite/deployment/deploymentManagement.py

import vertexai
from vertexai import agent_engines

# ... (setup code for project_id, location, etc.)

def deploy_agent(agent_name: str = "workflow_agent"):
    """Deploys the specified agent to Vertex AI Reasoning Engines."""

    # Path to the agent's root module
    agent_module_path = f"src.agent_suite.agents.{agent_name}.agent"

    # Path to the wheel file generated by 'poetry build'
    whl_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../dist/ai_hub-1.0.0-py3-none-any.whl'))
    print(f"whl_path: {whl_path}")

    remote_agent = agent_engines.create(
            adk_app,
            display_name=args.display_name,
            description=args.description,
            gcs_dir_name=args.gcs_dir_name,
            requirements=args.requirements,
            env_vars=args.env_vars,
            extra_packages=[whl_path]
        )
    )
    print(f"Successfully created reasoning engine: {reasoning_engine.resource_name}")
    return remote_agent 

Attempted Solutions & Analysis: Local Execution Success: The entire multi-agent application runs without import errors locally and when using the adk web local test server. This strongly suggests that our packaging and import logic is correct for a local context.

output_schema vs. LoopAgent Workaround: The core of the issue originally appeared when we attempted to use an output_schema in the last step of our workflow_agent, before this, our multi-agent system deployed fine though it had issues with output consistency. We removed the output_schema and tried to use a LoopAgent with a tool-based exit condition (final_response_agent) to structure the final output. This workaround works correctly locally but still faces the same deployment error, indicating the problem is with pickling the agent structure itself, not a specific feature.

Absolute Imports: Initially, our agent code used absolute imports (e.g., from src.agent_suite.agents.specialty_agent_one.agent import root_agent as specialty_agent_one). This worked locally but failed on deployment with the ModuleNotFoundError: No module named 'src'. Relative Imports: We refactored the entire agent_suite package to use relative imports (e.g., from ..specialty_agent_one.agent import root_agent as specialty_agent_one). Still no luck. Packaging with Poetry: We have configured pyproject.toml to correctly identify the package within the src directory (packages = [{include = "agent_suite", from = "src"}]). We built a .whl file using poetry build. extra_packages: We explicitly included the path to the generated .whl file in the extra_packages list during ReasoningEngine.create.

Despite these steps, the ModuleNotFoundError: No module named 'src' persists on deployment. This suggests that even when our packaged code is available in the remote environment, the unpickling process is still attempting to resolve dependencies using an absolute path that includes src, which does not exist in the remote Python path. This seems to indicate an issue with how the agent object is pickled locally and/or how its dependencies are resolved upon unpickling in the Vertex AI environment.

Would love any guidance to resolve this issue, as it has been painful to debug.

Thanks

reyolivo avatar Jul 18 '25 20:07 reyolivo

We are all set here. I ended up having to run the deployment command from my 'src' folder and include the parent folder ('agent_suite') as the extra_packages variables instead. No .whl file was needed

reyolivo avatar Jul 21 '25 18:07 reyolivo