Skip to content

Commit 74ee875

Browse files
committed
some beauty updates
1 parent 339a805 commit 74ee875

File tree

3 files changed

+22
-62
lines changed

3 files changed

+22
-62
lines changed

sgr_agent_core/agent_config.py

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,6 @@ def from_yaml(cls, yaml_path: str) -> Self:
3838
yaml_path = Path(yaml_path)
3939
if not yaml_path.exists():
4040
raise FileNotFoundError(f"Configuration file not found: {yaml_path}")
41-
42-
# Add config file directory to sys.path for dynamic imports
43-
config_dir = str(yaml_path.resolve().parent)
44-
if config_dir not in sys.path:
45-
sys.path.insert(0, config_dir)
46-
4741
config_data = yaml.safe_load(yaml_path.read_text(encoding="utf-8"))
4842
main_config_agents = config_data.pop("agents", {})
4943
if cls._instance is None:
@@ -54,15 +48,11 @@ def from_yaml(cls, yaml_path: str) -> Self:
5448
cls._initialized = False
5549
cls._instance = cls(**config_data, agents=cls._instance.agents)
5650
# agents should be initialized last to allow merging
57-
cls._definitions_from_dict({"agents": main_config_agents}, config_dir=config_dir)
51+
cls._definitions_from_dict({"agents": main_config_agents})
5852
return cls._instance
5953

6054
@classmethod
61-
def _definitions_from_dict(cls, agents_data: dict, config_dir: str | None = None) -> Self:
62-
# Add config directory to sys.path if provided
63-
if config_dir and config_dir not in sys.path:
64-
sys.path.insert(0, config_dir)
65-
55+
def _definitions_from_dict(cls, agents_data: dict) -> Self:
6656
for agent_name, agent_config in agents_data.get("agents", {}).items():
6757
agent_config["name"] = agent_name
6858

@@ -92,14 +82,13 @@ def definitions_from_yaml(cls, agents_yaml_path: str) -> Self:
9282
ValueError: If YAML file doesn't contain 'agents' key
9383
"""
9484
agents_yaml_path = Path(agents_yaml_path)
95-
config_dir = str(agents_yaml_path.resolve().parent)
96-
if config_dir not in sys.path:
97-
sys.path.insert(0, config_dir)
85+
86+
sys.path.append(str(agents_yaml_path.resolve().parent))
9887
if not agents_yaml_path.exists():
9988
raise FileNotFoundError(f"Agents definitions file not found: {agents_yaml_path}")
10089

10190
yaml_data = yaml.safe_load(agents_yaml_path.read_text(encoding="utf-8"))
10291
if not yaml_data.get("agents"):
10392
raise ValueError(f"Agents definitions file must contain 'agents' key: {agents_yaml_path}")
10493

105-
return cls._definitions_from_dict(yaml_data, config_dir=config_dir)
94+
return cls._definitions_from_dict(yaml_data)

sgr_agent_core/agent_definition.py

Lines changed: 15 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
import importlib.util
12
import inspect
23
import logging
34
import os
4-
import sys
55
from functools import cached_property
66
from pathlib import Path
77
from typing import Any, Self
@@ -138,56 +138,26 @@ class AgentDefinition(AgentConfig):
138138

139139
@field_validator("base_class", mode="before")
140140
def base_class_import_points_to_file(cls, v: Any) -> Any:
141-
"""Ensure ImportString based base_class points to an existing file or
142-
package directory to catch a FileError and not interpret it as str
143-
class_name.
141+
"""Ensure ImportString based base_class points to an existing file to
142+
catch a FileError and not interpret it as str class_name.
144143
145144
A dotted path indicates an import string (e.g.,
146-
my_pkg.module.Class). We map the module portion to either:
147-
- A .py file (e.g., my_module.py)
148-
- A package directory with __init__.py (e.g., my_module/__init__.py)
149-
150-
Checks relative to current working directory and sys.path entries
151-
(including config file directory).
145+
dir.agent.MyAgent). We use importlib to automatically search for
146+
the module in sys.path.
152147
"""
153148
if isinstance(v, str) and "." in v:
154149
module_parts = v.split(".")
155150
if len(module_parts) >= 2:
156-
module_path = os.sep.join(module_parts[:-1])
157-
158-
def check_module_exists(base_path: Path) -> bool:
159-
"""Check if module exists as file or package directory."""
160-
# Check for .py file
161-
file_candidate = base_path / (module_path + ".py")
162-
if file_candidate.exists():
163-
return True
164-
165-
# Check for package directory with __init__.py
166-
package_candidate = base_path / module_path / "__init__.py"
167-
if package_candidate.exists():
168-
return True
169-
170-
return False
171-
172-
# Try to find relative to current working directory first
173-
if check_module_exists(Path.cwd()):
174-
return v
175-
176-
# Try to find relative to sys.path entries (including config directory)
177-
for sys_path in sys.path:
178-
if sys_path:
179-
base_path = Path(sys_path)
180-
if check_module_exists(base_path):
181-
return v
182-
183-
# If not found, raise error with helpful message
184-
file_candidate = Path(os.sep.join(module_parts[:-1]) + ".py")
185-
package_candidate = Path(os.sep.join(module_parts[:-1])) / "__init__.py"
186-
raise FileNotFoundError(
187-
f"base_class import '{v}' points to module '{module_path}', but neither "
188-
f"'{file_candidate}' nor '{package_candidate}' exists. "
189-
f"Checked relative to current directory and sys.path entries."
190-
)
151+
# Get module path (everything except the class name)
152+
module_path = ".".join(module_parts[:-1])
153+
# Use importlib to find module in sys.path automatically
154+
spec = importlib.util.find_spec(module_path)
155+
if spec is None or spec.origin is None:
156+
file_path = Path(*module_parts[:-1]).with_suffix(".py")
157+
raise FileNotFoundError(
158+
f"base_class import '{v}' points to '{file_path}', "
159+
f"but the file could not be found in sys.path"
160+
)
191161
return v
192162

193163
@model_validator(mode="before")

sgr_agent_core/server/settings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ def setup_logging(logging_file: str) -> None:
2727
"""
2828
logging_config_path = Path(logging_file)
2929
if not logging_config_path.exists():
30-
raise FileNotFoundError(f"Logging config file not found: {logging_config_path}")
30+
logger.warning(f"Logging config file not found: {logging_config_path}")
31+
return
3132

3233
with open(logging_config_path, "r", encoding="utf-8") as f:
3334
logging_config = yaml.safe_load(f)

0 commit comments

Comments
 (0)