Skip to content

fix(types): widen type hints for agent init#1278

Open
MervinPraison wants to merge 4 commits intomainfrom
fix/agent-init-type-hints
Open

fix(types): widen type hints for agent init#1278
MervinPraison wants to merge 4 commits intomainfrom
fix/agent-init-type-hints

Conversation

@MervinPraison
Copy link
Copy Markdown
Owner

@MervinPraison MervinPraison commented Apr 5, 2026

  • Fix context type hint: restored str/Dict — runtime handles presets "sliding_window"/"summarize"/"truncate" and dict→ContextConfig
  • Fix autonomy type hint: restored str — runtime handles level presets "suggest"/"auto_edit"/"full_auto"
  • Fix templates type hint: removed str (no TEMPLATE_PRESETS defined; resolver returns None for unknown strings)
  • Fix approval type hint: restored Dict[str, Any] — runtime converts dict to ApprovalConfig(**dict)
  • Fix learn type hint: restored str — runtime maps "agentic"/"propose"/"disabled" to LearnConfig(mode=...)
  • Fix learn passthrough bug: replaced silent _learn_config = learn with a logged warning for truly unknown types
  • Update docstrings for context/autonomy/output/execution/templates/learn to reflect all actual supported input types
  • All functional tests pass; context test suite (132 tests) passes
  • CodeQL: no security alerts; Code review: only 2 minor style comments on pre-existing code

Copilot AI review requested due to automatic review settings April 5, 2026 05:09
@qodo-code-review
Copy link
Copy Markdown

Review Summary by Qodo

Widen type hints for agent initialization parameters

🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Widen type hints for agent initialization parameters
• Add support for string and dict configuration formats
• Improve flexibility in accepting multiple input types
• Align with actual parameter handling capabilities
Diagram
flowchart LR
  A["Agent Init Parameters"] -->|"Add str, Dict support"| B["context, autonomy, output"]
  A -->|"Add str, Dict support"| C["execution, templates, caching"]
  A -->|"Add str, Dict support"| D["hooks, skills, approval, learn"]
  B --> E["Flexible Type Hints"]
  C --> E
  D --> E
Loading

Grey Divider

File Changes

1. src/praisonai-agents/praisonaiagents/agent/agent.py 🐞 Bug fix +10/-10

Broaden agent parameter type hints for flexibility

• Expanded context parameter type hint to include str and Dict[str, Any]
• Expanded autonomy parameter type hint to include str
• Expanded output parameter type hint to include bool, str, and Dict[str, Any]
• Expanded execution parameter type hint to include bool, str, and Dict[str, Any]
• Expanded templates parameter type hint to include str and Dict[str, Any]
• Expanded caching parameter type hint to include str and Dict[str, Any]
• Expanded hooks parameter type hint to include Dict[str, Any]
• Expanded skills parameter type hint to include str and Dict[str, Any]
• Expanded approval parameter type hint to include Dict[str, Any]
• Expanded learn parameter type hint to include str

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


Grey Divider

Qodo Logo

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review bot commented Apr 5, 2026

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX Issues (0)

Grey Divider


Action required

1. Autonomy preset strings ignored 🐞 Bug ≡ Correctness
Description
Agent.__init__ now advertises autonomy can be a string, but _init_autonomy does not handle str
values and will disable autonomy instead of applying presets like "full_auto". This breaks the
public contract implied by AUTONOMY_PRESETS and AutonomyConfig docs.
Code

src/praisonai-agents/praisonaiagents/agent/agent.py[492]

+        autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
Evidence
The new type hint includes str, but _init_autonomy only accepts True, dict, or AutonomyConfig and
otherwise disables autonomy. The codebase also defines AUTONOMY_PRESETS (including "full_auto") and
AutonomyConfig documentation shows string usage, demonstrating string presets are intended to work.

src/praisonai-agents/praisonaiagents/agent/agent.py[491-503]
src/praisonai-agents/praisonaiagents/agent/agent.py[2137-2188]
src/praisonai-agents/praisonaiagents/config/presets.py[298-307]
src/praisonai-agents/praisonaiagents/agent/autonomy.py[114-127]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`Agent.__init__` now type-hints `autonomy` as accepting `str`, but the runtime path (`_init_autonomy`) does not handle strings and silently disables autonomy when a string is passed (e.g. `"full_auto"`).

### Issue Context
The repo already defines `AUTONOMY_PRESETS` containing `"full_auto"`, and `AutonomyConfig` docs show `Agent(autonomy="full_auto")`, so string presets appear to be a supported user-facing API.

