Address PR feedback: Add logging, input validation, and error handling

Co-Authored-By: Joe Moura <joao@crewai.com>
This commit is contained in:
Devin AI
2025-04-05 22:38:38 +00:00
parent 79cf137f72
commit 4fd75203bc
3 changed files with 28 additions and 1 deletions

View File

@@ -4,10 +4,15 @@ Example script showing how to run a CrewAI flow from a custom script.
This example demonstrates how to avoid the ModuleNotFoundError when
starting flows from custom scripts outside of the CLI command context.
"""
import logging
import os
from crewai.utilities.path_utils import add_project_to_path
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("Adding project directory to Python path")
add_project_to_path()
from my_flow.main import MyFlow # noqa: E402

View File

@@ -9,7 +9,11 @@ def kickoff_flow() -> None:
"""
Kickoff the flow by running a command in the UV environment.
"""
add_project_to_path()
try:
add_project_to_path()
except ValueError as e:
click.echo(f"Error setting up project path: {e}", err=True)
return
command = ["uv", "run", "kickoff"]

View File

@@ -1,9 +1,13 @@
import logging
import os
import sys
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
def add_project_to_path(project_dir: Optional[str] = None) -> None:
"""
Add the project directory to the Python path to resolve module imports.
@@ -15,6 +19,9 @@ def add_project_to_path(project_dir: Optional[str] = None) -> None:
project_dir: Optional path to the project directory. If not provided,
the current working directory is used.
Raises:
ValueError: If the provided directory does not exist.
Example:
```python
from crewai.utilities.path_utils import add_project_to_path
@@ -29,15 +36,26 @@ def add_project_to_path(project_dir: Optional[str] = None) -> None:
"""
if project_dir is None:
project_dir = os.getcwd()
logger.debug(f"Using current working directory: {project_dir}")
else:
logger.debug(f"Using provided directory: {project_dir}")
project_path = Path(project_dir).resolve()
if not project_path.exists():
raise ValueError(f"Invalid directory: {project_dir} does not exist")
if (project_path / "src").exists() and (project_path / "src").is_dir():
logger.debug(f"Found 'src' directory in {project_path}")
if str(project_path) not in sys.path:
sys.path.insert(0, str(project_path))
logger.debug(f"Added {project_path} to sys.path")
if str(project_path / "src") not in sys.path:
sys.path.insert(0, str(project_path / "src"))
logger.debug(f"Added {project_path / 'src'} to sys.path")
else:
logger.debug(f"No 'src' directory found in {project_path}")
if str(project_path) not in sys.path:
sys.path.insert(0, str(project_path))
logger.debug(f"Added {project_path} to sys.path")