Skip to content

Commit b845520

Browse files
Merge pull request #1278 from MervinPraison/fix/agent-init-type-hints
fix(types): widen type hints for agent init
2 parents a10af4e + a42c6d3 commit b845520

2 files changed

Lines changed: 129 additions & 18 deletions

File tree

src/praisonai-agents/praisonaiagents/agent/agent.py

Lines changed: 126 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -488,18 +488,18 @@ def __init__(
488488
reflection: Optional[Union[bool, str, 'ReflectionConfig']] = None,
489489
guardrails: Optional[Union[bool, str, Callable, 'GuardrailConfig']] = None,
490490
web: Optional[Union[bool, str, 'WebConfig']] = None,
491-
context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
492-
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,
491+
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
492+
autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
493493
verification_hooks: Optional[List[Any]] = None, # Deprecated: use autonomy=AutonomyConfig(verification_hooks=[...])
494-
output: Optional[Union[str, 'OutputConfig']] = None,
495-
execution: Optional[Union[str, 'ExecutionConfig']] = None,
496-
templates: Optional['TemplateConfig'] = None,
497-
caching: Optional[Union[bool, 'CachingConfig']] = None,
498-
hooks: Optional[Union[List[Any], 'HooksConfig']] = None,
499-
skills: Optional[Union[List[str], 'SkillsConfig']] = None,
500-
approval: Optional[Union[bool, str, 'ApprovalConfig', 'ApprovalProtocol']] = None,
494+
output: Optional[Union[bool, str, Dict[str, Any], 'OutputConfig']] = None,
495+
execution: Optional[Union[bool, str, Dict[str, Any], 'ExecutionConfig']] = None,
496+
templates: Optional[Union[Dict[str, Any], 'TemplateConfig']] = None,
497+
caching: Optional[Union[bool, str, Dict[str, Any], 'CachingConfig']] = None,
498+
hooks: Optional[Union[List[Any], Dict[str, Any], 'HooksConfig']] = None,
499+
skills: Optional[Union[List[str], str, Dict[str, Any], 'SkillsConfig']] = None,
500+
approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
501501
tool_timeout: Optional[int] = None, # P8/G11: Timeout in seconds for each tool call
502-
learn: Optional[Union[bool, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)
502+
learn: Optional[Union[bool, str, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)
503503
):
504504
"""Initialize an Agent instance.
505505
@@ -544,22 +544,32 @@ def __init__(
544544
- WebConfig: Custom configuration
545545
context: Context management. Accepts:
546546
- bool: True enables with defaults
547-
- ManagerConfig: Custom configuration
547+
- str: Preset name ("sliding_window", "summarize", "truncate")
548+
- Dict[str, Any]: ContextConfig fields
549+
- ContextConfig: Custom configuration
550+
- ContextManager: Pre-configured instance
548551
autonomy: Autonomy settings. Accepts:
549552
- bool: True enables with defaults
550-
- Dict: Configuration dict
553+
- str: Level preset ("suggest", "auto_edit", "full_auto")
554+
- Dict[str, Any]: Configuration dict
551555
- AutonomyConfig: Custom configuration
552556
verification_hooks: **Deprecated** — use ``autonomy=AutonomyConfig(verification_hooks=[...])``.
553557
Still works for backward compatibility.
554558
output: Output configuration. Accepts:
559+
- bool: True=default OutputConfig, False=disabled
555560
- str: Preset name ("silent", "actions", "verbose", "json", "stream")
561+
- Dict[str, Any]: Config overrides (e.g. {"verbose": 2, "stream": True})
556562
- OutputConfig: Custom configuration
557563
Controls: verbose, markdown, stream, metrics, reasoning_steps
558564
execution: Execution configuration. Accepts:
565+
- bool: True=default ExecutionConfig, False=disabled
559566
- str: Preset name ("fast", "balanced", "thorough")
567+
- Dict[str, Any]: Config overrides (e.g. {"max_iter": 10, "max_rpm": 60})
560568
- ExecutionConfig: Custom configuration
561569
Controls: max_iter, max_rpm, max_execution_time, max_retry_limit
562-
templates: Template configuration (TemplateConfig).
570+
templates: Template configuration. Accepts:
571+
- Dict[str, Any]: Template fields (e.g. {"system": "...", "prompt": "..."})
572+
- TemplateConfig: Custom configuration
563573
Controls: system_template, prompt_template, response_template
564574
caching: Caching configuration. Accepts:
565575
- bool: True enables with defaults
@@ -571,7 +581,9 @@ def __init__(
571581
- List[str]: Skill directory paths
572582
- SkillsConfig: Custom configuration
573583
learn: Continuous learning configuration. Accepts:
574-
- bool: True enables with defaults, False disables
584+
- bool: True enables with defaults (AGENTIC mode), False disables
585+
- str: Mode string ("disabled", "agentic", "propose")
586+
- Dict[str, Any]: Config fields (e.g. {"mode": "agentic", "backend": "sqlite"})
575587
- LearnConfig: Custom configuration
576588
Learning is a first-class citizen, peer to memory. It captures patterns,
577589
preferences, and insights from interactions to improve future responses.
@@ -1076,8 +1088,24 @@ def __init__(
10761088
_learn_config = learn
10771089
elif isinstance(learn, dict):
10781090
_learn_config = LearnConfig(**learn)
1091+
elif isinstance(learn, str):
1092+
# String mode: "disabled", "agentic", "propose"
1093+
from ..memory.learn.protocols import LearnMode
1094+
if learn == "disabled":
1095+
_learn_config = None
1096+
elif learn == "agentic":
1097+
_learn_config = LearnConfig(mode=LearnMode.AGENTIC)
1098+
elif learn == "propose":
1099+
_learn_config = LearnConfig(mode=LearnMode.PROPOSE)
1100+
else:
1101+
# Unknown string mode, disable learning
1102+
_learn_config = None
10791103
else:
1080-
_learn_config = learn # Pass through
1104+
logging.warning(
1105+
"Unsupported learn= value %r; expected bool, dict, or LearnConfig. "
1106+
"Learning disabled.", learn
1107+
)
1108+
_learn_config = None
10811109
elif _memory_config is not None and isinstance(_memory_config, MemoryConfig):
10821110
# Fallback to memory.learn for backward compatibility
10831111
if _memory_config.learn:
@@ -1651,6 +1679,12 @@ def __init__(
16511679
self._approval_backend = approval.backend
16521680
self._approve_all_tools = approval.all_tools
16531681
self._approval_timeout = approval.timeout # None = indefinite, 0 = backend default
1682+
elif isinstance(approval, dict):
1683+
# Dict config: convert to ApprovalConfig
1684+
approval_config = ApprovalConfig(**approval)
1685+
self._approval_backend = approval_config.backend
1686+
self._approve_all_tools = approval_config.all_tools
1687+
self._approval_timeout = approval_config.timeout
16541688
else:
16551689
# Plain backend object — dangerous tools only, backend default timeout
16561690
self._approval_backend = approval
@@ -1958,6 +1992,64 @@ def context_manager(self) -> Optional[Any]:
19581992
elif hasattr(self._context_param, 'process'):
19591993
# Already a ContextManager instance
19601994
self._context_manager = self._context_param
1995+
elif isinstance(self._context_param, str):
1996+
# String preset: "sliding_window", "summarize", "truncate"
1997+
from ..config.presets import CONTEXT_PRESETS
1998+
preset_config = CONTEXT_PRESETS.get(self._context_param)
1999+
if preset_config is not None:
2000+
# Convert preset to ContextConfig, then to ManagerConfig
2001+
try:
2002+
from ..context.models import ContextConfig as _ContextConfig
2003+
context_config = _ContextConfig(**preset_config)
2004+
manager_config = ManagerConfig(
2005+
auto_compact=context_config.auto_compact,
2006+
compact_threshold=context_config.compact_threshold,
2007+
strategy=context_config.strategy,
2008+
output_reserve=context_config.output_reserve,
2009+
default_tool_output_max=context_config.tool_output_max,
2010+
protected_tools=list(context_config.protected_tools),
2011+
keep_recent_turns=context_config.keep_recent_turns,
2012+
monitor_enabled=context_config.monitor.enabled if context_config.monitor else False,
2013+
)
2014+
self._context_manager = ContextManager(
2015+
model=self.llm if isinstance(self.llm, str) else "gpt-4o-mini",
2016+
config=manager_config,
2017+
agent_name=self.name or "Agent",
2018+
session_cache=self._session_dedup_cache,
2019+
llm_summarize_fn=None,
2020+
)
2021+
except Exception as e:
2022+
logging.debug(f"Context preset conversion failed: {e}")
2023+
self._context_manager = None
2024+
else:
2025+
# Unknown string preset, disable
2026+
self._context_manager = None
2027+
elif isinstance(self._context_param, dict):
2028+
# Dict config: convert to ContextConfig, then to ManagerConfig
2029+
try:
2030+
from ..context.models import ContextConfig as _ContextConfig
2031+
context_config = _ContextConfig(**self._context_param)
2032+
manager_config = ManagerConfig(
2033+
auto_compact=context_config.auto_compact,
2034+
compact_threshold=context_config.compact_threshold,
2035+
strategy=context_config.strategy,
2036+
output_reserve=context_config.output_reserve,
2037+
default_tool_output_max=context_config.tool_output_max,
2038+
protected_tools=list(context_config.protected_tools),
2039+
keep_recent_turns=context_config.keep_recent_turns,
2040+
monitor_enabled=context_config.monitor.enabled if context_config.monitor else False,
2041+
)
2042+
llm_summarize_enabled = self._context_param.get('llm_summarize', False)
2043+
self._context_manager = ContextManager(
2044+
model=self.llm if isinstance(self.llm, str) else "gpt-4o-mini",
2045+
config=manager_config,
2046+
agent_name=self.name or "Agent",
2047+
session_cache=self._session_dedup_cache,
2048+
llm_summarize_fn=self._create_llm_summarize_fn() if llm_summarize_enabled else None,
2049+
)
2050+
except Exception as e:
2051+
logging.debug(f"Context dict conversion failed: {e}")
2052+
self._context_manager = None
19612053
else:
19622054
# Unknown type, disable
19632055
self._context_manager = None
@@ -2174,6 +2266,25 @@ def _init_autonomy(self, autonomy: Any, verification_hooks: Optional[List[Any]]
21742266
# Extract verification_hooks from AutonomyConfig if provided
21752267
if autonomy.verification_hooks and not verification_hooks:
21762268
self._verification_hooks = autonomy.verification_hooks
2269+
elif isinstance(autonomy, str):
2270+
# String preset: "suggest", "auto_edit", "full_auto"
2271+
from ..config.presets import AUTONOMY_PRESETS
2272+
preset_config = AUTONOMY_PRESETS.get(autonomy)
2273+
if preset_config is not None:
2274+
config = AutonomyConfig.from_dict(preset_config)
2275+
else:
2276+
# Unknown string preset — disable autonomy
2277+
self.autonomy_enabled = False
2278+
self.autonomy_config = {}
2279+
self._autonomy_trigger = None
2280+
self._doom_loop_tracker = None
2281+
self._file_snapshot = None
2282+
self._snapshot_stack = []
2283+
self._redo_stack = []
2284+
self._autonomy_turn_tool_count = 0
2285+
self._consecutive_no_tool_turns = 0
2286+
self._doom_recovery_active = False
2287+
return
21772288
else:
21782289
self.autonomy_enabled = False
21792290
self.autonomy_config = {}

src/praisonai-agents/praisonaiagents/config/presets.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,9 +300,9 @@
300300
# =============================================================================
301301

302302
AUTONOMY_PRESETS: Dict[str, Dict[str, Any]] = {
303-
"suggest": {"mode": "suggest"},
304-
"auto_edit": {"mode": "auto_edit"},
305-
"full_auto": {"mode": "full_auto"},
303+
"suggest": {"level": "suggest"},
304+
"auto_edit": {"level": "auto_edit"},
305+
"full_auto": {"level": "full_auto"},
306306
}
307307

308308

0 commit comments

Comments
 (0)