### Fix Focus Areas
- src/praisonai-agents/praisonaiagents/agent/agent.py[1314-1320]
- src/praisonai-agents/praisonaiagents/agent/agent.py[2137-2188]
- src/praisonai-agents/praisonaiagents/config/presets.py[298-307]
- src/praisonai-agents/praisonaiagents/config/param_resolver.py[600-610]

### Suggested fix
Either:
1) Implement `str` handling by resolving presets before `_init_autonomy` (e.g., use `AUTONOMY_PRESETS` / `resolve_autonomy()` to produce an `AutonomyConfig`), or
2) Revert the type hint to remove `str` if string presets are not intended to be supported.

Add/adjust a unit test for `Agent(autonomy="full_auto")` to assert `agent.autonomy_enabled is True` and that the configured level/mode matches the preset.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Context presets/dicts ignored 🐞 Bug ≡ Correctness
Description
Agent.__init__ now advertises context can be a str or dict, but context_manager lazy-init only
supports bool, ManagerConfig/ContextConfig, or a ContextManager instance; str/dict values fall into
the unknown-type branch and disable context. This causes silent misconfiguration where context
management never activates.
Code

src/praisonai-agents/praisonaiagents/agent/agent.py[491]

+        context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
Evidence
The context value is stored raw in self._context_param. When context_manager initializes, it
does not handle str or dict; unknown types result in _context_manager = None. The repo defines
CONTEXT_PRESETS and a resolve_context() helper that supports string presets, but Agent is not
using that resolver.

src/praisonai-agents/praisonaiagents/agent/agent.py[491-503]
src/praisonai-agents/praisonaiagents/agent/agent.py[1753-1761]
src/praisonai-agents/praisonaiagents/agent/agent.py[1876-1964]
src/praisonai-agents/praisonaiagents/config/presets.py[287-296]
src/praisonai-agents/praisonaiagents/config/param_resolver.py[586-598]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`Agent.__init__` now type-hints `context` as accepting `str` and `dict`, but the runtime context initialization only recognizes `True/False`, `ManagerConfig`/`ContextConfig`, or `ContextManager`. Passing a preset string or a dict results in context being silently disabled.

### Issue Context
The repo already provides `CONTEXT_PRESETS` and a canonical `resolve_context()` helper (supports string presets and dict-to-config conversion), but Agent stores the raw value and never resolves it.

### Fix Focus Areas
- src/praisonai-agents/praisonaiagents/agent/agent.py[1753-1761]
- src/praisonai-agents/praisonaiagents/agent/agent.py[1876-1964]
- src/praisonai-agents/praisonaiagents/config/presets.py[287-296]
- src/praisonai-agents/praisonaiagents/config/param_resolver.py[586-598]

### Suggested fix
Implement one of:
1) Resolve `context` in `__init__` before assigning `self._context_param`:
  - `str` -> apply `CONTEXT_PRESETS` and build a `ContextConfig` (or ManagerConfig alias)
  - `dict` -> `ContextConfig(**context)` with key validation
2) Alternatively, add handling for `str`/`dict` inside `context_manager` property.

Add tests for `Agent(context="summarize")` and `Agent(context={...})` ensuring `agent.context_manager` is not `None`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Approval dict backend crash 🐞 Bug ≡ Correctness
Description
Agent.__init__ now advertises approval can be a dict, but approval setup stores unknown types
directly as _approval_backend, so a dict becomes the backend. Tool execution then calls
backend.request_approval(...), which will raise AttributeError on a dict.
Code

src/praisonai-agents/praisonaiagents/agent/agent.py[500]

+        approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
Evidence
The approval initialization assigns self._approval_backend = approval for
non-bool/str/ApprovalConfig values, which includes dicts. The tool approval path calls
backend.request_approval(request) when a backend is configured, so a dict backend will fail at
runtime.

src/praisonai-agents/praisonaiagents/agent/agent.py[494-503]
src/praisonai-agents/praisonaiagents/agent/agent.py[1619-1658]
src/praisonai-agents/praisonaiagents/agent/tool_execution.py[426-452]
src/praisonai-agents/praisonaiagents/approval/protocols.py[84-112]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`Agent.__init__` now type-hints `approval` as accepting a `dict`, but the approval initialization code does not handle dicts and will store them as `_approval_backend`. Later, tool execution calls `backend.request_approval(...)`, which will crash with `AttributeError` for dict backends.

### Issue Context
There is an `ApprovalConfig` dataclass intended for structured configuration, and the runtime expects `_approval_backend` to implement `ApprovalProtocol` (`request_approval`).

