Compare commits

..
Author SHA1 Message Date
DhivyaandDhivya-Bharathy 8536325cc1 fix(examples): phase-3 API alignment for consolidated params on v4.6.52 (#1864)
Co-authored-by: Dhivya-Bharathy <[email protected]>
2026-06-08 07:47:16 +01:00
praisonai-triage-agent[bot]andMervin Praison 8b4db44159 fix: resolve Gemini reviewer issues - remove redundant arguments and fix temp file pollution
- Remove redundant argument from workflow.run() in basic_workflow.py since variables are already set in constructor
- Fix temp file pollution by using system temp directory instead of repository directory in auto_rag_agent_basic.py and knowledge-agents-task.py

Co-authored-by: Mervin Praison <[email protected]>
2026-06-05 10:18:45 +00:00
Dhivya-Bharathy 3d3fdd045e fix(examples): align AgentTeam memory and knowledge configs with v4.6.52 API 2026-06-05 15:37:37 +05:30
praisonai-triage-agent[bot]andMervin Praison bfa9d0ca48 fix: correct TypeError in 3 example files by using proper parameter names
- Fix MemoryConfig(memory=...) → user_id=... in agent_centric_api.py
- Fix Session(memory=...) → user_id=... in session-example.py
- Fix build_context_for_task(memory=...) → user_id=... in memory-quality-example.py

Co-authored-by: Mervin Praison <[email protected]>
2026-06-05 11:26:13 +05:30
Dhivya-Bharathy 3f14324036 fix(examples): resolve syntax errors and align with consolidated-params API 2026-06-04 16:30:02 +05:30
a9f4bd593e fix: wrapper layer gaps - InteractiveRuntime lifecycle, tool resolution, cli_backend support (#1797)
* fix: wrapper layer gaps - InteractiveRuntime lifecycle, tool resolution, cli_backend support

Fixes #1646

- Issue #1: Fixed InteractiveRuntime lifecycle bug where runtime was stopped before agents.start()
  * Removed premature stop() in inner finally block at lines 1234-1240
  * Added proper loop closure check in cleanup block
  * Runtime now stays alive until after agent execution completes

- Issue #2: Consolidated tool resolution implementations
  * Added instantiate=True parameter to ToolResolver.resolve() for automatic class instantiation
  * Removed hardcoded standard_tools whitelist in agents_generator.py
  * Replaced custom tool resolution in bots_cli.py and job_workflow.py with unified ToolResolver
  * All entry points now use the same 4-step fallback chain consistently

- Issue #3: Fixed cli_backend support across frameworks
  * Added resolve_cli_backend_config() in cli_backends module for unified YAML/Python handling
  * Updated Agent wrapper class to accept both string and dict cli_backend configurations
  * Added framework compatibility validation with clear error messages
  * YAML and Python entry points now handle cli_backend identically

- Added comprehensive regression tests to prevent future regressions

Co-authored-by: MervinPraison <[email protected]>

* fix: address reviewer feedback - test fixes, validation improvements, error handling

- Fix broken test imports and patch paths in test_wrapper_layer_regression.py
- Replace hasattr(__call__) with callable() per Ruff B004
- Fix CLI backend validation to handle both 'roles' and 'agents' keys
- Add input validation for empty strings and malformed dicts in resolve_cli_backend_config
- Include class tools in local tools.py resolution
- Add per-tool error handling to prevent single tool failures from breaking all tools
- Remove unused logger parameter from resolve_cli_backend_config
- Fix exception handling in _resolve_yaml_cli_backend to not mask errors

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-06-04 09:44:31 +01:00
998dd9477f fix: wrapper layer key gaps - native async, template substitution, per-agent LLM (fixes #1758) (#1794)
* fix: wrapper layer key gaps - native async, template substitution, per-agent LLM (fixes #1758)

- Add native async execution path with arun() protocol and implementations
- Fix silent template substitution failure using brace-safe regex
- Add per-agent LLM support in praisonai adapter
- Remove orphaned safe_format() function to eliminate DRY violation

Co-authored-by: MervinPraison <[email protected]>

* fix: critical async path bugs and feature parity gaps

- Fixed missing _extract_topic causing AttributeError in all arun() calls
- Restored complete feature parity between sync/async execution paths:
  - Canonical agents→roles format conversion
  - Full tool loading (YAML tools, tools.py, tools/ directory)
  - AutoGen version detection and adapter selection
  - AgentOps initialization
  - Proper CLI config merging via _merge_cli_config()
- Fixed broken unit tests by restoring safe_format function
- Improved _arun_yaml_workflow with proper YAMLWorkflowParser integration
- Ensured async path mirrors sync path logic exactly

Resolves all critical issues identified by automated reviewers:
Greptile, CodeRabbit, Gemini, and Copilot

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
2026-06-04 09:42:24 +01:00
0aa0d5b598 fix: make CLI session store cross-platform compatible (fixes #1836) (#1837)
* fix: make CLI session store cross-platform compatible (fixes #1836)

- Replace hard fcntl import with optional import pattern
- Add Windows msvcrt locking support in UnifiedSessionStore
- Implement graceful degradation when no locking available
- Fix Path handling in session store constructor
- Follows same pattern as praisonaiagents/session/store.py fix from #1792

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* fix: resolve critical Windows locking bugs in CLI session store

- Fix msvcrt.locking position consistency by seeking to 0 before lock/unlock
- Use blocking locks (LK_LOCK/LK_RLCK) instead of non-blocking (LK_NBLCK)
- Prevent truncation race by using r+b mode and locking before truncate
- Add flush()+fsync() before unlock to ensure data persistence
- Maintain backward compatibility on Unix systems

Fixes critical OSError on every Windows save/load operation.
Addresses issues identified by Greptile and CodeRabbit reviewers.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-03 11:29:59 +01:00
MervinPraison 676f2d6588 docs: auto-update feature parity trackers [skip ci] 2026-06-03 09:49:42 +00:00
cursor[bot] 90aacf064b fix: Telegram command security bypass and MCP result queue races (#1835)
Fixes security follow-up from #1791. Includes regression tests for Telegram allowlist and MCP queue concurrency.
2026-06-03 10:49:06 +01:00
MervinPraison 0a8ce9eb7d Release v4.6.52 2026-06-03 10:07:09 +01:00
MervinPraison 9fcac3a951 Remove deprecated test script for tool search implementation, consolidating testing functionality into existing modules. 2026-06-02 20:17:33 +01:00
MervinPraison 6878780000 Release v4.6.51 2026-06-02 20:07:49 +01:00
e55789e8cf fix: HierarchicalSessionStore stale extended cache after cross-instance writes (#1785)
* fix: reload HierarchicalSessionStore extended cache on reads

PR #1759 fixed stale reads for DefaultSessionStore but left
_extended_cache out of sync. get_extended_session could return
truncated message lists after cross-process or cross-instance writes.

Align extended cache with _read_session_fresh and clear it on
invalidate_cache. Regression test added.

Co-authored-by: Mervin Praison <[email protected]>

* fix: atomic cache invalidation and stale cache writes in HierarchicalSessionStore

- Fix race condition in invalidate_cache() by clearing both caches under single lock
- Fix stale cache overwrites in write methods (set_title, share_session, unshare_session, revert_to_*, create_session parent update, auto_title)
- Replace load-modify-save pattern with _modify_session_locked for atomic updates
- Add regression test for concurrent write preservation

Addresses critical issues identified by code reviewers (Qodo/CodeRabbit)

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-06-02 20:06:34 +01:00
Maulanaandulsreall e0fb8e7dd1 fix: harden JWT secret handling and replace eval() in examples (#1793)
Addresses remaining attack surface from security advisories:

GHSA-3qg8-5g3r-79v5 (JWT signing key - CRITICAL):
  auth_service.py: PLATFORM_ENV no longer defaults to 'dev' when unset.
  When PLATFORM_JWT_SECRET is not set and PLATFORM_ENV is not explicitly
  'dev', an ephemeral random secret is auto-generated with a warning.
  This prevents production deployments from silently using the well-known
  'dev-secret-change-me' key.

GHSA-vg22-4gmj-prxw (unauthenticated eval - CRITICAL):
  Replaced all eval() calls in official examples and benchmarks with an
  AST-based safe math evaluator that only allows numeric literals and
  arithmetic operators. Files fixed:
  - examples/python/a2a/a2a-server.py (the primary advisory target)
  - examples/mcp/multi_server.py
  - examples/python/mcp/mcp-tools-server.py
  - examples/python/mcp/mcp-tools-server-sse.py
  - examples/mcp_server/custom_tools_server.py
  - examples/python/mcp_server_example.py
  - examples/python/custom_tools/tools_with_latency.py
  - examples/eval/reliability_example.py
  - src/praisonai-agents/benchmarks/real_benchmark.py

The character-filter approach (allowlist '0123456789+-*/.()') was
insufficient because () enables attribute access chains. AST-based
evaluation only permits numeric literals and binary/unary arithmetic.

GHSA-hvhp-v2gc-268q and GHSA-9cr9-25q5-8prj (file read/write):
  Already fixed in prior commits via _resolve_rule_path() and
  _resolve_cwd_yaml_path() containment helpers.

Co-authored-by: ulsreall <[email protected]>
2026-06-02 20:01:09 +01:00
bc73dd1db9 Issue #1540: Changes from Claude (#1792)
* fix: make session store fcntl import cross-platform compatible (fixes #1540)

- Add conditional fcntl import like file_memory.py already has
- Use _HAS_FCNTL flag to check fcntl availability before usage
- Windows uses msvcrt for locking, Unix uses fcntl when available
- Fixes Windows test collection failure due to missing fcntl module

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* fix: add one-time warning for degraded file locking

Addresses CodeRabbit feedback about silent no-op locking when fcntl
is unavailable on non-Windows platforms. Adds module-level sentinel
to emit warning only once, following AGENTS.md error handling principles.

Co-authored-by: Mervin Praison <[email protected]>

* fix: improve fcntl import robustness and fix unreachable code

- Replace platform-based fcntl import with try/except for better cross-platform compatibility
- Fix unreachable warning code branch that could never execute
- Remove misleading msvcrt reference in Unix-only warning message
- Now gracefully handles environments where fcntl is unavailable (GAE, Pyodide, etc.)
- All reviewer feedback from Qodo, CodeRabbit, Gemini, Copilot, and Greptile addressed

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>

* fix: harden optional fcntl import and add regression test

* test: cover missing fcntl import path for session store

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-06-02 19:59:48 +01:00
5216274924 fix: Gateway Telegram polling path bypasses security controls (fixes #1747) (#1791)
* fix: Gateway Telegram polling path bypasses security controls (fixes #1747)

- Extract shared process_inbound_telegram_message() security pipeline
- Enforce channel allowlist, user allowlist, pairing, and group policies
- Used by both standalone bot and gateway polling paths
- Add comprehensive tests for security enforcement
- Prevents unauthorized access in gateway mode

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* fix: resolve security pipeline bugs from code review

- Fix case sensitivity bug in bot mention check (lowercase bot_username)
- Fix user allowlist logic to match BotConfig.is_user_allowed semantics
- Fix test failures by using private chat type for allowlist tests
- Clean up unused imports and trailing whitespace

Addresses critical bugs identified by CodeRabbit, Greptile, and Copilot reviewers.

Co-authored-by: Mervin Praison <[email protected]>

* fix: align Telegram security pipeline with BotConfig semantics

* fix: tighten Telegram security checks and test coverage

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-06-02 19:58:07 +01:00
2e5eca1db6 fix: disable streaming by default in sync chat methods (fixes #1733) (#1734)
* fix: disable streaming by default in sync chat methods (fixes #1733)

Fixes the 'Streaming is not supported in sync OpenAIAdapter' error when using
multi-agent functionality with Deepseek provider.

Root cause:
- _chat_completion() and _execute_unified_chat_completion() methods in
  chat_mixin.py defaulted to stream=True
- This caused sync OpenAIAdapter to reject requests with streaming enabled
- Multi-agent workflows use sync execution path, triggering the error

Changes:
- Changed stream=True to stream=False as default in both sync methods
- Sync adapters now receive non-streaming requests by default
- Async methods can still use streaming when explicitly requested
- Maintains backward compatibility as streaming was already broken in sync context

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* test: replace ad-hoc script with unit test for sync stream defaults

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/c4a541cc-a3dc-4637-85d9-53f7090dcb35

Co-authored-by: MervinPraison <[email protected]>

* test: clarify helper naming in sync stream default tests

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/c4a541cc-a3dc-4637-85d9-53f7090dcb35

Co-authored-by: MervinPraison <[email protected]>

* test: harden sync stream default AST checks

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/c4a541cc-a3dc-4637-85d9-53f7090dcb35

Co-authored-by: MervinPraison <[email protected]>

* test: align stream default test names with target methods

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/c4a541cc-a3dc-4637-85d9-53f7090dcb35

Co-authored-by: MervinPraison <[email protected]>

* docs: clarify async/sync stream default asymmetry

Addresses reviewer feedback about intentional difference between:
- sync methods: stream=False (sync adapters don't support streaming)
- async methods: stream=True (async adapters do support streaming)

Co-authored-by: Mervin Praison <[email protected]>

* feat: implement smart streaming fallback for better UX

- Change sync method defaults: stream=False → stream=None
- Add intelligent fallback: try streaming first, gracefully fall back to non-streaming if unsupported
- Maintains UX benefits of streaming while ensuring compatibility with all adapters
- Benefits: users see real-time progress when possible, silent fallback when needed
- Updated tests to validate new None defaults
- Async methods unchanged (still default stream=True)

Co-authored-by: Mervin Praison <[email protected]>

* cleanup: remove test file

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-02 19:56:27 +01:00
f51fe294e7 fix: HierarchicalSessionStore stale cache could wipe session messages (#1781)
* fix: HierarchicalSessionStore stale extended cache could wipe messages

After DefaultSessionStore began reloading on reads (#1759),
HierarchicalSessionStore still served writes from a separate
_extended_cache that could lag disk. set_title, share_session,
and revert paths then saved truncated message lists.

Reload via _read_session_fresh for all extended reads and sync
both caches. Add regression test for set_title after cross-store writes.

Co-authored-by: Mervin Praison <[email protected]>

* perf: optimize HierarchicalSessionStore with smart cache invalidation

- Add file modification time-based cache validation
- Restore performance while maintaining data integrity
- Preserve force_reload API contract
- Add comprehensive regression tests

Fixes performance regression from stale cache fix while
preventing message loss from concurrent writes.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-06-02 19:55:02 +01:00
a1b7ed5c91 fix: wrapper layer architectural gaps (#1763)
* fix: wrapper layer architectural gaps - async-sync bridge, unified registry, framework logic separation (fixes #1762)

- Gap 1: Create separate sync/async SQLite stores, remove problematic sync wrappers
  - Add SyncSQLiteConversationStore with thread-safe operations
  - Remove sync wrappers from AsyncSQLiteConversationStore
  - Update factory to support mode parameter (sync/async/auto)

- Gap 2: Replace manual __getattr__ ladder with unified registry
  - Extend existing PluginRegistry with lazy __getattr__ support
  - Create IntegrationRegistry replacing 70-line manual dispatch
  - Consolidate four parallel registries into data-driven approach

- Gap 3: Move framework logic from orchestrator to adapters
  - Add resolve() and setup() methods to FrameworkAdapter protocol
  - Extract AutoGen version logic to adapter.resolve()
  - Centralize AgentOps init in observability/hooks module
  - Remove framework-specific code from agents_generator.py

Restores protocol-driven core principle and eliminates event loop issues.

Co-authored-by: MervinPraison <[email protected]>

* fix: restore lazy integration exports and parameterize sync sqlite paging

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-06-02 19:48:58 +01:00
aaed51eee8 fix: replace undefined AgentFlow with Workflow in workflow_conditional.py (closes #1750) (#1765)
* fix: replace undefined AgentFlow with Workflow in workflow_conditional.py (closes #1750)

* Update workflow_conditional.py

---------

Co-authored-by: botbikamordehai2-sketch <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-02 14:46:31 +01:00
48407be580 fix: architectural gaps in wrapper package - thread safety, async safety, feature parity (#1771)
* fix: architectural gaps in wrapper package - thread safety, async safety, feature parity

- Fix TOCTOU race in jobs server singleton initialization with thread-safe locking
- Replace deprecated asyncio.get_event_loop() calls with asyncio.run() and asyncio.to_thread()
- Restore AsyncAgentScheduler feature parity: add missing timeout and max_cost parameters
- Ensure async/sync scheduler classes have identical safety features

Fixes #1770

Co-authored-by: MervinPraison <[email protected]>

* fix: address critical architectural issues in PR #1771

- Fix event loop splitting in CLI standardise.py by using single asyncio.run() lifecycle
- Fix budget scheduler stopping issue by setting stop event when budget exceeded
- Complete asyncio migration in e2b.py by replacing remaining get_event_loop() calls
- Update factory function to expose timeout and max_cost parameters

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-02 14:45:31 +01:00
0ad42ff2c5 fix: MCP client lifecycle - thin core wiring, OAuth honesty, remote support (#1777)
* fix: MCP client lifecycle - thin core wiring, OAuth honesty, remote support

Implements comprehensive fixes for MCP client integration addressing
broken imports, misleading OAuth documentation, and missing remote
server support. Adds thin wiring between config and agents following
protocol-driven architecture.

Tier A - Critical Fixes:
- Fix MCPConfig.to_mcp_instance() import from praisonaiagents.mcp
- Mark OAuth CLI commands as experimental until real implementation
- Update doctor checks to use canonical ~/.praisonai/mcp/ paths

Tier B - Core Agent Value:
- Add MCPClientProtocol interface for extensibility
- Create load_mcp_tools() helper for agent-centric tool loading
- Wire tool filtering with allowed_tools/disabled_tools parameters
- Add safe environment policy (baseline + explicit config only)
- Prepare tool name collision handling framework

Tier C - Wrapper Improvements:
- Add remote server support to mcp test/sync CLI commands
- Create YAML MCP configuration example

Tests: All smoke tests pass, no performance regressions (13ms import)

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <[email protected]>

* fix: Critical MCP client lifecycle issues - syntax, env, filters, async

Fixes identified by code reviewers (CodeRabbit, Greptile, Copilot):

1. Fixed syntax error in CLI - orphaned except blocks (CRITICAL)
2. Fixed environment inheritance regression in mcp test command
3. Fixed filter precedence - allowed_tools now properly wins over disabled_tools
4. Added missing SYSTEMROOT/COMSPEC for Windows stdio MCP servers
5. Added async protocol methods for non-blocking MCP operations
6. Fixed typer.Exit propagation in remote server tests
7. Updated YAML example to remove unsupported description fields
8. Fixed canonical path discovery in doctor checks fallback
9. Updated loader docs to clarify prefix_tools not yet implemented

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-02 14:45:09 +01:00
2943c3b77e fix: HierarchicalSessionStore stale writes lose concurrent chat messages (#1790)
* fix: prevent HierarchicalSessionStore stale writes on fork and metadata updates

PR #1745 fixed add_message races but fork_session, create_session parent
linking, snapshots, and revert still saved stale in-memory sessions and could
overwrite concurrent add_message writes.

Route parent/field updates through _modify_session_locked and add a regression
test for fork_session concurrent with add_message.

Co-authored-by: Mervin Praison <[email protected]>

* fix: address Qodo reviewer bugs in HierarchicalSessionStore

1. Fix revert_to_message() - validate index before writing to prevent
   unnecessary session writes on invalid indices

2. Fix revert_to_snapshot() - use read-only lookup to avoid double writes
   and unnecessary writes when snapshot not found

3. Fix test_fork_session_preserves_concurrent_messages() - use proper
   concurrent testing with two store instances and threading to simulate
   real race conditions

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-06-02 14:43:32 +01:00
84627f593c fix: reload session file on read to prevent stale chat history (#1764)
_load_session returned an in-memory cache without checking disk when a
session JSON file already existed. A second DefaultSessionStore instance
(or direct file edits) could add messages that get_chat_history never saw
until invalidate_cache was called manually.

Always reload from disk under FileLock when the session file exists.
Adds regression test for cross-instance reads.

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-06-02 14:01:40 +01:00
927020cea8 fix: session message loss in managed stream and bot history saves (#1768)
* fix: session message loss in managed stream and bot history saves

- Persist user/assistant messages and state after LocalManagedAgent.stream()
- Add DefaultSessionStore.set_chat_history for atomic locked replace
- BotSessionManager uses set_chat_history instead of clear + re-add loop
- DbSessionAdapter.update_session_metadata accepts **fields like file store
- Add regression tests for stream persistence and metadata API

Co-authored-by: Mervin Praison <[email protected]>

* fix: preserve timestamps and metadata in set_chat_history

- Fix SessionMessage construction in set_chat_history to preserve
  original timestamp when provided in input messages
- Also preserve metadata field for completeness
- Prevents loss of temporal ordering information during history replacement

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-06-02 14:00:16 +01:00
MervinPraison 23ca2a80d6 docs: auto-update feature parity trackers [skip ci] 2026-06-02 12:56:41 +00:00
f931173e60 feat: implement Tool Search progressive MCP/plugin tool disclosure (#1778)
* feat: implement Tool Search progressive MCP/plugin tool disclosure

Implements Hermes-parity progressive disclosure layer for MCP and non-core plugin tools:

Phase P0 Complete:
- Added ToolSearchConfig with auto/on/off modes and threshold controls
- Implemented BM25 search with substring fallback (no external dependencies)
- Created bridge tools (tool_search, tool_describe, tool_call) with lazy loading
- Integrated into Agent class with tool_search parameter
- Updated chat_mixin for tool assembly and bridge mode detection
- Added tool_execution unwrapping with security validation
- Marked all MCP tools as deferrable (__praisonai_deferrable__ = True)
- Comprehensive unit tests covering all core functionality

Design Invariants (from Hermes):
1. Core tools never defer (PRAISONAI_CORE_TOOLS)
2. Unknown tools stay visible (never silently dropped)
3. Stateless catalog (rebuilt every assembly)
4. Unwrap before trace/stream (hooks see real tool names)
5. Session scoping (agent's own tool list only)
6. Auto threshold (10% context window default)
7. Zero overhead when disabled (opt-in, lazy imports)

Default: tool_search=False (opt-in). Zero overhead when disabled.
Auto mode activates based on token threshold vs context window.
Core SDK tools (file/shell/web/schedule/memory/clarify) never defer.

Fixes #1775

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <[email protected]>

* fix: address critical Tool Search issues

- Fix unconditional bridge tool hijacking that broke user tools when disabled
- Resolve duplicate ToolSearchConfig classes by consolidating to tools module
- Add missing resolve_tool_search resolver function
- Fix hot path performance issues in BM25 scoring
- Add input validation for tool_call bridge args
- Fix cache metadata mismatches in chat_mixin
- Remove unnecessary f-string prefixes
- Strip __praisonai_deferrable__ from provider payloads
- Preserve tool_search config in clone_for_channel
- Improve type validation in agent constructor
- Fix overly broad MCP name heuristic

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-02 13:56:03 +01:00
ba12269d5d fix: wrapper layer gaps - async support, lazy imports, event loop fixes (#1789)
* fix: wrapper layer gaps - add async support, fix heavy imports, stream relay event loop (fixes #1788)

- Add async arun() methods to FrameworkAdapter protocol and BaseFrameworkAdapter
- Override arun() in AutoGenV4Adapter for async-native execution without run_sync wrapper
- Fix AutoGenAdapter.is_available() to use centralized lazy probe instead of full import autogen
- Fix Gateway._make_stream_relay to capture event loop in async context, not threaded callback
- Add agenerate_crew_and_kickoff() async method for user-facing async API
- Promote stream relay errors from debug to warning for better visibility

All fixes address the wrapper's stated principles: async-safe by default, lazy imports, no hot-path performance impact.

Co-authored-by: MervinPraison <[email protected]>

* fix: align async framework path with sync behavior and add regression tests

* fix: align async framework path with sync behavior and add regression tests

- Fix async _arun_framework() to honor config.get('autogen_version') like sync path
- Stop silently swallowing RuntimeError from run_sync() - re-raise event loop errors
- Remove duplicate import os in autogen_adapter.py
- Enhance stream relay error logging with full traceback info

All critical reviewer bugs addressed. Architecture compliant with AGENTS.md.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-06-02 13:52:34 +01:00
MervinPraison 7839196391 Release v4.6.50 2026-06-02 07:19:27 +01:00
praisonai-triage-agent[bot]andMervin Praison e958968307 fix: wrapper layer gaps - case normalization, lazy loading, async persistence (#1767)
* fix: wrapper layer gaps - case normalization, lazy loading, async persistence (fixes #1766)

- Gap 1: Fix PluginRegistry case normalization inconsistency by normalizing names during storage and using lazy loaders
- Gap 2: Implement lazy loading in PluginRegistry by storing loaders instead of immediately executing them
- Gap 3: Add async persistence support with aon_* methods and achat wrapping in agent hooks

Co-authored-by: MervinPraison <[email protected]>

* fix: critical bugs in wrapper layer - registry consistency and async event loop blocking

- Fix registry inconsistency: register() now writes to both _loaders and _items
- Fix event loop blocking: PersistentAgent.achat uses asyncio.to_thread for sync fallback
- Fix threading deadlock: use RLock and release lock before calling loader()
- Add async session end methods (aend_session) for proper async lifecycle

Addresses critical P1/P2 issues identified by code reviewers.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
2026-06-02 07:16:38 +01:00
MervinPraison 1c26a5bf14 docs: auto-update api.md [skip ci] 2026-06-02 06:15:46 +00:00
ba8cd6b3c1 feat: implement Hermes-style persistent kanban system (#1769)
* feat: implement Hermes-style persistent kanban system

Implements comprehensive kanban task management system for PraisonAI wrapper:

Phase 1 - Persistent Store & Host Integration:
- SQLite kanban store with WAL, CAS, and dependency DAG support
- Task models with status enum and dataclasses
- Multi-board support via environment variables
- Host bridge injection for PraisonAIUI integration
- Updated claw navigation with kanban & jobs-board pages

Phase 2 - Agent Tools & Dispatcher:
- Complete agent tool suite (create, list, show, complete, block, etc.)
- Gateway dispatcher for task claiming and worker spawning
- Hook event integration (graceful degradation if unavailable)
- Lazy tool loading in tools module

Phase 3 - CLI & Human Operations:
- Full CLI command suite (praisonai kanban list, create, show, etc.)
- Multi-board management and task lifecycle operations
- Manual dispatcher triggering and task recovery commands
- Integrated with main CLI app registration

Features:
- Compatible with PraisonAIUI kanban API endpoints
- Parent/child task dependencies with automatic promotion
- Atomic operations with optimistic concurrency control
- Comprehensive logging and event trails
- Environment variable configuration support

Testing:
- Unit tests for SQLite store CRUD operations
- Integration tests for host injection and bridge setup
- Smoke tests for basic functionality validation

Fixes #1720

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>

* fix: address 6 critical issues in kanban system implementation

- Fix subprocess deadlock by redirecting output to temp files instead of PIPE
- Enable foreign key constraints on all SQLite connections for proper cascades
- Replace immediate dispatcher startup with proper event handler registration
- Add persistent CLI board switching via ~/.praisonai/kanban_config.json
- Prevent database locking with connection-reusing internal methods
- Replace deprecated datetime.utcnow() with datetime.now(timezone.utc)
- Fix optimistic locking by incrementing version in claim/release operations

Fixes all issues identified in code review by Gemini.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-02 07:15:18 +01:00
8327f8e8b8 fix: accept multi-channel bot.yaml keys with platform field (#1772)
* fix: accept multi-channel bot.yaml keys with platform field (#1757 regression)

Onboard generates channels like telegram_cfo with platform: telegram.
BotYamlSchema rejected any channel key not exactly matching a platform name,
so praisonai doctor reported invalid bot.yaml after multi-bot onboard.

Validate using channel.platform when present; extend ChannelConfigSchema for
gateway-style fields used in generated configs.

Co-authored-by: Mervin Praison <[email protected]>

* fix: use monkeypatch for env isolation in multi-channel test

- Replace direct os.environ manipulation with pytest monkeypatch
- Ensures test environment isolation and automatic cleanup
- Addresses CodeRabbit review feedback

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-06-02 07:13:57 +01:00
praisonai-triage-agent[bot]andMervin Praison f78ba6348c fix: eliminate wrapper layer architecture issues (#1780)
* fix: eliminate wrapper layer architecture issues (fixes #1779)

- Remove redundant framework availability wrappers in auto.py that only delegated to is_available()
- Make agents_generator module-level constants lazy via __getattr__() to avoid import-time probes
- Fix async bridge singleton creation (now lazy) and encapsulation breaks in run_sync()
- Deprecate AutoGen-specific methods in ToolRegistry to guide toward proper separation

Addresses three key architectural violations:
1. DRY violation: 8 wrapper functions that added no value over is_available()
2. Import-time work: 6 package probes ran on every agents_generator import
3. Encapsulation break: run_sync() accessed private _BG._lock directly

Performance impact: Eliminates import-time package probing and eager singleton creation.

Co-authored-by: MervinPraison <[email protected]>

* fix: address reviewer feedback for architecture issues

1. Fix shutdown() lazy-init defeat - read _BG directly instead of calling _get_bg()
2. Fix tool registry race condition - move _autogen_adapters init inside lock
3. Add __all__/__dir__ for legacy flag discoverability in agents_generator
4. Suppress internal deprecation warnings for backward compatibility paths

Addresses feedback from Greptile and CodeRabbit reviewers.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
2026-06-02 07:11:40 +01:00
Putra Jadi Muktianddymux 4f3daa8628 docs: fix broken Full Flow docs link in README (#1782)
The link pointed to /docs/concepts/flow which returns 404. The actual
page is published at /docs/concepts/agentflow.

Co-authored-by: dymux <[email protected]>
2026-06-02 07:10:32 +01:00
d7f68a0870 fix: complete AsyncAgentScheduler parity, fail-loud pip installs, remove broken resolver (fixes #1783) (#1784)
* fix: complete AsyncAgentScheduler parity, fail-loud pip installs, remove broken resolver

Fixes #1783

Three critical gap fixes in the PraisonAI wrapper layer:

1. **AsyncAgentScheduler Feature Parity**
   - Add missing timeout and max_cost parameters to match sync version
   - Port budget tracking logic with cost estimation
   - Port timeout support using asyncio.wait_for()
   - Add from_yaml() and from_recipe() class methods for YAML/recipe support
   - Update stats methods to include cost tracking
   - Remove 16 TODO markers now that features are ported

2. **Fail-Loud Pip Install Failures**
   - Convert silent pip install failures to raised RuntimeError exceptions
   - Fix managed_local.py _install_packages() to fail early on pip errors
   - Fix _install_packages_in_compute() to raise on compute pip failures
   - Eliminates confusing ImportError deep in tool execution

3. **Remove Broken reset_default_resolver Definition**
   - Remove second definition that shadows working first definition
   - Eliminates NameError on function call due to undefined globals
   - Preserves working ContextVar-based implementation at line 545

All changes maintain backward compatibility while fixing production-blocking issues
in async scheduling, managed agent bootstrap, and tool resolution.

Co-authored-by: MervinPraison <[email protected]>

* fix: restore async stats API and safe budget-stop behavior

* fix: tighten async budget checks and stats parity

* fix: remove redundant asyncio import in from_recipe method

Removes the unnecessary nested import asyncio statement inside the
astart method, since asyncio is already imported at module level.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-06-02 07:09:42 +01:00
Anna Tao 1bf62b0416 feat: add CLIENT SETNAME for connection identification (#1787)
Adds client_name="praisonai_valkey_client" to the shared Valkey client
factory so all PraisonAI connections are identifiable via CLIENT LIST.

Signed-off-by: Anna Tao <[email protected]>
2026-06-02 07:08:46 +01:00
praison d5f1114aaf Release v4.6.48 2026-05-30 07:22:17 +01:00
Anna Tao d364fa5020 feat: add CLIENT SETNAME to Valkey client for connection identification (#1761)
Sets client_name="praisonai_persistence_client" on GlideClientConfiguration
so connections are identifiable in CLIENT LIST, Valkey Admin, and CloudWatch.

Naming convention: {project}_{purpose}_client
- praisonai = project
- persistence = purpose (state, knowledge, and session storage)
- _client = convention (matches Valkey Admin pattern)
2026-05-30 07:20:59 +01:00
c1db6317c8 fix: reload session from disk on get_chat_history reads (#1759)
* fix: reload session from disk on get_chat_history reads

get_chat_history and get_session returned stale in-memory cache when
another DefaultSessionStore instance (or worker process with a warm
cache) had written newer messages to the same session file. Bot
load_history paths then fed the LLM truncated context.

Reload under FileLock before returning reads; add regression test.

Co-authored-by: Mervin Praison <[email protected]>

* fix: address session store test failure and consistency issues

- Update test_invalidate_cache to reflect new always-reload behavior
- Fix inconsistency in get_sessions_by_agent() to use fresh reads
- Ensures consistent staleness guarantees across all read methods

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-05-30 07:20:30 +01:00
f88727cb75 feat: Multi-Telegram-channel deployments with per-channel token env convention (#1757)
* feat: implement multi-channel Telegram bot support (fixes #1751)

- Add multi-channel support to onboard wizard with role-based naming
- Implement TELEGRAM_<ROLE>_BOT_TOKEN environment variable convention
- Add doctor validation for duplicate token usage and naming conventions
- Create YAML generation for multiple channels per platform with agent routing
- Add documentation and example for Hermes-style multi-bot workforces

This enables operators to run multiple Telegram bots (e.g. @company_cfo_bot,
@company_ops_bot) each routing to different agents with specialized knowledge,
matching Hermes workforce deployment patterns.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* fix: critical structural regression in onboard wizard and improve validation

- Fix unreachable code in onboard wizard - Steps 2-6 were dead code after return statement
- Restore self.tokens attribute for backward compatibility with legacy methods
- Improve duplicate token detection to check actual token values, not just env var names
- Add role sanitization (regex) and duplicate channel prevention
- Fix markdown language specifier to resolve markdownlint warning

Fixes structural issue where wizard would exit after Step 1 without collecting tokens,
generating YAML, or installing daemon. All critical reviewer feedback addressed.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-30 07:19:36 +01:00
MervinPraison 7ab0479e82 docs: auto-update api.md [skip ci] 2026-05-30 06:18:38 +00:00
0e0241d15f fix: Gateway port 8765 collision — add preflight bind check and single-instance guard (#1756)
* fix: Gateway port 8765 collision — add preflight bind check and single-instance guard (fixes #1749)

- Add port_utils.py with collision detection utilities:
  * is_port_in_use() - Check if port is bound
  * check_port_available() - Check port and find PID using it
  * GatewayPIDLock - Single-instance enforcement with PID lock files
  * format_collision_error() - Actionable error messages

- Update gateway server with preflight port checking:
  * Check port availability before uvicorn starts
  * Acquire/release PID lock for single-instance enforcement
  * Clear error messages when port conflicts detected

- Enhance gateway CLI with stop command and GATEWAY_PORT support:
  * Add 'praisonai gateway stop' with graceful/force options
  * Enhanced 'praisonai gateway status' shows PID lock and port status
  * Support GATEWAY_PORT environment variable in all commands

- Implement gateway handler stop functionality:
  * PID detection and graceful/force process termination
  * Enhanced status checking with port and lock information

Resolves port bind failures, duplicate process scenarios, and Windows restart loops.
Provides clear error messages with actionable guidance for operators.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* fix: Resolve critical PID lock and port collision issues

Fixes 5 critical bugs identified in gateway collision prevention:

1. Multi-port conflict: PID lock now port-specific to allow different ports
2. Lock cleanup failure: Added exception handler around uvicorn startup
3. TOCTOU race: Use atomic temp file + rename for lock acquisition
4. Windows compatibility: Use SIGTERM on Windows instead of SIGKILL
5. Unused variable: Remove unused output controller in stop command

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-30 07:18:15 +01:00
MervinPraison 5815dc61bf docs: auto-update api.md [skip ci] 2026-05-30 06:17:53 +00:00
e720c0bc3d fix: Agent RLock not picklable in multi-channel gateway (#1755)
* fix: Agent RLock not picklable in multi-channel gateway (fixes #1746)

- Add Agent.clone_for_channel() method to safely clone agents without threading.RLock issues
- Update WebSocketGateway._create_bot() to use clone_for_channel() instead of copy.deepcopy()
- Add comprehensive tests for multi-channel scenarios
- Resolves 'cannot pickle _thread.RLock object' error when creating 2nd+ gateway channels

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* Changes before error encountered

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/356b719f-451d-4adf-93ad-1a33350b555b

* fix: comprehensive Agent.clone_for_channel() implementation

- Replace deepcopy approach with proper cloning logic
- Shallow copy tools to avoid nested RLock deepcopy failures
- Exclude handoffs from clones (no shared agents across channels)
- Create fresh interrupt_controller for each clone (no shared state)
- Preserve all config objects and core attributes properly
- Add deprecation warnings for backward compatibility
- Remove ad-hoc test files, use proper test structure

Resolves all issues identified in code reviews while maintaining
full backward compatibility and following AGENTS.md guidelines.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-30 07:17:30 +01:00
cd448fa710 fix: Gateway Telegram error replies crash on non-ASCII exception text (fixes #1752) (#1754)
* fix: Gateway Telegram error replies crash on non-ASCII exception text

- Create safe error message helper in unicode_utils.py
- Update Telegram bot error handling to use ASCII-safe formatting
- Fix gateway server error handler to extract root cause errors
- Ensure UTF-8 encoding for YAML config file reads
- Add support for accented character conversion to ASCII

Fixes #1752

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* Changes before error encountered

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/a921937b-8ef2-4716-a4c1-16e7e340f16d

* fix: address reviewer feedback on unicode_utils performance and logic

- Remove dead code comment and simplify safe_log_message implementation
- Fix double sanitization in extract_root_cause_from_error by returning raw text
- Improve code comments for clarity

Addresses Greptile review feedback on performance and logic issues.

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-05-30 07:16:38 +01:00
c35dadebdb feat: implement Telegram typing indicator renewal during long agent operations (#1753)
* feat: implement Telegram typing indicator renewal during long agent operations

- Add TypingIndicator utility class with configurable renewal interval
- Update TelegramBot standalone mode to use typing renewal during agent.chat()
- Update gateway polling handler to use typing renewal during agent.chat()
- Enable ack_emoji (⏳) and done_emoji (✅) in onboard-generated configs
- Typing indicator now renews every 4 seconds during long operations
- Fixes issue where users thought bot was broken during 20-30s agent responses

Fixes #1748

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* Changes before error encountered

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/964cb77f-55a0-4e60-b20d-348759d336d8

* docs: improve docstring coverage for typing indicator module

Enhance docstring for _typing_loop method to improve coverage
and meet repository documentation standards.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-30 07:15:55 +01:00
f9ae9e9aa4 fix: HierarchicalSessionStore message loss and extended field wipe (#1745)
* fix: HierarchicalSessionStore message loss and extended field wipe

HierarchicalSessionStore.add_message used an unlocked load-modify-save
path, so concurrent writers could overwrite each other's messages.
Inherited _modify_session_locked also loaded SessionData, which dropped
parent_id, snapshots, and children_ids on metadata updates.

- Load ExtendedSessionData under the existing file lock
- Route add_message through _modify_session_locked
- Keep _extended_cache in sync after locked writes
- Add regression tests for concurrency and extended fields

Co-authored-by: Mervin Praison <[email protected]>

* fix: remove redundant SessionMessage import in hierarchy.py

Copilot found redundant local import of SessionMessage in add_message
method since it's already imported at module scope. This removes
the unnecessary import statement.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-05-30 07:15:24 +01:00
9d9a9a7ad8 fix: Security vulnerabilities in wrapper layer (#1744)
* fix: Security vulnerabilities in wrapper layer (fixes #1743)

- Fix 1: Gateway magic-link auth secret mismatch - export resolved token to environment for single source of truth across HTTP and WebSocket auth paths
- Fix 2a: SSH sandbox timeout cleanup - add try/finally to ensure remote temp files are always cleaned up
- Fix 2b: SSH sandbox remote process orphaning - wrap commands with timeout to ensure remote processes self-terminate
- Fix 2c: Docker sandbox container orphaning - add container names and docker kill on timeout to stop actual containers
- Fix 3: Cloud deploy API key exposure - replace inline argv secrets with secure temporary YAML file approach

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>

* fix: ensure gateway auth token env stays in sync

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/174baeba-8504-435e-875b-60dc62d3972c

Co-authored-by: MervinPraison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-30 07:14:53 +01:00
44d9d8c4c0 fix: eliminate wrapper layer architectural gaps (#1723)
* fix: eliminate wrapper layer architectural gaps (fixes #1722)

Gap 1 - Remove dead duplicate framework runners (~790 lines):
- Delete _run_autogen, _run_autogen_v4, _run_ag2, _run_crewai, _run_praisonai from agents_generator.py
- These methods were never called (execution goes through framework_adapter.run())
- Eliminates maintenance drift between duplicate implementations

Gap 2 - Complete async scheduler migration:
- Move AsyncAgentScheduler to canonical location scheduler/async_agent_scheduler.py
- Reduce root async_agent_scheduler.py to thin re-export with deprecation warning
- Add TODO comments for missing features (timeout, max_cost, from_yaml, etc.)
- Maintains backward compatibility while stopping feature drift

Gap 3 - Replace global singletons with contextvars:
- interactive_tools.py: _shared_runtime → _runtime_var for per-context config
- tool_resolver.py: _default_resolver → _resolver_var for CWD isolation
- Prevents race conditions and config capture in concurrent execution
- Add reset_default_resolver() for daemon/IDE plugin invalidation

All fixes preserve backward compatibility while aligning with project philosophy:
DRY, multi-agent safe, async-safe, no global singletons, protocol-driven core.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>

* fix: align async scheduler compatibility logging and docs

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/043eb2d4-7868-4904-8b6f-2301a38da452

Co-authored-by: MervinPraison <[email protected]>

* fix: resolve reviewer issues in wrapper layer fixes

- Fix hot retry loop on asyncio.TimeoutError by adding backoff delay
- Remove unused _cancel_event attribute from AsyncAgentScheduler
- Add missing get_stats_async() and get_stats_sync() methods for backward compatibility
- Remove unnecessary process-wide lock from context-local runtime creation
- Document first-caller-wins behavior for runtime config

Addresses critical issues identified by Greptile and CodeRabbit reviewers.
Maintains full backward compatibility while fixing architectural gaps.

Co-authored-by: Mervin Praison <[email protected]>

* fix: simplify get_stats_sync to avoid event loop issues

Use direct synchronous access instead of trying to coordinate with event loop.
This prevents timeouts and maintains backward compatibility.

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Claude <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-30 07:13:29 +01:00
praison bf2656cee9 Release v4.6.47 2026-05-30 07:11:48 +01:00
d55cd989ea fix: persist DbSessionAdapter metadata across process restarts (#1742)
* fix: persist DbSessionAdapter metadata to conversation store

Managed agents using PraisonDB lost token counts, session history, and
compute refs after process restart because set_metadata was in-memory only.
Flush metadata on write and reload from the conversation session on read.

Co-authored-by: Mervin Praison <[email protected]>

* fix: address CodeRabbit findings in DbSessionAdapter metadata persistence

- Add _purge_persisted_metadata() to clear metadata on session deletion
- Fix test mock configuration to prevent auto-creation of conversation attr
- Add integration test as required by AGENTS.md §9.4

Resolves stale metadata resurrection and improves test coverage.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-05-30 07:05:57 +01:00
0305214695 fix: wrapper defects - scheduler timeout, tool loading, and YAML surface (#1741)
* fix: wrapper defects - scheduler timeout, tool loading, and YAML surface

- Replace signal.SIGALRM with ThreadPoolExecutor timeout in AgentScheduler (fixes #1738)
- Add thread safety with _stats_lock for execution counters
- Consolidate tool loading through ToolResolver, remove duplicate _extract_tool_classes
- Add YAML surface for handoff, web, and web_fetch CLI features
- Ensure CLI flags propagate to YAML-driven agent configurations

Co-authored-by: MervinPraison <[email protected]>

* fix: restore YAML CLI parity extraction and scheduler timeout behavior

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* test: simplify scheduler timeout regression fixture

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* test: make scheduler delay intent explicit

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* test: replace timeout threshold literal with named variable

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* test: document scheduler timeout threshold buffer

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* test: use timeout-relative threshold for scheduler regression

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* fix: guarantee scheduler timeout executor cleanup

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* test: name scheduler timing buffer constant

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/005274fc-241b-4332-8eca-96b9f814a5b8

Co-authored-by: MervinPraison <[email protected]>

* fix: resolve reviewer issues - timeout blocking, BaseTool import, boolean conversion

- Fix ThreadPoolExecutor timeout blocking by using non-blocking shutdown
- Replace BaseTool import error with safe tool instantiation pattern
- Fix case-sensitive boolean conversion for handoff_detect_cycles
- Consolidate duplicate tool loading code in ToolResolver
- Improve per-file error isolation in directory tool loading

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-30 07:05:30 +01:00
3f26bf166c fix: correct callback signature mismatch in multi-agent startup (fixes #1730) (#1740)
* fix: correct callback signature mismatch in multi-agent startup (fixes #1730)

- Fix composed_on_task_start to accept both task and task_id parameters
- Fix composed_on_task_complete to accept both task and task_output parameters
- Ensures callbacks receive the correct number of arguments as expected
- Resolves AgentTeam startup error with function signature mismatch

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* fix: forward correct parameters to verbose callbacks (fixes verbose display issue)

- Pass task_id to verbose_task_start_callback(task, task_id)
- Pass task_output to verbose_task_complete_callback(task, task_output)
- Resolves silent TypeError in verbose mode identified by all reviewers

Co-authored-by: Mervin Praison <[email protected]>

* fix: forward verbose callback args and add regression test

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/bd0c3ea8-33b8-4148-b703-2c368de0aa14

Co-authored-by: MervinPraison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-30 07:04:06 +01:00
ab19a13cc4 fix: make deduplicate_chunks and build_context handle SearchResultItem objects (#1739)
* fix: make deduplicate_chunks and build_context handle SearchResultItem objects

- Add _extract_value helper to handle both dict and SearchResultItem objects
- Update type hints to accept Union[Dict[str, Any], Any] in context functions
- Maintain full backward compatibility with existing dict-based usage
- Fix AttributeError when SearchResultItem objects are passed to .get() method

Fixes #1732

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* fix: improve SearchResultItem handling in rag context builder

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/fbaed72c-c0f6-4426-8cb4-09c3542f499f

Co-authored-by: MervinPraison <[email protected]>

* refactor: tighten source fallback semantics in rag context

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/fbaed72c-c0f6-4426-8cb4-09c3542f499f

Co-authored-by: MervinPraison <[email protected]>

* refactor: dedupe metadata fallback extraction in rag context

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/fbaed72c-c0f6-4426-8cb4-09c3542f499f

Co-authored-by: MervinPraison <[email protected]>

* test: add comprehensive SearchResultItem test coverage for RAG context module

- Add tests for _extract_value and _extract_metadata_value helpers
- Add tests for SearchResultItem deduplication functionality
- Add tests for mixed dict/SearchResultItem format handling
- Add tests for source/filename fallback behavior from top-level attributes
- Verify metadata preference over top-level attributes works correctly

Ensures all reviewer feedback scenarios are properly tested.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-30 07:03:16 +01:00
28d487b66d fix: resolve three high-impact gaps in praisonai wrapper layer (#1736)
* fix: resolve three high-impact gaps in praisonai wrapper layer (fixes #1735)

- Fix blocking ollama serve calls: Replace subprocess.run(['ollama', 'serve'])
  with proper daemon management across 4 files. Created shared _ollama.py
  helper with non-blocking daemon startup and connection checking.

- Fix multi-tenant unsafe tool resolver: Resolve paths eagerly in constructor
  instead of lazy CWD binding. Add reset_default_resolver() function to clear
  process-level cache, following _framework_availability.invalidate() pattern.

- Fix sync-only auto-generator: Add async API with _astructured_completion(),
  agenerate() methods, and proper async context managers (__aenter__/__aexit__).
  Remove unreliable __del__ cleanup in favor of explicit close() and aclose().

All fixes maintain backward compatibility while adding async-safe and
multi-tenant-safe alternatives as required by project architecture.

Co-authored-by: MervinPraison <[email protected]>

* fix(auto): close sync client in async cleanup path

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/55e92785-fa2d-40bb-b67a-0ef213025ab3

Co-authored-by: MervinPraison <[email protected]>

* fix(auto): avoid blocking event loop during async close

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/55e92785-fa2d-40bb-b67a-0ef213025ab3

Co-authored-by: MervinPraison <[email protected]>

* refactor(auto): clarify async cleanup variable naming

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/55e92785-fa2d-40bb-b67a-0ef213025ab3

Co-authored-by: MervinPraison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-30 07:02:22 +01:00
MervinPraison a06239fb15 docs: auto-update api.md [skip ci] 2026-05-30 06:00:55 +00:00
dabe2cf671 feat: integration follow-up - Pattern C CLI, L3 pages, aiui 0.3.121, cross-repo CI (#1718)
* feat: integration follow-up - Pattern C CLI, L3 pages, aiui 0.3.121, cross-repo CI (fixes #1717)

Comprehensive integration follow-up implementing Pattern B→C transition:

**Tier 1 - Release & CI:**
- Pin aiui>=0.3.121,<0.4 across all optional dependencies (8 occurrences)
- Add cross-repo CI workflow testing PraisonAI + PraisonAIUI integration
- Create RELEASE_INTEGRATION.md with version matrix and troubleshooting
- Include optional agentic testing job for end-to-end validation

**Tier 2 - Pattern C & CLI:**
- Add configure_host(style=...) parameter with dashboard/chat options
- Implement 'praisonai serve ui-gateway' command for Pattern C
- Export run_integrated_gateway in main package API
- Add sync wrapper for async gateway function

**Tier 3 - L3 Pages & Infrastructure:**
- Register L3 dashboard pages (workflow-runs, bot-health)
- Add context_paths parameter for AGENTS.md-style injection
- Upgrade bridge failure logs from debug to warning level
- Set up framework for backend slot injection

Co-authored-by: MervinPraison <[email protected]>

* fix: critical issues in Pattern C UI-Gateway integration

- Fix TypeError: remove unsupported agents_file parameter from CLI call
- Align default ports: change gateway_host.py default from 8080 to 8765
- Add **kwargs to configure_host for resilience against extra arguments
- Revert log levels: warning back to debug for optional dependencies

Fixes review feedback from gemini-code-assist

Co-authored-by: Mervin Praison <[email protected]>

* fix: address PR review findings for ui-gateway and integration CI

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/3ee145c5-72dc-4884-9840-c85ba238e718

Co-authored-by: MervinPraison <[email protected]>

* test: tighten ui-gateway assertions and remove test magic number

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/3ee145c5-72dc-4884-9840-c85ba238e718

Co-authored-by: MervinPraison <[email protected]>

* Delete RELEASE_INTEGRATION.md

* fix: correct path to PraisonAIUI in cross-repo CI workflow

Both cross-repo-integration and agentic-integration jobs were using
cd ../../PraisonAIUI which resolves to PraisonAI/PraisonAIUI (doesn't exist).
Changed to cd ../../../PraisonAIUI to correctly reach the sibling checkout
at /home/runner/work/PraisonAI/PraisonAI/PraisonAIUI.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-30 07:00:29 +01:00
MervinPraison 619787c9da docs: auto-update feature parity trackers [skip ci] 2026-05-30 06:00:01 +00:00
2fa6a6efd0 fix: RAG filtering error with multiple where conditions (fixes #1728) (#1729)
* fix: RAG filtering with multiple where conditions using ChromaDB  operator

- Fix ChromaKnowledgeAdapter to handle multiple filter conditions properly
- Use ChromaDB's  operator when len(where_filter) > 1
- Resolves validation error: len(where) != 1 when filtering by user_id, agent_id, run_id
- Maintains backward compatibility with single condition filters
- Fixes #1728

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>

* test: add Chroma where-filter coverage for single and multi conditions

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/49aeab8d-0c2b-4a87-b55a-e30f79086d29

Co-authored-by: MervinPraison <[email protected]>

* fix: add logging to ChromaDB search exception handler

Improves debugging for ChromaDB query failures by logging warnings
instead of silently returning empty results.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-30 06:59:37 +01:00
8acf77c531 fix: DbSessionAdapter.clear_session must purge persisted messages (#1737)
clear_session only cleared the in-memory cache while BotSessionManager
and managed agents rewrite history via clear_session + add_message.
Stale DB rows were reloaded on the next on_agent_start, resurrecting
trimmed or cleared chat history.

- Call conversation.delete_messages when available
- Reset session tracking and skip stale on_agent_start hydration
- Add regression test for bot history trim roundtrip

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-25 09:15:23 +01:00
5ff79d39c9 fix: prevent session message loss in LocalManagedAgent._persist_state (#1727)
* fix: prevent session message loss in LocalManagedAgent._persist_state

Use update_session_metadata (locked read-modify-write) instead of
get_session + _save_session, which could overwrite messages written
concurrently via add_message on another store instance.

Adds regression test mirroring session store race coverage from #1724.

Co-authored-by: Mervin Praison <[email protected]>

* fix: preserve legacy _persist_state fallback when session is absent

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/4d08ce0a-1b7b-4e50-b841-6a08416f2f53

Co-authored-by: MervinPraison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-23 10:29:01 +01:00
6902147f13 fix: architectural gaps in wrapper layer execution paths (#1726)
* fix: architectural gaps in wrapper layer execution paths

- Add per-name resolution caching to ToolResolver for performance
- Replace eager 17-tool resolution with demand-driven YAML parsing
- Fix InteractiveRuntime lifecycle safety in exception paths
- Remove dead framework methods (_run_autogen, _run_crewai, etc.)

Fixes #1725

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <[email protected]>

* fix: resolve critical architectural gaps identified in code review

- Fix lock-order inversion in ToolResolver.resolve() to prevent deadlock
- Remove PRAISONAI_TOOLS_AVAILABLE gating from YAML tool resolution
- Preserve partial tool successes when individual tool initialization fails
- Add graceful degradation for common InteractiveRuntime startup errors

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2026-05-23 09:54:56 +01:00
321b6b28a9 fix: prevent session message loss in set_agent_info and clear_session (#1724)
* fix: prevent session message loss in set_agent_info and clear_session

Apply locked read-modify-write (same pattern as update_session_metadata)
to set_agent_info, clear_session, and set_gateway_info so stale in-memory
copies cannot overwrite messages written by add_message on another instance.

Co-authored-by: Mervin Praison <[email protected]>

* test: add regression test for set_gateway_info message preservation

Addresses Copilot's suggestion to ensure set_gateway_info also preserves
messages when racing with concurrent message writes from another instance.
Completes test coverage for all four methods migrated to _modify_session_locked.

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
2026-05-22 13:21:31 +01:00
1c5b58aa13 fix: async-safety gaps in praisonai wrapper (#1692)
* fix: async-safety gaps in praisonai wrapper

- Replace InteractiveRuntime separate event loop with shared _async_bridge
- Add proper cancellation to run_sync timeouts to prevent resource leaks
- Add timeout wrapper at wrapper boundary for defense-in-depth tool_timeout
- Remove deprecated run_async in favor of consistent run_sync usage

Fixes #1662

Co-authored-by: MervinPraison <[email protected]>

* fix: resolve ThreadPoolExecutor blocking and Python 3.10 TimeoutError compatibility

- Fix ThreadPoolExecutor context manager that defeated timeout purpose
- Add explicit concurrent.futures.TimeoutError handling for Python 3.10 compat
- Ensure consistent JSON return types for timeout errors
- Use shutdown(wait=False) to prevent blocking on timeout

Addresses reviewer feedback from Copilot on PR #1692

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>

* fix: prevent sync timeout wrapper from blocking and harden run_sync cancellation

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/91864b65-201b-4168-8287-2c6e31d70c63

Co-authored-by: MervinPraison <[email protected]>

* Changes before error encountered

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/91864b65-201b-4168-8287-2c6e31d70c63

Co-authored-by: MervinPraison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-22 13:20:42 +01:00
Mervin Praison 71834d39d7 Delete knowledge.db 2026-05-22 10:28:34 +01:00
MervinPraison 6971d8ecc9 docs: auto-update feature parity trackers [skip ci] 2026-05-22 07:32:16 +00:00
8348c2b7ab feat: add kanban protocols and hook events (praisonai-agents core SDK) (#1721)
* feat: add kanban protocols and hook events for praisonaiagents core SDK

- Add KanbanStoreProtocol in praisonaiagents/kanban/protocols.py
- Add VALID_KANBAN_STATUSES constant matching PraisonAIUI columns
- Add 6 kanban hook events to HookEvent enum (KANBAN_TASK_*)
- Add KanbanHookInput dataclass for typed payloads
- Add comprehensive unit tests covering all functionality
- Follow AGENTS.md protocol-driven design (protocols in core, implementations in wrapper)
- No new dependencies or heavy implementations

Fixes #1719

Co-authored-by: MervinPraison <[email protected]>

* test: fix HookEvent serialization assertion for Enum semantics

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/5480309b-3d48-4bd9-b55f-89dc11e39468

Co-authored-by: MervinPraison <[email protected]>

* test: verify HookEvent JSON serialization round-trip

Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/5480309b-3d48-4bd9-b55f-89dc11e39468

Co-authored-by: MervinPraison <[email protected]>

* fix: split kanban protocol optional methods into extension protocols

Fixes CodeRabbit finding about @runtime_checkable protocols requiring
all declared methods at runtime. Splits optional methods (add_comment,
link_tasks, unlink_tasks) into separate extension protocols:

- KanbanCommentingProtocol for commenting functionality
- KanbanLinkingProtocol for task relationship functionality

This allows stores to implement core KanbanStoreProtocol without
breaking isinstance checks, while optionally implementing extension
protocols for additional features.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>

---------

Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com>
Co-authored-by: MervinPraison <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MervinPraison <[email protected]>
2026-05-22 08:31:49 +01:00
praison 9cfc636a92 Release v4.6.46 2026-05-21 23:24:42 +01:00
Mervin Praison b43e93c502 Delete test_capability_implementation.py 2026-05-21 23:21:50 +01:00
Mervin Praison b09450d9dc Delete test_backward_compatibility.py 2026-05-21 23:21:41 +01:00
Mervin Praison 710d607f6e Merge pull request #1705 from edlng/add-valkey
feat: Add Valkey Integration
2026-05-21 23:18:17 +01:00
MervinPraison a7910c2eb0 docs: auto-update api.md [skip ci] 2026-05-21 20:39:24 +00:00
Mervin Praison c98e1a1972 Merge pull request #1710 from MervinPraison/claude/issue-1697-20260520-0959
feat: implement Hermes/OpenClaw skill metadata capability gates
2026-05-21 21:38:56 +01:00
Mervin Praison aee9552dd0 Delete docs/skill_capability_gates.md 2026-05-21 19:54:27 +01:00
MervinPraison 6507b8e7ef docs: auto-update api.md [skip ci] 2026-05-21 18:54:06 +00:00
Mervin Praison 50652531e7 Merge pull request #1711 from MervinPraison/claude/issue-1696-20260520-0959
fix: enhance BaseTool schema validation for OpenAI compatibility
2026-05-21 19:53:34 +01:00
Mervin Praison a949579759 Merge pull request #1713 from MervinPraison/claude/issue-1694-20260520-0812
fix: resolve critical gaps in praisonai wrapper layer
2026-05-21 19:51:11 +01:00
Mervin Praison 79702ba1ff Merge pull request #1709 from MervinPraison/cursor/critical-correctness-bugs-989e
fix: prevent session message loss in update_session_metadata
2026-05-21 19:50:17 +01:00
MervinPraison e9b75bfef9 docs: auto-update feature parity trackers [skip ci] 2026-05-21 13:51:06 +00:00
Mervin Praison 982b7dfe4f Merge pull request #1712 from MervinPraison/claude/issue-1695-20260520-0959
fix: add UTF-8 encoding for Windows skills subsystem files (fixes #1695)
2026-05-21 14:50:21 +01:00
MervinPraison f372821b9e docs: auto-update api.md [skip ci] 2026-05-21 10:43:07 +00:00
praison 445003042e Release v4.6.45 2026-05-21 11:42:37 +01:00
copilot-swe-agent[bot]andMervinPraison 00b40e8cc4 fix: address review findings for capability gates
Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/b4c856b3-93a3-4a2b-ad6c-bb90ef413121

Co-authored-by: MervinPraison <[email protected]>
2026-05-21 10:02:52 +00:00
copilot-swe-agent[bot]andMervinPraison 6dca959eda fix: correct deployment scheduler parser import and add regression test
Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/2b3a43a6-84a1-42f9-bd87-2a92ac3188e0

Co-authored-by: MervinPraison <[email protected]>
2026-05-21 10:02:28 +00:00
copilot-swe-agent[bot]andMervinPraison 5ba8782bf7 fix: return clear UTF-8 decode errors from skill validator
Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/11761ef3-3173-426f-b016-9fee9fd66a1e

Co-authored-by: MervinPraison <[email protected]>
2026-05-21 10:02:07 +00:00
copilot-swe-agent[bot]andMervinPraison a2402063f8 fix: handle non-UTF8 SKILL.md decoding errors in validator
Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/11761ef3-3173-426f-b016-9fee9fd66a1e

Co-authored-by: MervinPraison <[email protected]>
2026-05-21 09:59:32 +00:00
praisonai-triage-agent[bot]andMervin Praison 302bbcbec2 perf: optimize BaseTool validation per Gemini review
- Simplify required field validation logic (line 307)
- Move get_tool_schema import outside loop for better performance
- Use set for O(n) duplicate detection instead of O(n²) list lookup

Addresses valid performance issues identified in PR review while
maintaining backward compatibility and test coverage.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>
2026-05-21 09:57:20 +00:00
praisonai-triage-agent[bot]andMervin Praison ac309e99ea fix: address reviewer feedback on skill capability gates
- Fix hardcoded paths in test scripts to use relative paths
- Treat missing environment variables as errors in STRICT mode
- Add support for comma-separated strings in requirement parsing

Co-authored-by: Mervin Praison <[email protected]>
2026-05-21 09:56:28 +00:00
praisonai-triage-agent[bot]andMervin Praison 727ee626c8 fix: catch UnicodeDecodeError in skills validator
Validator should gracefully handle encoding errors and return
validation errors rather than crashing. Fixes issue found by
code review.

Co-authored-by: Mervin Praison <[email protected]>
2026-05-21 09:56:15 +00:00
Mervin Praison 1dc61d3946 Merge pull request #1706 from MervinPraison/feat/aiui-integration-host
feat: PraisonAIUI host integration (Patterns B/C) + core protocol bridges
2026-05-21 10:49:26 +01:00
praisonai-triage-agent[bot]andMervin Praison 50a0399f1c fix: handle FileLock acquisition failure in context manager
CodeRabbit identified a critical security bug where FileLock.__enter__()
didn't check if acquire() succeeded, potentially allowing unlocked
execution. Fixed to properly raise IOError when lock acquisition fails.

Co-authored-by: Mervin Praison <[email protected]>
2026-05-21 09:30:11 +00:00
MervinPraison 40bfd66797 docs: auto-update api.md [skip ci] 2026-05-21 09:28:35 +00:00
Mervin Praison 0da4a90c80 Merge pull request #1708 from MervinPraison/claude/issue-1707-20260521-0816
fix: consolidate framework availability detection and add simple Python API
2026-05-21 10:28:04 +01:00
Cursor AgentandMervin Praison dc75c51fea fix: prevent session message loss in update_session_metadata
Use locked read-modify-write when merging session stats so a stale
in-memory copy cannot overwrite messages written by add_message.
Adds a regression test for the two-store race introduced with UI
session telemetry.

Co-authored-by: Mervin Praison <[email protected]>
2026-05-21 09:18:52 +00:00
praisonai-triage-agent[bot]andMervin Praison b95a7f6ded fix: address reviewer feedback - explicit arun signature, remove unused imports, add framework validation
- Make arun() signature explicit instead of opaque **kwargs
- Remove unused importlib.util import from inbuilt_tools/__init__.py
- Add trailing newline to _entrypoint.py
- Add framework validation for explicit framework param like CLI does

Co-authored-by: Mervin Praison <[email protected]>
2026-05-21 08:31:41 +00:00
praisonai-triage-agent[bot]andMervinPraison 92953fdbe6 fix: consolidate framework availability detection and add simple Python API (fixes #1707)
- Consolidate framework availability detection in _framework_availability.py
  - Add missing probes for acp, rich, gradio, unsloth
  - Replace ~30 direct find_spec calls with centralized is_available()
  - Update cli/main.py, tool_resolver.py, inbuilt_tools, acp, console.py

- Add simple Python API entry points
  - Create _entrypoint.py with run() and arun() functions
  - Export in __init__.py with lazy loading
  - Use same LLM endpoint resolution as CLI for consistency
  - Enables one-liner: praisonai.run('agents.yaml')

Addresses Gaps 2 and 3 from architectural review.
Gap 1 (dead _run_* methods) requires adapter functionality porting first.

Co-authored-by: MervinPraison <[email protected]>
2026-05-21 08:22:12 +00:00
MervinPraison b3cd7ecfd0 docs: auto-update feature parity trackers [skip ci] 2026-05-21 06:59:29 +00:00
copilot-swe-agent[bot]andMervinPraison 01ea0f5a05 fix: address gemini review findings in tool emitter + usage summary
Agent-Logs-Url: https://github.com/MervinPraison/PraisonAI/sessions/c2c4c0e0-0cb7-4608-ab5e-3a259f9bd635

Co-authored-by: MervinPraison <[email protected]>
2026-05-21 06:58:47 +00:00
praisonai-triage-agent[bot]andMervin Praison eddcae8d31 fix: replace fragile name mangling with proper stream_emitter property access
- Replace getattr(self, '_Agent__stream_emitter', None) with self.stream_emitter
- Optimize token summary calculation with single-pass algorithm
- Fix inconsistent total_tokens calculation in telemetry protocols

Co-authored-by: Mervin Praison <[email protected]>
2026-05-21 06:55:55 +00:00
praison 71f891003e Add PraisonAIUI host integration layer (Patterns B/C) with core protocol bridges.
Introduces configure_host/build_host_app, optional L1 bridges (hooks, workflows, usage, approvals, schedules), refactors bundled default apps, and adds session/telemetry protocols plus integration tests so aiui can run standalone or wired via set_backend injection.
2026-05-21 07:49:50 +01:00
praison 13750a4ccd Release v4.6.44 2026-05-20 20:45:21 +01:00
Mervin Praison c9e1d1a202 Merge pull request #1704 from MervinPraison/claude/issue-1703-20260520-1507
fix: Agent.achat hanging - unified dispatch missing response handling
2026-05-20 20:43:31 +01:00
praisonai-triage-agent[bot]andMervin Praison 5515290329 refactor: extract shared guardrail validation logic to reduce code duplication
- Extract _validate_with_guardrail() method containing common validation logic
- Simplified _apply_guardrail_with_retry() and _aapply_guardrail_with_retry() to use shared validation
- Reduced code duplication from ~126 lines to ~25 lines of shared core logic
- Maintains identical functionality while improving maintainability

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>
2026-05-20 19:41:18 +00:00
praisonai-triage-agent[bot]andMervin Praison cb1cefd94b fix: resolve async guardrail retry bug and improve response handling
- Fixed critical bug in _aapply_guardrail_with_retry line 4732
- Changed await self._achat_completion to await self._execute_unified_achat_completion
- _achat_completion expects response object, not message list
- Added response type safety guards (hasattr checks, isinstance fallbacks)
- Prevents AttributeError crashes during async guardrail retries
- Maintains both sync and async guardrail methods for architectural clarity

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>
2026-05-20 19:04:14 +00:00
praisonai-triage-agent[bot]andMervin Praison a90666a19f fix: resolve async guardrails and response.choices access issues in unified dispatch
- Add proper hasattr guards for response.choices access to prevent crashes when dispatcher returns plain strings
- Fix stale reflection context by properly updating reflection_messages with new responses
- Create async _aapply_guardrail_with_retry method to prevent event loop blocking
- Update unified async dispatch path to use async guardrails while preserving sync guardrails in sync paths
- Resolves critical issues identified in Greptile review while maintaining backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2026-05-20 16:21:45 +00:00
Mervin Praison 89df701c2a Merge branch 'main' into claude/issue-1703-20260520-1507 2026-05-20 16:51:34 +01:00
praisonai-triage-agent[bot]andMervin Praison 480848c26d fix: implement async self-reflection in unified dispatch to prevent infinite loop
- Add complete self-reflection logic to unified achat dispatch path
- Prevent infinite loop when self.self_reflect=True with unified dispatch
- Mirror sync implementation with proper async/await patterns
- Handle OpenAI client unavailability gracefully for custom LLMs
- Add proper return statements to break while loop
- Maintain reflection limits (min_reflect, max_reflect)
- Include comprehensive error handling and retry logic

Fixes infinite hanging issue for achat with self-reflection enabled.

Co-authored-by: Mervin Praison <[email protected]>
2026-05-20 15:33:16 +00:00
praisonai-triage-agent[bot]andMervinPraison a064a286f3 fix: Agent.achat hanging - unified dispatch missing response handling (fixes #1703)
- Fix execute_tool_async issue in _execute_unified_achat_completion
- Add proper response processing after unified dispatch call
- Mirror sync _chat_impl behavior for content extraction, history update
- Add guardrails, callbacks, and proper return to exit while loop
- Prevents infinite loop by handling response and returning result

Co-authored-by: MervinPraison <[email protected]>
2026-05-20 15:11:24 +00:00
praisonai-triage-agent[bot] 1d78204b0b feat: implement Hermes/OpenClaw skill metadata capability gates
This implements comprehensive capability gate enforcement for Agent Skills as requested in issue #1697.

Key Features:
- SkillRequirements data model with support for requires_* frontmatter
- CapabilityValidator with layered enforcement levels (disabled/warn/strict)
- Integration with existing SkillManager and discovery pipeline
- CLI doctor diagnostics for missing dependencies
- Feature flag control via SKILL_CAPABILITY_ENFORCEMENT env var
- Full backward compatibility with existing skills

Architecture:
- Core SDK implementation in praisonaiagents following protocol-driven design
- Extends existing skills system without breaking changes
- Tool registry integration for automatic capability detection
- Lazy loading and zero performance impact when disabled

Enforcement Levels:
- disabled: No enforcement (legacy behavior)
- telemetry: Log missing deps only
- warn: Show warnings but allow activation (default)
- strict: Block skill activation until deps satisfied

Skills can now declare requirements in SKILL.md frontmatter.

CLI usage:
- praisonai doctor skills - Check capability status
- SKILL_CAPABILITY_ENFORCEMENT=strict - Enable strict enforcement

Fixes #1697
2026-05-20 10:07:34 +00:00
praisonai-triage-agent[bot]andpraisonai-triage-agent[bot] bba5d43cc1 fix: enhance BaseTool schema validation for OpenAI compatibility (fixes #1696)
- Enhanced BaseTool.validate() with OpenAI schema compatibility checks
- Added validate_schema_roundtrip() for JSON serialization verification
- Added validate_tool_schema_consistency() for tool list validation
- Enhanced @tool decorator with automatic validation at creation time
- Added comprehensive test suite for schema round-trip validation
- Improved error messages with specific remediation guidance

Ensures robust tool schema handling while maintaining backward compatibility.
All tools now validate against OpenAI function calling format requirements.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
2026-05-20 10:05:10 +00:00
praisonai-triage-agent[bot]andpraisonai-triage-agent[bot] c2dfa859c3 fix: add UTF-8 encoding for Windows skills subsystem files (fixes #1695)
- Fix parser.py: add encoding='utf-8' to skill_md.read_text()
- Fix validator.py: add encoding='utf-8' to skill_md.read_text()
- Fix loader.py: add encoding='utf-8' to all read_text() calls for SKILL.md body, scripts, and references
- Add comprehensive UTF-8 tests to verify fix works across all file types
- Prevents UnicodeDecodeError on Windows when SKILL.md contains non-ASCII characters like em dashes, smart quotes, arrows, or non-Latin scripts

Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: praisonai-triage-agent[bot] <praisonai-triage-agent[bot]@users.noreply.github.com>
2026-05-20 10:04:31 +00:00
praisonai-triage-agent[bot]andMervinPraison bb8a56e33c fix: resolve critical gaps in praisonai wrapper layer
Fixes three architectural issues that violated DRY and "safe by default" principles:

1. Shadow scheduler module issue:
   - Remove dead scheduler.py that was shadowed by scheduler/ package
   - Replace mock create_scheduler with real DeploymentScheduler factory
   - CLI --deploy --schedule now uses actual deployment logic instead of MockAgent

2. Disjoint tool registry/resolver issue:
   - Connect ToolRegistry to ToolResolver resolution chain
   - Tools registered via register_function() are now discoverable by YAML resolver
   - Add ToolRegistry as step 2 in resolution order (after local tools.py)

3. Incompatible async-bridging strategies:
   - Standardize on _async_bridge.run_sync() as single source of truth
   - Remove per-call asyncio.run() loops from agent_tools.py
   - Fix InteractiveRuntime to run on shared background loop
   - Eliminate dormant event loop anti-pattern in praisonai_adapter.py

All fixes follow protocol-driven design principles from AGENTS.md.

Fixes #1694

Co-authored-by: MervinPraison <[email protected]>
2026-05-20 08:17:51 +00:00
318 changed files with 19280 additions and 3642 deletions

No files matched your search

@@ -0,0 +1,158 @@
name: Cross-Repo Integration Tests
on:
push:
branches: [ main ]
paths:
- 'src/praisonai/praisonai/integration/**'
- 'src/praisonai/tests/integration/test_aiui_*'
- 'src/praisonai/pyproject.toml'
pull_request:
branches: [ main ]
paths:
- 'src/praisonai/praisonai/integration/**'
- 'src/praisonai/tests/integration/test_aiui_*'
- 'src/praisonai/pyproject.toml'
workflow_dispatch:
jobs:
cross-repo-integration:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout PraisonAI
uses: actions/checkout@v4
with:
path: PraisonAI
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- name: Checkout PraisonAIUI
uses: actions/checkout@v4
with:
repository: MervinPraison/PraisonAIUI
path: PraisonAIUI
ref: main
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
# Install PraisonAI packages in development mode
cd PraisonAI/src/praisonai-agents
pip install -e .
cd ../praisonai
pip install -e ".[ui,dev]"
# Install PraisonAIUI in development mode
cd ../../../PraisonAIUI
pip install -e .
- name: Verify versions
run: |
python -c "import praisonaiagents; print(f'praisonaiagents: {praisonaiagents.__version__}')"
python -c "import praisonai; print(f'praisonai: {praisonai.__version__}')"
python -c "import praisonaiui; print(f'praisonaiui: {praisonaiui.__version__}')"
- name: Run PraisonAI integration tests
run: |
cd PraisonAI/src/praisonai
python -m pytest tests/integration/test_aiui_* -v --timeout=300
- name: Run PraisonAIUI integration tests
run: |
cd PraisonAIUI
if [ -f tests/integration/test_agentic_roundtrip.py ]; then
python -m pytest tests/integration/test_agentic_roundtrip.py -v --timeout=300
fi
if [ -f tests/test_feature_sdk_backends.py ]; then
python -m pytest tests/test_feature_sdk_backends.py -v --timeout=300
fi
- name: Test Pattern C CLI
run: |
cd PraisonAI/src/praisonai
# Test that ui-gateway command exists
python -m praisonai serve --help | grep ui-gateway
- name: Test public API exports
run: |
cd PraisonAI/src/praisonai
python -c "from praisonai import run_integrated_gateway; print('✓ run_integrated_gateway imported')"
python -c "from praisonai import configure_host; print('✓ configure_host imported')"
- name: Integration smoke test
env:
PRAISONAI_TEST_MODE: "1"
PYTHONPATH: ${{ github.workspace }}/PraisonAI/src/praisonai:${{ github.workspace }}/PraisonAI/src/praisonai-agents:${{ github.workspace }}/PraisonAIUI
run: |
cd PraisonAI/src/praisonai
python -c "
import sys
sys.path.insert(0, '.')
from praisonai.integration.host_app import configure_host
from praisonai import run_integrated_gateway
print('✓ Integration imports successful')
# Test configure_host with new parameters
try:
configure_host(
style='dashboard',
context_paths=['AGENTS.md'],
title='Test App'
)
print('✓ configure_host with new parameters works')
except Exception as e:
print(f'× configure_host failed: {e}')
sys.exit(1)
"
# Optional job with API key for agentic tests (if secret is available)
agentic-integration:
runs-on: ubuntu-latest
timeout-minutes: 30
if: ${{ vars.RUN_AGENTIC_TESTS == 'true' }}
needs: cross-repo-integration
steps:
- name: Checkout PraisonAI
uses: actions/checkout@v4
with:
path: PraisonAI
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- name: Checkout PraisonAIUI
uses: actions/checkout@v4
with:
repository: MervinPraison/PraisonAIUI
path: PraisonAIUI
ref: main
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
cd PraisonAI/src/praisonai-agents
pip install -e .
cd ../praisonai
pip install -e ".[ui,dev]"
cd ../../../PraisonAIUI
pip install -e .
- name: Run agentic integration test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
cd PraisonAI/src/praisonai
if [ -n "$OPENAI_API_KEY" ]; then
python -m pytest tests/integration/test_aiui_host_agentic.py -v --timeout=600
else
echo "OPENAI_API_KEY not available, skipping agentic tests"
fi
+1 -1
View File
@@ -382,7 +382,7 @@ praisonai flow
Open **http://localhost:7861** — use the **Agent** and **Agent Team** components to create sequential or parallel workflows. Connect Chat Input → Agent Team → Chat Output for instant multi-agent pipelines.
> 📖 [Full Flow docs](https://docs.praison.ai/docs/concepts/flow) — visual agent building, component reference, and deployment
> 📖 [Full Flow docs](https://docs.praison.ai/docs/concepts/agentflow) — visual agent building, component reference, and deployment
### 8. PraisonAI UI 🤖 (Clean Chat)
+28 -1
View File
@@ -40,6 +40,7 @@ Methods:
* <code title="class Agent">Agent.<a href="./src/praisonai-agents/praisonaiagents/agent/agent.py">chat_with_context</a>(message: str, context: 'ContextPack', **kwargs) -> str</code>
* <code title="class Agent">Agent.<a href="./src/praisonai-agents/praisonaiagents/agent/agent.py">checkpoints</a>() -> Optional[bool]</code>
* <code title="class Agent">Agent.<a href="./src/praisonai-agents/praisonaiagents/agent/agent.py">checkpoints</a>(value: Optional[bool]) -> None</code>
* <code title="class Agent">Agent.<a href="./src/praisonai-agents/praisonaiagents/agent/agent.py">clone_for_channel</a>() -> 'Agent'</code>
* <code title="class Agent">Agent.<a href="./src/praisonai-agents/praisonaiagents/agent/agent.py">close</a>() -> None</code>
* <code title="class Agent">Agent.<a href="./src/praisonai-agents/praisonaiagents/agent/agent.py">console</a>() -> Optional[Any]</code>
* <code title="class Agent">Agent.<a href="./src/praisonai-agents/praisonaiagents/agent/agent.py">context_manager</a>() -> Optional[Any]</code>
@@ -171,6 +172,7 @@ Methods:
* <code title="class BaseTool">BaseTool.<a href="./src/praisonai-agents/praisonaiagents/tools/base.py">safe_run</a>(**kwargs) -> ToolResult</code>
* <code title="class BaseTool">BaseTool.<a href="./src/praisonai-agents/praisonaiagents/tools/base.py">validate</a>() -> bool</code>
* <code title="class BaseTool">BaseTool.<a href="./src/praisonai-agents/praisonaiagents/tools/base.py">validate_class</a>() -> bool</code>
* <code title="class BaseTool">BaseTool.<a href="./src/praisonai-agents/praisonaiagents/tools/base.py">validate_schema_roundtrip</a>() -> bool</code>
* <code title="class FunctionTool">FunctionTool.<a href="./src/praisonai-agents/praisonaiagents/tools/decorator.py">__call__</a>(*args, **kwargs) -> Any</code>
* <code title="class FunctionTool">FunctionTool.<a href="./src/praisonai-agents/praisonaiagents/tools/decorator.py">check_availability</a>() -> tuple[bool, str]</code>
* <code title="class FunctionTool">FunctionTool.<a href="./src/praisonai-agents/praisonaiagents/tools/decorator.py">injected_params</a>() -> Dict[str, Any]</code>
@@ -477,8 +479,10 @@ Methods:
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">edit_skill</a>(name: str, content: str) -> dict</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">get_allowed_tools</a>(name: str) -> List[str]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">get_available_skills</a>() -> List[SkillMetadata]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">get_available_skills_by_state</a>(state: SkillState) -> List[LoadedSkill]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">get_instructions</a>(name: str) -> Optional[str]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">get_skill</a>(name: str) -> Optional[LoadedSkill]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">get_skills_diagnostics</a>() -> Dict[str, ValidationResult]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">get_user_invocable_skills</a>() -> List[LoadedSkill]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">invoke</a>(name: str, raw_args: str = '', session_id: Optional[str] = None, shell_exec: bool = False) -> Optional[str]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">load_resources</a>(name: str) -> bool</code>
@@ -487,6 +491,7 @@ Methods:
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">skill_names</a>() -> List[str]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">skills</a>() -> List[LoadedSkill]</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">to_prompt</a>() -> str</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">validate_skill_capabilities</a>(skill_name: str, force_refresh: bool = False) -> ValidationResult</code>
* <code title="class SkillManager">SkillManager.<a href="./src/praisonai-agents/praisonaiagents/skills/manager.py">write_skill_file</a>(name: str, file_path: str, file_content: str) -> dict</code>
* <code title="class SkillMetadata">SkillMetadata.<a href="./src/praisonai-agents/praisonaiagents/skills/models.py">from_properties</a>(props: SkillProperties) -> 'SkillMetadata'</code>
* <code title="class SkillProperties">SkillProperties.<a href="./src/praisonai-agents/praisonaiagents/skills/models.py">to_dict</a>() -> dict</code>
@@ -602,6 +607,13 @@ Methods:
* <code title="class ContextManager">ContextManager.<a href="./src/praisonai-agents/praisonaiagents/context/manager.py">set_tool_budget</a>(tool_name: str, max_tokens: int, protected: bool = False) -> None</code>
* <code title="class ContextManager">ContextManager.<a href="./src/praisonai-agents/praisonaiagents/context/manager.py">truncate_tool_output</a>(tool_name: str, output: str) -> str</code>
# UI
Types:
```python
from praisonaiagents import A2UI
```
# Config
Types:
@@ -756,7 +768,7 @@ Methods:
Types:
```python
from praisonai import Agent, AgentApp, AgentOS, AnthropicManagedAgent, CloudProvider, DB, Deploy, DeployConfig, DeployType, HostedAgent, HostedAgentConfig, LocalAgent, LocalAgentConfig, LocalManagedAgent, LocalManagedConfig, ManagedAgent, ManagedConfig, PraisonAI, __version__
from praisonai import Agent, AgentApp, AgentOS, AnthropicManagedAgent, CloudProvider, DB, Deploy, DeployConfig, DeployType, HostedAgent, HostedAgentConfig, LocalAgent, LocalAgentConfig, LocalManagedAgent, LocalManagedConfig, ManagedAgent, ManagedConfig, PraisonAI, __version__, arun, run, run_integrated_gateway
```
# CLI
@@ -861,6 +873,7 @@ Methods:
* <code title="cli">praisonai doctor packaging <a href="./src/praisonai/praisonai/cli/commands/doctor.py">--help</a></code>
* <code title="cli">praisonai doctor performance <a href="./src/praisonai/praisonai/cli/commands/doctor.py">--help</a></code>
* <code title="cli">praisonai doctor selftest <a href="./src/praisonai/praisonai/cli/commands/doctor.py">--help</a></code>
* <code title="cli">praisonai doctor skills <a href="./src/praisonai/praisonai/cli/commands/doctor.py">--help</a></code>
* <code title="cli">praisonai doctor tools <a href="./src/praisonai/praisonai/cli/commands/doctor.py">--help</a></code>
* <code title="cli">praisonai doctor troubleshoot <a href="./src/praisonai/praisonai/cli/commands/doctor.py">--help</a></code>
* <code title="cli">praisonai endpoints list <a href="./src/praisonai/praisonai/cli/commands/endpoints.py">--help</a></code>
@@ -892,11 +905,24 @@ Methods:
* <code title="cli">praisonai gateway send <a href="./src/praisonai/praisonai/cli/commands/gateway.py">--help</a></code>
* <code title="cli">praisonai gateway start <a href="./src/praisonai/praisonai/cli/commands/gateway.py">--help</a></code>
* <code title="cli">praisonai gateway status <a href="./src/praisonai/praisonai/cli/commands/gateway.py">--help</a></code>
* <code title="cli">praisonai gateway stop <a href="./src/praisonai/praisonai/cli/commands/gateway.py">--help</a></code>
* <code title="cli">praisonai gateway uninstall <a href="./src/praisonai/praisonai/cli/commands/gateway.py">--help</a></code>
* <code title="cli">praisonai github triage <a href="./src/praisonai/praisonai/cli/commands/github.py">--help</a></code>
* <code title="cli">praisonai hooks add <a href="./src/praisonai/praisonai/cli/commands/hooks.py">--help</a></code>
* <code title="cli">praisonai hooks list <a href="./src/praisonai/praisonai/cli/commands/hooks.py">--help</a></code>
* <code title="cli">praisonai hooks remove <a href="./src/praisonai/praisonai/cli/commands/hooks.py">--help</a></code>
* <code title="cli">praisonai kanban block <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban boards <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban comment <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban complete <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban create <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban dispatch <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban link <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban list <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban move <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban reclaim <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban show <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai kanban unblock <a href="./src/praisonai/praisonai/cli/commands/kanban.py">--help</a></code>
* <code title="cli">praisonai knowledge add <a href="./src/praisonai/praisonai/cli/commands/knowledge.py">--help</a></code>
* <code title="cli">praisonai knowledge index <a href="./src/praisonai/praisonai/cli/commands/knowledge.py">--help</a></code>
* <code title="cli">praisonai knowledge list <a href="./src/praisonai/praisonai/cli/commands/knowledge.py">--help</a></code>
@@ -1054,6 +1080,7 @@ Methods:
* <code title="cli">praisonai serve status <a href="./src/praisonai/praisonai/cli/commands/serve.py">--help</a></code>
* <code title="cli">praisonai serve stop <a href="./src/praisonai/praisonai/cli/commands/serve.py">--help</a></code>
* <code title="cli">praisonai serve ui <a href="./src/praisonai/praisonai/cli/commands/serve.py">--help</a></code>
* <code title="cli">praisonai serve ui-gateway <a href="./src/praisonai/praisonai/cli/commands/serve.py">--help</a></code>
* <code title="cli">praisonai serve unified <a href="./src/praisonai/praisonai/cli/commands/serve.py">--help</a></code>
* <code title="cli">praisonai session delete <a href="./src/praisonai/praisonai/cli/commands/session.py">--help</a></code>
* <code title="cli">praisonai session export <a href="./src/praisonai/praisonai/cli/commands/session.py">--help</a></code>
+1 -1
View File
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=4.6.43" \
"praisonai>=4.6.52" \
"praisonai[chat]" \
"embedchain[github,youtube]"
+1 -1
View File
@@ -20,7 +20,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=4.6.43" \
"praisonai>=4.6.52" \
"praisonai[ui]" \
"praisonai[chat]" \
"praisonai[realtime]" \
+1 -1
View File
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=4.6.43" \
"praisonai>=4.6.52" \
"praisonai[ui]" \
"praisonai[crewai]"
+3 -3
View File
@@ -35,7 +35,7 @@ def run_quick_comparison():
prompt="What is 2+2?",
iterations=2,
paths=["openai_sdk", "praisonai_agent"],
output="verbose"
verbose=True
)
# Print comparison table
@@ -56,7 +56,7 @@ def run_full_benchmark():
report = handler.run_full_benchmark(
prompt="Hi",
iterations=3,
output="verbose"
verbose=True
)
# Print full report
@@ -78,7 +78,7 @@ def run_agent_benchmark():
prompt="Explain Python in one sentence",
iterations=3,
paths=["openai_sdk", "praisonai_agent"],
output="verbose"
verbose=True
)
# Show timeline diagrams
+1 -1
View File
@@ -22,7 +22,7 @@ custom_modes = {
}
# Create handler with verbose output
handler = CompareHandler(output="verbose")
handler = CompareHandler(verbose=True)
# Example: Manually create comparison results for analysis
# (useful for testing without API calls)
+1 -1
View File
@@ -22,7 +22,7 @@ modes = parse_modes("basic,tools,planning")
print(f"\nParsed modes: {modes}")
# Create compare handler
handler = CompareHandler(output="verbose")
handler = CompareHandler(verbose=True)
# Compare modes (this will run actual agent calls)
# Uncomment to run:
@@ -15,7 +15,7 @@ agent = Agent(
# With array [preset, overrides]
agent_override = Agent(
instructions="You are a helpful assistant.",
memory=["redis", {"user_id": "custom_user"}],
memory=MemoryConfig(backend="redis", user_id="custom_user"),
)
if __name__ == "__main__":
@@ -2,7 +2,7 @@
from praisonaiagents import Agent
from praisonaiagents import AgentFlow, Task
from praisonaiagents.workflows.workflow_configs import (
WorkflowOutputConfig, WorkflowPlanningConfig, WorkflowMemoryConfig,
WorkflowPlanningConfig, WorkflowMemoryConfig,
)
# Full-featured workflow with all consolidated params
@@ -32,7 +32,7 @@ workflow = AgentFlow(
),
],
# Workflow-level consolidated params
output=WorkflowOutputConfig(output="verbose", stream=True),
output="verbose",
planning=WorkflowPlanningConfig(enabled=True, reasoning=True),
memory=WorkflowMemoryConfig(backend="file"),
# Agent-like params
+13 -1
View File
@@ -15,8 +15,20 @@ workflow = AgentFlow(
],
output="verbose",
planning=True,
variables={"topic": "AI agents"},
)
if __name__ == "__main__":
result = workflow.run(variables={"topic": "AI agents"})
import os
import sys
if not os.environ.get("OPENAI_API_KEY"):
print("Set OPENAI_API_KEY to run this example.")
sys.exit(0)
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
result = workflow.run()
print(result)
+2 -2
View File
@@ -24,7 +24,7 @@ if has_api_key:
input_text="What is 2 + 2?",
expected_output="4",
num_iterations=3, # Run 3 times for statistical significance
output="verbose"
verbose=True
)
# Run evaluation
@@ -42,7 +42,7 @@ else:
input_text="What is 2 + 2?",
expected_output="4",
num_iterations=1,
output="verbose"
verbose=True
)
# Test with mock output
+2 -2
View File
@@ -27,7 +27,7 @@ if has_api_key:
scoring_type="numeric", # Score 1-10
threshold=7.0, # Pass if score >= 7
num_iterations=2,
output="verbose"
verbose=True
)
# Run evaluation
@@ -45,7 +45,7 @@ if has_api_key:
agent=agent,
input_text="Tell me a joke",
scoring_type="binary", # Pass or Fail
output="verbose"
verbose=True
)
binary_result = binary_evaluator.run(print_summary=True)
+1 -1
View File
@@ -26,7 +26,7 @@ if has_api_key:
num_iterations=10, # Run 10 benchmark iterations
warmup_runs=2, # 2 warmup runs before measurement
track_memory=True, # Track memory usage
output="verbose"
verbose=True
)
# Run evaluation
+15 -4
View File
@@ -16,8 +16,19 @@ def search_web(query: str) -> str:
def calculate(expression: str) -> str:
"""Calculate a math expression."""
return str(eval(expression))
"""Calculate a math expression safely."""
import ast, operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod, ast.Pow: operator.pow,
ast.USub: operator.neg, ast.UAdd: operator.pos}
def _ev(n):
if isinstance(n, ast.Expression): return _ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.operand))
if isinstance(n, ast.BinOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.left), _ev(n.right))
raise ValueError(f"Unsupported: {ast.dump(n)}")
return str(_ev(ast.parse(expression, mode="eval")))
# Check if we have an API key
@@ -37,7 +48,7 @@ if has_api_key:
input_text="Search for the weather in Paris and calculate 25 * 4",
expected_tools=["search_web", "calculate"], # Tools that should be called
forbidden_tools=["delete_file"], # Tools that should NOT be called
output="verbose"
verbose=True
)
# Run evaluation
@@ -59,7 +70,7 @@ evaluator = ReliabilityEvaluator(
agent=mock_agent,
expected_tools=["search_web", "calculate"], # Tools that should be called
forbidden_tools=["delete_file"], # Tools that should NOT be called
output="verbose"
verbose=True
)
result2 = evaluator.evaluate_tool_calls(
+1 -1
View File
@@ -184,7 +184,7 @@ Answer questions based ONLY on the provided knowledge context.
When asked about codes, provide the EXACT code from the documents.
Be concise but accurate.""",
knowledge=[temp_dir],
user_id="compression_demo_user",
memory={"user_id": "compression_demo_user"},
output="verbose",
)
@@ -164,7 +164,7 @@ Answer questions based ONLY on the provided knowledge context.
When asked about department codes, provide the EXACT code from the documents.
Be specific about which department you're referring to.""",
knowledge=[temp_dir],
user_id="hierarchy_demo_user",
memory={"user_id": "hierarchy_demo_user"},
output="verbose",
)
@@ -124,7 +124,7 @@ def main():
# Show strategy selection for different corpus sizes
print(f"\nStrategy selection by corpus size:")
for size in [100, 1000, 10000, 50000, 100000]:
strategy = select_strategy(corpus_tokens=size)
strategy = select_strategy(CorpusStats(file_count=max(1, size // 1000), total_tokens=size))
print(f" {size:>6} tokens -> {strategy.value}")
except ImportError as e:
@@ -142,7 +142,7 @@ Answer questions based ONLY on the provided knowledge context.
When asked about verification codes, provide the EXACT code from the documents.
If information is not in the context, say 'Information not found in documents.'""",
knowledge=[temp_dir],
user_id="strategy_demo_user",
memory={"user_id": "strategy_demo_user"},
output="verbose", # Use new consolidated param
)
+1 -1
View File
@@ -65,7 +65,7 @@ def main():
name="PolicyExpert",
instructions="You are a company policy expert. Answer questions based ONLY on the provided knowledge. Quote exact values when asked about codes or numbers.",
knowledge=[temp_dir], # Add directory with documents
user_id="example_user", # Required for mem0 backend
memory={"user_id": "example_user"},
)
print("\n1. Testing Agent.chat() with context-required question:")
@@ -50,7 +50,7 @@ def main():
name="HR_Assistant_User1",
instructions="You are an HR assistant.",
knowledge=[temp_dir],
user_id="user_alice", # Knowledge scoped to Alice
memory={"user_id": "user_alice"},
)
response = user1_agent.chat("What is the policy on remote work?")
@@ -80,7 +80,7 @@ def main():
name="Personal_HR_Bot",
instructions="You are a personal HR assistant.",
knowledge=[temp_dir],
user_id="user_bob",
memory={"user_id": "user_bob"},
agent_id="hr_bot_v2",
)
@@ -49,7 +49,7 @@ Only authorized personnel with code WRENCH-992 may access this project.
name="AgentA_Ingester",
instructions="You ingest and store knowledge.",
knowledge=[temp_dir],
user_id="user_alice", # Scoped to Alice
memory={"user_id": "user_alice"},
output="silent",
)
@@ -103,7 +103,7 @@ Only authorized personnel with code WRENCH-992 may access this project.
name="AgentB_Querier",
instructions="Answer questions based on the provided knowledge. If you don't have the information, say so.",
knowledge=[temp_dir],
user_id="user_alice", # Same scope as Agent A
memory={"user_id": "user_alice"},
output="silent",
)
@@ -17,8 +17,10 @@ from praisonaiagents import Agent
agent = Agent(
name="CockroachDB Agent",
instructions="You are a helpful assistant.",
db={"database_url": os.getenv("COCKROACHDB_URL")},
session_id="crdb-demo-session",
memory={
"session_id": "crdb-demo-session",
"db": {"database_url": os.getenv("COCKROACHDB_URL")},
},
)
result = agent.start("What is distributed SQL? Explain in 2 sentences.")
@@ -18,8 +18,10 @@ from praisonaiagents import Agent
agent = Agent(
name="Neon Agent",
instructions="You are a helpful assistant.",
db={"database_url": os.getenv("NEON_DATABASE_URL")},
session_id="neon-demo-session",
memory={
"session_id": "neon-demo-session",
"db": {"database_url": os.getenv("NEON_DATABASE_URL")},
},
)
# Option 2: Direct URL
@@ -20,8 +20,10 @@ from praisonaiagents import Agent
agent = Agent(
name="Supabase Agent",
instructions="You are a helpful assistant.",
db={"database_url": os.getenv("SUPABASE_DATABASE_URL")},
session_id="supabase-demo-session",
memory={
"session_id": "supabase-demo-session",
"db": {"database_url": os.getenv("SUPABASE_DATABASE_URL")},
},
)
result = agent.start("What is Supabase? Explain in 2 sentences.")
@@ -18,11 +18,13 @@ from praisonaiagents import Agent
agent = Agent(
name="Turso Agent",
instructions="You are a helpful assistant.",
db={
"database_url": os.getenv("TURSO_DATABASE_URL"),
"auth_token": os.getenv("TURSO_AUTH_TOKEN"),
memory={
"session_id": "turso-demo-session",
"db": {
"database_url": os.getenv("TURSO_DATABASE_URL"),
"auth_token": os.getenv("TURSO_AUTH_TOKEN"),
},
},
session_id="turso-demo-session",
)
result = agent.start("What is edge computing? Explain in 2 sentences.")
+31 -8
View File
@@ -19,20 +19,43 @@ import os
def calculate(expression: str) -> str:
"""
A simple calculator tool that evaluates mathematical expressions.
A simple calculator tool that evaluates mathematical expressions safely.
Args:
expression: A mathematical expression to evaluate (e.g., "2 + 2")
Returns:
The result of the calculation
"""
import ast
import operator
_OPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
def _safe_eval(node):
if isinstance(node, ast.Expression):
return _safe_eval(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_safe_eval(node.operand))
if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
raise ValueError(f"Unsupported expression: {ast.dump(node)}")
try:
# Safe evaluation of mathematical expressions
allowed_chars = set("0123456789+-*/.() ")
if not all(c in allowed_chars for c in expression):
return "Error: Invalid characters in expression"
result = eval(expression)
tree = ast.parse(expression, mode="eval")
result = _safe_eval(tree)
return f"Result: {result}"
except Exception as e:
return f"Error: {str(e)}"
+12 -6
View File
@@ -24,12 +24,18 @@ def main():
def calculate(expression: str) -> str:
"""Safely evaluate a mathematical expression."""
try:
# Only allow safe math operations
allowed = set("0123456789+-*/.(). ")
if not all(c in allowed for c in expression):
return "Error: Invalid characters in expression"
result = eval(expression) # Safe due to character filtering
return f"Result: {result}"
import ast, operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod, ast.Pow: operator.pow,
ast.USub: operator.neg, ast.UAdd: operator.pos}
def _ev(n):
if isinstance(n, ast.Expression): return _ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.operand))
if isinstance(n, ast.BinOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.left), _ev(n.right))
raise ValueError(f"Unsupported: {ast.dump(n)}")
return f"Result: {_ev(ast.parse(expression, mode='eval'))}"
except Exception as e:
return f"Error: {e}"
+1 -2
View File
@@ -10,8 +10,7 @@ from praisonaiagents import Agent
agent = Agent(
name="FlexBot",
instructions="You are a helpful assistant.",
llm="gpt-4o-mini",
llm_config={"configurable": True}
llm={"model": "gpt-4o-mini", "configurable": True},
)
if __name__ == "__main__":
+1 -1
View File
@@ -21,7 +21,7 @@ agent = Agent(
name="ContextBot",
instructions="You help show context information.",
tools=[show_context],
session_id="my-session-123"
memory={"session_id": "my-session-123"},
)
if __name__ == "__main__":
+5 -3
View File
@@ -50,10 +50,12 @@ print("=== Qdrant Knowledge Store Demo (Agent-First) ===")
agent = Agent(
name="KnowledgeAssistant",
instructions="You are a helpful assistant with access to technical documentation.",
knowledge=[doc_path],
knowledge={
"vector_store": "qdrant",
"url": "http://localhost:6333"
"sources": [doc_path],
"vector_store": {
"provider": "qdrant",
"url": "http://localhost:6333",
},
}
)
+1 -1
View File
@@ -57,8 +57,8 @@ def main():
agent = Agent(
name="SecureAgent",
instructions="You are a file management assistant.",
policy=engine
)
agent.policy = engine
print("\n--- Agent with Policy Enforcement Created ---")
print(f"Agent: {agent.name}")
+29 -2
View File
@@ -21,9 +21,36 @@ def search_web(query: str) -> str:
return f"Search results for: {query}"
def calculate(expression: str) -> str:
"""Calculate a mathematical expression."""
"""Calculate a mathematical expression safely."""
import ast
import operator
_OPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_eval(node.operand))
if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_eval(node.left), _eval(node.right))
raise ValueError(f"Unsupported expression: {ast.dump(node)}")
try:
return f"Result: {eval(expression)}"
tree = ast.parse(expression, mode="eval")
return f"Result: {_eval(tree)}"
except Exception:
return "Invalid expression"
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Minimal A2UI example — agent + send_a2ui_messages tool.
Install:
pip install praisonaiagents[a2ui]
Run:
python send_surface.py
For live rendering, use PraisonAIUI with AG-UI (/agui) — see integrate-a2ui-frontend docs.
"""
from praisonaiagents import Agent
from praisonaiagents.tools.a2ui_tools import send_a2ui_messages
agent = Agent(
name="ui-assistant",
instructions=(
"When asked for UI, call send_a2ui_messages with A2UI v0.9 JSON "
"(createSurface on surface id 'main')."
),
tools=[send_a2ui_messages],
)
if __name__ == "__main__":
result = agent.start("Show a simple welcome card on surface main")
print(result)
+1 -1
View File
@@ -75,7 +75,7 @@ class ContinuousCameraMonitor:
agents=[self.vision_agent],
tasks=[task],
process="sequential",
verbose=0 # Reduced verbosity for continuous monitoring
output="silent", # Reduced verbosity for continuous monitoring
)
return agents.start()
@@ -8,7 +8,7 @@ Docs: https://docs.praison.ai/cli/git-integration
from praisonai.cli.features import GitIntegrationHandler
# Initialize
handler = GitIntegrationHandler(output="verbose")
handler = GitIntegrationHandler(verbose=True)
git = handler.initialize(repo_path=".")
# Check if it's a git repo
+1 -1
View File
@@ -8,7 +8,7 @@ Docs: https://docs.praison.ai/cli/repo-map
from praisonai.cli.features import RepoMapHandler
# Initialize with current directory
handler = RepoMapHandler(output="verbose")
handler = RepoMapHandler(verbose=True)
repo_map = handler.initialize(root=".")
# Get the repository map
@@ -9,7 +9,7 @@ from praisonai.cli.features import SandboxExecutorHandler
from praisonai.cli.features.sandbox_executor import SandboxMode
# Initialize with basic sandbox
handler = SandboxExecutorHandler(output="verbose")
handler = SandboxExecutorHandler(verbose=True)
sandbox = handler.initialize(mode="basic")
print(f"Sandbox mode: {handler.get_mode()}")
+1 -2
View File
@@ -25,8 +25,7 @@ pdf_agent = Agent(
goal="Help users understand and extract information from PDF documents",
backstory="You are an expert at reading, analyzing, and answering questions about PDF documents. You provide accurate, detailed answers based on the document content.",
instructions="Read the provided PDF document and answer questions about its content. Be specific and cite relevant sections when possible.",
knowledge=["document.pdf"], # Replace with your PDF file path
knowledge=config,
knowledge={**config, "sources": ["document.pdf"]}, # Replace with your PDF path
reflection=True,
@@ -1,6 +1,8 @@
from praisonaiagents import Agent, Task, AgentTeam
import logging
import tempfile
import os
import sys
import logging
from praisonaiagents import Agent, Task, AgentTeam
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
@@ -17,14 +19,20 @@ config = {
}
}
# Create sample file in system temp directory
_sample_path = os.path.join(tempfile.gettempdir(), "sample_knowledge.txt")
if not os.path.exists(_sample_path):
with open(_sample_path, "w", encoding="utf-8") as f:
f.write("Mervin Praison is the creator of PraisonAI.\n")
# Create an agent with knowledge capabilities
knowledge_agent = Agent(
name="KnowledgeAgent",
role="Information Specialist",
goal="Store and retrieve knowledge efficiently",
backstory="Expert in managing and utilizing stored knowledge",
knowledge=["sample.pdf"],
knowledge=config)
knowledge={**config, "sources": [_sample_path]},
)
# Define a task for the agent
knowledge_task = Task(
@@ -39,8 +47,16 @@ agents = AgentTeam(
agents=[knowledge_agent],
tasks=[knowledge_task],
process="sequential",
user_id="user1"
)
# Start execution
result = agents.start()
if __name__ == "__main__":
if not os.environ.get("OPENAI_API_KEY"):
print("Set OPENAI_API_KEY to run this example.")
sys.exit(0)
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
result = agents.start()
print(result)
@@ -138,8 +138,7 @@ def main():
agent = Agent(
name="AI Research Assistant",
instructions="You are an AI research assistant. Use your knowledge base to answer questions about artificial intelligence topics.",
knowledge=sample_documents, # Will use default knowledge config
knowledge=rerank_config, # Use reranking config
knowledge={**rerank_config, "sources": sample_documents},
llm="gpt-4o-mini"
)
+7 -3
View File
@@ -32,8 +32,12 @@ rag_task = Task(
agents = AgentTeam(
agents=[rag_agent],
tasks=[rag_task],
user_id="user1"
)
# Start Agents
agents.start()
if __name__ == "__main__":
import os
import sys
if not os.environ.get("OPENAI_API_KEY"):
print("Set OPENAI_API_KEY to run this example.")
sys.exit(0)
agents.start()
@@ -16,7 +16,7 @@ agents = AgentTeam(
agents=[agent],
tasks=[task],
process="workflow",
max_iter=30
execution={"max_iter": 30},
)
agents.start()
@@ -61,7 +61,6 @@ def example_with_wrappers():
role="Data Analyst",
goal="Analyze data and provide insights",
llm="gpt-4o-mini",
request_id="request_2" # Unique request ID
)
# Operations are automatically tracked
@@ -49,7 +49,18 @@ def calculate_with_tracking(expression: str) -> str:
time.sleep(0.05)
try:
result = eval(expression)
import ast, operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod, ast.Pow: operator.pow,
ast.USub: operator.neg, ast.UAdd: operator.pos}
def _ev(n):
if isinstance(n, ast.Expression): return _ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.operand))
if isinstance(n, ast.BinOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.left), _ev(n.right))
raise ValueError(f"Unsupported: {ast.dump(n)}")
result = _ev(ast.parse(expression, mode="eval"))
return f"Result: {result}"
except Exception as e:
return f"Error: {str(e)}"
+2 -1
View File
@@ -132,7 +132,8 @@ agents = AgentTeam(
agents=[qa_generator, total_questions_evaluator, cot_generator, upload_to_huggingface],
tasks=[generate_task, evaluate_total_questions_task, generate_cot_task, upload_to_huggingface_task],
process="workflow",
max_iter=30, output="minimal"
execution={"max_iter": 30},
output="minimal",
)
agents.start()
+3 -3
View File
@@ -18,7 +18,7 @@ openai_profile = AuthProfile(
provider="openai",
api_key=os.environ.get("OPENAI_API_KEY", "sk-..."),
priority=1, # Highest priority
rate_limit=100,
rate_limit_rpm=100,
)
anthropic_profile = AuthProfile(
@@ -26,7 +26,7 @@ anthropic_profile = AuthProfile(
provider="anthropic",
api_key=os.environ.get("ANTHROPIC_API_KEY", "sk-ant-..."),
priority=2, # Second priority
rate_limit=50,
rate_limit_rpm=50,
)
groq_profile = AuthProfile(
@@ -34,7 +34,7 @@ groq_profile = AuthProfile(
provider="groq",
api_key=os.environ.get("GROQ_API_KEY", "gsk-..."),
priority=3, # Third priority (fast but limited)
rate_limit=30,
rate_limit_rpm=30,
)
# Configure failover behavior
+3 -3
View File
@@ -5,7 +5,7 @@ import os
def main():
# Initialize memory config
memory_config = {
"provider": "rag",
"backend": "sqlite",
"use_embedding": True,
"storage": {
"type": "sqlite",
@@ -105,13 +105,13 @@ def main():
agents=[researcher, retriever],
tasks=[store_task, verify_task, query_task, query_both_task], # Use same verbose level as memory
memory={
"provider": "rag",
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small"
}
}
},
"config": {"provider": "sqlite"},
}
)
@@ -6,6 +6,7 @@ built-in validation and safety mechanisms for secure agent operations.
"""
from praisonaiagents import Agent, Task, AgentTeam
from praisonaiagents.config.feature_configs import GuardrailConfig
from praisonaiagents.tools import internet_search
print("=== Production Guardrails Patterns Example ===\n")
@@ -38,8 +39,8 @@ production_agent = Agent(
goal="Generate safe, compliant content for production use",
backstory="Production-ready agent with built-in safety and compliance checks",
tools=[internet_search],
guardrails=content_guardrail,
max_retries=3)
guardrails=GuardrailConfig(validator=content_guardrail, max_retries=3),
)
# Create secure task with validation
secure_task = Task(
+1 -1
View File
@@ -40,7 +40,7 @@ agent = Agent(
"execute_command"
],
memory=True,
web_search=True,
web=True,
auto_approve_tools=True,
)
+12 -4
View File
@@ -36,10 +36,18 @@ def calculate(expression: str) -> dict:
expression: Math expression (e.g., "2 + 2 * 3")
"""
try:
allowed = set("0123456789+-*/.() ")
if not all(c in allowed for c in expression):
return {"error": "Invalid characters"}
return {"expression": expression, "result": eval(expression)}
import ast, operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod, ast.Pow: operator.pow,
ast.USub: operator.neg, ast.UAdd: operator.pos}
def _ev(n):
if isinstance(n, ast.Expression): return _ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.operand))
if isinstance(n, ast.BinOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.left), _ev(n.right))
raise ValueError(f"Unsupported: {ast.dump(n)}")
return {"expression": expression, "result": _ev(ast.parse(expression, mode="eval"))}
except Exception as e:
return {"error": str(e)}
+12 -6
View File
@@ -47,12 +47,18 @@ def calculate(expression: str) -> Dict[str, Any]:
The result of the calculation
"""
try:
# Safe evaluation of mathematical expressions
allowed_chars = set("0123456789+-*/.() ")
if not all(c in allowed_chars for c in expression):
return {"error": "Invalid characters in expression"}
result = eval(expression) # Use safer alternative in production
import ast, operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod, ast.Pow: operator.pow,
ast.USub: operator.neg, ast.UAdd: operator.pos}
def _ev(n):
if isinstance(n, ast.Expression): return _ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.operand))
if isinstance(n, ast.BinOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.left), _ev(n.right))
raise ValueError(f"Unsupported: {ast.dump(n)}")
result = _ev(ast.parse(expression, mode="eval"))
return {"expression": expression, "result": result}
except Exception as e:
return {"error": str(e)}
+12 -7
View File
@@ -49,13 +49,18 @@ def calculate(expression: str) -> Dict[str, Any]:
The result of the calculation
"""
try:
# Safe evaluation of mathematical expressions
# In production, use a proper math parser
allowed_chars = set("0123456789+-*/.() ")
if not all(c in allowed_chars for c in expression):
return {"error": "Invalid characters in expression"}
result = eval(expression) # Note: Use safer alternative in production
import ast, operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod, ast.Pow: operator.pow,
ast.USub: operator.neg, ast.UAdd: operator.pos}
def _ev(n):
if isinstance(n, ast.Expression): return _ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.operand))
if isinstance(n, ast.BinOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.left), _ev(n.right))
raise ValueError(f"Unsupported: {ast.dump(n)}")
result = _ev(ast.parse(expression, mode="eval"))
return {"expression": expression, "result": result}
except Exception as e:
return {"error": str(e)}
@@ -12,8 +12,8 @@ print("=== Advanced Graph Memory Integration Example ===\n")
# Configure simple graph memory
memory_config = {
"provider": "mem0",
"config": {
"provider": "mem0",
"vector_store": {
"provider": "chroma",
"config": {
@@ -60,8 +60,8 @@ query_task = Task(
agents_system = AgentTeam(
agents=[knowledge_agent],
tasks=[build_task, query_task],
memory=True,
memory=memory_config, output="verbose"
memory=memory_config,
output="verbose",
)
print("Starting graph memory demonstration...")
@@ -12,8 +12,8 @@ print("=== Advanced Memory Search and Optimization Example ===\n")
# Configure optimized memory settings
memory_config = {
"provider": "mem0",
"config": {
"provider": "mem0",
"vector_store": {
"provider": "chroma",
"config": {
@@ -61,8 +61,8 @@ search_task = Task(
agents_system = AgentTeam(
agents=[research_agent],
tasks=[build_memory_task, search_task],
memory=True,
memory=memory_config, output="verbose"
memory=memory_config,
output="verbose",
)
print("Starting memory search optimization demonstration...")
@@ -86,13 +86,13 @@ def main():
agents=[researcher, retriever],
tasks=[store_task, retrieve_task],
memory={
"provider": "rag",
"embedder": {
"provider": "gemini",
"config": {
"model": "text-embedding-004",
}
}
},
"config": {"provider": "sqlite"},
}
)
+1 -2
View File
@@ -152,8 +152,7 @@ def main():
agents_system = AgentTeam(
agents=[researcher],
tasks=[build_knowledge_task, query_knowledge_task, expand_knowledge_task],
memory=True,
memory=memory_config
memory=memory_config,
)
print("\n🚀 Starting graph memory demonstration...")
@@ -30,7 +30,7 @@ def main():
try:
# Create memory instance
memory = Memory(config={
"provider": "rag",
"backend": "sqlite",
"use_embedding": False,
"agent_name": "demo_agent", # Used in trace events
})
@@ -32,9 +32,8 @@ def init_agent():
return Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["kag-research-paper.pdf"],
knowledge=config,
user_id="user1",
knowledge={**config, "sources": ["kag-research-paper.pdf"]},
memory={"user_id": "user1"},
llm="deepseek-r1"
)
@@ -30,9 +30,12 @@ config = {
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["kag-research-paper.pdf"], # Indexing
knowledge=config,
user_id="user1",
knowledge={
"sources": ["kag-research-paper.pdf"],
"vector_store": config["vector_store"],
"embedder": config["embedder"],
},
memory={"user_id": "user1"},
llm="deepseek-r1"
)
@@ -31,10 +31,9 @@ llm_config = {
agent = Agent(
instructions="You are a helpful Assistant specialized in scientific explanations. "
"Provide clear, accurate, and engaging responses.",
llm=llm_config, # Pass the detailed configuration
# Enable detailed output
markdown=True, # Format responses in markdown
reflection=True # Enable self-reflection
llm=llm_config,
output={"markdown": True},
reflection=True,
)
# Test the agent
@@ -189,8 +189,8 @@ def main():
business_system = AgentTeam(
agents=[data_manager, knowledge_curator, business_analyst, customer_service],
tasks=business_tasks,
memory=True,
memory=mongodb_memory_config, output="verbose"
memory=mongodb_memory_config,
output="verbose",
)
# Execute the comprehensive business pipeline
@@ -55,8 +55,10 @@ def main():
retrieve information from a comprehensive MongoDB knowledge base. You excel
at finding relevant information, synthesizing knowledge from multiple sources,
and providing accurate, context-aware responses.""",
knowledge=mongodb_knowledge_config,
knowledge=[os.path.join(os.path.dirname(__file__), "llms.md")],
knowledge={
**mongodb_knowledge_config,
"sources": [os.path.join(os.path.dirname(__file__), "llms.md")],
},
memory=True,
llm="gpt-4o-mini"
)
@@ -28,8 +28,8 @@ if not os.environ.get("OPENAI_API_KEY"):
def main():
# MongoDB memory configuration
mongodb_memory_config = {
"provider": "mongodb",
"config": {
"provider": "mongodb",
"connection_string": "mongodb://localhost:27017/", # Replace with your MongoDB connection string
"database": "praisonai_memory",
"use_vector_search": True, # Enable Atlas Vector Search (requires MongoDB Atlas)
@@ -93,8 +93,8 @@ def main():
research_system = AgentTeam(
agents=[research_agent],
tasks=research_tasks,
memory=True,
memory=mongodb_memory_config, output="verbose"
memory=mongodb_memory_config,
output="verbose",
)
# Execute the research pipeline
+1 -1
View File
@@ -50,7 +50,7 @@ agent = Agent(
name="TechSupport",
instructions="You are a technical support assistant.",
knowledge=[sample_doc],
user_id="comparison_user",
memory={"user_id": "comparison_user"},
llm="openai/gpt-4o-mini",
output="minimal",
)
+4 -3
View File
@@ -12,6 +12,7 @@ Environment:
"""
import os
import tempfile
from praisonaiagents import Agent, AutoRagAgent
# Ensure API key is set
@@ -20,8 +21,8 @@ if not os.environ.get("OPENAI_API_KEY"):
exit(1)
# Create a sample document for testing
sample_doc = "/tmp/sample_doc.txt"
with open(sample_doc, "w") as f:
sample_doc = os.path.join(tempfile.gettempdir(), "sample_doc.txt")
with open(sample_doc, "w", encoding="utf-8") as f:
f.write("""
PraisonAI Framework Documentation
@@ -44,7 +45,7 @@ agent = Agent(
name="DocBot",
instructions="You are a helpful documentation assistant. Answer questions based on the provided context.",
knowledge=[sample_doc],
user_id="example_user", # Required for RAG retrieval
memory={"user_id": "example_user"},
llm="openai/gpt-4o-mini",
output="minimal",
)
+1 -1
View File
@@ -38,7 +38,7 @@ agent = Agent(
name="PolicyBot",
instructions="You are a customer service assistant.",
knowledge=[sample_doc],
user_id="policy_user",
memory={"user_id": "policy_user"},
llm="openai/gpt-4o-mini",
output="minimal",
)
+1 -1
View File
@@ -44,7 +44,7 @@ agent = Agent(
name="MLExpert",
instructions="You are a machine learning expert. Answer questions based on the provided context.",
knowledge=[sample_doc],
user_id="rag_user",
memory={"user_id": "rag_user"},
llm="openai/gpt-4o-mini",
output="minimal",
)
+1 -1
View File
@@ -59,7 +59,7 @@ agent = Agent(
name="APIDocBot",
instructions="You are an API documentation assistant.",
knowledge=[sample_doc],
user_id="hybrid_user",
memory={"user_id": "hybrid_user"},
llm="openai/gpt-4o-mini",
output="minimal",
)
+1 -1
View File
@@ -44,7 +44,7 @@ agent = Agent(
name="ResearchBot",
instructions="You are a research assistant. Always cite your sources.",
knowledge=[doc1, doc2],
user_id="citation_user",
memory={"user_id": "citation_user"},
llm="openai/gpt-4o-mini",
output="minimal",
)
@@ -28,7 +28,7 @@ def example_basic_persistence():
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant. Be very brief.",
session_id=session_id,
memory={"session_id": session_id},
output="minimal",
)
@@ -59,7 +59,7 @@ def example_session_restoration():
agent1 = Agent(
name="MemoryBot",
instructions="You are a helpful assistant. Be very brief.",
session_id=session_id,
memory={"session_id": session_id},
output="minimal",
)
@@ -72,7 +72,7 @@ def example_session_restoration():
agent2 = Agent(
name="MemoryBot",
instructions="You are a helpful assistant. Be very brief.",
session_id=session_id,
memory={"session_id": session_id},
output="minimal",
)
@@ -172,7 +172,7 @@ print("="*70)
# Create sessions for different users working on the same project
reviewer_session = Session(
session_id="peer_review_001",
user_id="user_reviewer_01", # Different user
user_id="user_reviewer_01",
storage_path=session_dir
)
@@ -14,13 +14,12 @@ def main():
# Initialize memory with quality-based configuration
memory_config = {
"provider": "rag",
"use_embedding": True,
"rag_db_path": "quality_memory_db"
"backend": "sqlite",
"user_id": "quality_demo_user",
}
memory = Memory(config=memory_config, verbose=5)
print(f"📦 Initialized memory system with provider: {memory_config['provider']}")
print(f"📦 Initialized memory system with backend: {memory_config['backend']}")
# Create agent with memory
agent = Agent(
@@ -28,7 +27,6 @@ def main():
role="Information Quality Specialist",
instructions="Store and retrieve information with quality assessment",
memory=memory,
user_id="quality_demo_user"
)
print(f"🤖 Created agent: {agent.name}")
+1 -1
View File
@@ -15,7 +15,7 @@ def main():
# Create a session with persistent storage
session = Session(
session_id="demo_chat_001",
user_id="demo_user"
user_id="demo_user",
)
print(f"📝 Created session: {session}")
@@ -88,9 +88,8 @@ def main():
workflow = AgentTeam(
agents=[researcher, analyzer, writer],
tasks=[research_task, analysis_task, report_task],
memory=True,
memory={"user_id": "research_project_001"},
process="workflow",
user_id="research_project_001",
)
print(f"🤖 Created workflow with {len(workflow.agents)} agents and {len(workflow.tasks)} tasks")
@@ -14,7 +14,7 @@ def main():
goal="Find information about a topic",
backstory="You are an expert researcher who finds comprehensive information.",
llm="gpt-4o-mini", # Use a cost-effective model for examples
metrics=True # 🎯 SIMPLIFIED: Just add this parameter!
output={"metrics": True} # Token metrics via consolidated output config
)
# Create a simple task
@@ -14,7 +14,7 @@ def main():
goal="Analyze data and provide insights",
backstory="You are an experienced data analyst with expertise in market research.",
llm="gpt-4o-mini",
metrics=True # 🎯 Enable metrics tracking
output={"metrics": True}
)
writer_agent = Agent(
@@ -23,7 +23,7 @@ def main():
goal="Create well-structured content",
backstory="You are a skilled technical writer who creates clear, engaging content.",
llm="gpt-4o-mini",
metrics=True # 🎯 Enable metrics tracking
output={"metrics": True}
)
# Create multiple tasks
@@ -14,7 +14,7 @@ def main():
goal="Conduct comprehensive market research",
backstory="You are a seasoned market researcher with 10+ years of experience.",
llm="gpt-4o-mini",
metrics=True # 🎯 Enable automatic metrics tracking
output={"metrics": True}
)
strategy_agent = Agent(
@@ -23,7 +23,7 @@ def main():
goal="Develop actionable business strategies",
backstory="You are a strategic consultant who translates research into business plans.",
llm="gpt-4o-mini",
metrics=True # 🎯 Enable automatic metrics tracking
output={"metrics": True}
)
# Create tasks that will generate substantial token usage
@@ -22,7 +22,8 @@ rag_agent = Agent(
You can use the internet_search function to search the web when needed.""",
llm="gpt-4o",
markdown=True)
output={"markdown": True},
)
if __name__ == "__main__":
print("🤖 Thai Recipe RAG Agent is ready!")
@@ -32,9 +32,8 @@ def init_agent():
return Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["kag-research-paper.pdf"],
knowledge=config,
user_id="user1",
knowledge={**config, "sources": ["kag-research-paper.pdf"]},
memory={"user_id": "user1"},
llm="deepseek-r1"
)
@@ -264,13 +264,12 @@ agents = AgentTeam(
tasks=[tool_query_task, pentester_analysis_task, ciso_review_task],
process="hierarchical",
manager_llm="gpt-4o-mini",
memory=True, # Enable shared memory for domain context
memory={
"provider": "rag",
"backend": "sqlite",
"config": {
"collection_name": f"{domain.replace('.', '_')}_security_analysis"
}
}
},
},
)
# Main Execution Workflow
@@ -5,7 +5,7 @@ Demonstrates using should_run to conditionally execute agent steps
based on input or previous results.
"""
from praisonaiagents import Agent, Workflow, Task
from praisonaiagents import Agent, AgentFlow, Task
# Condition functions
def is_technical(ctx) -> bool:
@@ -53,7 +53,7 @@ workflow = AgentFlow(
# Step 4: Function - formats output
format_output
],
default_llm="gpt-4o-mini" # Used for action-based steps
llm="gpt-4o-mini", # Used for action-based steps
)
if __name__ == "__main__":
+1 -1
View File
@@ -207,7 +207,7 @@ def api_augmented_rag():
instructions="""You are a financial assistant with access to market APIs.
Provide accurate financial information and context.
Always note that prices are subject to change.""",
user_id="api_demo"
memory={"user_id": "api_demo"},
)
queries = [
+9 -7
View File
@@ -51,13 +51,15 @@ print("=" * 60)
agent = Agent(
name="Knowledge Agent",
instructions="You are a helpful assistant that answers questions based on the provided knowledge. Be concise.",
knowledge=[".praison/test_docs/overview.txt"],
retrieval_config={
"policy": "always", # Always retrieve for this demo
"top_k": 3, # Get top 3 chunks
"citations": True, # Include citations
"max_context_tokens": 2000,
}
knowledge={
"sources": [".praison/test_docs/overview.txt"],
"config": {
"policy": "always",
"top_k": 3,
"citations": True,
"max_context_tokens": 2000,
},
},
)
# Test 1: Basic chat with retrieval
+1 -1
View File
@@ -60,7 +60,7 @@ print("=" * 50)
agent_with_discovery = Agent(
name="Multi-Skill Agent",
instructions="You are a versatile assistant with multiple skills.",
skills_dirs=["./"], # Scan current directory for skill subdirectories
skills=["./"], # Scan current directory for skill subdirectories
)
if agent_with_discovery.skill_manager:
+222
View File
@@ -0,0 +1,222 @@
# Multi-Channel Bot Deployment Guide
This guide explains how to set up multiple bots on the same platform (e.g., multiple Telegram bots) for different roles using PraisonAI, similar to Hermes-style AI workforces.
## Overview
PraisonAI supports running multiple bots on the same platform, each routing to different agents with specialized knowledge and capabilities. This is useful for:
- **Role-based bots**: `@company_cfo_bot`, `@company_ops_bot`, `@company_content_bot`
- **Department-specific agents**: Each with different knowledge brains and tool access
- **Workflow separation**: Different bots handle different types of requests
## Quick Start with Onboard Wizard
The easiest way to set up multiple channels is using the onboard wizard:
```bash
praisonai onboard
```
The wizard now supports:
1. **Multi-channel setup**: Add multiple bots for the same platform
2. **Role-based naming**: Automatically generates `TELEGRAM_<ROLE>_BOT_TOKEN` environment variables
3. **Agent routing**: Each channel routes to a different agent
### Onboard Wizard Flow
1. **Choose platform**: Start with your first platform (e.g., telegram)
2. **Add more channels**: Wizard asks "Add another bot channel?"
3. **Specify role**: Enter role name (e.g., "cfo", "ops", "content")
4. **Configure tokens**: Each channel gets its own environment variable
5. **Test connections**: Wizard tests each bot separately
## Environment Variable Convention
For multiple bots on the same platform, use this naming convention:
| Channel | Environment Variable | Bot Purpose |
|---------|---------------------|-------------|
| `telegram_cfo` | `TELEGRAM_CFO_BOT_TOKEN` | CFO-related tasks |
| `telegram_ops` | `TELEGRAM_OPS_BOT_TOKEN` | Operations tasks |
| `telegram_content` | `TELEGRAM_CONTENT_BOT_TOKEN` | Content creation |
| `telegram_support` | `TELEGRAM_SUPPORT_BOT_TOKEN` | Customer support |
### Setting Up Tokens
1. **Create bots in @BotFather**:
```text
/newbot
Bot name: Company CFO Bot
Username: @company_cfo_bot
-> Copy token
/newbot
Bot name: Company Ops Bot
Username: @company_ops_bot
-> Copy token
```
2. **Set environment variables**:
```bash
export TELEGRAM_CFO_BOT_TOKEN="123456789:ABC..."
export TELEGRAM_OPS_BOT_TOKEN="987654321:DEF..."
export TELEGRAM_CONTENT_BOT_TOKEN="456789123:GHI..."
```
3. **Or use `~/.praisonai/.env`**:
```env
TELEGRAM_CFO_BOT_TOKEN=123456789:ABC...
TELEGRAM_OPS_BOT_TOKEN=987654321:DEF...
TELEGRAM_CONTENT_BOT_TOKEN=456789123:GHI...
TELEGRAM_ALLOWED_USERS=123456789,987654321
```
## Example Configuration
See `multi-telegram-hermes-workforce.yaml` for a complete example.
### Key Features
1. **Multiple Channels**:
```yaml
channels:
telegram_cfo:
platform: telegram
token: ${TELEGRAM_CFO_BOT_TOKEN}
routes:
default: cfo
telegram_ops:
platform: telegram
token: ${TELEGRAM_OPS_BOT_TOKEN}
routes:
default: ops
```
2. **Specialized Agents**:
```yaml
agents:
cfo:
instructions: "You are a CFO agent. Help with financial analysis..."
model: gpt-4o-mini
ops:
instructions: "You are an ops agent. Help with system monitoring..."
model: gpt-4o-mini
```
## Validation with Doctor
Use the doctor command to validate your multi-channel setup:
```bash
praisonai doctor
```
The doctor checks for:
- ✅ **Unique tokens**: Each channel uses a different bot token
- ✅ **Naming convention**: Follows `PLATFORM_ROLE_BOT_TOKEN` pattern
- ✅ **Missing tokens**: All referenced environment variables are set
- ❌ **Duplicate tokens**: Same token used by multiple channels (fails)
## Deployment
### Start Gateway
```bash
# Start the multi-bot gateway
praisonai gateway start --config multi-telegram-hermes-workforce.yaml
# Or install as daemon
praisonai onboard # Wizard installs daemon automatically
praisonai gateway status
```
### Verify Setup
1. **Check health**: `curl http://127.0.0.1:8765/health`
2. **View dashboard**: `praisonai claw` → http://127.0.0.1:8082
3. **Test bots**: Send messages to each bot to verify routing
## Common Patterns
### Basic Multi-Role Setup
```yaml
# Single platform, multiple roles
channels:
telegram_support:
token: ${TELEGRAM_SUPPORT_BOT_TOKEN}
routes:
default: support_agent
telegram_sales:
token: ${TELEGRAM_SALES_BOT_TOKEN}
routes:
default: sales_agent
```
### Cross-Platform Workforce
```yaml
# Multiple platforms, multiple roles
channels:
telegram_cfo:
platform: telegram
token: ${TELEGRAM_CFO_BOT_TOKEN}
routes:
default: cfo
discord_ops:
platform: discord
token: ${DISCORD_OPS_BOT_TOKEN}
routes:
default: ops
slack_content:
platform: slack
token: ${SLACK_CONTENT_BOT_TOKEN}
routes:
default: content
```
## Troubleshooting
### Common Issues
1. **"Token is used by multiple channels"**
- Each bot needs its own unique token from @BotFather
- Check environment variables for duplicates
2. **"Channel skipped - no token"**
- Set the environment variable: `export TELEGRAM_CFO_BOT_TOKEN="..."`
- Or update `~/.praisonai/.env`
3. **"Bot not responding"**
- Verify token is correct: `praisonai doctor`
- Check bot is not already running elsewhere
- Ensure allowlist includes your user ID
### Debugging Commands
```bash
# Check configuration
praisonai doctor
# View logs
praisonai gateway logs
# Test connection
curl -H "Authorization: Bearer $GATEWAY_AUTH_TOKEN" \
http://127.0.0.1:8765/info
```
## Migration from Single-Bot Setup
If you currently have a single bot setup, you can add more channels:
1. **Run onboard wizard**: `praisonai onboard`
2. **Add new channels**: Wizard will preserve existing setup
3. **Update configuration**: New channels added to existing `bot.yaml`
4. **Restart gateway**: `praisonai gateway restart`
The wizard preserves backward compatibility with single-bot configurations.
+19
View File
@@ -0,0 +1,19 @@
# A2UI canvas agent — YAML example
#
# Usage:
# pip install praisonaiagents[a2ui]
# praisonai agent run --file a2ui-canvas.yaml --prompt "Show a welcome card"
#
# For live A2UI rendering, use PraisonAIUI (AG-UI / surfaces):
# pip install praisonaiui
# See examples/python/a2ui/send_surface.py and PraisonAIUI example 29.
agent:
name: "ui-assistant"
instructions: |
You are a helpful assistant. When the user asks for UI elements
(buttons, cards, forms), call send_a2ui_messages with valid A2UI v0.9 JSON.
Use surface id "main" unless told otherwise.
llm: gpt-4o-mini
tools:
- send_a2ui_messages
+40
View File
@@ -0,0 +1,40 @@
# Example: Agent with MCP Tool Integration
#
# This example shows how to configure an agent with MCP (Model Context Protocol)
# servers for additional tool capabilities.
#
# Usage:
# praisonai workflow run --file examples/yaml/agent-with-mcp.yaml
agent:
name: mcp_assistant
instructions: |
You are a helpful assistant with access to filesystem and time tools.
Use the MCP tools when needed to help users with file operations or time queries.
llm: gpt-4o-mini
# MCP server configuration
mcp:
servers:
filesystem:
# Filesystem access for the agent
command: npx
args:
- "-y"
- "@modelcontextprotocol/server-filesystem"
- "."
env: {}
enabled: true
time:
# Time and date utilities
command: npx
args:
- "-y"
- "@modelcontextprotocol/server-time"
env: {}
enabled: true
# NOTE: Per-server tool filtering (tools.include/exclude) is not yet supported
# by the MCP server config schema. Tool filtering should be applied after
# calling mcp.get_tools() in your application code.
@@ -0,0 +1,66 @@
# Multi-Telegram Channel Hermes Workforce Example
# Generated by `praisonai onboard` with multi-channel support
# Start with: praisonai gateway start --config multi-telegram-hermes-workforce.yaml
gateway:
host: "127.0.0.1"
port: 8765
# Legacy single-agent block for backward compatibility
agent:
name: "assistant"
instructions: "You are a helpful AI assistant. You can search the web, manage schedules, and remember past conversations. Use your tools proactively."
model: "gpt-4o-mini"
# Multi-agent workforce with different specialized roles
agents:
cfo:
instructions: "You are a CFO agent. You are a helpful AI assistant. Use your tools proactively to help with CFO-related tasks like financial analysis, budget planning, and cost optimization."
model: gpt-4o-mini
memory: false
ops:
instructions: "You are an ops agent. You are a helpful AI assistant. Use your tools proactively to help with ops-related tasks like system monitoring, deployment, and infrastructure management."
model: gpt-4o-mini
memory: false
content:
instructions: "You are a content agent. You are a helpful AI assistant. Use your tools proactively to help with content-related tasks like writing, editing, and content strategy."
model: gpt-4o-mini
memory: false
# Multiple Telegram channels - each with unique tokens and routing
channels:
telegram_cfo:
platform: telegram
token: ${TELEGRAM_CFO_BOT_TOKEN}
group_policy: mention_only
allowed_users: ${TELEGRAM_ALLOWED_USERS}
# auto_approve_tools: true
# Chat bots cannot show CLI approval prompts; safe tools auto-approved by default.
routes:
default: cfo
telegram_ops:
platform: telegram
token: ${TELEGRAM_OPS_BOT_TOKEN}
group_policy: mention_only
allowed_users: ${TELEGRAM_ALLOWED_USERS}
# auto_approve_tools: true
# Chat bots cannot show CLI approval prompts; safe tools auto-approved by default.
routes:
default: ops
telegram_content:
platform: telegram
token: ${TELEGRAM_CONTENT_BOT_TOKEN}
group_policy: mention_only
allowed_users: ${TELEGRAM_ALLOWED_USERS}
# auto_approve_tools: true
# Chat bots cannot show CLI approval prompts; safe tools auto-approved by default.
routes:
default: content
# Legacy routing block
routing:
default: assistant
+1 -1
View File
@@ -93,7 +93,7 @@ def example_3_execute_yaml_directly():
result = manager.execute_yaml(
yaml_file,
input_data="The future of AI",
output="verbose"
verbose=True,
)
print(f"Status: {result['status']}")
+2 -1
View File
@@ -95,4 +95,5 @@ chroma_db/
.windsurf
.ruff_cache
*.sfdx
.sfdx/
.sfdx/
.cursor/
@@ -79,10 +79,20 @@ def get_time(timezone: Literal["est", "pst"]) -> str:
def calculate(expression: str) -> str:
"""Calculate a math expression."""
"""Calculate a math expression safely."""
try:
result = eval(expression)
return f"Result: {result}"
import ast, operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod, ast.Pow: operator.pow,
ast.USub: operator.neg, ast.UAdd: operator.pos}
def _ev(n):
if isinstance(n, ast.Expression): return _ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.operand))
if isinstance(n, ast.BinOp) and type(n.op) in _OPS: return _OPS[type(n.op)](_ev(n.left), _ev(n.right))
raise ValueError(f"Unsupported: {ast.dump(n)}")
return f"Result: {_ev(ast.parse(expression, mode='eval'))}"
except Exception:
return "Error: Invalid expression"
@@ -343,6 +343,7 @@ _LAZY_IMPORTS = {
# UI (optional)
'AGUI': ('praisonaiagents.ui.agui', 'AGUI'),
'A2A': ('praisonaiagents.ui.a2a', 'A2A'),
'A2UI': ('praisonaiagents.ui.a2ui', 'A2UI'),
# Feature configs
'MemoryConfig': ('praisonaiagents.config.feature_configs', 'MemoryConfig'),
@@ -383,6 +384,7 @@ _LAZY_IMPORTS = {
'MultiAgentExecutionConfig': ('praisonaiagents.config.feature_configs', 'MultiAgentExecutionConfig'),
'MultiAgentPlanningConfig': ('praisonaiagents.config.feature_configs', 'MultiAgentPlanningConfig'),
'MultiAgentMemoryConfig': ('praisonaiagents.config.feature_configs', 'MultiAgentMemoryConfig'),
'ToolSearchConfig': ('praisonaiagents.config.feature_configs', 'ToolSearchConfig'),
# Parameter resolver
'resolve': ('praisonaiagents.config.param_resolver', 'resolve'),
@@ -814,6 +816,6 @@ def __dir__():
# - Workflow, Task, Route, Parallel, Loop, Repeat, Pipeline, etc.
# - MCP, FlowDisplay, track_workflow, FastContext, etc.
# - Plan, PlanStep, TodoList, PlanningAgent, ApprovalCallback, etc.
# - RAG, RAGConfig, RAGResult, AGUI, A2A, etc.
# - RAG, RAGConfig, RAGResult, AGUI, A2A, A2UI, etc.
# - All telemetry, display, and utility functions
# ============================================================================
@@ -556,6 +556,7 @@ class Agent(SandboxMixin, UnifiedExecutionMixin, ToolExecutionMixin, ChatHandler
backend: Optional[Any] = None, # External managed agent backend (e.g., ManagedAgentIntegration)
cli_backend: Optional[Union[str, Any]] = None, # CLI backend for delegating turns (e.g., "claude-code")
interrupt_controller: Optional['InterruptController'] = None, # G2: Cooperative cancellation
tool_search: Optional[Union[bool, str, Dict[str, Any], 'ToolSearchConfig']] = False, # Progressive tool disclosure
sandbox: Optional[Union[bool, 'SandboxConfig']] = None, # Sandbox for safe code execution
):
"""Initialize an Agent instance.
@@ -660,6 +661,14 @@ class Agent(SandboxMixin, UnifiedExecutionMixin, ToolExecutionMixin, ChatHandler
When provided, agent delegates entire conversation turns to the CLI tool
instead of using the built-in LLM. Enables session continuity and
tool integration through external AI coding assistants.
tool_search: Progressive tool disclosure configuration. Accepts:
- bool: False=disabled (default), True=auto mode
- str: Mode ("auto", "on", "off")
- Dict[str, Any]: Config overrides (e.g. {"threshold_pct": 15})
- ToolSearchConfig: Custom configuration
When enabled, replaces large tool schemas with bridge tools (tool_search,
tool_describe, tool_call) to save context. Core SDK tools never defer.
Auto mode activates based on token threshold. Opt-in feature.
Raises:
ValueError: If all of name, role, goal, backstory, and instructions are None.
@@ -1430,6 +1439,34 @@ class Agent(SandboxMixin, UnifiedExecutionMixin, ToolExecutionMixin, ChatHandler
web_search = False
web_fetch = False
# ─────────────────────────────────────────────────────────────────────
# Resolve TOOL_SEARCH param
# ─────────────────────────────────────────────────────────────────────
# Fast path: None/False -> disabled (zero overhead)
if tool_search is None or tool_search is False:
self._tool_search_config = None
elif tool_search is True:
# True -> auto mode with defaults
from ..tools.tool_search import ToolSearchConfig as _ToolSearchConfig
self._tool_search_config = _ToolSearchConfig(enabled="auto")
elif isinstance(tool_search, str):
# String mode ("auto", "on", "off")
from ..tools.tool_search import ToolSearchConfig as _ToolSearchConfig
self._tool_search_config = _ToolSearchConfig.from_raw(tool_search)
elif isinstance(tool_search, dict):
# Dict -> config overrides
from ..tools.tool_search import ToolSearchConfig as _ToolSearchConfig
self._tool_search_config = _ToolSearchConfig(**tool_search)
else:
from ..tools.tool_search import ToolSearchConfig as _ToolSearchConfig
if isinstance(tool_search, _ToolSearchConfig):
self._tool_search_config = tool_search
else:
raise TypeError(
"tool_search must be False/None, True, a mode string, "
"a dict of ToolSearchConfig fields, or ToolSearchConfig"
)
# ============================================================
# END CONSOLIDATED PARAMS EXTRACTION
# ============================================================
@@ -1952,6 +1989,130 @@ Your Goal: {self.goal}
# Sandbox configuration - initialize SandboxMixin
super().__init__(sandbox=sandbox)
def __deepcopy__(self, memo: dict) -> "Agent":
"""Custom deepcopy that creates fresh threading primitives.
threading.RLock (self.__cache_lock) and threading.Lock (self._cost_lock)
cannot be deep-copied on CPython < 3.13. This hook deep-copies every
other attribute normally and replaces the locks with new instances so
that copy.deepcopy(agent) works in any Python version.
"""
import copy
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k in ("_Agent__cache_lock",):
object.__setattr__(result, k, threading.RLock())
elif k == "_cost_lock":
object.__setattr__(result, k, threading.Lock())
else:
object.__setattr__(result, k, copy.deepcopy(v, memo))
return result
def clone_for_channel(self) -> "Agent":
"""Return a fully independent copy of this agent for a gateway channel.
This method safely clones an agent for use in multi-channel scenarios
by avoiding deepcopy issues with tools/handoffs and creating fresh
instances of mutable objects like interrupt_controller.
Returns:
Agent: A new Agent instance with copied configuration but fresh
locks, interrupt controller, and shallow-copied tools.
"""
import copy
from ..tools.base import BaseTool
# Build kwargs for new Agent instance, copying core attributes
clone_kwargs = {
# Core identity
'name': self.name,
'role': self.role,
'goal': self.goal,
'backstory': self.backstory,
'instructions': self.instructions,
# LLM configuration
'llm': self.llm,
'base_url': getattr(self, 'base_url', None),
'api_key': getattr(self, 'api_key', None),
'auth': getattr(self, 'auth', None),
# Shallow copy tools to avoid deepcopy issues with nested objects
'tools': list(self.tools) if self.tools else None,
# Skip handoffs entirely - they shouldn't be shared across channels
# and can contain nested Agent instances that cause RLock issues
'handoffs': None,
# Feature configurations - check for actual stored config objects
'memory': getattr(self, '_memory_config', None),
'knowledge': getattr(self, '_knowledge_config', None),
'planning': getattr(self, '_planning_config', None),
'reflection': getattr(self, '_reflection_config', None),
'guardrails': getattr(self, '_guardrails_config', None),
'web': getattr(self, '_web_config', None),
'context': getattr(self, '_context_config', None),
'autonomy': getattr(self, '_autonomy_config', None),
'output': getattr(self, '_output_config', None),
'execution': getattr(self, '_execution_config', None),
'templates': getattr(self, '_template_config', None),
'caching': getattr(self, '_caching_config', None),
'hooks': getattr(self, '_hooks_config', None),
'skills': getattr(self, '_skills_config', None),
'approval': getattr(self, '_approval_config', None),
'learn': getattr(self, '_learn_config', None),
'tool_search': getattr(self, '_tool_search_config', None),
# Tool configuration
'tool_timeout': getattr(self, '_tool_timeout', None),
'parallel_tool_calls': getattr(self, 'parallel_tool_calls', False),
# CLI backend
'cli_backend': getattr(self, '_cli_backend', None),
# Create fresh interrupt controller to avoid shared state
'interrupt_controller': None, # Let new instance create its own
# Sandbox config
'sandbox': getattr(self, '_sandbox_config', None),
}
# Handle deprecated parameters for backward compatibility
import warnings
# Check for deprecated standalone attributes and emit warnings
deprecated_attrs = [
('allow_code_execution', 'execution'),
('code_execution_mode', 'execution'),
('auto_save', 'memory'),
('rate_limiter', 'execution'),
('allow_delegation', 'handoffs'),
('verification_hooks', 'autonomy')
]
for old_attr, new_param in deprecated_attrs:
if hasattr(self, old_attr):
value = getattr(self, old_attr)
if value is not None and value != False: # Skip None/False defaults
warnings.warn(
f"Deprecated attribute '{old_attr}' found in agent clone. "
f"Use '{new_param}=' parameter instead.",
DeprecationWarning,
stacklevel=2
)
# For basic compatibility, include in clone_kwargs if not already set
if old_attr == 'allow_code_execution' and clone_kwargs['execution'] is None:
from ..config.execution import ExecutionConfig
clone_kwargs['execution'] = ExecutionConfig(code_execution=value)
elif old_attr == 'auto_save' and clone_kwargs['memory'] is None:
from ..config.memory import MemoryConfig
clone_kwargs['memory'] = MemoryConfig(auto_save=value)
# Create new Agent instance
return self.__class__(**{k: v for k, v in clone_kwargs.items() if v is not None})
@property
def _telemetry(self):
"""Lazy-loaded telemetry instance for performance."""
@@ -4616,60 +4777,57 @@ Answer:"""
error=f"Agent guardrail validation error: {str(e)}"
)
def _apply_guardrail_with_retry(self, response_text, prompt, temperature=1.0, tools=None, task_name=None, task_description=None, task_id=None):
"""Apply guardrail validation with retry logic.
Args:
response_text: The response to validate
prompt: Original prompt for regeneration if needed
temperature: Temperature for regeneration
tools: Tools for regeneration
Returns:
str: The validated response text or None if validation fails after retries
"""
def _validate_with_guardrail(self, response_text):
"""Validate response with guardrail. Returns (success, result, error)."""
if not self._guardrail_fn:
return response_text
return True, response_text, None
from ..main import TaskOutput
task_output = TaskOutput(
description="Agent response output",
raw=response_text,
agent=self.name
)
guardrail_result = self._process_guardrail(task_output)
if guardrail_result.success:
# Return the potentially modified result
if guardrail_result.result and hasattr(guardrail_result.result, 'raw'):
return True, guardrail_result.result.raw, None
elif guardrail_result.result:
return True, str(guardrail_result.result), None
else:
return True, response_text, None
else:
return False, None, guardrail_result.error
def _apply_guardrail_with_retry(self, response_text, prompt, temperature=1.0, tools=None, task_name=None, task_description=None, task_id=None):
"""Apply guardrail validation with retry logic (sync version)."""
retry_count = 0
current_response = response_text
while retry_count <= self.max_guardrail_retries:
# Create TaskOutput object
task_output = TaskOutput(
description="Agent response output",
raw=current_response,
agent=self.name
)
success, result, error = self._validate_with_guardrail(current_response)
# Process guardrail
guardrail_result = self._process_guardrail(task_output)
if guardrail_result.success:
if success:
logging.info(f"Agent {self.name}: Guardrail validation passed")
# Return the potentially modified result
if guardrail_result.result and hasattr(guardrail_result.result, 'raw'):
return guardrail_result.result.raw
elif guardrail_result.result:
return str(guardrail_result.result)
else:
return current_response
return result
# Guardrail failed
if retry_count >= self.max_guardrail_retries:
raise Exception(
f"Agent {self.name} response failed guardrail validation after {self.max_guardrail_retries} retries. "
f"Last error: {guardrail_result.error}"
f"Last error: {error}"
)
retry_count += 1
logging.warning(f"Agent {self.name}: Guardrail validation failed (retry {retry_count}/{self.max_guardrail_retries}): {guardrail_result.error}")
logging.warning(f"Agent {self.name}: Guardrail validation failed (retry {retry_count}/{self.max_guardrail_retries}): {error}")
# Regenerate response for retry
try:
retry_prompt = f"{prompt}\n\nNote: Previous response failed validation due to: {guardrail_result.error}. Please provide an improved response."
retry_prompt = f"{prompt}\n\nNote: Previous response failed validation due to: {error}. Please provide an improved response."
response = self._chat_completion([{"role": "user", "content": retry_prompt}], temperature, tools, task_name=task_name, task_description=task_description, task_id=task_id)
if response and response.choices:
content = response.choices[0].message.content
@@ -4678,10 +4836,46 @@ Answer:"""
raise Exception("Failed to generate retry response")
except Exception as e:
logging.error(f"Agent {self.name}: Error during guardrail retry: {e}")
# If we can't regenerate, fail the guardrail
raise Exception(f"Agent {self.name} guardrail retry failed: {e}")
return current_response
async def _aapply_guardrail_with_retry(self, response_text, prompt, temperature=1.0, tools=None, task_name=None, task_description=None, task_id=None):
"""Apply guardrail validation with retry logic (async version)."""
retry_count = 0
current_response = response_text
while retry_count <= self.max_guardrail_retries:
success, result, error = self._validate_with_guardrail(current_response)
if success:
logging.info(f"Agent {self.name}: Guardrail validation passed")
return result
# Guardrail failed
if retry_count >= self.max_guardrail_retries:
raise Exception(
f"Agent {self.name} guardrail retry failed: {e}"
f"Agent {self.name} response failed guardrail validation after {self.max_guardrail_retries} retries. "
f"Last error: {error}"
)
retry_count += 1
logging.warning(f"Agent {self.name}: Guardrail validation failed (retry {retry_count}/{self.max_guardrail_retries}): {error}")
# Regenerate response for retry (async version)
try:
retry_prompt = f"{prompt}\n\nNote: Previous response failed validation due to: {error}. Please provide an improved response."
response = await self._execute_unified_achat_completion([{"role": "user", "content": retry_prompt}], temperature, tools, task_name=task_name, task_description=task_description, task_id=task_id)
if response and hasattr(response, 'choices') and response.choices:
content = response.choices[0].message.content
current_response = content.strip() if content else ""
elif isinstance(response, str):
current_response = response.strip()
else:
raise Exception("Failed to generate retry response")
except Exception as e:
logging.error(f"Agent {self.name}: Error during guardrail retry: {e}")
raise Exception(f"Agent {self.name} guardrail retry failed: {e}")
return current_response
@@ -331,6 +331,7 @@ Your Goal: {self.goal}"""
- Callable functions
- String function names
- Objects with to_openai_tool() method
- Tool Search progressive disclosure (if enabled)
Args:
tools: List of tools in various formats or None to use self.tools
@@ -344,10 +345,14 @@ Your Goal: {self.goal}"""
if not tools:
return []
# Check cache first
# Check cache first - include tool_search config in cache key for safety
tools_key = self._get_tools_cache_key(tools)
cached_tools = self._cache_get(self._formatted_tools_cache, tools_key)
if cached_tools is not None:
tool_search_enabled = getattr(self, '_tool_search_config', None) is not None
cache_key = f"{tools_key}:tool_search={tool_search_enabled}"
cached_entry = self._cache_get(self._formatted_tools_cache, cache_key)
if cached_entry is not None:
cached_tools, cached_metadata = cached_entry
self._tool_search_metadata = cached_metadata
return cached_tools
formatted_tools = []
@@ -399,9 +404,46 @@ Your Goal: {self.goal}"""
logging.error(f"Tools are not JSON serializable: {e}")
return []
# Cache the formatted tools with LRU eviction
self._cache_put(self._formatted_tools_cache, tools_key, formatted_tools)
return formatted_tools
# Apply tool search assembly if enabled (after formatting, before caching)
if hasattr(self, '_tool_search_config') and self._tool_search_config is not None:
try:
from ..tools.tool_search import assemble_tool_defs
# Get context length from LLM config if available
context_length = getattr(self, '_context_window_size', None)
# Assemble tools with bridge mode check
assembled_tools, metadata = assemble_tool_defs(
tool_defs=formatted_tools,
config=self._tool_search_config,
context_length=context_length
)
# Store metadata for bridge tool dispatch
self._tool_search_metadata = metadata
formatted_tools = assembled_tools
except ImportError:
# Tool search module not available, continue with original tools
logging.warning("Tool search requested but tool_search module not available")
# Strip __praisonai_deferrable__ from provider-facing tool payloads
# Keep the marker only for internal tool classification
cleaned_tools = []
for tool in formatted_tools:
if isinstance(tool, dict) and "__praisonai_deferrable__" in tool:
tool_copy = tool.copy()
tool_copy.pop("__praisonai_deferrable__", None)
cleaned_tools.append(tool_copy)
else:
cleaned_tools.append(tool)
# Cache the formatted tools with LRU eviction, including tool search metadata
self._cache_put(
self._formatted_tools_cache,
cache_key,
(cleaned_tools, getattr(self, "_tool_search_metadata", None)),
)
return cleaned_tools
def _build_multimodal_prompt(
self,
@@ -507,7 +549,7 @@ Your Goal: {self.goal}"""
emit_events=True
)
def _chat_completion(self, messages, temperature=1.0, tools=None, stream=True, reasoning_steps=False, task_name=None, task_description=None, task_id=None, response_format=None, _retry_depth=0):
def _chat_completion(self, messages, temperature=1.0, tools=None, stream=None, reasoning_steps=False, task_name=None, task_description=None, task_id=None, response_format=None, _retry_depth=0):
start_time = time.time()
# --- Context compaction (opt-in via ExecutionConfig.context_compaction) ---
@@ -577,6 +619,39 @@ Your Goal: {self.goal}"""
# Use the new _format_tools_for_completion helper method
formatted_tools = self._format_tools_for_completion(tools)
# Smart fallback for streaming: try streaming first, fall back to non-streaming if unsupported
if stream is None:
# Auto-detect: prefer streaming for better UX, fallback if adapter doesn't support it
try:
# First attempt: try with streaming enabled for better user experience
stream_callback = self.stream_emitter.emit if hasattr(self, 'stream_emitter') else None
final_response = self._execute_unified_chat_completion(
messages=messages,
temperature=temperature,
tools=formatted_tools,
stream=True, # Try streaming first
reasoning_steps=reasoning_steps,
task_name=task_name,
task_description=task_description,
task_id=task_id,
response_format=response_format,
stream_callback=stream_callback,
emit_events=True
)
return final_response
except ValueError as e:
if "Streaming is not supported" in str(e):
# Fallback: retry with non-streaming for sync adapters
logging.debug(f"{self.name}: Streaming not supported by adapter, falling back to non-streaming")
stream = False # Set for the main execution below
else:
raise # Re-raise if it's a different ValueError
except Exception:
# For any other exception, fall back to non-streaming
logging.debug(f"{self.name}: Streaming attempt failed, falling back to non-streaming")
stream = False # Set for the main execution below
# If stream was explicitly set or fallback occurred, use the specified/fallback value
try:
# NEW: Unified protocol dispatch path (Issue #1304, #1362)
# UNIFIED: Single protocol-driven dispatch path (fixes DRY violation)
@@ -774,7 +849,7 @@ Your Goal: {self.goal}"""
messages,
temperature=1.0,
tools=None,
stream=True,
stream=None,
reasoning_steps=False,
task_name=None,
task_description=None,
@@ -806,6 +881,47 @@ Your Goal: {self.goal}"""
# Cache the dispatcher
self._unified_dispatcher = dispatcher
# Smart fallback for streaming: try streaming first, fall back to non-streaming if unsupported
if stream is None:
# Auto-detect: prefer streaming for better UX, fallback if adapter doesn't support it
try:
# First attempt: try with streaming enabled for better user experience
if stream_callback is None and hasattr(self, 'stream_emitter'):
stream_callback = getattr(self.stream_emitter, 'emit', None)
final_response = self._unified_dispatcher.chat_completion(
messages=messages,
tools=tools,
tool_choice=getattr(self, 'tool_choice', None),
temperature=temperature,
max_tokens=getattr(self, 'max_tokens', None),
stream=True, # Try streaming first
response_format=response_format,
execute_tool_fn=getattr(self, 'execute_tool', None),
console=self.console if (self.verbose or True) else None, # Enable console for streaming
display_fn=self._display_generating if self.verbose else None,
stream_callback=stream_callback,
emit_events=emit_events,
verbose=self.verbose,
max_iterations=10,
reasoning_steps=reasoning_steps,
task_name=task_name,
task_description=task_description,
task_id=task_id,
agent_name=getattr(self, 'name', 'assistant')
)
return final_response
except ValueError as e:
if "Streaming is not supported" in str(e):
# Fallback: retry with non-streaming for sync adapters
logging.debug(f"Agent: Streaming not supported by adapter, falling back to non-streaming")
stream = False # Set for the main execution below
else:
raise # Re-raise if it's a different ValueError
except Exception:
# For any other exception, fall back to non-streaming
logging.debug(f"Agent: Streaming attempt failed, falling back to non-streaming")
stream = False # Set for the main execution below
# Execute unified dispatch with all necessary parameters
# Includes all parameters from both legacy paths to ensure full compatibility
try:
@@ -857,7 +973,7 @@ Your Goal: {self.goal}"""
messages,
temperature=1.0,
tools=None,
stream=True,
stream=True, # Async methods keep stream=True default (async adapters support streaming vs sync smart fallback)
reasoning_steps=False,
task_name=None,
task_description=None,
@@ -2079,7 +2195,7 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
# Apply guardrail validation for custom LLM response
try:
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools, task_name, task_description, task_id)
validated_response = await self._aapply_guardrail_with_retry(response_text, prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(normalized_content, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(prompt, validated_response, start_time)
@@ -2187,22 +2303,216 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
task_id=task_id,
response_format=response_format
)
return await self._finalize_unified_achat_response(
response=response,
original_prompt=original_prompt,
temperature=temperature,
tools=tools,
output_json=output_json,
output_pydantic=output_pydantic,
reasoning_steps=reasoning_steps,
stream=stream,
messages=messages,
chat_history_length=chat_history_length,
start_time=start_time,
task_name=task_name,
task_description=task_description,
task_id=task_id,
)
# Process response - mirror sync _chat_impl behavior (lines ~1544-1602)
if not response:
# Rollback chat history on response failure
self._truncate_chat_history(chat_history_length)
return None
# Extract response content using the same method as sync
response_text = self._extract_llm_response_content(response)
if isinstance(response_text, str):
response_text = response_text.strip()
# Handle output_json or output_pydantic if specified
if output_json or output_pydantic:
# Add to chat history and return raw response
# User message already added before LLM call via _build_messages
self._append_to_chat_history({"role": "assistant", "content": response_text})
# Persist assistant message to DB
self._persist_message("assistant", response_text)
# Apply guardrail validation even for JSON output
try:
validated_response = await self._aapply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_response, start_time)
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for JSON output: {e}")
# Rollback chat history on guardrail failure
self._truncate_chat_history(chat_history_length)
return None
# For regular responses (no self-reflection)
if not self.self_reflect:
# User message already added before LLM call via _build_messages
self._append_to_chat_history({"role": "assistant", "content": response_text})
# Persist assistant message to DB (non-reflect path)
self._persist_message("assistant", response_text)
if self.verbose:
logging.debug(f"Agent {self.name} final response: {response_text}")
# Return only reasoning content if reasoning_steps is True
if reasoning_steps and hasattr(response, 'choices') and response.choices and hasattr(response.choices[0].message, 'reasoning_content') and response.choices[0].message.reasoning_content:
# Apply guardrail to reasoning content
try:
validated_reasoning = await self._aapply_guardrail_with_retry(response.choices[0].message.reasoning_content, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_reasoning, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_reasoning, start_time)
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for reasoning content: {e}")
# Rollback chat history on guardrail failure
self._truncate_chat_history(chat_history_length)
return None
else:
# Apply guardrail to regular response content
try:
validated_response = await self._aapply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_response, start_time)
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
# Rollback chat history on guardrail failure
self._truncate_chat_history(chat_history_length)
return None
# If self-reflection is enabled, implement reflection logic
if self.self_reflect:
# Implement async self-reflection similar to sync path
reflection_prompt = f"""
Reflect on your previous response: '{response_text}'.
{self.reflect_prompt if self.reflect_prompt else "Identify any flaws, improvements, or actions."}
Provide a "satisfactory" status ('yes' or 'no').
Output MUST be JSON with 'reflection' and 'satisfactory'.
"""
# Add reflection prompt to messages
reflection_messages = messages + [
{"role": "assistant", "content": response_text},
{"role": "user", "content": reflection_prompt}
]
reflection_count = 0
while True:
try:
# Check if OpenAI client is available for self-reflection
if self._openai_client is None:
# For custom LLMs, self-reflection with structured output is not supported
if self.verbose:
_get_display_functions()['display_self_reflection'](f"Agent {self.name}: Self-reflection with structured output is not supported for custom LLM providers. Skipping reflection.", console=self.console)
# Return the original response without reflection
self._append_to_chat_history({"role": "assistant", "content": response_text})
# Persist assistant message to DB
self._persist_message("assistant", response_text)
try:
validated_response = await self._aapply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_response, start_time)
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
# Rollback chat history on guardrail failure
self._truncate_chat_history(chat_history_length)
return None
reflection_response = await self._openai_client.async_client.beta.chat.completions.parse(
model=self.reflect_llm if self.reflect_llm else self.llm,
messages=reflection_messages,
temperature=temperature,
response_format=_get_display_functions()['ReflectionOutput']
)
reflection_output = reflection_response.choices[0].message.parsed
if self.verbose:
_get_display_functions()['display_self_reflection'](f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
# Only consider satisfactory after minimum reflections
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
if self.verbose:
_get_display_functions()['display_self_reflection']("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
# Add to chat history and return
self._append_to_chat_history({"role": "assistant", "content": response_text})
# Persist assistant message to DB
self._persist_message("assistant", response_text)
try:
validated_response = await self._aapply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_response, start_time)
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed after reflection: {e}")
# Rollback chat history on guardrail failure
self._truncate_chat_history(chat_history_length)
return None
# Check if we've hit max reflections
if reflection_count >= self.max_reflect - 1:
if self.verbose:
_get_display_functions()['display_self_reflection']("Maximum reflection count reached, returning current response", console=self.console)
# Add to chat history and return
self._append_to_chat_history({"role": "assistant", "content": response_text})
# Persist assistant message to DB
self._persist_message("assistant", response_text)
try:
validated_response = await self._aapply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_response, start_time)
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed after max reflections: {e}")
# Rollback chat history on guardrail failure
self._truncate_chat_history(chat_history_length)
return None
# Regenerate response based on reflection
regenerate_messages = reflection_messages + [
{"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"},
{"role": "user", "content": "Now regenerate your response using the reflection you made"}
]
new_response = await self._execute_unified_achat_completion(
messages=regenerate_messages,
temperature=temperature,
tools=formatted_tools,
stream=stream,
reasoning_steps=reasoning_steps,
task_name=task_name,
task_description=task_description,
task_id=task_id,
response_format=response_format
)
if new_response:
new_response_text = self._extract_llm_response_content(new_response)
if isinstance(new_response_text, str):
response_text = new_response_text.strip()
# Update reflection_messages to include the new response for next iteration
reflection_messages = regenerate_messages + [
{"role": "assistant", "content": response_text}
]
reflection_count += 1
except Exception as e:
if self.verbose:
_get_display_functions()['display_error'](f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
logging.error("Reflection parsing failed.", exc_info=True)
reflection_count += 1
if reflection_count >= self.max_reflect:
# Return original response after max reflection attempts
self._append_to_chat_history({"role": "assistant", "content": response_text})
# Persist assistant message to DB
self._persist_message("assistant", response_text)
try:
validated_response = await self._aapply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_response, start_time)
except Exception as guard_e:
logging.error(f"Agent {self.name}: Guardrail validation failed after reflection error: {guard_e}")
# Rollback chat history on guardrail failure
self._truncate_chat_history(chat_history_length)
return None
continue
# This should never be reached due to the returns above
# But adding as safety fallback
logging.warning(f"Agent {self.name}: Unexpected code path reached in unified dispatch")
return None
else:
# LEGACY: Check if OpenAI client is available
if self._openai_client is None:
@@ -2339,7 +2649,7 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
# Apply guardrail validation for OpenAI client response
try:
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
validated_response = await self._aapply_guardrail_with_retry(response_text, original_prompt, temperature, tools, task_name, task_description, task_id)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time, task_name, task_description, task_id)
return await self._atrigger_after_agent_hook(original_prompt, validated_response, start_time)
@@ -403,9 +403,33 @@ class MemoryMixin:
self._session_store.add_user_message(self._session_id, content)
elif role == "assistant":
self._session_store.add_assistant_message(self._session_id, content)
self._persist_session_stats()
except Exception as e:
logging.warning(f"Failed to persist message to session store: {e}")
def _persist_session_stats(self):
"""Flush agent cost/token stats into session JSON metadata."""
store = getattr(self, "_session_store", None)
session_id = getattr(self, "_session_id", None)
if store is None or session_id is None:
return
if not hasattr(store, "update_session_metadata"):
return
try:
summary = getattr(self, "cost_summary", {}) or {}
llm = getattr(self, "llm", None)
model = str(llm) if llm is not None else None
store.update_session_metadata(
session_id,
model=model,
total_tokens=summary.get("tokens_in", 0) + summary.get("tokens_out", 0),
cost=summary.get("cost", 0),
source=getattr(self, "_session_source", "chat"),
agent_id=getattr(self, "agent_id", None) or getattr(self, "_agent_id", None),
)
except Exception as e:
logging.debug(f"Session stats persist skipped: {e}")
def session_id(self) -> Optional[str]:
"""Get the current session ID."""
return self._session_id
@@ -26,6 +26,21 @@ if TYPE_CHECKING:
class ToolExecutionMixin:
"""Mixin providing toolexecution methods for the Agent class."""
def _get_existing_stream_emitter(self):
"""Return an already-initialized stream emitter without creating one."""
emitter = getattr(self, "_stream_emitter", None)
if emitter is not None:
return emitter
# Support name-mangled private attributes across class renames/inheritance.
for cls in type(self).mro():
mangled = f"_{cls.__name__}__stream_emitter"
if hasattr(self, mangled):
emitter = getattr(self, mangled, None)
if emitter is not None:
return emitter
return None
def _resolve_tool_names(self, tool_names):
"""Resolve tool names to actual tool instances from registry.
@@ -120,6 +135,12 @@ class ToolExecutionMixin:
"""
logging.debug(f"{self.name} executing tool {function_name} with arguments: {arguments}")
# Handle bridge tool unwrapping BEFORE trace/stream/hooks (design invariant #6)
# Only intercept when tool_search is active; otherwise fall through to real tool execution
if (getattr(self, '_tool_search_config', None) is not None and
function_name in ("tool_search", "tool_describe", "tool_call")):
return self._handle_bridge_tool_call(function_name, arguments, tool_call_id)
# NOTE: tool_call callback is triggered by display_tool_call in openai_client.py
# Do NOT call it here to avoid duplicate output
@@ -160,8 +181,9 @@ class ToolExecutionMixin:
# Emit TOOL_CALL_START to stream_emitter (for AIUI/AG-UI consumers)
# Zero overhead when no callbacks registered
if hasattr(self, '_Agent__stream_emitter') and getattr(self, "_Agent__stream_emitter", None) is not None and getattr(self, "_Agent__stream_emitter", None).has_callbacks:
getattr(self, "_Agent__stream_emitter", None).emit(StreamEvent(
_stream_emitter = self._get_existing_stream_emitter()
if _stream_emitter is not None and _stream_emitter.has_callbacks:
_stream_emitter.emit(StreamEvent(
type=StreamEventType.TOOL_CALL_START,
timestamp=_tool_start_perf,
tool_call={
@@ -275,10 +297,10 @@ class ToolExecutionMixin:
# Emit TOOL_CALL_RESULT to stream_emitter (for AIUI/AG-UI consumers)
# Zero overhead when no callbacks registered
if hasattr(self, '_Agent__stream_emitter') and getattr(self, "_Agent__stream_emitter", None) is not None and getattr(self, "_Agent__stream_emitter", None).has_callbacks:
if _stream_emitter is not None and _stream_emitter.has_callbacks:
# Truncate result for stream event (keep it reasonable for UI display)
result_summary = str(result)[:500] if result else None
getattr(self, "_Agent__stream_emitter", None).emit(StreamEvent(
_stream_emitter.emit(StreamEvent(
type=StreamEventType.TOOL_CALL_RESULT,
timestamp=_time.perf_counter(),
tool_call={
@@ -290,6 +312,18 @@ class ToolExecutionMixin:
agent_id=self.name,
metadata={"duration_ms": _duration_ms},
))
_stream_emitter.emit(StreamEvent(
type=StreamEventType.TOOL_CALL_END,
timestamp=_time.perf_counter(),
tool_call={
"name": function_name,
"arguments": arguments,
"result": result_summary,
"id": tool_call_id,
},
agent_id=self.name,
metadata={"duration_ms": _duration_ms},
))
# Trigger AFTER_TOOL hook
from ..hooks import HookEvent, AfterToolInput
@@ -926,4 +960,97 @@ class ToolExecutionMixin:
def pending_approval_count(self) -> int:
"""Number of approval requests still waiting."""
return len(self._pending_approvals)
def _handle_bridge_tool_call(self, function_name: str, arguments: Dict[str, Any], tool_call_id: Optional[str] = None) -> Any:
"""
Handle bridge tool calls (tool_search, tool_describe, tool_call).
This implements the tool search unwrapping logic before trace/stream/hooks
as required by design invariant #6.
Args:
function_name: Bridge tool name
arguments: Arguments passed to bridge tool
tool_call_id: Optional tool call ID
Returns:
Result of bridge tool execution or unwrapped real tool call
"""
# Ensure tool search metadata is available
if not hasattr(self, '_tool_search_metadata') or self._tool_search_metadata is None:
return "Tool search not available or not in bridge mode"
metadata = self._tool_search_metadata
# Check if we're in bridge mode
if not metadata.get("bridge_mode", False):
return "Tool search not in bridge mode"
# Get deferrable tools from metadata
deferrable_tools = metadata.get("deferrable_tools", [])
if function_name == "tool_search":
# Handle tool_search bridge call
try:
from ..tools.tool_search import dispatch_tool_search
query = arguments.get("query", "")
limit = arguments.get("limit", None)
result = dispatch_tool_search(
query=query,
limit=limit,
deferrable_tools=deferrable_tools,
config=self._tool_search_config
)
return json.dumps(result, indent=2)
except ImportError:
return "Tool search module not available"
except Exception as e:
logging.error(f"Error in tool_search: {e}")
return f"Error searching tools: {e}"
elif function_name == "tool_describe":
# Handle tool_describe bridge call
try:
from ..tools.tool_search import dispatch_tool_describe
tool_name = arguments.get("tool_name", "")
result = dispatch_tool_describe(
tool_name=tool_name,
deferrable_tools=deferrable_tools
)
return json.dumps(result, indent=2)
except ImportError:
return "Tool search module not available"
except Exception as e:
logging.error(f"Error in tool_describe: {e}")
return f"Error describing tool: {e}"
elif function_name == "tool_call":
# Handle tool_call bridge - unwrap and recurse with real tool
try:
from ..tools.tool_search import resolve_underlying_call
# Unwrap the real tool call
real_function_name, real_arguments = resolve_underlying_call(function_name, arguments)
# Validate that the real tool is in our deferrable set (security check)
deferrable_names = {
tool_def.get("function", {}).get("name", "")
for tool_def in deferrable_tools
}
if real_function_name not in deferrable_names:
return f"Tool '{real_function_name}' is not available for execution"
# Recursively execute the real tool (this will go through normal execution path)
return self.execute_tool(real_function_name, real_arguments, tool_call_id)
except ImportError:
return "Tool search module not available"
except Exception as e:
logging.error(f"Error in tool_call unwrap: {e}")
return f"Error executing tool: {e}"
else:
return f"Unknown bridge tool: {function_name}"
@@ -15,9 +15,9 @@ from enum import Enum
# Import token tracking
try:
from ..telemetry.token_collector import _token_collector
from ..telemetry.token_collector import get_token_collector
except ImportError:
_token_collector = None
get_token_collector = None
# Import async utility for hot-path usage
try:
@@ -1609,25 +1609,25 @@ class AgentTeam:
original_on_task_start = self.on_task_start
original_on_task_complete = self.on_task_complete
def composed_on_task_start(task):
def composed_on_task_start(task, task_id):
try:
verbose_task_start_callback(task)
verbose_task_start_callback(task, task_id)
except Exception as e:
logging.debug(f"Error in verbose task start callback: {e}")
if original_on_task_start:
try:
original_on_task_start(task)
original_on_task_start(task, task_id)
except Exception as e:
logging.debug(f"Error in original task start callback: {e}")
def composed_on_task_complete(task):
def composed_on_task_complete(task, task_output):
try:
verbose_task_complete_callback(task)
verbose_task_complete_callback(task, task_output)
except Exception as e:
logging.debug(f"Error in verbose task complete callback: {e}")
if original_on_task_complete:
try:
original_on_task_complete(task)
original_on_task_complete(task, task_output)
except Exception as e:
logging.debug(f"Error in original task complete callback: {e}")
@@ -1826,18 +1826,19 @@ class AgentTeam:
def get_token_usage_summary(self) -> Dict[str, Any]:
"""Get a summary of token usage across all agents and tasks."""
if not _token_collector:
if not get_token_collector:
return {"error": "Token tracking not available"}
return _token_collector.get_session_summary()
return get_token_collector().get_session_summary()
def get_detailed_token_report(self) -> Dict[str, Any]:
"""Get a detailed token usage report."""
if not _token_collector:
if not get_token_collector:
return {"error": "Token tracking not available"}
summary = _token_collector.get_session_summary()
recent = _token_collector.get_recent_interactions(limit=20)
collector = get_token_collector()
summary = collector.get_session_summary()
recent = collector.get_recent_interactions(limit=20)
# Calculate cost estimates (example rates)
cost_per_1k_input = 0.0005 # $0.0005 per 1K input tokens
@@ -1861,11 +1862,11 @@ class AgentTeam:
def display_token_usage(self):
"""Display token usage in a formatted table."""
if not _token_collector:
if not get_token_collector:
print("Token tracking not available")
return
summary = _token_collector.get_session_summary()
summary = get_token_collector().get_session_summary()
print("\n" + "="*50)
print("TOKEN USAGE SUMMARY")
@@ -39,6 +39,7 @@ __all__ = [
"CachingConfig",
"HooksConfig",
"SkillsConfig",
"ToolSearchConfig",
# Type aliases
"MemoryParam",
"KnowledgeParam",
@@ -122,6 +123,7 @@ _MODULE_MAP = {
"CachingConfig": "feature_configs",
"HooksConfig": "feature_configs",
"SkillsConfig": "feature_configs",
"ToolSearchConfig": "feature_configs",
"MemoryParam": "feature_configs",
"KnowledgeParam": "feature_configs",
"PlanningParam": "feature_configs",
Loaded 100 of 318 files, more files were not shown because too many files have changed in this diff. Show more