### Fix Focus Areas
- src/praisonai-agents/praisonaiagents/agent/agent.py[1619-1658]
- src/praisonai-agents/praisonaiagents/agent/tool_execution.py[426-485]
- src/praisonai-agents/praisonaiagents/approval/protocols.py[55-83]

### Suggested fix
Add an explicit dict branch in Agent approval setup, e.g.:
- `elif isinstance(approval, dict): approval = ApprovalConfig(**approval)` (and optionally validate allowed keys)
Then let the existing `isinstance(approval, ApprovalConfig)` branch configure `_approval_backend`.

Alternatively, remove `Dict[str, Any]` from the type hint if dict configuration is not supported.

Add a unit test that passes `approval={"backend": SomeBackend(), "all_tools": True, "timeout": 10}` and verifies tool execution reaches the backend without crashing.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. Learn string does nothing 🐞 Bug ≡ Correctness
Description
Agent.__init__ now advertises learn can be a string, but the memory learning code only activates for
True/dict/LearnConfig; string values result in learning staying disabled with no error. This is a
silent behavioral mismatch between annotations and runtime.
Code

src/praisonai-agents/praisonaiagents/agent/agent.py[502]

+        learn: Optional[Union[bool, str, Dict[str, Any], 'LearnConfig']] = None,  # Continuous learning (peer to memory)
Evidence
The Agent learn extraction path passes through unknown types (including strings). Memory’s learn
manager initialization only supports True, dict, or LearnConfig and returns None otherwise, so
string inputs cannot enable learning.

src/praisonai-agents/praisonaiagents/agent/agent.py[1059-1099]
src/praisonai-agents/praisonaiagents/memory/memory.py[1946-1959]
src/praisonai-agents/praisonaiagents/agent/memory_mixin.py[447-489]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`learn` is now type-hinted to accept `str`, but runtime only supports `bool`, `dict`, or `LearnConfig`. A string value becomes a no-op (learning remains disabled) without a clear error.

### Issue Context
The learning initialization in `Memory` only constructs `LearnConfig` for `True`, `dict`, or `LearnConfig`, and otherwise returns `None`.

### Fix Focus Areas
- src/praisonai-agents/praisonaiagents/agent/agent.py[1059-1100]
- src/praisonai-agents/praisonaiagents/memory/memory.py[1946-1959]

### Suggested fix
Either:
1) Remove `str` from the type hint to match current behavior, or
2) Implement string shorthands/presets (e.g., `"agentic"`, `"propose"`, `"disabled"`) that map to `LearnConfig(mode=...)`.

Add a test for `Agent(learn="agentic")` (if implemented) verifying `_learn_config.mode` and that `memory.learn` is non-null.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 5, 2026

Caution

Review failed

The head commit changed during the review from 72e477f to 724e4af.

📝 Walkthrough

Walkthrough

The Agent.__init__ method's parameter type hints were expanded to accept str and Dict[str, Any] forms in addition to existing config objects and primitive types across multiple feature arguments (context, autonomy, output, execution, templates, caching, hooks, skills, approval, learn). No logic or control flow changes were made.

Changes

Cohort / File(s) Summary
Agent Initialization Type Hints
src/praisonai-agents/praisonaiagents/agent/agent.py
Expanded parameter type hints in Agent.__init__ to accept str and/or Dict[str, Any] forms alongside existing config objects and primitives for context, autonomy, output, execution, templates, caching, hooks, skills, approval, and learn parameters.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Type hints bloom like clover in spring,
Flexible parameters take wing,
Strings and dicts now welcome too,
The Agent stands renewed and true! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: widening type hints in the Agent.init method to accept additional input forms (str and Dict) for configuration parameters.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/agent-init-type-hints

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request widens the type hints for several parameters in the Agent constructor, including context, autonomy, approval, and learn, to support strings and dictionaries. However, the review identifies multiple instances where the underlying implementation has not been updated to handle these new types, which could lead to runtime errors or features being silently disabled.

caching: Optional[Union[bool, str, Dict[str, Any], 'CachingConfig']] = None,
hooks: Optional[Union[List[Any], Dict[str, Any], 'HooksConfig']] = None,
skills: Optional[Union[List[str], str, Dict[str, Any], 'SkillsConfig']] = None,
approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The widened type hint for approval includes Dict[str, Any], but the implementation (lines 1624-1659) does not convert a dictionary to an ApprovalConfig or backend instance. Instead, it assigns the dictionary directly to self._approval_backend in the else block at line 1654. This will cause runtime errors when the agent attempts to call backend methods on a dictionary object.

web: Optional[Union[bool, str, 'WebConfig']] = None,
context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The widened type hint for context includes str and Dict[str, Any], but the implementation in the context_manager property (lines 1877-1966) does not currently handle these types. If a string or dictionary is passed, the context manager will be silently disabled (set to None).

context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The widened type hint for autonomy includes str, but the _init_autonomy method (lines 2138-2188) does not handle string inputs. Passing a string (e.g., a preset name) will result in autonomy being disabled because it falls into the else block at line 2177.

approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
tool_timeout: Optional[int] = None, # P8/G11: Timeout in seconds for each tool call
learn: Optional[Union[bool, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)
learn: Optional[Union[bool, str, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The widened type hint for learn includes str, but the initialization logic (lines 1067-1080) does not explicitly handle string values. This may lead to unexpected behavior or truthiness issues when the value is passed through to the memory system at line 1096.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/praisonai-agents/praisonaiagents/agent/agent.py`:
- Around line 491-492: Update the type hints for the Agent parameters to match
only the runtime-supported shapes: remove str (and dict for context) from the
annotated unions so `context` is Optional[Union[bool, Dict[str, Any],
'ContextConfig', 'ContextManager']]` becomes Optional[Union[bool,
'ContextConfig', 'ContextManager']]` (or Optional[Union[bool, 'ContextManager',
'ContextConfig']] as appropriate) and `autonomy` drops `str` to be
Optional[Union[bool, 'AutonomyConfig']]; locate the parameter declarations in
agent.py (the `context` and `autonomy` parameters), and also scan
`_init_autonomy` and `context_manager` code paths to ensure annotations match
implemented branches and update any docstrings/comments to reflect the
false=True=Config contract.
- Line 500: The public type for the approval parameter includes Dict[str, Any]
but the approval handling logic only handles bool, True, ApprovalConfig and
ApprovalProtocol and sends any other value to the generic else branch; add a
dedicated branch that detects when approval is a dict and coerces it into an
ApprovalConfig (e.g., ApprovalConfig(**approval) or
ApprovalConfig.from_dict(approval)) before the existing protocol/object handling
so dictionaries follow the same config-path as ApprovalConfig; update the code
that currently checks approval (the approval processing block in the Agent
constructor/initializer where approval is normalized) to convert dict ->
ApprovalConfig and then continue with the existing branches for ApprovalConfig
and ApprovalProtocol.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 37222d53-da7d-41fe-8989-3fc9f207ac5e

📥 Commits

Reviewing files that changed from the base of the PR and between d80bff2 and 9c2f14e.

📒 Files selected for processing (1)
  • src/praisonai-agents/praisonaiagents/agent/agent.py

Comment on lines +491 to +492
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

context/autonomy type hints now advertise unsupported runtime inputs.

Line 491 and Line 492 add str (and dict for context), but current runtime paths don’t normalize these forms (context_manager has no str/dict branch; _init_autonomy treats unsupported types as disabled). This creates a silent contract mismatch.

💡 Proposed fix (narrow hints to implemented behavior)
-        context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
-        autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
+        context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
+        autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,

As per coding guidelines: src/praisonai-agents/praisonaiagents/agent/*.py: “Consolidate Agent parameters into Config objects following the pattern: False=disabled, True=defaults, Config=custom.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/praisonai-agents/praisonaiagents/agent/agent.py` around lines 491 - 492,
Update the type hints for the Agent parameters to match only the
runtime-supported shapes: remove str (and dict for context) from the annotated
unions so `context` is Optional[Union[bool, Dict[str, Any], 'ContextConfig',
'ContextManager']]` becomes Optional[Union[bool, 'ContextConfig',
'ContextManager']]` (or Optional[Union[bool, 'ContextManager', 'ContextConfig']]
as appropriate) and `autonomy` drops `str` to be Optional[Union[bool,
'AutonomyConfig']]; locate the parameter declarations in agent.py (the `context`
and `autonomy` parameters), and also scan `_init_autonomy` and `context_manager`
code paths to ensure annotations match implemented branches and update any
docstrings/comments to reflect the false=True=Config contract.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR cherry-picks a commit that broadens Agent.__init__ configuration type hints to accept additional shorthand forms (e.g., str/dict/bool) for several consolidated feature parameters, aiming to make agent initialization more flexible and consistent with config-driven usage.

Changes:

  • Widened type hints for context, autonomy, output, execution, templates, caching, hooks, skills, approval, and learn.
  • Expanded several parameters to allow Dict[str, Any] (and in some cases str / bool) in the constructor signature.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type hint now allows autonomy to be a str, but _init_autonomy() currently only handles True, dict, or AutonomyConfig and will silently disable autonomy for string inputs (e.g. documented autonomy="full_auto"). Either add explicit string handling (map presets like "full_auto"/"auto_edit"/"suggest" to an AutonomyConfig(level=...)) or remove str from the public signature to match behavior.

Suggested change
autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,

Copilot uses AI. Check for mistakes.
web: Optional[Union[bool, str, 'WebConfig']] = None,
context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The signature now claims context supports str/dict, but context_manager initialization only recognizes True, ManagerConfig, ContextConfig, or a ContextManager-like object; str/dict fall through to the “unknown type, disable” branch. Either implement parsing for dict/str (e.g. dict -> ManagerConfig(**...) / ContextConfig.from_dict(...), and define what string means), or narrow the type hint so callers don’t get a false affordance.

Suggested change
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,

Copilot uses AI. Check for mistakes.
approval: Optional[Union[bool, str, 'ApprovalConfig', 'ApprovalProtocol']] = None,
output: Optional[Union[bool, str, Dict[str, Any], 'OutputConfig']] = None,
execution: Optional[Union[bool, str, Dict[str, Any], 'ExecutionConfig']] = None,
templates: Optional[Union[str, Dict[str, Any], 'TemplateConfig']] = None,
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

templates is now typed as accepting str, but the resolver path doesn’t interpret non-path-like strings for TemplateConfig (it will generally return an empty TemplateConfig() which has no effect). If the intent is to accept a template preset name or file path, add explicit handling for those string forms; otherwise, remove str from the type hint to avoid misleading API docs/type-checkers.

Suggested change
templates: Optional[Union[str, Dict[str, Any], 'TemplateConfig']] = None,
templates: Optional[Union[Dict[str, Any], 'TemplateConfig']] = None,

Copilot uses AI. Check for mistakes.
caching: Optional[Union[bool, str, Dict[str, Any], 'CachingConfig']] = None,
hooks: Optional[Union[List[Any], Dict[str, Any], 'HooksConfig']] = None,
skills: Optional[Union[List[str], str, Dict[str, Any], 'SkillsConfig']] = None,
approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

approval is now typed to accept a Dict[str, Any], but the approval initialization logic only handles str presets, bool, or ApprovalConfig; a dict will fall into the “plain backend object” branch and likely fail later when treated as an ApprovalProtocol. Either support dict form explicitly (e.g. approval={"backend": ..., "all_tools": ..., "timeout": ...} -> ApprovalConfig(**...)) or drop Dict[...] from the type hint.

Suggested change
approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
approval: Optional[Union[bool, str, 'ApprovalConfig', 'ApprovalProtocol']] = None,

Copilot uses AI. Check for mistakes.
approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
tool_timeout: Optional[int] = None, # P8/G11: Timeout in seconds for each tool call
learn: Optional[Union[bool, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)
learn: Optional[Union[bool, str, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

learn is now typed to accept a str, but __init__ currently passes unknown types through into memory["learn"], and Memory.learn only enables learning for bool, dict, or LearnConfig (other types return None). If you want a string shorthand (e.g. learn="agentic"), convert it into LearnConfig(mode=...); otherwise, remove str from the type hint to match runtime behavior.

Suggested change
learn: Optional[Union[bool, str, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)
learn: Optional[Union[bool, Dict[str, Any], 'LearnConfig']] = None, # Continuous learning (peer to memory)

Copilot uses AI. Check for mistakes.
Comment on lines +494 to +495
output: Optional[Union[bool, str, Dict[str, Any], 'OutputConfig']] = None,
execution: Optional[Union[bool, str, Dict[str, Any], 'ExecutionConfig']] = None,
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

output/execution type hints were widened to include bool and Dict[str, Any], but the Args: docstring section still only documents the str preset and *Config forms. Please update the docstring to reflect the supported bool/dict shorthands (and their semantics: True -> defaults, False -> disabled, dict -> config overrides).

Suggested change
output: Optional[Union[bool, str, Dict[str, Any], 'OutputConfig']] = None,
execution: Optional[Union[bool, str, Dict[str, Any], 'ExecutionConfig']] = None,
output: Optional[Union[bool, str, Dict[str, Any], 'OutputConfig']] = None, # True=default OutputConfig, False=disabled, dict=config overrides
execution: Optional[Union[bool, str, Dict[str, Any], 'ExecutionConfig']] = None, # True=default ExecutionConfig, False=disabled, dict=config overrides

Copilot uses AI. Check for mistakes.
context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']] = None,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Autonomy preset strings ignored 🐞 Bug ≡ Correctness

Agent.__init__ now advertises autonomy can be a string, but _init_autonomy does not handle str
values and will disable autonomy instead of applying presets like "full_auto". This breaks the
public contract implied by AUTONOMY_PRESETS and AutonomyConfig docs.
Agent Prompt
### Issue description
`Agent.__init__` now type-hints `autonomy` as accepting `str`, but the runtime path (`_init_autonomy`) does not handle strings and silently disables autonomy when a string is passed (e.g. `"full_auto"`).

### Issue Context
The repo already defines `AUTONOMY_PRESETS` containing `"full_auto"`, and `AutonomyConfig` docs show `Agent(autonomy="full_auto")`, so string presets appear to be a supported user-facing API.

### Fix Focus Areas
- src/praisonai-agents/praisonaiagents/agent/agent.py[1314-1320]
- src/praisonai-agents/praisonaiagents/agent/agent.py[2137-2188]
- src/praisonai-agents/praisonaiagents/config/presets.py[298-307]
- src/praisonai-agents/praisonaiagents/config/param_resolver.py[600-610]

### Suggested fix
Either:
1) Implement `str` handling by resolving presets before `_init_autonomy` (e.g., use `AUTONOMY_PRESETS` / `resolve_autonomy()` to produce an `AutonomyConfig`), or
2) Revert the type hint to remove `str` if string presets are not intended to be supported.

Add/adjust a unit test for `Agent(autonomy="full_auto")` to assert `agent.autonomy_enabled is True` and that the configured level/mode matches the preset.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

web: Optional[Union[bool, str, 'WebConfig']] = None,
context: Optional[Union[bool, 'ContextConfig', 'ContextManager']] = None,
autonomy: Optional[Union[bool, Dict[str, Any], 'AutonomyConfig']] = None,
context: Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']] = None,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

2. Context presets/dicts ignored 🐞 Bug ≡ Correctness

Agent.__init__ now advertises context can be a str or dict, but context_manager lazy-init only
supports bool, ManagerConfig/ContextConfig, or a ContextManager instance; str/dict values fall into
the unknown-type branch and disable context. This causes silent misconfiguration where context
management never activates.
Agent Prompt
### Issue description
`Agent.__init__` now type-hints `context` as accepting `str` and `dict`, but the runtime context initialization only recognizes `True/False`, `ManagerConfig`/`ContextConfig`, or `ContextManager`. Passing a preset string or a dict results in context being silently disabled.

### Issue Context
The repo already provides `CONTEXT_PRESETS` and a canonical `resolve_context()` helper (supports string presets and dict-to-config conversion), but Agent stores the raw value and never resolves it.

### Fix Focus Areas
- src/praisonai-agents/praisonaiagents/agent/agent.py[1753-1761]
- src/praisonai-agents/praisonaiagents/agent/agent.py[1876-1964]
- src/praisonai-agents/praisonaiagents/config/presets.py[287-296]
- src/praisonai-agents/praisonaiagents/config/param_resolver.py[586-598]

### Suggested fix
Implement one of:
1) Resolve `context` in `__init__` before assigning `self._context_param`:
   - `str` -> apply `CONTEXT_PRESETS` and build a `ContextConfig` (or ManagerConfig alias)
   - `dict` -> `ContextConfig(**context)` with key validation
2) Alternatively, add handling for `str`/`dict` inside `context_manager` property.

Add tests for `Agent(context="summarize")` and `Agent(context={...})` ensuring `agent.context_manager` is not `None`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

caching: Optional[Union[bool, str, Dict[str, Any], 'CachingConfig']] = None,
hooks: Optional[Union[List[Any], Dict[str, Any], 'HooksConfig']] = None,
skills: Optional[Union[List[str], str, Dict[str, Any], 'SkillsConfig']] = None,
approval: Optional[Union[bool, str, Dict[str, Any], 'ApprovalConfig', 'ApprovalProtocol']] = None,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

3. Approval dict backend crash 🐞 Bug ≡ Correctness

Agent.__init__ now advertises approval can be a dict, but approval setup stores unknown types
directly as _approval_backend, so a dict becomes the backend. Tool execution then calls
backend.request_approval(...), which will raise AttributeError on a dict.
Agent Prompt
### Issue description
`Agent.__init__` now type-hints `approval` as accepting a `dict`, but the approval initialization code does not handle dicts and will store them as `_approval_backend`. Later, tool execution calls `backend.request_approval(...)`, which will crash with `AttributeError` for dict backends.

### Issue Context
There is an `ApprovalConfig` dataclass intended for structured configuration, and the runtime expects `_approval_backend` to implement `ApprovalProtocol` (`request_approval`).

### Fix Focus Areas
- src/praisonai-agents/praisonaiagents/agent/agent.py[1619-1658]
- src/praisonai-agents/praisonaiagents/agent/tool_execution.py[426-485]
- src/praisonai-agents/praisonaiagents/approval/protocols.py[55-83]

### Suggested fix
Add an explicit dict branch in Agent approval setup, e.g.:
- `elif isinstance(approval, dict): approval = ApprovalConfig(**approval)` (and optionally validate allowed keys)
Then let the existing `isinstance(approval, ApprovalConfig)` branch configure `_approval_backend`.

Alternatively, remove `Dict[str, Any]` from the type hint if dict configuration is not supported.

Add a unit test that passes `approval={"backend": SomeBackend(), "all_tools": True, "timeout": 10}` and verifies tool execution reaches the backend without crashing.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@MervinPraison
Copy link
Copy Markdown
Owner Author

@copilot Do a thorough review of this PR. Read ALL existing reviewer comments above first.

Review areas:

  1. Bloat check: Are changes minimal and focused?
  2. Security: Any hardcoded secrets, unsafe eval/exec, missing input validation?
  3. Performance: Any module-level heavy imports? Hot-path regressions?
  4. Tests: Are tests included? Do they cover the changes adequately?
  5. Backward compat: Any public API changes without deprecation?
  6. Code quality: DRY violations, naming conventions, error handling?
  7. Suggest specific improvements with code examples where possible

@MervinPraison
Copy link
Copy Markdown
Owner Author

@claude You are the FINAL architecture reviewer. Read ALL comments above from Gemini, Qodo, CodeRabbit, and Copilot carefully before responding.

Phase 1: Review per AGENTS.md

  1. Protocol-driven: check heavy implementations vs core SDK
  2. Backward compatible: ensure zero feature regressions
  3. Performance: no hot-path regressions

Phase 2: FIX Valid Issues
4. For any VALID bugs or architectural flaws found by Gemini, CodeRabbit, Qodo, Copilot, or any other reviewer: implement the fix
5. Push all code fixes directly to THIS branch (do NOT create a new PR)
6. Comment a summary of exact files modified and what you skipped

Phase 3: Final Verdict
7. If all issues are resolved, approve the PR / close the Issue
8. If blocking issues remain, request changes / leave clear action items

@praisonai-triage-agent
Copy link
Copy Markdown
Contributor

praisonai-triage-agent bot commented Apr 5, 2026

Claude finished @MervinPraison's task —— View job


Final Architecture Review & Bug Fixes ✅

I've completed the final review and implemented all necessary fixes.

Phase 1: Architecture Review per AGENTS.md

  • Read AGENTS.md guidelines
  • Check protocol-driven design compliance ✅
  • Verify backward compatibility ✅
  • Check for performance regressions ✅

Phase 2: Fix Valid Issues

  • Analyze bugs found by Gemini, Qodo, CodeRabbit, Copilot
  • Fix autonomy string handling issue
  • Fix context str/dict handling issue
  • Fix approval dict handling issue
  • Fix learn string handling issue
  • Run tests to verify fixes

Phase 3: Final Verdict

  • Push all fixes to branch
  • Provide final approval/rejection decision

Architecture Compliance Summary

AGENTS.md Compliant: This PR properly follows the parameter consolidation pattern (§5.3): False=disabled, True=defaults, Config=custom

Protocol-Driven: No heavy implementations added to core SDK
Backward Compatible: All existing APIs continue to work
Performance Safe: No module-level imports or hot-path changes


Bugs Fixed

All 4 critical bugs identified by reviewers have been RESOLVED:

1. ✅ Autonomy String Bug (agent.py:2177-2195)

  • Issue: Type hint allowed autonomy="full_auto" but runtime disabled autonomy for strings
  • Fix: Added string preset handling with AUTONOMY_PRESETS resolver
  • Also Fixed: Corrected presets to use level field (not mode) per AutonomyConfig

2. ✅ Context String/Dict Bug (agent.py:1961-2021)

  • Issue: Type hint allowed context="summarize" and context={} but runtime returned None
  • Fix: Added string preset and dict-to-config conversion in context_manager property

3. ✅ Approval Dict Bug (agent.py:1654-1659)

  • Issue: Type hint allowed approval={} but runtime assigned dict as backend, causing crashes
  • Fix: Added isinstance(approval, dict) branch to convert to ApprovalConfig

4. ✅ Learn String Bug (agent.py:1079-1091)

  • Issue: Type hint allowed learn="agentic" but runtime didn't enable learning
  • Fix: Added string mode handling for "disabled", "agentic", "propose"

Testing Results

All fixes verified working:

  • Agent(autonomy="full_auto")autonomy_enabled=True
  • Agent(context="summarize")context_manager properly initialized
  • Agent(approval={"backend": None, "all_tools": True}) → No crashes
  • Agent(learn="agentic") → Learning properly enabled
  • Existing tests still pass (no regressions)

Files Modified

Pushed to branch fix/agent-init-type-hints in commit 72e477f4:

  1. src/praisonai-agents/praisonaiagents/agent/agent.py (+95 lines)

    • Added string preset handling in _init_autonomy()
    • Added str/dict support in context_manager property
    • Added dict-to-ApprovalConfig conversion
    • Added string mode handling for learn parameter
  2. src/praisonai-agents/praisonaiagents/config/presets.py (+3/-3 lines)

    • Fixed AUTONOMY_PRESETS to use level field per AutonomyConfig spec

🎯 Final Verdict: APPROVED

This PR is READY TO MERGE

  • ✅ All identified bugs have been fixed
  • ✅ Architecture follows AGENTS.md guidelines
  • ✅ No breaking changes or regressions
  • ✅ Type hints now match runtime behavior
  • ✅ Tests verify the fixes work correctly

The widened type hints now have proper runtime support, delivering the promised flexibility while maintaining backward compatibility.

View Changes

MervinPraison and others added 3 commits April 5, 2026 05:20
- Add string preset handling in _init_autonomy() for autonomy='full_auto' etc.
- Add str/dict support in context_manager property for context='summarize' etc.
- Add dict-to-ApprovalConfig conversion for approval={'backend': ..., 'all_tools': True}
- Add string mode handling in learn parameter for learn='agentic' etc.
- Fix AUTONOMY_PRESETS to use 'level' field (not 'mode') per AutonomyConfig

Resolves type hint/implementation mismatches identified by code reviewers.
All new type hints now have proper runtime support.

Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
- Narrow context hint: remove str/Dict (init has no handling for those)
- Narrow autonomy hint: remove str (no string-level preset handling)
- Narrow templates hint: remove str (resolve() returns None with no presets)
- Narrow approval hint: remove Dict (init only handles bool/str/ApprovalConfig/Protocol)
- Narrow learn hint: remove str; replace silent passthrough with a logged warning
- Update docstrings for output/execution/templates/learn to reflect actual supported types

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/e371c8e1-a816-4fb2-8eb8-a18242daa2de

Co-authored-by: MervinPraison <454862+MervinPraison@users.noreply.github.com>
…e that don't

After rebase, commit 72e477f added runtime support for:
- context str/dict -> restore to type hint
- autonomy str -> restore to type hint
- approval dict -> restore to type hint
- learn str -> restore to type hint

templates str remains removed (resolve() with no presets returns None).
Updated all docstrings to document actual supported types including new forms.

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/e371c8e1-a816-4fb2-8eb8-a18242daa2de

Co-authored-by: MervinPraison <454862+MervinPraison@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 5, 2026

@copilot Do a thorough review of this PR. Read ALL existing reviewer comments above first.

Review areas:...

Completed a thorough review and addressed all the reviewer feedback in commit a42c6d3. Here's a summary of findings and changes:

Type hints vs. runtime behavior (addressed in 724e4af + a42c6d3):

Parameter Action Reason
context Kept str/Dict[str, Any] Runtime support confirmed: string presets ("sliding_window", "summarize", "truncate") and dict→ContextConfig conversion both implemented in the context_manager property
autonomy Kept str Runtime support confirmed: string level presets ("suggest", "auto_edit", "full_auto") handled in _init_autonomy()
templates Removed str No TEMPLATE_PRESETS defined; resolve() returns None for unknown strings — silently ignores input
approval Kept Dict[str, Any] Runtime support confirmed: dict is converted via ApprovalConfig(**dict)
learn Kept str Runtime support confirmed: "agentic"/"propose"/"disabled" mapped to LearnConfig(mode=...)

Bug fix: Replaced the silent _learn_config = learn passthrough for unknown types with a proper logging.warning(...) + _learn_config = None — prevents silently corrupting the learn config with an unsupported value.

Docstrings: Updated context, autonomy, output, execution, templates, and learn docstrings to accurately document all accepted input forms.

Review areas:

  1. Bloat check: Changes are minimal — only type hints, one bug fix, docstring updates
  2. Security: No hardcoded secrets, no unsafe eval/exec; ApprovalConfig(**approval) is safe (dataclass constructor, no code execution)
  3. Performance: No new module-level imports; lazy imports preserved
  4. Tests: 132 context tests pass; functional smoke tests for all changed params pass
  5. Backward compat: All widened type hints are additive (no removal of previously-working inputs)
  6. Code quality: Bug fixed in learn passthrough; docstrings aligned with implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants