mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-09 11:51:37 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45419c40d8 | ||
|
|
9df792b218 | ||
|
|
0526cdc528 | ||
|
|
e6f3438cfa |
No files matched your search
@@ -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.2.2" \
|
||||
"praisonai>=4.3.0" \
|
||||
"praisonai[chat]" \
|
||||
"embedchain[github,youtube]"
|
||||
|
||||
|
||||
@@ -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.2.2" \
|
||||
"praisonai>=4.3.0" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[chat]" \
|
||||
"praisonai[realtime]" \
|
||||
|
||||
@@ -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.2.2" \
|
||||
"praisonai>=4.3.0" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[crewai]"
|
||||
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Smoke Test: Condition Syntax Comparison
|
||||
|
||||
This script tests both condition syntaxes WITHOUT LLM calls (deterministic):
|
||||
1. AgentFlow with when() string expressions
|
||||
2. AgentTeam with Task.condition dict routing
|
||||
|
||||
Run: python examples/smoke_test_condition_syntax.py
|
||||
"""
|
||||
from praisonaiagents import AgentFlow, Task
|
||||
from praisonaiagents.workflows import when
|
||||
|
||||
print("=" * 60)
|
||||
print("SMOKE TEST: Condition Syntax Comparison")
|
||||
print("=" * 60)
|
||||
|
||||
# ============================================================
|
||||
# TEST 1: AgentFlow with when() - String Expression Syntax
|
||||
# ============================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 1: AgentFlow with when() - String Expression")
|
||||
print("=" * 60)
|
||||
|
||||
def high_score_handler(ctx):
|
||||
print(" ✅ HIGH SCORE PATH: Score was >= 50")
|
||||
return {"output": "High score processed"}
|
||||
|
||||
def low_score_handler(ctx):
|
||||
print(" ❌ LOW SCORE PATH: Score was < 50")
|
||||
return {"output": "Low score processed"}
|
||||
|
||||
# AgentFlow uses STRING condition: "{{score}} >= 50"
|
||||
flow = AgentFlow(
|
||||
name="Score-Based Flow",
|
||||
steps=[
|
||||
when(
|
||||
condition="{{score}} >= 50", # STRING expression
|
||||
then_steps=[high_score_handler],
|
||||
else_steps=[low_score_handler]
|
||||
)
|
||||
],
|
||||
variables={"score": 75} # Pre-set score for deterministic test
|
||||
)
|
||||
|
||||
print("\nAgentFlow Syntax:")
|
||||
print(' when(condition="{{score}} >= 50", then_steps=[...], else_steps=[...])')
|
||||
print(" Variables: {'score': 75}")
|
||||
print("\nRunning AgentFlow...")
|
||||
|
||||
try:
|
||||
result = flow.start("Process the score")
|
||||
print("\n✅ AgentFlow completed successfully")
|
||||
except Exception as e:
|
||||
print(f"\n❌ AgentFlow failed: {e}")
|
||||
|
||||
# ============================================================
|
||||
# TEST 2: AgentTeam with Task.condition - Dict Routing Syntax
|
||||
# ============================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 2: AgentTeam with Task.condition - Dict Routing")
|
||||
print("=" * 60)
|
||||
|
||||
# Task uses DICT condition: {"approved": ["publish"], "rejected": ["edit"]}
|
||||
# NOTE: This is just showing the syntax - no LLM call needed
|
||||
review_task = Task(
|
||||
name="review",
|
||||
description="Review the content and decide: approved or rejected",
|
||||
task_type="decision",
|
||||
is_start=True,
|
||||
condition={ # DICT routing
|
||||
"approved": ["publish"],
|
||||
"rejected": ["edit"]
|
||||
}
|
||||
)
|
||||
|
||||
print("\nAgentTeam/Task Syntax:")
|
||||
print(' Task(condition={"approved": ["publish"], "rejected": ["edit"]})')
|
||||
print(" task_type='decision' triggers LLM to output a decision value")
|
||||
print("\nTask condition structure:")
|
||||
print(f" review_task.condition = {review_task.condition}")
|
||||
print(f" review_task.task_type = '{review_task.task_type}'")
|
||||
print("\n✅ Task condition syntax validated (no LLM call needed)")
|
||||
|
||||
# ============================================================
|
||||
# TEST 3: NEW UNIFIED SYNTAX - Task.when (same as AgentFlow!)
|
||||
# ============================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 3: NEW UNIFIED SYNTAX - Task.when (same as AgentFlow!)")
|
||||
print("=" * 60)
|
||||
|
||||
# Task now supports the same string expression syntax as AgentFlow!
|
||||
unified_task = Task(
|
||||
name="score_check",
|
||||
description="Check if score passes threshold",
|
||||
when="{{score}} > 80", # SAME syntax as AgentFlow!
|
||||
then_task="approve",
|
||||
else_task="reject"
|
||||
)
|
||||
|
||||
print("\nNEW Unified Task Syntax:")
|
||||
print(' Task(when="{{score}} > 80", then_task="approve", else_task="reject")')
|
||||
print("\nTask structure:")
|
||||
print(f" unified_task.when = '{unified_task.when}'")
|
||||
print(f" unified_task.then_task = '{unified_task.then_task}'")
|
||||
print(f" unified_task.else_task = '{unified_task.else_task}'")
|
||||
|
||||
# Test evaluate_when method
|
||||
print("\nTesting evaluate_when():")
|
||||
result_high = unified_task.evaluate_when({"score": 90})
|
||||
result_low = unified_task.evaluate_when({"score": 70})
|
||||
print(f" evaluate_when({{'score': 90}}) = {result_high}")
|
||||
print(f" evaluate_when({{'score': 70}}) = {result_low}")
|
||||
|
||||
# Test get_next_task method
|
||||
print("\nTesting get_next_task():")
|
||||
next_high = unified_task.get_next_task({"score": 90})
|
||||
next_low = unified_task.get_next_task({"score": 70})
|
||||
print(f" get_next_task({{'score': 90}}) = '{next_high}'")
|
||||
print(f" get_next_task({{'score': 70}}) = '{next_low}'")
|
||||
|
||||
print("\n✅ NEW unified Task.when syntax works!")
|
||||
|
||||
# ============================================================
|
||||
# SUMMARY: Syntax Differences
|
||||
# ============================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("SUMMARY: Syntax Differences (CONFUSING FOR USERS)")
|
||||
print("=" * 60)
|
||||
|
||||
print("""
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ CONDITION SYNTAX COMPARISON │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ AGENTFLOW (Deterministic Pipelines) │
|
||||
│ ───────────────────────────────────── │
|
||||
│ Syntax: STRING expression with {{variable}} placeholders │
|
||||
│ │
|
||||
│ when( │
|
||||
│ condition="{{score}} >= 50", ← STRING │
|
||||
│ then_steps=[approve], │
|
||||
│ else_steps=[reject] │
|
||||
│ ) │
|
||||
│ │
|
||||
│ Supported: >, <, >=, <=, ==, !=, in, contains │
|
||||
│ │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ AGENTTEAM (Multi-Agent Task Graphs) │
|
||||
│ ───────────────────────────────────── │
|
||||
│ Syntax: DICT mapping decision values to next task names │
|
||||
│ │
|
||||
│ Task( │
|
||||
│ condition={ ← DICT │
|
||||
│ "approved": ["publish"], │
|
||||
│ "rejected": ["edit"] │
|
||||
│ }, │
|
||||
│ task_type="decision" │
|
||||
│ ) │
|
||||
│ │
|
||||
│ LLM outputs a decision value, Process routes by key lookup │
|
||||
│ │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ 🚨 CONFUSION POINTS FOR BEGINNERS: │
|
||||
│ │
|
||||
│ 1. Same word "condition" means DIFFERENT things │
|
||||
│ 2. AgentFlow: evaluates expression → boolean │
|
||||
│ 3. AgentTeam: routes by key lookup → next task │
|
||||
│ 4. No unified syntax for simple use cases │
|
||||
│ 5. Task also has should_run (callable) - 3rd way! │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
""")
|
||||
|
||||
print("\n✅ Smoke test completed!")
|
||||
@@ -150,10 +150,19 @@ _LAZY_IMPORTS = {
|
||||
'Parallel': ('praisonaiagents.workflows', 'Parallel'),
|
||||
'Loop': ('praisonaiagents.workflows', 'Loop'),
|
||||
'Repeat': ('praisonaiagents.workflows', 'Repeat'),
|
||||
'If': ('praisonaiagents.workflows', 'If'),
|
||||
'route': ('praisonaiagents.workflows', 'route'),
|
||||
'parallel': ('praisonaiagents.workflows', 'parallel'),
|
||||
'loop': ('praisonaiagents.workflows', 'loop'),
|
||||
'repeat': ('praisonaiagents.workflows', 'repeat'),
|
||||
'when': ('praisonaiagents.workflows', 'when'),
|
||||
|
||||
# Conditions (Protocol-driven condition evaluation)
|
||||
'ConditionProtocol': ('praisonaiagents.conditions.protocols', 'ConditionProtocol'),
|
||||
'RoutingConditionProtocol': ('praisonaiagents.conditions.protocols', 'RoutingConditionProtocol'),
|
||||
'ExpressionCondition': ('praisonaiagents.conditions.evaluator', 'ExpressionCondition'),
|
||||
'DictCondition': ('praisonaiagents.conditions.evaluator', 'DictCondition'),
|
||||
'evaluate_condition': ('praisonaiagents.conditions.evaluator', 'evaluate_condition'),
|
||||
|
||||
# Handoff
|
||||
'Handoff': ('praisonaiagents.agent.handoff', 'Handoff'),
|
||||
@@ -421,6 +430,33 @@ _LAZY_IMPORTS = {
|
||||
'ProviderStatus': ('praisonaiagents.llm.failover', 'ProviderStatus'),
|
||||
'FailoverConfig': ('praisonaiagents.llm.failover', 'FailoverConfig'),
|
||||
'FailoverManager': ('praisonaiagents.llm.failover', 'FailoverManager'),
|
||||
|
||||
# Plugins - Core classes
|
||||
'PluginManager': ('praisonaiagents.plugins', 'PluginManager'),
|
||||
'Plugin': ('praisonaiagents.plugins', 'Plugin'),
|
||||
'PluginInfo': ('praisonaiagents.plugins', 'PluginInfo'),
|
||||
'PluginHook': ('praisonaiagents.plugins', 'PluginHook'),
|
||||
'FunctionPlugin': ('praisonaiagents.plugins', 'FunctionPlugin'),
|
||||
'get_plugin_manager': ('praisonaiagents.plugins', 'get_plugin_manager'),
|
||||
|
||||
# Plugins - Protocols
|
||||
'PluginProtocol': ('praisonaiagents.plugins', 'PluginProtocol'),
|
||||
'ToolPluginProtocol': ('praisonaiagents.plugins', 'ToolPluginProtocol'),
|
||||
'HookPluginProtocol': ('praisonaiagents.plugins', 'HookPluginProtocol'),
|
||||
'AgentPluginProtocol': ('praisonaiagents.plugins', 'AgentPluginProtocol'),
|
||||
'LLMPluginProtocol': ('praisonaiagents.plugins', 'LLMPluginProtocol'),
|
||||
|
||||
# Plugins - Single-file plugin support
|
||||
'PluginMetadata': ('praisonaiagents.plugins', 'PluginMetadata'),
|
||||
'PluginParseError': ('praisonaiagents.plugins', 'PluginParseError'),
|
||||
'parse_plugin_header': ('praisonaiagents.plugins', 'parse_plugin_header'),
|
||||
'parse_plugin_header_from_file': ('praisonaiagents.plugins', 'parse_plugin_header_from_file'),
|
||||
'discover_plugins': ('praisonaiagents.plugins', 'discover_plugins'),
|
||||
'load_plugin': ('praisonaiagents.plugins', 'load_plugin'),
|
||||
'discover_and_load_plugins': ('praisonaiagents.plugins', 'discover_and_load_plugins'),
|
||||
'get_default_plugin_dirs': ('praisonaiagents.plugins', 'get_default_plugin_dirs'),
|
||||
'get_plugin_template': ('praisonaiagents.plugins', 'get_plugin_template'),
|
||||
'ensure_plugin_dir': ('praisonaiagents.plugins', 'ensure_plugin_dir'),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1085,9 +1085,19 @@ class Agent:
|
||||
self.__stream_emitter = None # Will be initialized on first access
|
||||
self._hooks_registry_param = hooks # Store for lazy init
|
||||
|
||||
# Handle model= alias for llm= (NO warnings - both are valid)
|
||||
if llm is None and model is not None:
|
||||
llm = model # model= is an alias for llm=
|
||||
# Handle llm= deprecation: model= is the preferred parameter name
|
||||
# llm= still works but shows deprecation warning
|
||||
if llm is not None and model is None:
|
||||
import warnings
|
||||
warnings.warn(
|
||||
"Parameter 'llm' is deprecated, use 'model' instead. "
|
||||
"Example: Agent(model='gpt-4o-mini') instead of Agent(llm='gpt-4o-mini')",
|
||||
DeprecationWarning,
|
||||
stacklevel=2
|
||||
)
|
||||
# model= is the preferred parameter (no warning)
|
||||
if model is not None:
|
||||
llm = model # model= takes precedence
|
||||
|
||||
# Store rate limiter (optional, zero overhead when None)
|
||||
self._rate_limiter = rate_limiter
|
||||
|
||||
@@ -51,10 +51,17 @@ class BackgroundRunner:
|
||||
"""
|
||||
self.config = config or BackgroundConfig()
|
||||
self._tasks: Dict[str, BackgroundTask] = {}
|
||||
self._semaphore = asyncio.Semaphore(self.config.max_concurrent_tasks)
|
||||
# Lazily create asyncio.Semaphore() to avoid Python 3.9 event loop issues
|
||||
self._semaphore: Optional[asyncio.Semaphore] = None
|
||||
self._running = False
|
||||
self._cleanup_task: Optional[asyncio.Task] = None
|
||||
|
||||
def _get_semaphore(self) -> asyncio.Semaphore:
|
||||
"""Get or create the semaphore lazily (Python 3.9 compatible)."""
|
||||
if self._semaphore is None:
|
||||
self._semaphore = asyncio.Semaphore(self.config.max_concurrent_tasks)
|
||||
return self._semaphore
|
||||
|
||||
@property
|
||||
def tasks(self) -> List[BackgroundTask]:
|
||||
"""Get all tasks."""
|
||||
@@ -109,7 +116,7 @@ class BackgroundRunner:
|
||||
|
||||
# Create the execution coroutine
|
||||
async def execute():
|
||||
async with self._semaphore:
|
||||
async with self._get_semaphore():
|
||||
task.start()
|
||||
logger.info(f"Background task started: {task.name} ({task.id})")
|
||||
|
||||
|
||||
@@ -48,7 +48,16 @@ class BackgroundTask:
|
||||
_cancel_event: Optional[asyncio.Event] = field(default=None, repr=False)
|
||||
|
||||
def __post_init__(self):
|
||||
self._cancel_event = asyncio.Event()
|
||||
# Lazily create asyncio.Event() to avoid Python 3.9 event loop issues
|
||||
self._cancel_event = None
|
||||
# Simple flag for sync cancellation check (doesn't require event loop)
|
||||
self._cancelled = False
|
||||
|
||||
def _get_cancel_event(self) -> asyncio.Event:
|
||||
"""Get or create the cancel event lazily (Python 3.9 compatible)."""
|
||||
if self._cancel_event is None:
|
||||
self._cancel_event = asyncio.Event()
|
||||
return self._cancel_event
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
@@ -93,7 +102,10 @@ class BackgroundTask:
|
||||
|
||||
def cancel(self):
|
||||
"""Request task cancellation."""
|
||||
if self._cancel_event:
|
||||
# Set simple flag (works without event loop)
|
||||
self._cancelled = True
|
||||
# Also set the event if it exists (for async waiters)
|
||||
if self._cancel_event is not None:
|
||||
self._cancel_event.set()
|
||||
self.status = TaskStatus.CANCELLED
|
||||
self.completed_at = datetime.now()
|
||||
@@ -135,6 +147,10 @@ class BackgroundTask:
|
||||
|
||||
def should_cancel(self) -> bool:
|
||||
"""Check if cancellation was requested."""
|
||||
# Check simple flag first (works without event loop)
|
||||
if self._cancelled:
|
||||
return True
|
||||
# Also check event if it exists
|
||||
return self._cancel_event is not None and self._cancel_event.is_set()
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
|
||||
@@ -19,6 +19,14 @@ from .types import (
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _parse_iso_timestamp(timestamp: str) -> datetime:
|
||||
"""Parse ISO format timestamp, handling 'Z' suffix for Python 3.9 compatibility."""
|
||||
# Python 3.9's fromisoformat() doesn't support 'Z' suffix
|
||||
if timestamp.endswith('Z'):
|
||||
timestamp = timestamp[:-1] + '+00:00'
|
||||
return datetime.fromisoformat(timestamp)
|
||||
|
||||
# Protected paths that should never be checkpointed
|
||||
PROTECTED_PATHS = [
|
||||
os.path.expanduser("~"),
|
||||
@@ -275,7 +283,7 @@ class CheckpointService:
|
||||
id=commit_hash,
|
||||
short_id=commit_hash[:8],
|
||||
message=message,
|
||||
timestamp=datetime.fromisoformat(timestamp)
|
||||
timestamp=_parse_iso_timestamp(timestamp)
|
||||
)
|
||||
|
||||
self._checkpoints.append(checkpoint)
|
||||
@@ -321,7 +329,7 @@ class CheckpointService:
|
||||
id=checkpoint_id,
|
||||
short_id=checkpoint_id[:8],
|
||||
message=message,
|
||||
timestamp=datetime.fromisoformat(timestamp)
|
||||
timestamp=_parse_iso_timestamp(timestamp)
|
||||
)
|
||||
|
||||
self._emit(CheckpointEvent.CHECKPOINT_RESTORED, checkpoint)
|
||||
@@ -450,7 +458,7 @@ class CheckpointService:
|
||||
id=parts[0],
|
||||
short_id=parts[0][:8],
|
||||
message=parts[1],
|
||||
timestamp=datetime.fromisoformat(parts[2])
|
||||
timestamp=_parse_iso_timestamp(parts[2])
|
||||
))
|
||||
|
||||
return checkpoints
|
||||
|
||||
@@ -11,6 +11,15 @@ from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ..paths import get_checkpoints_dir
|
||||
|
||||
|
||||
def _parse_iso_timestamp(timestamp: str) -> datetime:
|
||||
"""Parse ISO format timestamp, handling 'Z' suffix for Python 3.9 compatibility."""
|
||||
if timestamp.endswith('Z'):
|
||||
timestamp = timestamp[:-1] + '+00:00'
|
||||
return datetime.fromisoformat(timestamp)
|
||||
|
||||
|
||||
class CheckpointEvent(str, Enum):
|
||||
"""Events emitted by the checkpoint service."""
|
||||
@@ -46,8 +55,8 @@ class CheckpointConfig:
|
||||
if self.storage_dir:
|
||||
self.storage_dir = os.path.expanduser(self.storage_dir)
|
||||
else:
|
||||
# Default storage in user's home directory
|
||||
self.storage_dir = os.path.expanduser("~/.praison/checkpoints")
|
||||
# Default storage in user's home directory (uses centralized paths - DRY)
|
||||
self.storage_dir = str(get_checkpoints_dir())
|
||||
|
||||
def get_checkpoint_dir(self) -> str:
|
||||
"""Get the checkpoint directory for this workspace."""
|
||||
@@ -77,7 +86,7 @@ class Checkpoint:
|
||||
id=commit_hash,
|
||||
short_id=commit_hash[:8],
|
||||
message=message,
|
||||
timestamp=datetime.fromisoformat(timestamp) if isinstance(timestamp, str) else timestamp
|
||||
timestamp=_parse_iso_timestamp(timestamp) if isinstance(timestamp, str) else timestamp
|
||||
)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
Conditions Module - Unified condition evaluation for workflows.
|
||||
|
||||
This module provides a protocol-driven approach to condition evaluation,
|
||||
enabling DRY condition handling across AgentFlow and AgentTeam.
|
||||
|
||||
Exports:
|
||||
- ConditionProtocol: Protocol interface for condition implementations
|
||||
- ExpressionCondition: String-based conditions like "{{score}} > 80"
|
||||
- DictCondition: Dict-based routing conditions
|
||||
- evaluate_condition: Standalone function for condition evaluation
|
||||
"""
|
||||
from .protocols import ConditionProtocol
|
||||
from .evaluator import (
|
||||
ExpressionCondition,
|
||||
DictCondition,
|
||||
evaluate_condition,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'ConditionProtocol',
|
||||
'ExpressionCondition',
|
||||
'DictCondition',
|
||||
'evaluate_condition',
|
||||
]
|
||||
@@ -0,0 +1,284 @@
|
||||
"""
|
||||
Condition Evaluator - Shared condition evaluation logic.
|
||||
|
||||
This module provides the shared condition evaluation logic used by both
|
||||
AgentFlow (string-based conditions) and AgentTeam (dict-based routing).
|
||||
|
||||
The implementation is extracted from workflows.py _evaluate_condition()
|
||||
to enable DRY condition handling across the codebase.
|
||||
"""
|
||||
import re
|
||||
import logging
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ExpressionCondition:
|
||||
"""
|
||||
String-based condition evaluator for expressions like "{{score}} > 80".
|
||||
|
||||
Supports:
|
||||
- Numeric comparison: "{{var}} > 80", "{{var}} >= 50", "{{var}} < 10"
|
||||
- String equality: "{{var}} == approved", "{{var}} != rejected"
|
||||
- Contains check: "error in {{message}}", "{{status}} contains success"
|
||||
- Boolean: "{{flag}}" (truthy check)
|
||||
- Nested property: "{{item.score}} >= 60"
|
||||
|
||||
Example:
|
||||
```python
|
||||
cond = ExpressionCondition("{{score}} > 80")
|
||||
result = cond.evaluate({"score": 90}) # True
|
||||
```
|
||||
"""
|
||||
|
||||
def __init__(self, expression: str):
|
||||
"""
|
||||
Initialize with a condition expression.
|
||||
|
||||
Args:
|
||||
expression: Condition string with {{var}} placeholders.
|
||||
"""
|
||||
self.expression = expression
|
||||
|
||||
def evaluate(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Evaluate the condition against the given context.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variables for evaluation.
|
||||
Special key 'previous_output' is also substituted.
|
||||
|
||||
Returns:
|
||||
Boolean result of condition evaluation.
|
||||
Returns False on evaluation errors (fail-safe).
|
||||
"""
|
||||
return evaluate_condition(
|
||||
self.expression,
|
||||
context,
|
||||
previous_output=context.get('previous_output')
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"ExpressionCondition({self.expression!r})"
|
||||
|
||||
|
||||
class DictCondition:
|
||||
"""
|
||||
Dict-based condition evaluator for routing decisions.
|
||||
|
||||
Used by AgentTeam for task routing based on decision keys.
|
||||
|
||||
Example:
|
||||
```python
|
||||
cond = DictCondition(
|
||||
{"approved": ["publish"], "rejected": ["revise"]},
|
||||
key="decision"
|
||||
)
|
||||
result = cond.evaluate({"decision": "approved"}) # True
|
||||
targets = cond.get_target({"decision": "approved"}) # ["publish"]
|
||||
```
|
||||
"""
|
||||
|
||||
def __init__(self, routes: Dict[str, List[str]], key: str = "decision"):
|
||||
"""
|
||||
Initialize with routing configuration.
|
||||
|
||||
Args:
|
||||
routes: Dict mapping decision values to target task lists.
|
||||
key: Context key to read decision value from.
|
||||
"""
|
||||
self.routes = routes
|
||||
self.key = key
|
||||
|
||||
def evaluate(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Check if the context contains a valid routing decision.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing the decision key.
|
||||
|
||||
Returns:
|
||||
True if decision value matches a route key.
|
||||
"""
|
||||
decision = context.get(self.key, "")
|
||||
if isinstance(decision, str):
|
||||
decision = decision.lower()
|
||||
return decision in self.routes
|
||||
|
||||
def get_target(self, context: Dict[str, Any]) -> List[str]:
|
||||
"""
|
||||
Get target tasks based on the decision value.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing the decision key.
|
||||
|
||||
Returns:
|
||||
List of target task names, or empty list if no match.
|
||||
"""
|
||||
decision = context.get(self.key, "")
|
||||
if isinstance(decision, str):
|
||||
decision = decision.lower()
|
||||
targets = self.routes.get(decision, [])
|
||||
if isinstance(targets, str):
|
||||
return [targets]
|
||||
return targets if targets else []
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"DictCondition(routes={self.routes!r}, key={self.key!r})"
|
||||
|
||||
|
||||
def evaluate_condition(
|
||||
condition: str,
|
||||
variables: Dict[str, Any],
|
||||
previous_output: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Evaluate a condition expression with variable substitution.
|
||||
|
||||
This is the shared condition evaluation function used by both
|
||||
AgentFlow and AgentTeam. It supports various condition formats.
|
||||
|
||||
Supported formats:
|
||||
- Numeric comparison: "{{var}} > 80", "{{var}} >= 50", "{{var}} < 10"
|
||||
- String equality: "{{var}} == approved", "{{var}} != rejected"
|
||||
- Contains check: "error in {{message}}", "{{status}} contains success"
|
||||
- Boolean: "{{flag}}" (truthy check)
|
||||
- Nested property: "{{item.score}} >= 60"
|
||||
|
||||
Args:
|
||||
condition: Condition expression with {{var}} placeholders.
|
||||
variables: Dictionary containing variables for substitution.
|
||||
previous_output: Optional output from previous step (substitutes {{previous_output}}).
|
||||
|
||||
Returns:
|
||||
Boolean result of condition evaluation.
|
||||
Returns False on evaluation errors (fail-safe).
|
||||
|
||||
Example:
|
||||
```python
|
||||
result = evaluate_condition("{{score}} > 80", {"score": 90}) # True
|
||||
result = evaluate_condition("{{status}} == approved", {"status": "approved"}) # True
|
||||
result = evaluate_condition("error in {{message}}", {"message": "An error occurred"}) # True
|
||||
```
|
||||
"""
|
||||
# Substitute variables in condition
|
||||
substituted = condition
|
||||
|
||||
# Handle nested property access like {{item.score}}
|
||||
def get_nested_value(var_path: str, vars_dict: Dict[str, Any]) -> Any:
|
||||
parts = var_path.split('.')
|
||||
value = vars_dict
|
||||
for part in parts:
|
||||
if isinstance(value, dict):
|
||||
value = value.get(part)
|
||||
else:
|
||||
return None
|
||||
return value
|
||||
|
||||
# First substitute {{previous_output}} if provided (before general variable substitution)
|
||||
if previous_output is not None:
|
||||
substituted = substituted.replace("{{previous_output}}", str(previous_output))
|
||||
|
||||
# Find all {{var}} patterns and substitute
|
||||
pattern = r'\{\{([^}]+)\}\}'
|
||||
matches = re.findall(pattern, substituted) # Use substituted, not condition
|
||||
|
||||
for var_name in matches:
|
||||
# Skip previous_output as it's already handled
|
||||
if var_name == 'previous_output':
|
||||
continue
|
||||
|
||||
if '.' in var_name:
|
||||
# Nested property access
|
||||
value = get_nested_value(var_name, variables)
|
||||
else:
|
||||
value = variables.get(var_name)
|
||||
|
||||
if value is None:
|
||||
value = ""
|
||||
|
||||
# Replace the placeholder with the value
|
||||
placeholder = f"{{{{{var_name}}}}}"
|
||||
if isinstance(value, (int, float)):
|
||||
substituted = substituted.replace(placeholder, str(value))
|
||||
elif isinstance(value, bool):
|
||||
substituted = substituted.replace(placeholder, str(value).lower())
|
||||
else:
|
||||
substituted = substituted.replace(placeholder, str(value))
|
||||
|
||||
# Now evaluate the substituted condition
|
||||
try:
|
||||
# Handle different condition formats
|
||||
|
||||
# Check if we have unsubstituted empty values in comparisons
|
||||
# If a variable was missing, it becomes empty string which can cause issues
|
||||
if ' > ' in substituted or ' < ' in substituted or ' >= ' in substituted or ' <= ' in substituted:
|
||||
# Check for empty left side in comparison (missing variable)
|
||||
if substituted.strip().startswith('>') or substituted.strip().startswith('<'):
|
||||
return False
|
||||
if substituted.strip().startswith('='):
|
||||
return False
|
||||
|
||||
# Numeric comparisons: "90 > 80", "50 >= 50", "10 < 20", etc.
|
||||
numeric_pattern = r'^(-?\d+(?:\.\d+)?)\s*(>|>=|<|<=|==|!=)\s*(-?\d+(?:\.\d+)?)$'
|
||||
numeric_match = re.match(numeric_pattern, substituted.strip())
|
||||
if numeric_match:
|
||||
left = float(numeric_match.group(1))
|
||||
op = numeric_match.group(2)
|
||||
right = float(numeric_match.group(3))
|
||||
|
||||
if op == '>':
|
||||
return left > right
|
||||
if op == '>=':
|
||||
return left >= right
|
||||
if op == '<':
|
||||
return left < right
|
||||
if op == '<=':
|
||||
return left <= right
|
||||
if op == '==':
|
||||
return left == right
|
||||
if op == '!=':
|
||||
return left != right
|
||||
|
||||
# String equality: "approved == approved", "status != rejected"
|
||||
string_eq_pattern = r'^(.+?)\s*(==|!=)\s*(.+)$'
|
||||
string_match = re.match(string_eq_pattern, substituted.strip())
|
||||
if string_match:
|
||||
left = string_match.group(1).strip()
|
||||
op = string_match.group(2)
|
||||
right = string_match.group(3).strip()
|
||||
|
||||
if op == '==':
|
||||
return left == right
|
||||
if op == '!=':
|
||||
return left != right
|
||||
|
||||
# Contains check: "error in some message", "status contains success"
|
||||
if ' in ' in substituted:
|
||||
parts = substituted.split(' in ', 1)
|
||||
if len(parts) == 2:
|
||||
needle = parts[0].strip()
|
||||
haystack = parts[1].strip()
|
||||
return needle.lower() in haystack.lower()
|
||||
|
||||
if ' contains ' in substituted:
|
||||
parts = substituted.split(' contains ', 1)
|
||||
if len(parts) == 2:
|
||||
haystack = parts[0].strip()
|
||||
needle = parts[1].strip()
|
||||
return needle.lower() in haystack.lower()
|
||||
|
||||
# Boolean check: truthy evaluation
|
||||
# Handle "true", "false", "True", "False"
|
||||
if substituted.strip().lower() == 'true':
|
||||
return True
|
||||
if substituted.strip().lower() == 'false':
|
||||
return False
|
||||
|
||||
# Non-empty string is truthy
|
||||
return bool(substituted.strip())
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Condition evaluation failed for '{condition}': {e}")
|
||||
return False
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
Condition Protocol Definitions.
|
||||
|
||||
Provides Protocol interfaces that define the minimal contract for condition implementations.
|
||||
This enables:
|
||||
- Unified condition evaluation across AgentFlow and AgentTeam
|
||||
- Custom condition implementations
|
||||
- Type checking with static analyzers
|
||||
- Mocking conditions in tests
|
||||
|
||||
These protocols are lightweight and have zero performance impact.
|
||||
"""
|
||||
from typing import Protocol, runtime_checkable, Dict, Any, List, Optional
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ConditionProtocol(Protocol):
|
||||
"""
|
||||
Minimal Protocol for condition implementations.
|
||||
|
||||
This defines the essential interface that any condition must provide.
|
||||
It enables unified condition evaluation across AgentFlow (string-based)
|
||||
and AgentTeam (dict-based) systems.
|
||||
|
||||
Example:
|
||||
```python
|
||||
# Create a custom condition
|
||||
class ScoreCondition:
|
||||
def __init__(self, threshold: int):
|
||||
self.threshold = threshold
|
||||
|
||||
def evaluate(self, context: Dict[str, Any]) -> bool:
|
||||
return context.get("score", 0) > self.threshold
|
||||
|
||||
# Use in workflows
|
||||
cond: ConditionProtocol = ScoreCondition(80)
|
||||
result = cond.evaluate({"score": 90}) # True
|
||||
```
|
||||
"""
|
||||
|
||||
def evaluate(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Evaluate the condition against the given context.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variables for evaluation.
|
||||
May include workflow variables, previous outputs, etc.
|
||||
|
||||
Returns:
|
||||
Boolean result of condition evaluation.
|
||||
Returns False on evaluation errors (fail-safe).
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class RoutingConditionProtocol(ConditionProtocol, Protocol):
|
||||
"""
|
||||
Extended Protocol for conditions that support routing to targets.
|
||||
|
||||
This extends ConditionProtocol with the ability to return target
|
||||
tasks/steps based on the condition evaluation. Used primarily
|
||||
by AgentTeam for task routing.
|
||||
|
||||
Example:
|
||||
```python
|
||||
class ApprovalCondition:
|
||||
def __init__(self, routes: Dict[str, List[str]]):
|
||||
self.routes = routes
|
||||
|
||||
def evaluate(self, context: Dict[str, Any]) -> bool:
|
||||
decision = context.get("decision", "")
|
||||
return decision in self.routes
|
||||
|
||||
def get_target(self, context: Dict[str, Any]) -> List[str]:
|
||||
decision = context.get("decision", "")
|
||||
return self.routes.get(decision, [])
|
||||
```
|
||||
"""
|
||||
|
||||
def get_target(self, context: Dict[str, Any]) -> List[str]:
|
||||
"""
|
||||
Get the target tasks/steps based on condition evaluation.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variables for evaluation.
|
||||
|
||||
Returns:
|
||||
List of target task/step names to route to.
|
||||
Returns empty list if no match found.
|
||||
"""
|
||||
...
|
||||
@@ -16,6 +16,7 @@ from typing import Any, Dict
|
||||
# =============================================================================
|
||||
|
||||
MEMORY_PRESETS: Dict[str, Dict[str, Any]] = {
|
||||
# Backend presets
|
||||
"file": {"backend": "file"},
|
||||
"sqlite": {"backend": "sqlite"},
|
||||
"redis": {"backend": "redis"},
|
||||
@@ -23,6 +24,8 @@ MEMORY_PRESETS: Dict[str, Dict[str, Any]] = {
|
||||
"postgresql": {"backend": "postgres"},
|
||||
"mem0": {"backend": "mem0"},
|
||||
"mongodb": {"backend": "mongodb"},
|
||||
# Feature presets
|
||||
"learn": {"backend": "file", "learn": True}, # Enable Agent Learn with file backend
|
||||
}
|
||||
|
||||
MEMORY_URL_SCHEMES: Dict[str, str] = {
|
||||
|
||||
@@ -86,7 +86,8 @@ class RateLimiter:
|
||||
else:
|
||||
self._tokens = float('inf')
|
||||
self._last_update = time.monotonic()
|
||||
self._lock = asyncio.Lock()
|
||||
# Lazily create asyncio.Lock() to avoid Python 3.9 event loop issues
|
||||
self._lock = None
|
||||
|
||||
# Token-based limiting
|
||||
if self.tokens_per_minute is not None:
|
||||
@@ -95,7 +96,8 @@ class RateLimiter:
|
||||
else:
|
||||
self._api_tokens = float('inf')
|
||||
self._api_tokens_last_update = time.monotonic()
|
||||
self._api_tokens_lock = asyncio.Lock()
|
||||
# Lazily create asyncio.Lock() to avoid Python 3.9 event loop issues
|
||||
self._api_tokens_lock = None
|
||||
|
||||
# Default implementations (can be overridden for testing)
|
||||
if self._get_time is None:
|
||||
@@ -105,6 +107,18 @@ class RateLimiter:
|
||||
if self._async_sleep is None:
|
||||
self._async_sleep = asyncio.sleep
|
||||
|
||||
def _get_lock(self) -> asyncio.Lock:
|
||||
"""Get or create the request lock lazily (Python 3.9 compatible)."""
|
||||
if self._lock is None:
|
||||
self._lock = asyncio.Lock()
|
||||
return self._lock
|
||||
|
||||
def _get_api_tokens_lock(self) -> asyncio.Lock:
|
||||
"""Get or create the API tokens lock lazily (Python 3.9 compatible)."""
|
||||
if self._api_tokens_lock is None:
|
||||
self._api_tokens_lock = asyncio.Lock()
|
||||
return self._api_tokens_lock
|
||||
|
||||
@property
|
||||
def _rate(self) -> float:
|
||||
"""Requests per second."""
|
||||
@@ -203,7 +217,7 @@ class RateLimiter:
|
||||
if self.requests_per_minute is None:
|
||||
return
|
||||
|
||||
async with self._lock:
|
||||
async with self._get_lock():
|
||||
self._refill()
|
||||
|
||||
wait = self._wait_time()
|
||||
@@ -228,7 +242,7 @@ class RateLimiter:
|
||||
if self.tokens_per_minute is None:
|
||||
return
|
||||
|
||||
async with self._api_tokens_lock:
|
||||
async with self._get_api_tokens_lock():
|
||||
self._refill_api_tokens()
|
||||
|
||||
wait = self._wait_time_for_tokens(num_tokens)
|
||||
|
||||
@@ -25,11 +25,10 @@ def get_default_auth_filepath() -> str:
|
||||
Returns:
|
||||
Path to mcp-auth.json in user's praison config directory
|
||||
"""
|
||||
# Use ~/.praison/ directory for config
|
||||
home = Path.home()
|
||||
praison_dir = home / ".praison"
|
||||
praison_dir.mkdir(parents=True, exist_ok=True)
|
||||
return str(praison_dir / "mcp-auth.json")
|
||||
# Use centralized paths (DRY)
|
||||
from ..paths import get_mcp_auth_path, ensure_dir, get_data_dir
|
||||
ensure_dir(get_data_dir())
|
||||
return str(get_mcp_auth_path())
|
||||
|
||||
|
||||
class MCPAuthStorage:
|
||||
|
||||
@@ -88,9 +88,10 @@ class BaseStore(ABC):
|
||||
pass
|
||||
|
||||
def _default_path(self) -> str:
|
||||
"""Default storage path."""
|
||||
base = Path.home() / ".praison" / "learn" / self.scope / self.user_id
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
"""Default storage path (uses centralized paths - DRY)."""
|
||||
from ...paths import get_learn_dir, ensure_dir
|
||||
base = get_learn_dir() / self.scope / self.user_id
|
||||
ensure_dir(base)
|
||||
return str(base / f"{self.store_name}.json")
|
||||
|
||||
def _load(self) -> None:
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
"""
|
||||
Centralized Path Utilities for PraisonAI Agents.
|
||||
|
||||
All persistent data uses ~/.praisonai/ by default.
|
||||
Override with PRAISONAI_HOME environment variable.
|
||||
|
||||
This module provides a single source of truth for all data storage paths,
|
||||
eliminating hardcoded paths throughout the codebase (DRY principle).
|
||||
|
||||
Usage:
|
||||
from praisonaiagents.paths import get_data_dir, get_sessions_dir
|
||||
|
||||
# Get user data directory
|
||||
data_dir = get_data_dir() # ~/.praisonai/
|
||||
|
||||
# Get specific subdirectories
|
||||
sessions_dir = get_sessions_dir() # ~/.praisonai/sessions/
|
||||
|
||||
# Override with environment variable
|
||||
# export PRAISONAI_HOME=/custom/path
|
||||
# data_dir = get_data_dir() # /custom/path/
|
||||
|
||||
Backward Compatibility:
|
||||
If ~/.praisonai/ doesn't exist but ~/.praison/ does, the legacy
|
||||
path will be used with a deprecation warning. Run 'praisonai migrate-data'
|
||||
to migrate to the new location.
|
||||
"""
|
||||
|
||||
import os
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional, Union
|
||||
|
||||
# Environment variable for override
|
||||
ENV_VAR = "PRAISONAI_HOME"
|
||||
|
||||
# Default directory name (branded)
|
||||
DEFAULT_DIR_NAME = ".praisonai"
|
||||
|
||||
# Legacy directory name (for backward compat)
|
||||
LEGACY_DIR_NAME = ".praison"
|
||||
|
||||
# Cache for data dir to avoid repeated filesystem checks
|
||||
_data_dir_cache: Optional[Path] = None
|
||||
|
||||
|
||||
def _clear_cache() -> None:
|
||||
"""Clear the data dir cache. Used for testing."""
|
||||
global _data_dir_cache
|
||||
_data_dir_cache = None
|
||||
|
||||
|
||||
def get_data_dir() -> Path:
|
||||
"""
|
||||
Get PraisonAI data directory.
|
||||
|
||||
Priority:
|
||||
1. PRAISONAI_HOME env var
|
||||
2. ~/.praisonai/ (default)
|
||||
3. ~/.praison/ (legacy fallback with warning)
|
||||
|
||||
Returns:
|
||||
Path to data directory
|
||||
|
||||
Example:
|
||||
>>> from praisonaiagents.paths import get_data_dir
|
||||
>>> data_dir = get_data_dir()
|
||||
>>> print(data_dir)
|
||||
/home/user/.praisonai
|
||||
"""
|
||||
global _data_dir_cache
|
||||
|
||||
# Check env var first (always takes precedence, no caching)
|
||||
env_path = os.environ.get(ENV_VAR)
|
||||
if env_path:
|
||||
return Path(env_path).expanduser()
|
||||
|
||||
# Return cached value if available
|
||||
if _data_dir_cache is not None:
|
||||
return _data_dir_cache
|
||||
|
||||
home = Path.home()
|
||||
|
||||
# Check new location first
|
||||
new_path = home / DEFAULT_DIR_NAME
|
||||
if new_path.exists():
|
||||
_data_dir_cache = new_path
|
||||
return new_path
|
||||
|
||||
# Check legacy location (backward compat)
|
||||
legacy_path = home / LEGACY_DIR_NAME
|
||||
if legacy_path.exists():
|
||||
warnings.warn(
|
||||
f"Using legacy data directory {legacy_path}. "
|
||||
f"Run 'praisonai migrate-data' to migrate to {new_path}.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2
|
||||
)
|
||||
_data_dir_cache = legacy_path
|
||||
return legacy_path
|
||||
|
||||
# Default to new location (will be created when needed)
|
||||
_data_dir_cache = new_path
|
||||
return new_path
|
||||
|
||||
|
||||
def get_sessions_dir() -> Path:
|
||||
"""
|
||||
Get sessions directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/sessions/
|
||||
"""
|
||||
return get_data_dir() / "sessions"
|
||||
|
||||
|
||||
def get_skills_dir() -> Path:
|
||||
"""
|
||||
Get user skills directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/skills/
|
||||
"""
|
||||
return get_data_dir() / "skills"
|
||||
|
||||
|
||||
def get_plugins_dir() -> Path:
|
||||
"""
|
||||
Get user plugins directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/plugins/
|
||||
"""
|
||||
return get_data_dir() / "plugins"
|
||||
|
||||
|
||||
def get_mcp_dir() -> Path:
|
||||
"""
|
||||
Get MCP config directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/mcp/
|
||||
"""
|
||||
return get_data_dir() / "mcp"
|
||||
|
||||
|
||||
def get_docs_dir() -> Path:
|
||||
"""
|
||||
Get docs directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/docs/
|
||||
"""
|
||||
return get_data_dir() / "docs"
|
||||
|
||||
|
||||
def get_rules_dir() -> Path:
|
||||
"""
|
||||
Get rules directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/rules/
|
||||
"""
|
||||
return get_data_dir() / "rules"
|
||||
|
||||
|
||||
def get_permissions_dir() -> Path:
|
||||
"""
|
||||
Get permissions directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/permissions/
|
||||
"""
|
||||
return get_data_dir() / "permissions"
|
||||
|
||||
|
||||
def get_storage_dir() -> Path:
|
||||
"""
|
||||
Get generic storage directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/storage/
|
||||
"""
|
||||
return get_data_dir() / "storage"
|
||||
|
||||
|
||||
def get_checkpoints_dir() -> Path:
|
||||
"""
|
||||
Get checkpoints directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/checkpoints/
|
||||
"""
|
||||
return get_data_dir() / "checkpoints"
|
||||
|
||||
|
||||
def get_snapshots_dir() -> Path:
|
||||
"""
|
||||
Get snapshots directory.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/snapshots/
|
||||
"""
|
||||
return get_data_dir() / "snapshots"
|
||||
|
||||
|
||||
def get_learn_dir() -> Path:
|
||||
"""
|
||||
Get learn directory for learning stores.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/learn/
|
||||
"""
|
||||
return get_data_dir() / "learn"
|
||||
|
||||
|
||||
def get_cache_dir() -> Path:
|
||||
"""
|
||||
Get cache directory (disposable data).
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/cache/
|
||||
"""
|
||||
return get_data_dir() / "cache"
|
||||
|
||||
|
||||
def get_mcp_auth_path() -> Path:
|
||||
"""
|
||||
Get path to MCP auth storage file.
|
||||
|
||||
Returns:
|
||||
Path to ~/.praisonai/mcp-auth.json
|
||||
"""
|
||||
return get_data_dir() / "mcp-auth.json"
|
||||
|
||||
|
||||
def get_project_data_dir(project_path: Optional[Union[str, Path]] = None) -> Path:
|
||||
"""
|
||||
Get project-level data directory.
|
||||
|
||||
Args:
|
||||
project_path: Project root (defaults to cwd)
|
||||
|
||||
Returns:
|
||||
Path to .praisonai/ in project
|
||||
|
||||
Example:
|
||||
>>> from praisonaiagents.paths import get_project_data_dir
|
||||
>>> project_dir = get_project_data_dir("/path/to/project")
|
||||
>>> print(project_dir)
|
||||
/path/to/project/.praisonai
|
||||
"""
|
||||
if project_path is None:
|
||||
base = Path.cwd()
|
||||
elif isinstance(project_path, str):
|
||||
base = Path(project_path)
|
||||
else:
|
||||
base = project_path
|
||||
return base / DEFAULT_DIR_NAME
|
||||
|
||||
|
||||
def ensure_dir(path: Union[str, Path]) -> Path:
|
||||
"""
|
||||
Ensure a directory exists, creating it if necessary.
|
||||
|
||||
Args:
|
||||
path: Directory path to ensure exists
|
||||
|
||||
Returns:
|
||||
Path object for the directory
|
||||
|
||||
Example:
|
||||
>>> from praisonaiagents.paths import ensure_dir, get_sessions_dir
|
||||
>>> sessions = ensure_dir(get_sessions_dir())
|
||||
"""
|
||||
if isinstance(path, str):
|
||||
path = Path(path)
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def get_all_paths() -> Dict[str, Path]:
|
||||
"""
|
||||
Get all PraisonAI data paths.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping path names to Path objects
|
||||
|
||||
Example:
|
||||
>>> from praisonaiagents.paths import get_all_paths
|
||||
>>> paths = get_all_paths()
|
||||
>>> for name, path in paths.items():
|
||||
... print(f"{name}: {path}")
|
||||
"""
|
||||
return {
|
||||
"data_dir": get_data_dir(),
|
||||
"sessions": get_sessions_dir(),
|
||||
"skills": get_skills_dir(),
|
||||
"plugins": get_plugins_dir(),
|
||||
"mcp": get_mcp_dir(),
|
||||
"docs": get_docs_dir(),
|
||||
"rules": get_rules_dir(),
|
||||
"permissions": get_permissions_dir(),
|
||||
"storage": get_storage_dir(),
|
||||
"checkpoints": get_checkpoints_dir(),
|
||||
"snapshots": get_snapshots_dir(),
|
||||
"learn": get_learn_dir(),
|
||||
"cache": get_cache_dir(),
|
||||
"mcp_auth": get_mcp_auth_path(),
|
||||
}
|
||||
@@ -14,10 +14,12 @@ from typing import Any, Callable, Dict, List, Optional
|
||||
from .rules import PermissionRule, PermissionAction, PermissionResult, PersistentApproval
|
||||
from .doom_loop import DoomLoopDetector
|
||||
|
||||
from ..paths import get_permissions_dir
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default storage path
|
||||
DEFAULT_PERMISSIONS_DIR = os.path.expanduser("~/.praison/permissions")
|
||||
# Default storage path (uses centralized paths - DRY)
|
||||
DEFAULT_PERMISSIONS_DIR = str(get_permissions_dir())
|
||||
|
||||
|
||||
class PermissionManager:
|
||||
|
||||
@@ -36,16 +36,21 @@ class PlanStorage:
|
||||
todos_dir: Directory for todo files
|
||||
"""
|
||||
|
||||
DEFAULT_BASE_PATH = ".praison"
|
||||
DEFAULT_BASE_PATH = ".praisonai" # Updated to use branded path
|
||||
|
||||
def __init__(self, base_path: Optional[str] = None):
|
||||
"""
|
||||
Initialize PlanStorage.
|
||||
|
||||
Args:
|
||||
base_path: Base directory for storage. Defaults to .praison/
|
||||
base_path: Base directory for storage. Defaults to .praisonai/
|
||||
"""
|
||||
self.base_path = base_path or self.DEFAULT_BASE_PATH
|
||||
# Use centralized paths for project-level data (DRY)
|
||||
if base_path is None:
|
||||
from ..paths import get_project_data_dir
|
||||
self.base_path = str(get_project_data_dir())
|
||||
else:
|
||||
self.base_path = base_path
|
||||
self.plans_dir = os.path.join(self.base_path, "plans")
|
||||
self.todos_dir = os.path.join(self.base_path, "todos")
|
||||
|
||||
|
||||
@@ -17,10 +17,12 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from ..paths import get_sessions_dir
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default session directory
|
||||
DEFAULT_SESSION_DIR = os.path.expanduser("~/.praison/sessions")
|
||||
# Default session directory (uses centralized paths - DRY)
|
||||
DEFAULT_SESSION_DIR = str(get_sessions_dir())
|
||||
|
||||
# Default limits
|
||||
DEFAULT_MAX_MESSAGES = 100
|
||||
|
||||
@@ -14,10 +14,12 @@ import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from ..paths import get_snapshots_dir
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default snapshot directory
|
||||
DEFAULT_SNAPSHOT_DIR = os.path.expanduser("~/.praison/snapshots")
|
||||
# Default snapshot directory (uses centralized paths - DRY)
|
||||
DEFAULT_SNAPSHOT_DIR = str(get_snapshots_dir())
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -19,8 +19,13 @@ import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from ..paths import get_storage_dir
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default storage directory (uses centralized paths - DRY)
|
||||
DEFAULT_STORAGE_DIR = str(get_storage_dir())
|
||||
|
||||
|
||||
class FileBackend:
|
||||
"""
|
||||
@@ -31,7 +36,7 @@ class FileBackend:
|
||||
|
||||
Example:
|
||||
```python
|
||||
backend = FileBackend(storage_dir="~/.praison/data")
|
||||
backend = FileBackend(storage_dir="~/.praisonai/storage")
|
||||
backend.save("session_123", {"messages": []})
|
||||
data = backend.load("session_123")
|
||||
```
|
||||
@@ -39,7 +44,7 @@ class FileBackend:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
storage_dir: str = "~/.praison/storage",
|
||||
storage_dir: str = None,
|
||||
suffix: str = ".json",
|
||||
pretty: bool = True,
|
||||
):
|
||||
@@ -51,7 +56,7 @@ class FileBackend:
|
||||
suffix: File suffix (default: .json)
|
||||
pretty: Use pretty-printed JSON
|
||||
"""
|
||||
self.storage_dir = Path(os.path.expanduser(storage_dir))
|
||||
self.storage_dir = Path(os.path.expanduser(storage_dir or DEFAULT_STORAGE_DIR))
|
||||
self.suffix = suffix
|
||||
self.pretty = pretty
|
||||
self._lock = threading.Lock()
|
||||
|
||||
@@ -47,6 +47,7 @@ class Task:
|
||||
name: Optional[str] = None,
|
||||
tools: Optional[List[Any]] = None,
|
||||
context: Optional[List[Union[str, List, 'Task']]] = None,
|
||||
depends_on: Optional[List[Union[str, List, 'Task']]] = None, # Alias for context (clearer semantics)
|
||||
async_execution: Optional[bool] = False,
|
||||
config: Optional[Dict[str, Any]] = None,
|
||||
output_file: Optional[str] = None,
|
||||
@@ -93,8 +94,17 @@ class Task:
|
||||
loop_var: str = "item",
|
||||
# Consolidated config objects (from Task)
|
||||
execution: Optional[Any] = None,
|
||||
routing: Optional[Any] = None,
|
||||
routing: Optional[Dict[str, List[str]]] = None, # Renamed from condition for clarity
|
||||
output_config: Optional[Any] = None,
|
||||
# ============================================================
|
||||
# UNIFIED CONDITION SYNTAX (same as AgentFlow)
|
||||
# ============================================================
|
||||
# String-based condition expression (e.g., "{{score}} > 80")
|
||||
when: Optional[str] = None,
|
||||
# Task to route to when condition is True
|
||||
then_task: Optional[str] = None,
|
||||
# Task to route to when condition is False
|
||||
else_task: Optional[str] = None,
|
||||
# Feature configs (from Task)
|
||||
autonomy: Optional[Any] = None,
|
||||
knowledge: Optional[Any] = None,
|
||||
@@ -136,7 +146,13 @@ class Task:
|
||||
self.expected_output = expected_output if expected_output is not None else "Complete the task successfully"
|
||||
self.agent = agent
|
||||
self.tools = tools if tools else []
|
||||
self.context = context if context else []
|
||||
# Handle depends_on as alias for context (depends_on takes precedence)
|
||||
if depends_on is not None:
|
||||
self.context = depends_on
|
||||
else:
|
||||
self.context = context if context else []
|
||||
# Store depends_on as property alias for context
|
||||
self._depends_on = self.context
|
||||
self.async_execution = async_execution
|
||||
self.config = config if config else {}
|
||||
self.output_file = output_file
|
||||
@@ -156,7 +172,17 @@ class Task:
|
||||
self.quality_check = quality_check
|
||||
self.rerun = rerun # Assigning the rerun parameter
|
||||
self.retain_full_context = retain_full_context
|
||||
self.guardrail = guardrail if guardrail is not None else guardrails # guardrails is alias
|
||||
# Handle guardrail/guardrails: guardrails (plural) is canonical, guardrail (singular) is deprecated
|
||||
if guardrail is not None and guardrails is None:
|
||||
import warnings
|
||||
warnings.warn(
|
||||
"Parameter 'guardrail' is deprecated, use 'guardrails' instead. "
|
||||
"Example: Task(guardrails=my_fn) instead of Task(guardrail=my_fn)",
|
||||
DeprecationWarning,
|
||||
stacklevel=2
|
||||
)
|
||||
# guardrails takes precedence over guardrail
|
||||
self.guardrail = guardrails if guardrails is not None else guardrail
|
||||
self.max_retries = max_retries
|
||||
self.retry_count = retry_count
|
||||
self._guardrail_fn = None
|
||||
@@ -182,8 +208,17 @@ class Task:
|
||||
self.loop_var = loop_var
|
||||
# Consolidated config objects (from Task)
|
||||
self.execution = execution
|
||||
self.routing = routing
|
||||
# Handle routing parameter - use routing if provided, else fall back to condition
|
||||
if routing is not None:
|
||||
self.condition = routing
|
||||
self.routing = self.condition # Alias for backward compat
|
||||
self.output_config = output_config
|
||||
# ============================================================
|
||||
# UNIFIED CONDITION SYNTAX (same as AgentFlow)
|
||||
# ============================================================
|
||||
self.when = when
|
||||
self.then_task = then_task
|
||||
self.else_task = else_task
|
||||
# Feature configs (from Task)
|
||||
self.autonomy = autonomy
|
||||
self.knowledge = knowledge
|
||||
@@ -258,6 +293,16 @@ class Task:
|
||||
# Initialize guardrail
|
||||
self._setup_guardrail()
|
||||
|
||||
@property
|
||||
def depends_on(self):
|
||||
"""Alias for context - returns the list of dependent tasks."""
|
||||
return self.context
|
||||
|
||||
@depends_on.setter
|
||||
def depends_on(self, value):
|
||||
"""Alias for context - sets the list of dependent tasks."""
|
||||
self.context = value
|
||||
|
||||
def _setup_guardrail(self):
|
||||
"""Setup the guardrail function based on the provided guardrail parameter."""
|
||||
if self.guardrail is None:
|
||||
@@ -316,6 +361,40 @@ class Task:
|
||||
def __str__(self):
|
||||
return f"Task(name='{self.name if self.name else 'None'}', description='{self.description}', agent='{self.agent.name if self.agent else 'None'}', status='{self.status}')"
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serialize the Task to a dictionary.
|
||||
|
||||
Returns:
|
||||
Dictionary representation of the Task.
|
||||
"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"action": self.action,
|
||||
"expected_output": self.expected_output,
|
||||
"status": self.status,
|
||||
"task_type": self.task_type,
|
||||
"tools": self.tools,
|
||||
"context": [str(c) if hasattr(c, '__str__') else c for c in self.context] if self.context else [],
|
||||
"next_tasks": self.next_tasks,
|
||||
"condition": self.condition,
|
||||
"routing": self.routing,
|
||||
"is_start": self.is_start,
|
||||
"max_retries": self.max_retries,
|
||||
"async_execution": self.async_execution,
|
||||
"output_file": self.output_file,
|
||||
"output_variable": self.output_variable,
|
||||
"retain_full_context": self.retain_full_context,
|
||||
"loop_over": self.loop_over,
|
||||
"loop_var": self.loop_var,
|
||||
"when": self.when,
|
||||
"then_task": self.then_task,
|
||||
"else_task": self.else_task,
|
||||
"agent_config": self.agent_config,
|
||||
"variables": self.variables,
|
||||
}
|
||||
|
||||
def initialize_memory(self):
|
||||
"""Initialize memory if config exists but memory doesn't"""
|
||||
if not self.memory and self.config.get('memory_config'):
|
||||
@@ -632,4 +711,51 @@ Context:
|
||||
if asyncio.iscoroutinefunction(self.callback):
|
||||
await self.callback(task_output)
|
||||
else:
|
||||
self.callback(task_output)
|
||||
self.callback(task_output)
|
||||
|
||||
def evaluate_when(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Evaluate the 'when' condition against the given context.
|
||||
|
||||
Uses the shared evaluate_condition function from the conditions module
|
||||
for DRY compliance with AgentFlow condition evaluation.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variables for evaluation.
|
||||
May include workflow variables, previous outputs, etc.
|
||||
|
||||
Returns:
|
||||
True if condition is met or no condition is set.
|
||||
False if condition is not met.
|
||||
"""
|
||||
if self.when is None:
|
||||
return True
|
||||
|
||||
from ..conditions.evaluator import evaluate_condition
|
||||
return evaluate_condition(
|
||||
self.when,
|
||||
context,
|
||||
previous_output=context.get('previous_output')
|
||||
)
|
||||
|
||||
def get_next_task(self, context: Dict[str, Any]) -> Optional[str]:
|
||||
"""
|
||||
Get the next task name based on the 'when' condition evaluation.
|
||||
|
||||
This provides a simple routing mechanism for Task objects,
|
||||
similar to AgentFlow's when() function.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variables for evaluation.
|
||||
|
||||
Returns:
|
||||
then_task if condition is True, else_task if False.
|
||||
None if no routing is configured.
|
||||
"""
|
||||
if self.when is None and self.then_task is None and self.else_task is None:
|
||||
return None
|
||||
|
||||
if self.evaluate_when(context):
|
||||
return self.then_task
|
||||
else:
|
||||
return self.else_task
|
||||
@@ -43,8 +43,8 @@ def internet_search(query: str, max_results: int = 5, retries: int = MAX_RETRIES
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
|
||||
# Try text search
|
||||
search_results = list(ddgs.text(keywords=query, max_results=max_results))
|
||||
# Try text search (use positional 'query' for v8+ compatibility)
|
||||
search_results = list(ddgs.text(query, max_results=max_results))
|
||||
|
||||
for result in search_results:
|
||||
results.append({
|
||||
|
||||
@@ -226,7 +226,8 @@ def _search_duckduckgo(query: str, max_results: int = 5) -> List[Dict[str, Any]]
|
||||
try:
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
search_results = list(ddgs.text(keywords=query, max_results=max_results))
|
||||
# Use positional 'query' (v8+) instead of keywords= (deprecated)
|
||||
search_results = list(ddgs.text(query, max_results=max_results))
|
||||
|
||||
for result in search_results:
|
||||
results.append({
|
||||
|
||||
@@ -2696,6 +2696,9 @@ CONCISE SUMMARY:"""
|
||||
) -> bool:
|
||||
"""Evaluate a condition expression with variable substitution.
|
||||
|
||||
This method delegates to the shared evaluate_condition() function
|
||||
from praisonaiagents.conditions for DRY condition handling.
|
||||
|
||||
Supported formats:
|
||||
- Numeric comparison: "{{var}} > 80", "{{var}} >= 50", "{{var}} < 10"
|
||||
- String equality: "{{var}} == approved", "{{var}} != rejected"
|
||||
@@ -2711,115 +2714,8 @@ CONCISE SUMMARY:"""
|
||||
Returns:
|
||||
Boolean result of condition evaluation
|
||||
"""
|
||||
import re
|
||||
|
||||
# Substitute variables in condition
|
||||
substituted = condition
|
||||
|
||||
# Handle nested property access like {{item.score}}
|
||||
def get_nested_value(var_path: str, vars_dict: Dict[str, Any]) -> Any:
|
||||
parts = var_path.split('.')
|
||||
value = vars_dict
|
||||
for part in parts:
|
||||
if isinstance(value, dict):
|
||||
value = value.get(part)
|
||||
else:
|
||||
return None
|
||||
return value
|
||||
|
||||
# Find all {{var}} patterns and substitute
|
||||
pattern = r'\{\{([^}]+)\}\}'
|
||||
matches = re.findall(pattern, condition)
|
||||
|
||||
for var_name in matches:
|
||||
if '.' in var_name:
|
||||
# Nested property access
|
||||
value = get_nested_value(var_name, variables)
|
||||
else:
|
||||
value = variables.get(var_name)
|
||||
|
||||
if value is None:
|
||||
value = ""
|
||||
|
||||
# Replace the placeholder with the value
|
||||
placeholder = f"{{{{{var_name}}}}}"
|
||||
if isinstance(value, (int, float)):
|
||||
substituted = substituted.replace(placeholder, str(value))
|
||||
elif isinstance(value, bool):
|
||||
substituted = substituted.replace(placeholder, str(value).lower())
|
||||
else:
|
||||
substituted = substituted.replace(placeholder, str(value))
|
||||
|
||||
# Also substitute {{previous_output}}
|
||||
if previous_output:
|
||||
substituted = substituted.replace("{{previous_output}}", str(previous_output))
|
||||
|
||||
# Now evaluate the substituted condition
|
||||
try:
|
||||
# Handle different condition formats
|
||||
|
||||
# Numeric comparisons: "90 > 80", "50 >= 50", "10 < 20", etc.
|
||||
numeric_pattern = r'^(-?\d+(?:\.\d+)?)\s*(>|>=|<|<=|==|!=)\s*(-?\d+(?:\.\d+)?)$'
|
||||
numeric_match = re.match(numeric_pattern, substituted.strip())
|
||||
if numeric_match:
|
||||
left = float(numeric_match.group(1))
|
||||
op = numeric_match.group(2)
|
||||
right = float(numeric_match.group(3))
|
||||
|
||||
if op == '>':
|
||||
return left > right
|
||||
if op == '>=':
|
||||
return left >= right
|
||||
if op == '<':
|
||||
return left < right
|
||||
if op == '<=':
|
||||
return left <= right
|
||||
if op == '==':
|
||||
return left == right
|
||||
if op == '!=':
|
||||
return left != right
|
||||
|
||||
# String equality: "approved == approved", "status != rejected"
|
||||
string_eq_pattern = r'^(.+?)\s*(==|!=)\s*(.+)$'
|
||||
string_match = re.match(string_eq_pattern, substituted.strip())
|
||||
if string_match:
|
||||
left = string_match.group(1).strip()
|
||||
op = string_match.group(2)
|
||||
right = string_match.group(3).strip()
|
||||
|
||||
if op == '==':
|
||||
return left == right
|
||||
if op == '!=':
|
||||
return left != right
|
||||
|
||||
# Contains check: "error in some message", "status contains success"
|
||||
if ' in ' in substituted:
|
||||
parts = substituted.split(' in ', 1)
|
||||
if len(parts) == 2:
|
||||
needle = parts[0].strip()
|
||||
haystack = parts[1].strip()
|
||||
return needle.lower() in haystack.lower()
|
||||
|
||||
if ' contains ' in substituted:
|
||||
parts = substituted.split(' contains ', 1)
|
||||
if len(parts) == 2:
|
||||
haystack = parts[0].strip()
|
||||
needle = parts[1].strip()
|
||||
return needle.lower() in haystack.lower()
|
||||
|
||||
# Boolean check: truthy evaluation
|
||||
# Handle "true", "false", "True", "False"
|
||||
if substituted.strip().lower() == 'true':
|
||||
return True
|
||||
if substituted.strip().lower() == 'false':
|
||||
return False
|
||||
|
||||
# Non-empty string is truthy
|
||||
return bool(substituted.strip())
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Condition evaluation failed for '{condition}': {e}")
|
||||
return False
|
||||
from praisonaiagents.conditions.evaluator import evaluate_condition
|
||||
return evaluate_condition(condition, variables, previous_output)
|
||||
|
||||
def _execute_include(
|
||||
self,
|
||||
@@ -3502,13 +3398,17 @@ class WorkflowManager:
|
||||
|
||||
context_parts = []
|
||||
|
||||
if step.context_from:
|
||||
# Use getattr with defaults for workflow-specific attributes that may not exist on Task
|
||||
context_from = getattr(step, 'context_from', None)
|
||||
retain_full_context = getattr(step, 'retain_full_context', False)
|
||||
|
||||
if context_from:
|
||||
# Include only specified steps
|
||||
for step_name in step.context_from:
|
||||
for step_name in context_from:
|
||||
for prev_result in results:
|
||||
if prev_result["step"] == step_name and prev_result.get("output"):
|
||||
context_parts.append(f"## {step_name} Output:\n{prev_result['output']}")
|
||||
elif step.retain_full_context:
|
||||
elif retain_full_context:
|
||||
# Include all previous outputs
|
||||
for prev_result in results:
|
||||
if prev_result.get("output") and prev_result.get("status") == "success":
|
||||
@@ -3867,18 +3767,21 @@ class WorkflowManager:
|
||||
|
||||
# Handle branching
|
||||
next_step_idx = None
|
||||
if step.branch_condition and step_result["output"]:
|
||||
# Use getattr with defaults for workflow-specific attributes that may not exist on Task
|
||||
branch_condition = getattr(step, 'branch_condition', None)
|
||||
next_steps = getattr(step, 'next_steps', None)
|
||||
if branch_condition and step_result["output"]:
|
||||
# Evaluate branch condition based on output
|
||||
output_lower = str(step_result["output"]).lower()
|
||||
for branch_key, branch_targets in step.branch_condition.items():
|
||||
for branch_key, branch_targets in branch_condition.items():
|
||||
if branch_key.lower() in output_lower or output_lower.startswith(branch_key.lower()):
|
||||
if branch_targets and branch_targets[0] in step_lookup:
|
||||
next_step_idx, _ = step_lookup[branch_targets[0]]
|
||||
break
|
||||
elif step.next_steps:
|
||||
elif next_steps:
|
||||
# Use explicit next_steps
|
||||
if step.next_steps[0] in step_lookup:
|
||||
next_step_idx, _ = step_lookup[step.next_steps[0]]
|
||||
if next_steps[0] in step_lookup:
|
||||
next_step_idx, _ = step_lookup[next_steps[0]]
|
||||
|
||||
# Move to next step
|
||||
if next_step_idx is not None:
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "praisonaiagents"
|
||||
version = "1.2.2"
|
||||
version = "1.3.0"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
@@ -57,6 +57,13 @@ api = [
|
||||
"uvicorn>=0.34.0"
|
||||
]
|
||||
|
||||
# AgentOS dependencies (alias for api + auth for deployment)
|
||||
os = [
|
||||
"fastapi>=0.115.0",
|
||||
"uvicorn>=0.34.0",
|
||||
"PyJWT>=2.8.0"
|
||||
]
|
||||
|
||||
# Telemetry dependencies
|
||||
telemetry = [
|
||||
"posthog>=3.0.0"
|
||||
|
||||
@@ -6,12 +6,13 @@ Requires OPENAI_API_KEY environment variable.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import pytest
|
||||
|
||||
# Skip if no API key
|
||||
if not os.environ.get("OPENAI_API_KEY"):
|
||||
print("Skipping integration tests - OPENAI_API_KEY not set")
|
||||
sys.exit(0)
|
||||
# Skip entire module if no API key
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not os.environ.get("OPENAI_API_KEY"),
|
||||
reason="OPENAI_API_KEY not set"
|
||||
)
|
||||
|
||||
|
||||
def test_guardrail_string_preset():
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
"""
|
||||
Integration tests comparing Task.condition vs AgentFlow when() syntax.
|
||||
|
||||
This test file validates both condition syntaxes work correctly and
|
||||
documents the differences for analysis.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
|
||||
class TestAgentFlowConditionSyntax:
|
||||
"""Test AgentFlow's when()/if_() string-based condition syntax."""
|
||||
|
||||
def test_agentflow_numeric_condition(self):
|
||||
"""AgentFlow uses string expressions: '{{score}} > 80'"""
|
||||
from praisonaiagents import AgentFlow
|
||||
from praisonaiagents.workflows import if_
|
||||
|
||||
results = []
|
||||
|
||||
def approve(ctx):
|
||||
results.append("approved")
|
||||
return {"output": "approved"}
|
||||
|
||||
def reject(ctx):
|
||||
results.append("rejected")
|
||||
return {"output": "rejected"}
|
||||
|
||||
# Test passing condition
|
||||
flow = AgentFlow(
|
||||
steps=[
|
||||
if_(
|
||||
condition="{{score}} > 80",
|
||||
then_steps=[approve],
|
||||
else_steps=[reject]
|
||||
)
|
||||
],
|
||||
variables={"score": 90}
|
||||
)
|
||||
flow.start("test")
|
||||
assert "approved" in results
|
||||
|
||||
# Test failing condition
|
||||
results.clear()
|
||||
flow2 = AgentFlow(
|
||||
steps=[
|
||||
if_(
|
||||
condition="{{score}} > 80",
|
||||
then_steps=[approve],
|
||||
else_steps=[reject]
|
||||
)
|
||||
],
|
||||
variables={"score": 70}
|
||||
)
|
||||
flow2.start("test")
|
||||
assert "rejected" in results
|
||||
|
||||
def test_agentflow_string_condition(self):
|
||||
"""AgentFlow string equality: '{{status}} == approved'"""
|
||||
from praisonaiagents import AgentFlow
|
||||
from praisonaiagents.workflows import when
|
||||
|
||||
results = []
|
||||
|
||||
def process_approved(ctx):
|
||||
results.append("processed_approved")
|
||||
return {"output": "done"}
|
||||
|
||||
def process_rejected(ctx):
|
||||
results.append("processed_rejected")
|
||||
return {"output": "done"}
|
||||
|
||||
flow = AgentFlow(
|
||||
steps=[
|
||||
when(
|
||||
condition="{{status}} == approved",
|
||||
then_steps=[process_approved],
|
||||
else_steps=[process_rejected]
|
||||
)
|
||||
],
|
||||
variables={"status": "approved"}
|
||||
)
|
||||
flow.start("test")
|
||||
assert "processed_approved" in results
|
||||
|
||||
|
||||
class TestTaskConditionSyntax:
|
||||
"""Test Task's Dict-based condition syntax for routing."""
|
||||
|
||||
def test_task_dict_condition_routing(self):
|
||||
"""Task uses Dict[str, List[str]]: {'approved': ['next_task']}"""
|
||||
from praisonaiagents import Task
|
||||
|
||||
# Task condition is a dict mapping decision values to next task names
|
||||
task = Task(
|
||||
name="review_task",
|
||||
description="Review and decide",
|
||||
task_type="decision",
|
||||
condition={
|
||||
"approved": ["publish_task"],
|
||||
"rejected": ["revise_task"]
|
||||
}
|
||||
)
|
||||
|
||||
# Verify condition structure
|
||||
assert isinstance(task.condition, dict)
|
||||
assert "approved" in task.condition
|
||||
assert task.condition["approved"] == ["publish_task"]
|
||||
assert task.condition["rejected"] == ["revise_task"]
|
||||
|
||||
def test_task_should_run_callable(self):
|
||||
"""Task also supports should_run callable for conditional execution."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
def check_condition(ctx):
|
||||
return ctx.get("score", 0) > 80
|
||||
|
||||
task = Task(
|
||||
name="conditional_task",
|
||||
description="Only run if score > 80",
|
||||
should_run=check_condition
|
||||
)
|
||||
|
||||
assert task.should_run is not None
|
||||
assert callable(task.should_run)
|
||||
# Test the callable
|
||||
assert task.should_run({"score": 90}) is True
|
||||
assert task.should_run({"score": 70}) is False
|
||||
|
||||
|
||||
class TestSyntaxComparison:
|
||||
"""Compare the two syntaxes side-by-side."""
|
||||
|
||||
def test_document_syntax_differences(self):
|
||||
"""Document the syntax differences for analysis."""
|
||||
|
||||
# ============================================================
|
||||
# AGENTFLOW SYNTAX (Deterministic Pipelines)
|
||||
# ============================================================
|
||||
# Uses: String expressions with {{variable}} placeholders
|
||||
# Location: workflows/workflows.py - when(), if_(), If class
|
||||
# Evaluation: evaluate_condition() in conditions/evaluator.py
|
||||
#
|
||||
# Example:
|
||||
# when(
|
||||
# condition="{{score}} > 80", # STRING expression
|
||||
# then_steps=[approve],
|
||||
# else_steps=[reject]
|
||||
# )
|
||||
#
|
||||
# Supported formats:
|
||||
# - Numeric: "{{var}} > 80", "{{var}} >= 50"
|
||||
# - String: "{{var}} == approved"
|
||||
# - Contains: "error in {{message}}"
|
||||
# - Boolean: "{{flag}}"
|
||||
# - Nested: "{{item.score}} >= 60"
|
||||
|
||||
agentflow_condition = "{{score}} > 80" # STRING
|
||||
|
||||
# ============================================================
|
||||
# TASK/AGENTTEAM SYNTAX (Multi-Agent Task Graphs)
|
||||
# ============================================================
|
||||
# Uses: Dict[str, List[str]] mapping decision values to task names
|
||||
# Location: task/task.py - Task.condition parameter
|
||||
# Evaluation: process/process.py - matches decision_str to dict keys
|
||||
#
|
||||
# Example:
|
||||
# Task(
|
||||
# condition={
|
||||
# "approved": ["publish_task"], # DICT routing
|
||||
# "rejected": ["revise_task"]
|
||||
# }
|
||||
# )
|
||||
#
|
||||
# How it works:
|
||||
# 1. Task with task_type="decision" returns a decision value
|
||||
# 2. Process looks up decision value in condition dict
|
||||
# 3. Routes to the corresponding next task(s)
|
||||
|
||||
task_condition = {"approved": ["publish_task"], "rejected": ["revise_task"]} # DICT
|
||||
|
||||
# ============================================================
|
||||
# KEY DIFFERENCES (CONFUSING FOR USERS)
|
||||
# ============================================================
|
||||
#
|
||||
# | Aspect | AgentFlow | Task/AgentTeam |
|
||||
# |-----------------|--------------------|-----------------------|
|
||||
# | Condition Type | STRING expression | DICT routing map |
|
||||
# | Evaluation | Expression parsing | Key lookup |
|
||||
# | Purpose | Branch on value | Route to next task |
|
||||
# | Variables | {{var}} syntax | decision_str from LLM |
|
||||
# | Flexibility | Any comparison | Exact key match |
|
||||
#
|
||||
# CONFUSION POINTS:
|
||||
# 1. Same word "condition" means different things
|
||||
# 2. AgentFlow: condition="{{x}} > 5" (evaluates expression)
|
||||
# 3. Task: condition={"yes": ["task_a"]} (routes by key)
|
||||
# 4. No unified syntax for beginners
|
||||
|
||||
assert isinstance(agentflow_condition, str)
|
||||
assert isinstance(task_condition, dict)
|
||||
|
||||
# This test documents the confusion - both use "condition" but differently
|
||||
|
||||
|
||||
class TestRealWorldScenarios:
|
||||
"""Test real-world scenarios with both syntaxes."""
|
||||
|
||||
def test_agentflow_score_based_routing(self):
|
||||
"""Real scenario: Route based on numeric score."""
|
||||
from praisonaiagents import AgentFlow
|
||||
from praisonaiagents.workflows import when
|
||||
|
||||
execution_log = []
|
||||
|
||||
def high_score_handler(ctx):
|
||||
execution_log.append("high_score")
|
||||
return {"output": "Premium service"}
|
||||
|
||||
def low_score_handler(ctx):
|
||||
execution_log.append("low_score")
|
||||
return {"output": "Standard service"}
|
||||
|
||||
# AgentFlow: Uses string expression
|
||||
flow = AgentFlow(
|
||||
steps=[
|
||||
when(
|
||||
condition="{{customer_score}} >= 80",
|
||||
then_steps=[high_score_handler],
|
||||
else_steps=[low_score_handler]
|
||||
)
|
||||
],
|
||||
variables={"customer_score": 85}
|
||||
)
|
||||
|
||||
result = flow.start("Assign service tier")
|
||||
assert "high_score" in execution_log
|
||||
|
||||
def test_task_decision_routing(self):
|
||||
"""Real scenario: Task decision routes to next task."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
# Task: Uses dict for routing
|
||||
review_task = Task(
|
||||
name="content_review",
|
||||
description="Review content and decide: approved or rejected",
|
||||
task_type="decision",
|
||||
condition={
|
||||
"approved": ["publish_content"],
|
||||
"rejected": ["request_revision"]
|
||||
}
|
||||
)
|
||||
|
||||
# The condition dict maps LLM decision output to next task names
|
||||
assert review_task.task_type == "decision"
|
||||
assert "approved" in review_task.condition
|
||||
assert "rejected" in review_task.condition
|
||||
@@ -3,11 +3,20 @@ Tests for Agent context trace emission.
|
||||
|
||||
TDD tests to verify that Agent emits context events when a global emitter is set.
|
||||
These tests use mocking to avoid actual LLM calls.
|
||||
|
||||
NOTE: These tests require OPENAI_API_KEY to be set for Agent initialization.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
# Skip tests if OPENAI_API_KEY is not set
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not os.environ.get("OPENAI_API_KEY"),
|
||||
reason="OPENAI_API_KEY not set"
|
||||
)
|
||||
|
||||
|
||||
class TestAgentTraceEmission:
|
||||
"""Tests for Agent emitting context trace events."""
|
||||
|
||||
@@ -49,7 +49,8 @@ class TestCheckpointConfig:
|
||||
def test_config_default_storage(self):
|
||||
"""Test default storage directory."""
|
||||
config = CheckpointConfig(workspace_dir="/tmp/test")
|
||||
assert ".praison/checkpoints" in config.storage_dir
|
||||
# Uses centralized paths module - .praisonai/checkpoints
|
||||
assert ".praisonai/checkpoints" in config.storage_dir or "checkpoints" in config.storage_dir
|
||||
|
||||
def test_config_exclude_patterns(self):
|
||||
"""Test default exclude patterns."""
|
||||
|
||||
@@ -2,10 +2,17 @@
|
||||
Tests for bot CLI commands.
|
||||
|
||||
Tests the enhanced bot command with full capability options.
|
||||
|
||||
NOTE: These tests require the praisonai package to be installed.
|
||||
They are skipped if praisonai is not available.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Skip entire module if praisonai is not installed
|
||||
pytest.importorskip("praisonai", reason="praisonai package not installed")
|
||||
|
||||
|
||||
class TestBotCapabilities:
|
||||
"""Tests for BotCapabilities dataclass."""
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# Tests for conditions module
|
||||
@@ -0,0 +1,166 @@
|
||||
"""
|
||||
Integration tests for ConditionProtocol with AgentFlow and AgentTeam.
|
||||
|
||||
These tests verify that the shared condition evaluation works correctly
|
||||
when used through the existing AgentFlow and AgentTeam APIs.
|
||||
"""
|
||||
|
||||
|
||||
class TestAgentFlowConditionIntegration:
|
||||
"""Test that AgentFlow _evaluate_condition uses shared evaluator."""
|
||||
|
||||
def test_agentflow_evaluate_condition_numeric(self):
|
||||
"""Test AgentFlow._evaluate_condition with numeric comparison."""
|
||||
from praisonaiagents.workflows.workflows import AgentFlow
|
||||
|
||||
flow = AgentFlow(steps=[])
|
||||
|
||||
# Test numeric comparisons
|
||||
assert flow._evaluate_condition("{{score}} > 80", {"score": 90}) is True
|
||||
assert flow._evaluate_condition("{{score}} > 80", {"score": 70}) is False
|
||||
assert flow._evaluate_condition("{{score}} >= 80", {"score": 80}) is True
|
||||
assert flow._evaluate_condition("{{score}} < 50", {"score": 30}) is True
|
||||
|
||||
def test_agentflow_evaluate_condition_string(self):
|
||||
"""Test AgentFlow._evaluate_condition with string comparison."""
|
||||
from praisonaiagents.workflows.workflows import AgentFlow
|
||||
|
||||
flow = AgentFlow(steps=[])
|
||||
|
||||
# Test string equality
|
||||
assert flow._evaluate_condition("{{status}} == approved", {"status": "approved"}) is True
|
||||
assert flow._evaluate_condition("{{status}} == approved", {"status": "rejected"}) is False
|
||||
assert flow._evaluate_condition("{{status}} != rejected", {"status": "approved"}) is True
|
||||
|
||||
def test_agentflow_evaluate_condition_contains(self):
|
||||
"""Test AgentFlow._evaluate_condition with contains check."""
|
||||
from praisonaiagents.workflows.workflows import AgentFlow
|
||||
|
||||
flow = AgentFlow(steps=[])
|
||||
|
||||
# Test contains
|
||||
assert flow._evaluate_condition("error in {{message}}", {"message": "An error occurred"}) is True
|
||||
assert flow._evaluate_condition("error in {{message}}", {"message": "Success!"}) is False
|
||||
assert flow._evaluate_condition("{{message}} contains success", {"message": "Operation success"}) is True
|
||||
|
||||
def test_agentflow_evaluate_condition_boolean(self):
|
||||
"""Test AgentFlow._evaluate_condition with boolean evaluation."""
|
||||
from praisonaiagents.workflows.workflows import AgentFlow
|
||||
|
||||
flow = AgentFlow(steps=[])
|
||||
|
||||
# Test boolean
|
||||
assert flow._evaluate_condition("{{flag}}", {"flag": True}) is True
|
||||
assert flow._evaluate_condition("{{flag}}", {"flag": False}) is False
|
||||
assert flow._evaluate_condition("{{flag}}", {"flag": "yes"}) is True
|
||||
|
||||
def test_agentflow_evaluate_condition_nested(self):
|
||||
"""Test AgentFlow._evaluate_condition with nested property access."""
|
||||
from praisonaiagents.workflows.workflows import AgentFlow
|
||||
|
||||
flow = AgentFlow(steps=[])
|
||||
|
||||
# Test nested property
|
||||
assert flow._evaluate_condition("{{item.score}} >= 60", {"item": {"score": 75}}) is True
|
||||
assert flow._evaluate_condition("{{item.score}} >= 60", {"item": {"score": 50}}) is False
|
||||
|
||||
def test_agentflow_evaluate_condition_previous_output(self):
|
||||
"""Test AgentFlow._evaluate_condition with previous_output."""
|
||||
from praisonaiagents.workflows.workflows import AgentFlow
|
||||
|
||||
flow = AgentFlow(steps=[])
|
||||
|
||||
# Test previous_output substitution
|
||||
result = flow._evaluate_condition(
|
||||
"success in {{previous_output}}",
|
||||
{},
|
||||
previous_output="Operation success"
|
||||
)
|
||||
assert result is True
|
||||
|
||||
|
||||
class TestSharedEvaluatorConsistency:
|
||||
"""Test that shared evaluator produces consistent results."""
|
||||
|
||||
def test_evaluator_and_agentflow_produce_same_results(self):
|
||||
"""Verify shared evaluator and AgentFlow produce identical results."""
|
||||
from praisonaiagents.conditions.evaluator import evaluate_condition
|
||||
from praisonaiagents.workflows.workflows import AgentFlow
|
||||
|
||||
flow = AgentFlow(steps=[])
|
||||
|
||||
test_cases = [
|
||||
("{{score}} > 80", {"score": 90}, None),
|
||||
("{{score}} > 80", {"score": 70}, None),
|
||||
("{{status}} == approved", {"status": "approved"}, None),
|
||||
("error in {{message}}", {"message": "An error occurred"}, None),
|
||||
("{{flag}}", {"flag": True}, None),
|
||||
("{{item.score}} >= 60", {"item": {"score": 75}}, None),
|
||||
("success in {{previous_output}}", {}, "Operation success"),
|
||||
]
|
||||
|
||||
for condition, variables, previous_output in test_cases:
|
||||
shared_result = evaluate_condition(condition, variables, previous_output)
|
||||
flow_result = flow._evaluate_condition(condition, variables, previous_output)
|
||||
assert shared_result == flow_result, f"Mismatch for {condition}"
|
||||
|
||||
|
||||
class TestDictConditionForAgentTeam:
|
||||
"""Test DictCondition for AgentTeam-style routing."""
|
||||
|
||||
def test_dict_condition_routing(self):
|
||||
"""Test dict condition for task routing."""
|
||||
from praisonaiagents.conditions.evaluator import DictCondition
|
||||
|
||||
# Simulate AgentTeam task routing
|
||||
cond = DictCondition(
|
||||
{"approved": ["publish_task"], "rejected": ["revise_task"]},
|
||||
key="decision"
|
||||
)
|
||||
|
||||
# Test routing
|
||||
assert cond.evaluate({"decision": "approved"}) is True
|
||||
assert cond.get_target({"decision": "approved"}) == ["publish_task"]
|
||||
|
||||
assert cond.evaluate({"decision": "rejected"}) is True
|
||||
assert cond.get_target({"decision": "rejected"}) == ["revise_task"]
|
||||
|
||||
assert cond.evaluate({"decision": "unknown"}) is False
|
||||
assert cond.get_target({"decision": "unknown"}) == []
|
||||
|
||||
def test_dict_condition_case_insensitive(self):
|
||||
"""Test dict condition is case-insensitive for decision values."""
|
||||
from praisonaiagents.conditions.evaluator import DictCondition
|
||||
|
||||
cond = DictCondition(
|
||||
{"approved": ["publish"], "rejected": ["revise"]},
|
||||
key="decision"
|
||||
)
|
||||
|
||||
# Test case insensitivity
|
||||
assert cond.evaluate({"decision": "APPROVED"}) is True
|
||||
assert cond.evaluate({"decision": "Approved"}) is True
|
||||
assert cond.get_target({"decision": "APPROVED"}) == ["publish"]
|
||||
|
||||
|
||||
class TestExpressionConditionClass:
|
||||
"""Test ExpressionCondition class wrapper."""
|
||||
|
||||
def test_expression_condition_class(self):
|
||||
"""Test ExpressionCondition class usage."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} > 80")
|
||||
|
||||
assert cond.evaluate({"score": 90}) is True
|
||||
assert cond.evaluate({"score": 70}) is False
|
||||
|
||||
def test_expression_condition_with_previous_output(self):
|
||||
"""Test ExpressionCondition with previous_output in context."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("success in {{previous_output}}")
|
||||
|
||||
# previous_output is passed via context
|
||||
assert cond.evaluate({"previous_output": "Operation success"}) is True
|
||||
assert cond.evaluate({"previous_output": "Operation failed"}) is False
|
||||
@@ -0,0 +1,252 @@
|
||||
"""
|
||||
TDD Tests for ConditionProtocol.
|
||||
|
||||
These tests define the expected behavior BEFORE implementation.
|
||||
All tests should FAIL initially, then PASS after implementation.
|
||||
"""
|
||||
from typing import Dict, Any
|
||||
|
||||
|
||||
class TestConditionProtocolExists:
|
||||
"""Test that ConditionProtocol can be imported."""
|
||||
|
||||
def test_condition_protocol_importable(self):
|
||||
"""ConditionProtocol should be importable from conditions module."""
|
||||
from praisonaiagents.conditions.protocols import ConditionProtocol
|
||||
assert ConditionProtocol is not None
|
||||
|
||||
def test_condition_protocol_is_runtime_checkable(self):
|
||||
"""ConditionProtocol should be runtime_checkable."""
|
||||
from praisonaiagents.conditions.protocols import ConditionProtocol
|
||||
|
||||
# Create a mock that implements the protocol
|
||||
class MockCondition:
|
||||
def evaluate(self, context: Dict[str, Any]) -> bool:
|
||||
return True
|
||||
|
||||
mock = MockCondition()
|
||||
assert isinstance(mock, ConditionProtocol)
|
||||
|
||||
def test_condition_protocol_has_evaluate_method(self):
|
||||
"""ConditionProtocol should define evaluate(context) -> bool."""
|
||||
from praisonaiagents.conditions.protocols import ConditionProtocol
|
||||
|
||||
# Check that evaluate is defined
|
||||
assert hasattr(ConditionProtocol, 'evaluate')
|
||||
|
||||
|
||||
class TestExpressionCondition:
|
||||
"""Test ExpressionCondition class for string-based conditions."""
|
||||
|
||||
def test_expression_condition_importable(self):
|
||||
"""ExpressionCondition should be importable."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
assert ExpressionCondition is not None
|
||||
|
||||
def test_expression_condition_implements_protocol(self):
|
||||
"""ExpressionCondition should implement ConditionProtocol."""
|
||||
from praisonaiagents.conditions.protocols import ConditionProtocol
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} > 80")
|
||||
assert isinstance(cond, ConditionProtocol)
|
||||
|
||||
def test_numeric_greater_than(self):
|
||||
"""Test numeric > comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} > 80")
|
||||
assert cond.evaluate({"score": 90}) is True
|
||||
assert cond.evaluate({"score": 80}) is False
|
||||
assert cond.evaluate({"score": 70}) is False
|
||||
|
||||
def test_numeric_greater_equal(self):
|
||||
"""Test numeric >= comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} >= 80")
|
||||
assert cond.evaluate({"score": 90}) is True
|
||||
assert cond.evaluate({"score": 80}) is True
|
||||
assert cond.evaluate({"score": 70}) is False
|
||||
|
||||
def test_numeric_less_than(self):
|
||||
"""Test numeric < comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} < 50")
|
||||
assert cond.evaluate({"score": 40}) is True
|
||||
assert cond.evaluate({"score": 50}) is False
|
||||
assert cond.evaluate({"score": 60}) is False
|
||||
|
||||
def test_numeric_less_equal(self):
|
||||
"""Test numeric <= comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} <= 50")
|
||||
assert cond.evaluate({"score": 40}) is True
|
||||
assert cond.evaluate({"score": 50}) is True
|
||||
assert cond.evaluate({"score": 60}) is False
|
||||
|
||||
def test_numeric_equal(self):
|
||||
"""Test numeric == comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} == 100")
|
||||
assert cond.evaluate({"score": 100}) is True
|
||||
assert cond.evaluate({"score": 99}) is False
|
||||
|
||||
def test_numeric_not_equal(self):
|
||||
"""Test numeric != comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{score}} != 0")
|
||||
assert cond.evaluate({"score": 1}) is True
|
||||
assert cond.evaluate({"score": 0}) is False
|
||||
|
||||
def test_string_equality(self):
|
||||
"""Test string == comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{status}} == approved")
|
||||
assert cond.evaluate({"status": "approved"}) is True
|
||||
assert cond.evaluate({"status": "rejected"}) is False
|
||||
|
||||
def test_string_not_equal(self):
|
||||
"""Test string != comparison."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{status}} != rejected")
|
||||
assert cond.evaluate({"status": "approved"}) is True
|
||||
assert cond.evaluate({"status": "rejected"}) is False
|
||||
|
||||
def test_contains_check(self):
|
||||
"""Test 'in' contains check."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("error in {{message}}")
|
||||
assert cond.evaluate({"message": "An error occurred"}) is True
|
||||
assert cond.evaluate({"message": "Success!"}) is False
|
||||
|
||||
def test_contains_keyword(self):
|
||||
"""Test 'contains' keyword."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{message}} contains success")
|
||||
assert cond.evaluate({"message": "Operation success"}) is True
|
||||
assert cond.evaluate({"message": "Operation failed"}) is False
|
||||
|
||||
def test_boolean_truthy(self):
|
||||
"""Test boolean truthy evaluation."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{flag}}")
|
||||
assert cond.evaluate({"flag": True}) is True
|
||||
assert cond.evaluate({"flag": "yes"}) is True
|
||||
assert cond.evaluate({"flag": False}) is False
|
||||
assert cond.evaluate({"flag": ""}) is False
|
||||
|
||||
def test_nested_property_access(self):
|
||||
"""Test nested property access like {{item.score}}."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{item.score}} >= 60")
|
||||
assert cond.evaluate({"item": {"score": 75}}) is True
|
||||
assert cond.evaluate({"item": {"score": 50}}) is False
|
||||
|
||||
def test_missing_variable_returns_false(self):
|
||||
"""Test that missing variables don't crash, return False."""
|
||||
from praisonaiagents.conditions.evaluator import ExpressionCondition
|
||||
|
||||
cond = ExpressionCondition("{{missing}} > 0")
|
||||
assert cond.evaluate({}) is False
|
||||
|
||||
|
||||
class TestDictCondition:
|
||||
"""Test DictCondition class for dict-based routing conditions."""
|
||||
|
||||
def test_dict_condition_importable(self):
|
||||
"""DictCondition should be importable."""
|
||||
from praisonaiagents.conditions.evaluator import DictCondition
|
||||
assert DictCondition is not None
|
||||
|
||||
def test_dict_condition_implements_protocol(self):
|
||||
"""DictCondition should implement ConditionProtocol."""
|
||||
from praisonaiagents.conditions.protocols import ConditionProtocol
|
||||
from praisonaiagents.conditions.evaluator import DictCondition
|
||||
|
||||
cond = DictCondition({"approved": ["task_a"]}, key="decision")
|
||||
assert isinstance(cond, ConditionProtocol)
|
||||
|
||||
def test_dict_condition_matches_key(self):
|
||||
"""Test dict condition matches decision key."""
|
||||
from praisonaiagents.conditions.evaluator import DictCondition
|
||||
|
||||
cond = DictCondition(
|
||||
{"approved": ["publish"], "rejected": ["revise"]},
|
||||
key="decision"
|
||||
)
|
||||
assert cond.evaluate({"decision": "approved"}) is True
|
||||
assert cond.evaluate({"decision": "rejected"}) is True
|
||||
assert cond.evaluate({"decision": "unknown"}) is False
|
||||
|
||||
def test_dict_condition_returns_target(self):
|
||||
"""Test dict condition can return target tasks."""
|
||||
from praisonaiagents.conditions.evaluator import DictCondition
|
||||
|
||||
cond = DictCondition(
|
||||
{"approved": ["publish"], "rejected": ["revise"]},
|
||||
key="decision"
|
||||
)
|
||||
assert cond.get_target({"decision": "approved"}) == ["publish"]
|
||||
assert cond.get_target({"decision": "rejected"}) == ["revise"]
|
||||
assert cond.get_target({"decision": "unknown"}) == []
|
||||
|
||||
|
||||
class TestEvaluateConditionFunction:
|
||||
"""Test the standalone evaluate_condition() function."""
|
||||
|
||||
def test_evaluate_condition_importable(self):
|
||||
"""evaluate_condition should be importable."""
|
||||
from praisonaiagents.conditions.evaluator import evaluate_condition
|
||||
assert evaluate_condition is not None
|
||||
|
||||
def test_evaluate_condition_string(self):
|
||||
"""Test evaluate_condition with string condition."""
|
||||
from praisonaiagents.conditions.evaluator import evaluate_condition
|
||||
|
||||
result = evaluate_condition("{{score}} > 80", {"score": 90})
|
||||
assert result is True
|
||||
|
||||
def test_evaluate_condition_with_previous_output(self):
|
||||
"""Test evaluate_condition with previous_output substitution."""
|
||||
from praisonaiagents.conditions.evaluator import evaluate_condition
|
||||
|
||||
result = evaluate_condition(
|
||||
"success in {{previous_output}}",
|
||||
{},
|
||||
previous_output="Operation success"
|
||||
)
|
||||
assert result is True
|
||||
|
||||
|
||||
class TestConditionExports:
|
||||
"""Test that conditions are properly exported."""
|
||||
|
||||
def test_exports_from_conditions_module(self):
|
||||
"""Test exports from conditions module."""
|
||||
from praisonaiagents.conditions import (
|
||||
ConditionProtocol,
|
||||
ExpressionCondition,
|
||||
DictCondition,
|
||||
evaluate_condition,
|
||||
)
|
||||
assert ConditionProtocol is not None
|
||||
assert ExpressionCondition is not None
|
||||
assert DictCondition is not None
|
||||
assert evaluate_condition is not None
|
||||
|
||||
def test_exports_from_main_package(self):
|
||||
"""Test exports from main praisonaiagents package."""
|
||||
from praisonaiagents import ConditionProtocol, evaluate_condition
|
||||
assert ConditionProtocol is not None
|
||||
assert evaluate_condition is not None
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
Tests for memory="learn" shorthand preset.
|
||||
|
||||
Tests that memory="learn" enables Agent Learn functionality with a simple string parameter.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestMemoryLearnPreset:
|
||||
"""Test that 'learn' preset exists in MEMORY_PRESETS."""
|
||||
|
||||
def test_learn_preset_exists(self):
|
||||
"""MEMORY_PRESETS should contain 'learn' key."""
|
||||
from praisonaiagents.config.presets import MEMORY_PRESETS
|
||||
|
||||
assert "learn" in MEMORY_PRESETS, "MEMORY_PRESETS should have 'learn' preset"
|
||||
|
||||
def test_learn_preset_has_learn_true(self):
|
||||
"""Learn preset should have learn=True."""
|
||||
from praisonaiagents.config.presets import MEMORY_PRESETS
|
||||
|
||||
preset = MEMORY_PRESETS.get("learn", {})
|
||||
assert preset.get("learn") is True, "Learn preset should have learn=True"
|
||||
|
||||
def test_learn_preset_has_backend(self):
|
||||
"""Learn preset should have a backend (file by default)."""
|
||||
from praisonaiagents.config.presets import MEMORY_PRESETS
|
||||
|
||||
preset = MEMORY_PRESETS.get("learn", {})
|
||||
assert "backend" in preset, "Learn preset should have backend"
|
||||
assert preset["backend"] == "file", "Learn preset should use file backend by default"
|
||||
|
||||
|
||||
class TestMemoryLearnResolution:
|
||||
"""Test that memory='learn' resolves correctly."""
|
||||
|
||||
def test_resolve_memory_learn_string(self):
|
||||
"""resolve() should convert 'learn' string to MemoryConfig with learn=True."""
|
||||
from praisonaiagents.config.param_resolver import resolve, ArrayMode
|
||||
from praisonaiagents.config.presets import MEMORY_PRESETS, MEMORY_URL_SCHEMES
|
||||
from praisonaiagents.config.feature_configs import MemoryConfig
|
||||
|
||||
result = resolve(
|
||||
value="learn",
|
||||
param_name="memory",
|
||||
config_class=MemoryConfig,
|
||||
presets=MEMORY_PRESETS,
|
||||
url_schemes=MEMORY_URL_SCHEMES,
|
||||
array_mode=ArrayMode.SINGLE_OR_LIST,
|
||||
default=None,
|
||||
)
|
||||
|
||||
assert result is not None, "Should resolve 'learn' to a config"
|
||||
assert isinstance(result, MemoryConfig), f"Should be MemoryConfig, got {type(result)}"
|
||||
assert result.learn is True, "MemoryConfig should have learn=True"
|
||||
|
||||
def test_memory_config_from_preset_dict(self):
|
||||
"""MemoryConfig should accept learn field from preset dict."""
|
||||
from praisonaiagents.config.feature_configs import MemoryConfig
|
||||
|
||||
# Simulate what happens when preset is converted to MemoryConfig
|
||||
preset_dict = {"backend": "file", "learn": True}
|
||||
config = MemoryConfig(**preset_dict)
|
||||
|
||||
assert config.backend == "file"
|
||||
assert config.learn is True
|
||||
|
||||
|
||||
class TestAgentMemoryLearnShorthand:
|
||||
"""Test Agent accepts memory='learn' parameter."""
|
||||
|
||||
def test_agent_accepts_memory_learn_string(self):
|
||||
"""Agent should accept memory='learn' without error."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Should not raise
|
||||
agent = Agent(
|
||||
instructions="Test agent with learn memory",
|
||||
memory="learn"
|
||||
)
|
||||
|
||||
assert agent is not None
|
||||
|
||||
def test_agent_memory_learn_sets_learn_config(self):
|
||||
"""Agent with memory='learn' should have memory enabled."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="Test agent",
|
||||
memory="learn"
|
||||
)
|
||||
|
||||
# Agent should have memory enabled (truthy value)
|
||||
assert agent.memory, "Agent.memory should be enabled when using memory='learn'"
|
||||
|
||||
|
||||
class TestMemoryLearnIntegration:
|
||||
"""Integration tests for memory='learn' with Memory class."""
|
||||
|
||||
def test_memory_class_with_learn_config(self):
|
||||
"""Memory class should initialize LearnManager when learn=True in config."""
|
||||
from praisonaiagents.memory.memory import Memory
|
||||
|
||||
memory = Memory({"provider": "rag", "learn": True, "use_embedding": False})
|
||||
|
||||
# Access learn property (lazy-loaded)
|
||||
learn_manager = memory.learn
|
||||
|
||||
assert learn_manager is not None, "Memory.learn should return LearnManager instance"
|
||||
|
||||
def test_memory_learn_captures_persona(self):
|
||||
"""LearnManager should capture persona entries."""
|
||||
import tempfile
|
||||
import shutil
|
||||
from praisonaiagents.memory.memory import Memory
|
||||
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
try:
|
||||
memory = Memory({
|
||||
"provider": "rag",
|
||||
"learn": True,
|
||||
"use_embedding": False,
|
||||
"user_id": "test_user"
|
||||
})
|
||||
|
||||
if memory.learn:
|
||||
entry = memory.learn.capture_persona("User prefers concise responses")
|
||||
assert entry is not None
|
||||
finally:
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
TDD Tests for Task.when parameter - Unified Condition Syntax.
|
||||
|
||||
These tests define the expected behavior for the new unified condition syntax.
|
||||
Tests should FAIL initially, then PASS after implementation.
|
||||
|
||||
The goal is to unify condition syntax between AgentFlow and Task:
|
||||
- AgentFlow: when(condition="{{score}} > 80", then_steps=[...], else_steps=[...])
|
||||
- Task: when="{{score}} > 80", then_task="approve", else_task="reject"
|
||||
"""
|
||||
|
||||
|
||||
class TestTaskWhenParameter:
|
||||
"""Test Task.when parameter for string-based conditions."""
|
||||
|
||||
def test_task_accepts_when_parameter(self):
|
||||
"""Task should accept a 'when' parameter as a string expression."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="conditional_task",
|
||||
description="A task with a condition",
|
||||
when="{{score}} > 80"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'when')
|
||||
assert task.when == "{{score}} > 80"
|
||||
|
||||
def test_task_when_with_then_task(self):
|
||||
"""Task should accept 'then_task' for routing when condition is True."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="review",
|
||||
description="Review content",
|
||||
when="{{score}} > 80",
|
||||
then_task="approve"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'then_task')
|
||||
assert task.then_task == "approve"
|
||||
|
||||
def test_task_when_with_else_task(self):
|
||||
"""Task should accept 'else_task' for routing when condition is False."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="review",
|
||||
description="Review content",
|
||||
when="{{score}} > 80",
|
||||
then_task="approve",
|
||||
else_task="reject"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'else_task')
|
||||
assert task.else_task == "reject"
|
||||
|
||||
def test_task_when_defaults_to_none(self):
|
||||
"""Task.when should default to None when not provided."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="simple_task",
|
||||
description="A simple task"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'when')
|
||||
assert task.when is None
|
||||
|
||||
def test_task_then_task_defaults_to_none(self):
|
||||
"""Task.then_task should default to None when not provided."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="simple_task",
|
||||
description="A simple task"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'then_task')
|
||||
assert task.then_task is None
|
||||
|
||||
def test_task_else_task_defaults_to_none(self):
|
||||
"""Task.else_task should default to None when not provided."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="simple_task",
|
||||
description="A simple task"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'else_task')
|
||||
assert task.else_task is None
|
||||
|
||||
|
||||
class TestTaskConditionRenameToRouting:
|
||||
"""Test that 'condition' is renamed to 'routing' with backward compatibility."""
|
||||
|
||||
def test_task_accepts_routing_parameter(self):
|
||||
"""Task should accept 'routing' parameter (new name for condition)."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="decision_task",
|
||||
description="Make a decision",
|
||||
task_type="decision",
|
||||
routing={"approved": ["publish"], "rejected": ["revise"]}
|
||||
)
|
||||
|
||||
# routing should be stored
|
||||
assert hasattr(task, 'routing')
|
||||
# For backward compat, condition should also work
|
||||
assert task.condition == {"approved": ["publish"], "rejected": ["revise"]}
|
||||
|
||||
def test_task_condition_still_works_backward_compat(self):
|
||||
"""Task should still accept 'condition' parameter for backward compatibility."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="decision_task",
|
||||
description="Make a decision",
|
||||
task_type="decision",
|
||||
condition={"approved": ["publish"], "rejected": ["revise"]}
|
||||
)
|
||||
|
||||
# condition should still work
|
||||
assert task.condition == {"approved": ["publish"], "rejected": ["revise"]}
|
||||
|
||||
|
||||
class TestTaskWhenEvaluation:
|
||||
"""Test that Task.when conditions can be evaluated."""
|
||||
|
||||
def test_task_has_evaluate_when_method(self):
|
||||
"""Task should have a method to evaluate the 'when' condition."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="conditional_task",
|
||||
description="A task with a condition",
|
||||
when="{{score}} > 80"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'evaluate_when')
|
||||
assert callable(task.evaluate_when)
|
||||
|
||||
def test_evaluate_when_returns_true(self):
|
||||
"""evaluate_when should return True when condition is met."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="conditional_task",
|
||||
description="A task with a condition",
|
||||
when="{{score}} > 80"
|
||||
)
|
||||
|
||||
result = task.evaluate_when({"score": 90})
|
||||
assert result is True
|
||||
|
||||
def test_evaluate_when_returns_false(self):
|
||||
"""evaluate_when should return False when condition is not met."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="conditional_task",
|
||||
description="A task with a condition",
|
||||
when="{{score}} > 80"
|
||||
)
|
||||
|
||||
result = task.evaluate_when({"score": 70})
|
||||
assert result is False
|
||||
|
||||
def test_evaluate_when_returns_true_when_no_condition(self):
|
||||
"""evaluate_when should return True when no 'when' condition is set."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="simple_task",
|
||||
description="A simple task"
|
||||
)
|
||||
|
||||
result = task.evaluate_when({})
|
||||
assert result is True
|
||||
|
||||
def test_evaluate_when_with_string_comparison(self):
|
||||
"""evaluate_when should handle string comparisons."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="conditional_task",
|
||||
description="A task with a condition",
|
||||
when="{{status}} == approved"
|
||||
)
|
||||
|
||||
assert task.evaluate_when({"status": "approved"}) is True
|
||||
assert task.evaluate_when({"status": "rejected"}) is False
|
||||
|
||||
|
||||
class TestTaskGetNextTask:
|
||||
"""Test Task routing based on when condition."""
|
||||
|
||||
def test_get_next_task_returns_then_task_when_true(self):
|
||||
"""get_next_task should return then_task when condition is True."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="review",
|
||||
description="Review content",
|
||||
when="{{score}} > 80",
|
||||
then_task="approve",
|
||||
else_task="reject"
|
||||
)
|
||||
|
||||
assert hasattr(task, 'get_next_task')
|
||||
next_task = task.get_next_task({"score": 90})
|
||||
assert next_task == "approve"
|
||||
|
||||
def test_get_next_task_returns_else_task_when_false(self):
|
||||
"""get_next_task should return else_task when condition is False."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="review",
|
||||
description="Review content",
|
||||
when="{{score}} > 80",
|
||||
then_task="approve",
|
||||
else_task="reject"
|
||||
)
|
||||
|
||||
next_task = task.get_next_task({"score": 70})
|
||||
assert next_task == "reject"
|
||||
|
||||
def test_get_next_task_returns_none_when_no_routing(self):
|
||||
"""get_next_task should return None when no routing is configured."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
name="simple_task",
|
||||
description="A simple task"
|
||||
)
|
||||
|
||||
next_task = task.get_next_task({})
|
||||
assert next_task is None
|
||||
@@ -2,18 +2,19 @@
|
||||
Tests for Gap Closure - LLM Consolidation + Parity
|
||||
|
||||
TDD: These tests define the expected behavior for:
|
||||
1. GAP A: No deprecation warnings for model/llm alias
|
||||
1. GAP A: model= is preferred, llm= shows deprecation warning
|
||||
2. GAP B: YAML parser supports consolidated params
|
||||
3. GAP C: Wrapper agents use output= (not verbose/markdown)
|
||||
4. GAP D: AutoAgents uses consolidated llm= (not function_calling_llm)
|
||||
5. GAP E: model= and llm= are aliases with NO warnings
|
||||
5. GAP E: model= and llm= both work (backward compatible)
|
||||
"""
|
||||
import os
|
||||
import pytest
|
||||
import warnings
|
||||
|
||||
|
||||
class TestNoDeprecationWarnings:
|
||||
"""GAP A + E: No deprecation warnings for model/llm or legacy params."""
|
||||
"""GAP A + E: model= preferred (no warning), llm= deprecated (shows warning)."""
|
||||
|
||||
def test_no_warning_for_model_alias(self):
|
||||
"""model= should work without any deprecation warning."""
|
||||
@@ -27,16 +28,18 @@ class TestNoDeprecationWarnings:
|
||||
deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)]
|
||||
assert len(deprecation_warnings) == 0, f"Unexpected warnings: {[str(x.message) for x in deprecation_warnings]}"
|
||||
|
||||
def test_no_warning_for_llm_param(self):
|
||||
"""llm= should work without any deprecation warning."""
|
||||
def test_llm_param_shows_deprecation_warning(self):
|
||||
"""llm= should work but show deprecation warning (model= is preferred)."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
warnings.simplefilter("always")
|
||||
agent = Agent(instructions="Test", llm="gpt-4o-mini")
|
||||
|
||||
# llm= is deprecated in favor of model=
|
||||
deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)]
|
||||
assert len(deprecation_warnings) == 0, f"Unexpected warnings: {[str(x.message) for x in deprecation_warnings]}"
|
||||
assert len(deprecation_warnings) >= 1, "llm= should produce deprecation warning"
|
||||
assert 'model' in str(deprecation_warnings[0].message).lower(), "Warning should suggest using 'model'"
|
||||
|
||||
def test_llm_config_removed(self):
|
||||
"""llm_config= is removed in v4 - should raise TypeError."""
|
||||
@@ -82,6 +85,10 @@ class TestAutoAgentsConsolidation:
|
||||
assert "function_calling_llm=self.function_calling_llm" not in source, \
|
||||
"AutoAgents._create_agents_and_tasks still passes function_calling_llm= to Agent()"
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not os.environ.get("OPENAI_API_KEY"),
|
||||
reason="OPENAI_API_KEY not set"
|
||||
)
|
||||
def test_autoagents_accepts_llm_param(self):
|
||||
"""AutoAgents should accept llm= parameter."""
|
||||
from praisonaiagents.agents.autoagents import AutoAgents
|
||||
|
||||
@@ -45,16 +45,17 @@ class TestLLMConsolidation:
|
||||
|
||||
assert agent1.llm == agent2.llm
|
||||
|
||||
def test_llm_takes_precedence_over_model(self):
|
||||
"""If both llm= and model= are provided, llm= takes precedence."""
|
||||
def test_model_takes_precedence_over_llm(self):
|
||||
"""If both llm= and model= are provided, model= takes precedence (new canonical name)."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# model= is the new canonical name, so it takes precedence over llm=
|
||||
agent = Agent(
|
||||
instructions="Test",
|
||||
llm="gpt-4o",
|
||||
model="gpt-3.5-turbo" # Should be ignored
|
||||
model="gpt-3.5-turbo" # model= takes precedence (new canonical name)
|
||||
)
|
||||
assert agent.llm == "gpt-4o"
|
||||
assert agent.llm == "gpt-3.5-turbo"
|
||||
|
||||
def test_llm_config_removed_in_v4(self):
|
||||
"""llm_config= is removed in v4 - should raise TypeError."""
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
"""
|
||||
TDD Tests for Parameter Naming Standardization.
|
||||
|
||||
Tests the following changes:
|
||||
1. llm= shows deprecation warning, model= is preferred
|
||||
2. Task depends_on= is alias for context=
|
||||
3. Task guardrails= is canonical (guardrail= deprecated)
|
||||
4. YAML parser normalizes depends_on
|
||||
|
||||
These tests are written FIRST (TDD) - they should FAIL initially.
|
||||
"""
|
||||
|
||||
import warnings
|
||||
|
||||
|
||||
class TestAgentLLMDeprecation:
|
||||
"""Test that llm= parameter shows deprecation warning."""
|
||||
|
||||
def test_model_param_no_warning(self):
|
||||
"""Using model= should NOT produce a deprecation warning."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
warnings.simplefilter("always")
|
||||
_agent = Agent( # noqa: F841
|
||||
name="test",
|
||||
instructions="Test agent",
|
||||
model="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Filter for DeprecationWarning about 'llm'
|
||||
llm_warnings = [x for x in w if 'llm' in str(x.message).lower()]
|
||||
assert len(llm_warnings) == 0, "model= should not produce deprecation warning"
|
||||
|
||||
def test_llm_param_shows_deprecation_warning(self):
|
||||
"""Using llm= should produce a deprecation warning."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
warnings.simplefilter("always")
|
||||
_agent = Agent( # noqa: F841
|
||||
name="test",
|
||||
instructions="Test agent",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Filter for DeprecationWarning about 'llm'
|
||||
llm_warnings = [x for x in w if 'llm' in str(x.message).lower() and issubclass(x.category, DeprecationWarning)]
|
||||
assert len(llm_warnings) >= 1, "llm= should produce deprecation warning"
|
||||
assert 'model' in str(llm_warnings[0].message).lower(), "Warning should suggest using 'model' instead"
|
||||
|
||||
def test_llm_and_model_both_work(self):
|
||||
"""Both llm= and model= should work (backward compatibility)."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore") # Ignore warnings for this test
|
||||
|
||||
agent1 = Agent(name="test1", instructions="Test", llm="gpt-4o-mini")
|
||||
agent2 = Agent(name="test2", instructions="Test", model="gpt-4o-mini")
|
||||
|
||||
# Both should have the same model configured
|
||||
assert agent1.llm == agent2.llm
|
||||
|
||||
|
||||
class TestTaskDependsOnAlias:
|
||||
"""Test that depends_on= is an alias for context= in Task."""
|
||||
|
||||
def test_depends_on_alias_works(self):
|
||||
"""depends_on= should work as alias for context=."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task1 = Task(description="First task")
|
||||
task2 = Task(
|
||||
description="Second task",
|
||||
depends_on=[task1]
|
||||
)
|
||||
|
||||
assert task2.context == [task1], "depends_on should set context"
|
||||
|
||||
def test_context_still_works(self):
|
||||
"""context= should still work (backward compatibility)."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task1 = Task(description="First task")
|
||||
task2 = Task(
|
||||
description="Second task",
|
||||
context=[task1]
|
||||
)
|
||||
|
||||
assert task2.context == [task1]
|
||||
|
||||
def test_depends_on_and_context_merge(self):
|
||||
"""If both provided, depends_on takes precedence."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task1 = Task(description="First task")
|
||||
task2 = Task(description="Second task")
|
||||
task3 = Task(
|
||||
description="Third task",
|
||||
context=[task1],
|
||||
depends_on=[task2]
|
||||
)
|
||||
|
||||
# depends_on should take precedence
|
||||
assert task3.context == [task2], "depends_on should take precedence over context"
|
||||
|
||||
def test_depends_on_attribute_accessible(self):
|
||||
"""depends_on should be accessible as an attribute."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task1 = Task(description="First task")
|
||||
task2 = Task(
|
||||
description="Second task",
|
||||
depends_on=[task1]
|
||||
)
|
||||
|
||||
# Should be accessible via both names
|
||||
assert task2.depends_on == [task1]
|
||||
assert task2.context == [task1]
|
||||
|
||||
|
||||
class TestTaskGuardrailsStandardization:
|
||||
"""Test that guardrails= is the canonical name."""
|
||||
|
||||
def test_guardrails_plural_works(self):
|
||||
"""guardrails= (plural) should work."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
def my_guardrail(output):
|
||||
return (True, output)
|
||||
|
||||
task = Task(
|
||||
description="Test task",
|
||||
guardrails=my_guardrail
|
||||
)
|
||||
|
||||
assert task.guardrail == my_guardrail
|
||||
|
||||
def test_guardrail_singular_shows_deprecation(self):
|
||||
"""guardrail= (singular) should show deprecation warning."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
def my_guardrail(output):
|
||||
return (True, output)
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
warnings.simplefilter("always")
|
||||
_task = Task( # noqa: F841
|
||||
description="Test task",
|
||||
guardrail=my_guardrail
|
||||
)
|
||||
|
||||
# Filter for DeprecationWarning about 'guardrail'
|
||||
gr_warnings = [x for x in w if 'guardrail' in str(x.message).lower() and issubclass(x.category, DeprecationWarning)]
|
||||
assert len(gr_warnings) >= 1, "guardrail= (singular) should produce deprecation warning"
|
||||
|
||||
def test_guardrails_takes_precedence(self):
|
||||
"""If both provided, guardrails= takes precedence."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
def guardrail1(output):
|
||||
return (True, "guardrail1")
|
||||
|
||||
def guardrail2(output):
|
||||
return (True, "guardrail2")
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
task = Task(
|
||||
description="Test task",
|
||||
guardrail=guardrail1,
|
||||
guardrails=guardrail2
|
||||
)
|
||||
|
||||
assert task.guardrail == guardrail2, "guardrails= should take precedence"
|
||||
|
||||
|
||||
class TestYAMLParserNormalization:
|
||||
"""Test YAML parser normalizes parameter names."""
|
||||
|
||||
def test_yaml_depends_on_normalized(self):
|
||||
"""YAML with depends_on should work - parser should accept the field."""
|
||||
from praisonaiagents.workflows.yaml_parser import YAMLWorkflowParser
|
||||
|
||||
yaml_content = """
|
||||
name: Test Workflow
|
||||
agents:
|
||||
researcher:
|
||||
name: Researcher
|
||||
instructions: Research topics
|
||||
steps:
|
||||
- name: step1
|
||||
agent: researcher
|
||||
action: "Do research"
|
||||
- name: step2
|
||||
agent: researcher
|
||||
action: "Summarize"
|
||||
depends_on: [step1]
|
||||
"""
|
||||
parser = YAMLWorkflowParser()
|
||||
# Should not raise an error - depends_on should be accepted
|
||||
workflow = parser.parse_string(yaml_content)
|
||||
|
||||
# The workflow should have 2 steps
|
||||
assert len(workflow.steps) == 2
|
||||
# Workflow parsed successfully with depends_on field
|
||||
assert workflow.name == "Test Workflow"
|
||||
|
||||
def test_yaml_context_still_works(self):
|
||||
"""YAML with context should still work."""
|
||||
from praisonaiagents.workflows.yaml_parser import YAMLWorkflowParser
|
||||
|
||||
yaml_content = """
|
||||
name: Test Workflow
|
||||
agents:
|
||||
researcher:
|
||||
name: Researcher
|
||||
instructions: Research topics
|
||||
steps:
|
||||
- name: step1
|
||||
agent: researcher
|
||||
action: "Do research"
|
||||
- name: step2
|
||||
agent: researcher
|
||||
action: "Summarize"
|
||||
context: [step1]
|
||||
"""
|
||||
parser = YAMLWorkflowParser()
|
||||
workflow = parser.parse_string(yaml_content)
|
||||
|
||||
assert len(workflow.steps) == 2
|
||||
|
||||
|
||||
class TestBackwardCompatibility:
|
||||
"""Ensure all changes are backward compatible."""
|
||||
|
||||
def test_agent_creation_unchanged(self):
|
||||
"""Basic agent creation should work unchanged."""
|
||||
from praisonaiagents import Agent
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
agent = Agent(
|
||||
name="test",
|
||||
role="Tester",
|
||||
goal="Test things",
|
||||
backstory="A test agent"
|
||||
)
|
||||
|
||||
assert agent.name == "test"
|
||||
assert agent.role == "Tester"
|
||||
|
||||
def test_task_creation_unchanged(self):
|
||||
"""Basic task creation should work unchanged."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(
|
||||
description="Test task",
|
||||
expected_output="Test output"
|
||||
)
|
||||
|
||||
assert task.description == "Test task"
|
||||
|
||||
def test_action_alias_still_works(self):
|
||||
"""action= should still work as alias for description=."""
|
||||
from praisonaiagents import Task
|
||||
|
||||
task = Task(action="Do something")
|
||||
|
||||
assert task.description == "Do something"
|
||||
assert task.action == "Do something"
|
||||
|
||||
|
||||
class TestPerformance:
|
||||
"""Ensure no performance regression."""
|
||||
|
||||
def test_import_time_acceptable(self):
|
||||
"""Import time should be under 200ms."""
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
# Run import in subprocess to get clean timing
|
||||
start = time.time()
|
||||
subprocess.run(
|
||||
['python3', '-c', 'import praisonaiagents'],
|
||||
capture_output=True,
|
||||
timeout=10
|
||||
)
|
||||
elapsed = time.time() - start
|
||||
|
||||
# Allow some overhead for subprocess startup
|
||||
# The actual import should be much faster
|
||||
assert elapsed < 5.0, f"Import took {elapsed:.2f}s, expected < 5s (including subprocess overhead)"
|
||||
@@ -0,0 +1,324 @@
|
||||
"""
|
||||
Unit tests for praisonaiagents.paths module.
|
||||
|
||||
Tests centralized path utilities for PraisonAI data storage.
|
||||
TDD: These tests define the expected behavior of the paths module.
|
||||
"""
|
||||
|
||||
import os
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
class TestGetDataDir:
|
||||
"""Tests for get_data_dir() function."""
|
||||
|
||||
def test_default_returns_praisonai_in_home(self):
|
||||
"""Default data dir should be ~/.praisonai/"""
|
||||
from praisonaiagents.paths import get_data_dir
|
||||
|
||||
result = get_data_dir()
|
||||
expected = Path.home() / ".praisonai"
|
||||
assert result == expected
|
||||
|
||||
def test_env_var_override(self):
|
||||
"""PRAISONAI_HOME env var should override default."""
|
||||
from praisonaiagents.paths import get_data_dir
|
||||
|
||||
with patch.dict(os.environ, {"PRAISONAI_HOME": "/custom/path"}):
|
||||
result = get_data_dir()
|
||||
assert result == Path("/custom/path")
|
||||
|
||||
def test_env_var_expands_tilde(self):
|
||||
"""PRAISONAI_HOME should expand ~ to home directory."""
|
||||
from praisonaiagents.paths import get_data_dir
|
||||
|
||||
with patch.dict(os.environ, {"PRAISONAI_HOME": "~/custom/praison"}):
|
||||
result = get_data_dir()
|
||||
assert result == Path.home() / "custom" / "praison"
|
||||
|
||||
def test_legacy_fallback_with_warning(self, tmp_path):
|
||||
"""Should fall back to ~/.praison/ if it exists and ~/.praisonai/ doesn't."""
|
||||
from praisonaiagents.paths import get_data_dir, _clear_cache
|
||||
|
||||
# Clear cache before test
|
||||
_clear_cache()
|
||||
|
||||
# Create mock home with only legacy dir
|
||||
mock_home = tmp_path / "home"
|
||||
legacy_dir = mock_home / ".praison"
|
||||
legacy_dir.mkdir(parents=True)
|
||||
|
||||
with patch("praisonaiagents.paths.Path.home", return_value=mock_home):
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
# Remove PRAISONAI_HOME if set
|
||||
os.environ.pop("PRAISONAI_HOME", None)
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
warnings.simplefilter("always")
|
||||
result = get_data_dir()
|
||||
|
||||
# Should return legacy path
|
||||
assert result == legacy_dir
|
||||
|
||||
# Should emit deprecation warning
|
||||
assert len(w) == 1
|
||||
assert issubclass(w[0].category, DeprecationWarning)
|
||||
assert ".praison" in str(w[0].message)
|
||||
|
||||
# Clear cache after test
|
||||
_clear_cache()
|
||||
|
||||
|
||||
class TestGetSessionsDir:
|
||||
"""Tests for get_sessions_dir() function."""
|
||||
|
||||
def test_returns_sessions_subdir(self):
|
||||
"""Should return sessions subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_sessions_dir
|
||||
|
||||
result = get_sessions_dir()
|
||||
assert result == Path.home() / ".praisonai" / "sessions"
|
||||
|
||||
def test_respects_env_override(self):
|
||||
"""Should respect PRAISONAI_HOME override."""
|
||||
from praisonaiagents.paths import get_sessions_dir
|
||||
|
||||
with patch.dict(os.environ, {"PRAISONAI_HOME": "/custom"}):
|
||||
result = get_sessions_dir()
|
||||
assert result == Path("/custom/sessions")
|
||||
|
||||
|
||||
class TestGetSkillsDir:
|
||||
"""Tests for get_skills_dir() function."""
|
||||
|
||||
def test_returns_skills_subdir(self):
|
||||
"""Should return skills subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_skills_dir
|
||||
|
||||
result = get_skills_dir()
|
||||
assert result == Path.home() / ".praisonai" / "skills"
|
||||
|
||||
|
||||
class TestGetPluginsDir:
|
||||
"""Tests for get_plugins_dir() function."""
|
||||
|
||||
def test_returns_plugins_subdir(self):
|
||||
"""Should return plugins subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_plugins_dir
|
||||
|
||||
result = get_plugins_dir()
|
||||
assert result == Path.home() / ".praisonai" / "plugins"
|
||||
|
||||
|
||||
class TestGetMcpDir:
|
||||
"""Tests for get_mcp_dir() function."""
|
||||
|
||||
def test_returns_mcp_subdir(self):
|
||||
"""Should return mcp subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_mcp_dir
|
||||
|
||||
result = get_mcp_dir()
|
||||
assert result == Path.home() / ".praisonai" / "mcp"
|
||||
|
||||
|
||||
class TestGetDocsDir:
|
||||
"""Tests for get_docs_dir() function."""
|
||||
|
||||
def test_returns_docs_subdir(self):
|
||||
"""Should return docs subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_docs_dir
|
||||
|
||||
result = get_docs_dir()
|
||||
assert result == Path.home() / ".praisonai" / "docs"
|
||||
|
||||
|
||||
class TestGetRulesDir:
|
||||
"""Tests for get_rules_dir() function."""
|
||||
|
||||
def test_returns_rules_subdir(self):
|
||||
"""Should return rules subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_rules_dir
|
||||
|
||||
result = get_rules_dir()
|
||||
assert result == Path.home() / ".praisonai" / "rules"
|
||||
|
||||
|
||||
class TestGetPermissionsDir:
|
||||
"""Tests for get_permissions_dir() function."""
|
||||
|
||||
def test_returns_permissions_subdir(self):
|
||||
"""Should return permissions subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_permissions_dir
|
||||
|
||||
result = get_permissions_dir()
|
||||
assert result == Path.home() / ".praisonai" / "permissions"
|
||||
|
||||
|
||||
class TestGetStorageDir:
|
||||
"""Tests for get_storage_dir() function."""
|
||||
|
||||
def test_returns_storage_subdir(self):
|
||||
"""Should return storage subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_storage_dir
|
||||
|
||||
result = get_storage_dir()
|
||||
assert result == Path.home() / ".praisonai" / "storage"
|
||||
|
||||
|
||||
class TestGetCheckpointsDir:
|
||||
"""Tests for get_checkpoints_dir() function."""
|
||||
|
||||
def test_returns_checkpoints_subdir(self):
|
||||
"""Should return checkpoints subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_checkpoints_dir
|
||||
|
||||
result = get_checkpoints_dir()
|
||||
assert result == Path.home() / ".praisonai" / "checkpoints"
|
||||
|
||||
|
||||
class TestGetSnapshotsDir:
|
||||
"""Tests for get_snapshots_dir() function."""
|
||||
|
||||
def test_returns_snapshots_subdir(self):
|
||||
"""Should return snapshots subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_snapshots_dir
|
||||
|
||||
result = get_snapshots_dir()
|
||||
assert result == Path.home() / ".praisonai" / "snapshots"
|
||||
|
||||
|
||||
class TestGetLearnDir:
|
||||
"""Tests for get_learn_dir() function."""
|
||||
|
||||
def test_returns_learn_subdir(self):
|
||||
"""Should return learn subdirectory of data dir."""
|
||||
from praisonaiagents.paths import get_learn_dir
|
||||
|
||||
result = get_learn_dir()
|
||||
assert result == Path.home() / ".praisonai" / "learn"
|
||||
|
||||
|
||||
class TestGetProjectDataDir:
|
||||
"""Tests for get_project_data_dir() function."""
|
||||
|
||||
def test_returns_praisonai_in_cwd(self):
|
||||
"""Should return .praisonai/ in current working directory."""
|
||||
from praisonaiagents.paths import get_project_data_dir
|
||||
|
||||
result = get_project_data_dir()
|
||||
assert result == Path.cwd() / ".praisonai"
|
||||
|
||||
def test_accepts_custom_project_path(self, tmp_path):
|
||||
"""Should accept custom project path."""
|
||||
from praisonaiagents.paths import get_project_data_dir
|
||||
|
||||
result = get_project_data_dir(tmp_path)
|
||||
assert result == tmp_path / ".praisonai"
|
||||
|
||||
|
||||
class TestEnsureDir:
|
||||
"""Tests for ensure_dir() function."""
|
||||
|
||||
def test_creates_directory(self, tmp_path):
|
||||
"""Should create directory if it doesn't exist."""
|
||||
from praisonaiagents.paths import ensure_dir
|
||||
|
||||
test_dir = tmp_path / "test" / "nested" / "dir"
|
||||
assert not test_dir.exists()
|
||||
|
||||
result = ensure_dir(test_dir)
|
||||
|
||||
assert test_dir.exists()
|
||||
assert test_dir.is_dir()
|
||||
assert result == test_dir
|
||||
|
||||
def test_returns_existing_directory(self, tmp_path):
|
||||
"""Should return existing directory without error."""
|
||||
from praisonaiagents.paths import ensure_dir
|
||||
|
||||
test_dir = tmp_path / "existing"
|
||||
test_dir.mkdir()
|
||||
|
||||
result = ensure_dir(test_dir)
|
||||
|
||||
assert result == test_dir
|
||||
|
||||
|
||||
class TestGetMcpAuthPath:
|
||||
"""Tests for get_mcp_auth_path() function."""
|
||||
|
||||
def test_returns_mcp_auth_json(self):
|
||||
"""Should return path to mcp-auth.json."""
|
||||
from praisonaiagents.paths import get_mcp_auth_path
|
||||
|
||||
result = get_mcp_auth_path()
|
||||
assert result == Path.home() / ".praisonai" / "mcp-auth.json"
|
||||
|
||||
|
||||
class TestConstants:
|
||||
"""Tests for module constants."""
|
||||
|
||||
def test_env_var_name(self):
|
||||
"""ENV_VAR should be PRAISONAI_HOME."""
|
||||
from praisonaiagents.paths import ENV_VAR
|
||||
|
||||
assert ENV_VAR == "PRAISONAI_HOME"
|
||||
|
||||
def test_default_dir_name(self):
|
||||
"""DEFAULT_DIR_NAME should be .praisonai."""
|
||||
from praisonaiagents.paths import DEFAULT_DIR_NAME
|
||||
|
||||
assert DEFAULT_DIR_NAME == ".praisonai"
|
||||
|
||||
def test_legacy_dir_name(self):
|
||||
"""LEGACY_DIR_NAME should be .praison."""
|
||||
from praisonaiagents.paths import LEGACY_DIR_NAME
|
||||
|
||||
assert LEGACY_DIR_NAME == ".praison"
|
||||
|
||||
|
||||
class TestGetAllPaths:
|
||||
"""Tests for get_all_paths() function."""
|
||||
|
||||
def test_returns_dict_of_all_paths(self):
|
||||
"""Should return dictionary with all path locations."""
|
||||
from praisonaiagents.paths import get_all_paths
|
||||
|
||||
result = get_all_paths()
|
||||
|
||||
assert isinstance(result, dict)
|
||||
assert "data_dir" in result
|
||||
assert "sessions" in result
|
||||
assert "skills" in result
|
||||
assert "plugins" in result
|
||||
assert "mcp" in result
|
||||
assert "docs" in result
|
||||
assert "rules" in result
|
||||
assert "permissions" in result
|
||||
assert "storage" in result
|
||||
assert "checkpoints" in result
|
||||
assert "snapshots" in result
|
||||
assert "learn" in result
|
||||
assert "mcp_auth" in result
|
||||
|
||||
|
||||
class TestImportPerformance:
|
||||
"""Tests for import performance."""
|
||||
|
||||
def test_import_time_under_10ms(self):
|
||||
"""Module import should be fast (no heavy deps)."""
|
||||
import time as time_module
|
||||
import sys as sys_module
|
||||
|
||||
# Remove from cache if present
|
||||
if "praisonaiagents.paths" in sys_module.modules:
|
||||
del sys_module.modules["praisonaiagents.paths"]
|
||||
|
||||
start = time_module.perf_counter()
|
||||
import praisonaiagents.paths as paths_module # noqa: F401
|
||||
elapsed = time_module.perf_counter() - start
|
||||
|
||||
# Should import in under 10ms (no heavy deps)
|
||||
assert elapsed < 0.01, f"Import took {elapsed*1000:.2f}ms, expected < 10ms"
|
||||
@@ -352,8 +352,8 @@ class TestZeroOverhead:
|
||||
Profiler.record_timing("test", 100.0)
|
||||
elapsed = (time.perf_counter() - start) * 1000
|
||||
|
||||
# Should complete 10k calls in under 10ms when disabled
|
||||
assert elapsed < 10, f"record_timing took {elapsed}ms for 10k calls"
|
||||
# Should complete 10k calls in under 50ms when disabled (conservative for CI)
|
||||
assert elapsed < 50, f"record_timing took {elapsed}ms for 10k calls"
|
||||
|
||||
def test_phase_context_overhead(self):
|
||||
"""phase context manager should be fast when disabled."""
|
||||
|
||||
@@ -139,9 +139,14 @@ class TestRateLimiterAgentIntegration:
|
||||
|
||||
def test_agent_rate_limiter_applied_to_llm_calls(self):
|
||||
"""Rate limiter should be applied before LLM calls."""
|
||||
import os
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.llm import RateLimiter
|
||||
|
||||
# Skip if no API key - this test requires mocking at a deeper level
|
||||
if not os.environ.get("OPENAI_API_KEY"):
|
||||
pytest.skip("OPENAI_API_KEY not set")
|
||||
|
||||
limiter = RateLimiter(requests_per_minute=60)
|
||||
acquire_count = [0]
|
||||
original_acquire = limiter.acquire
|
||||
|
||||
@@ -4,10 +4,16 @@ TDD tests for:
|
||||
1. list_processes NoneType bug fix
|
||||
2. internet_search retry logic
|
||||
3. search_web reliability
|
||||
|
||||
NOTE: These tests require psutil to be installed.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Skip entire module if psutil is not installed
|
||||
pytest.importorskip("psutil", reason="psutil package not installed")
|
||||
|
||||
|
||||
class TestListProcessesReliability:
|
||||
"""Tests for list_processes NoneType bug fix."""
|
||||
|
||||
@@ -432,8 +432,8 @@ class TestPerformance:
|
||||
emitter.tool_end("test", duration_ms=1, status="ok")
|
||||
elapsed = time.perf_counter() - start
|
||||
|
||||
# Should complete 10000 iterations in under 100ms
|
||||
assert elapsed < 0.1, f"NoOpSink too slow: {elapsed:.3f}s for 10000 iterations"
|
||||
# Should complete 10000 iterations in under 500ms (conservative for CI)
|
||||
assert elapsed < 0.5, f"NoOpSink too slow: {elapsed:.3f}s for 10000 iterations"
|
||||
|
||||
def test_disabled_emitter_overhead(self):
|
||||
"""Test that disabled emitter has near-zero overhead."""
|
||||
|
||||
Generated
+10
-2
@@ -2549,7 +2549,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "1.2.2"
|
||||
version = "1.3.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
@@ -2617,6 +2617,11 @@ mongodb = [
|
||||
{ name = "motor" },
|
||||
{ name = "pymongo" },
|
||||
]
|
||||
os = [
|
||||
{ name = "fastapi" },
|
||||
{ name = "pyjwt" },
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
telemetry = [
|
||||
{ name = "posthog" },
|
||||
]
|
||||
@@ -2630,6 +2635,7 @@ requires-dist = [
|
||||
{ name = "chromadb", marker = "extra == 'memory'", specifier = ">=1.0.0" },
|
||||
{ name = "fastapi", marker = "extra == 'api'", specifier = ">=0.115.0" },
|
||||
{ name = "fastapi", marker = "extra == 'mcp'", specifier = ">=0.115.0" },
|
||||
{ name = "fastapi", marker = "extra == 'os'", specifier = ">=0.115.0" },
|
||||
{ name = "litellm", marker = "extra == 'llm'", specifier = ">=1.81.0" },
|
||||
{ name = "litellm", marker = "extra == 'memory'", specifier = ">=1.81.0" },
|
||||
{ name = "markitdown", extras = ["all"], marker = "extra == 'knowledge'", specifier = ">=0.1.0" },
|
||||
@@ -2653,15 +2659,17 @@ requires-dist = [
|
||||
{ name = "pydantic", specifier = ">=2.10.0" },
|
||||
{ name = "pydantic", marker = "extra == 'llm'", specifier = ">=2.10.0" },
|
||||
{ name = "pyjwt", marker = "extra == 'auth'", specifier = ">=2.8.0" },
|
||||
{ name = "pyjwt", marker = "extra == 'os'", specifier = ">=2.8.0" },
|
||||
{ name = "pymongo", marker = "extra == 'mongodb'", specifier = ">=4.6.3" },
|
||||
{ name = "python-jose", extras = ["cryptography"], marker = "extra == 'auth'", specifier = ">=3.3.0" },
|
||||
{ name = "python-multipart", marker = "extra == 'auth'", specifier = ">=0.0.6" },
|
||||
{ name = "rich" },
|
||||
{ name = "uvicorn", marker = "extra == 'api'", specifier = ">=0.34.0" },
|
||||
{ name = "uvicorn", marker = "extra == 'mcp'", specifier = ">=0.34.0" },
|
||||
{ name = "uvicorn", marker = "extra == 'os'", specifier = ">=0.34.0" },
|
||||
{ name = "websockets", marker = "extra == 'mcp'", specifier = ">=12.0" },
|
||||
]
|
||||
provides-extras = ["mcp", "memory", "knowledge", "graph", "llm", "api", "telemetry", "mongodb", "auth", "all"]
|
||||
provides-extras = ["mcp", "memory", "knowledge", "graph", "llm", "api", "os", "telemetry", "mongodb", "auth", "all"]
|
||||
|
||||
[[package]]
|
||||
name = "propcache"
|
||||
|
||||
@@ -3,8 +3,8 @@ class Praisonai < Formula
|
||||
|
||||
desc "AI tools for various AI applications"
|
||||
homepage "https://github.com/MervinPraison/PraisonAI"
|
||||
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v4.2.2.tar.gz"
|
||||
sha256 `curl -sL https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v4.2.2.tar.gz | shasum -a 256`.split.first
|
||||
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v4.3.0.tar.gz"
|
||||
sha256 `curl -sL https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v4.3.0.tar.gz | shasum -a 256`.split.first
|
||||
license "MIT"
|
||||
|
||||
depends_on "[email protected]"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,463 @@
|
||||
"""
|
||||
Agent-Driven Migration Flow.
|
||||
|
||||
Uses AgentFlow with specialized agents to migrate code from various
|
||||
agent frameworks to PraisonAI format.
|
||||
|
||||
Architecture:
|
||||
1. Analyzer Agent - Scans all files, understands relationships
|
||||
2. Converter Agent - Transforms code using migration spec
|
||||
3. Evaluator Agent - Uses LLM-as-Judge to validate conversion
|
||||
4. Error Agent - Analyzes failures and suggests fixes
|
||||
|
||||
The flow includes a retry loop (max 3 iterations) for error recovery.
|
||||
"""
|
||||
|
||||
import os
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileContext:
|
||||
"""Context for a single file in the migration."""
|
||||
path: str
|
||||
content: str
|
||||
patterns_found: List[str] = field(default_factory=list)
|
||||
converted_content: Optional[str] = None
|
||||
errors: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MigrationContext:
|
||||
"""Complete context for multi-file migration."""
|
||||
source_path: str
|
||||
files: Dict[str, FileContext] = field(default_factory=dict)
|
||||
all_imports: List[str] = field(default_factory=list)
|
||||
all_classes: List[str] = field(default_factory=list)
|
||||
all_functions: List[str] = field(default_factory=list)
|
||||
cross_file_deps: Dict[str, List[str]] = field(default_factory=dict)
|
||||
|
||||
def to_prompt(self) -> str:
|
||||
"""Convert context to a prompt for LLM agents."""
|
||||
lines = [
|
||||
f"# Project Analysis: {self.source_path}",
|
||||
f"Total files: {len(self.files)}",
|
||||
"",
|
||||
"## Files:",
|
||||
]
|
||||
for path, ctx in self.files.items():
|
||||
lines.append(f"- {path}: {len(ctx.content)} chars, patterns: {ctx.patterns_found}")
|
||||
|
||||
if self.cross_file_deps:
|
||||
lines.append("")
|
||||
lines.append("## Cross-file Dependencies:")
|
||||
for file, deps in self.cross_file_deps.items():
|
||||
lines.append(f"- {file} imports from: {deps}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MigrationResult:
|
||||
"""Result of the migration flow."""
|
||||
success: bool
|
||||
files_converted: int = 0
|
||||
files_failed: int = 0
|
||||
iterations: int = 0
|
||||
evaluation_score: float = 0.0
|
||||
converted_files: Dict[str, str] = field(default_factory=dict)
|
||||
errors: List[str] = field(default_factory=list)
|
||||
warnings: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class MigrationFlow:
|
||||
"""
|
||||
Agent-driven migration flow using AgentFlow.
|
||||
|
||||
Uses specialized agents to analyze, convert, evaluate, and fix
|
||||
code migration from various agent frameworks to PraisonAI.
|
||||
|
||||
Example:
|
||||
flow = MigrationFlow(
|
||||
source_path="./my-project",
|
||||
output_path="./converted",
|
||||
max_retries=3
|
||||
)
|
||||
result = flow.run()
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
source_path: str,
|
||||
output_path: Optional[str] = None,
|
||||
max_retries: int = 3,
|
||||
llm: str = "gpt-4o-mini",
|
||||
dry_run: bool = True,
|
||||
):
|
||||
self.source_path = source_path
|
||||
self.output_path = output_path or f"{source_path}_converted"
|
||||
self.max_retries = max_retries
|
||||
self.llm = llm
|
||||
self.dry_run = dry_run
|
||||
self._context: Optional[MigrationContext] = None
|
||||
self._spec = None
|
||||
|
||||
def _gather_files(self) -> MigrationContext:
|
||||
"""Gather all Python files and build context."""
|
||||
context = MigrationContext(source_path=self.source_path)
|
||||
|
||||
source = Path(self.source_path)
|
||||
|
||||
if source.is_file():
|
||||
# Single file
|
||||
with open(source, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
context.files[str(source)] = FileContext(
|
||||
path=str(source),
|
||||
content=content
|
||||
)
|
||||
else:
|
||||
# Directory - scan for Python files
|
||||
exclude_dirs = {'venv', '.venv', '__pycache__', '.git', 'node_modules', '.tox', 'dist', 'build'}
|
||||
|
||||
for root, dirs, files in os.walk(source):
|
||||
# Filter out excluded directories
|
||||
dirs[:] = [d for d in dirs if d not in exclude_dirs]
|
||||
|
||||
for filename in files:
|
||||
if filename.endswith('.py'):
|
||||
filepath = os.path.join(root, filename)
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
rel_path = os.path.relpath(filepath, source)
|
||||
context.files[rel_path] = FileContext(
|
||||
path=rel_path,
|
||||
content=content
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not read {filepath}: {e}")
|
||||
|
||||
# Analyze cross-file dependencies
|
||||
self._analyze_dependencies(context)
|
||||
|
||||
return context
|
||||
|
||||
def _analyze_dependencies(self, context: MigrationContext) -> None:
|
||||
"""Analyze imports and cross-file dependencies."""
|
||||
import re
|
||||
|
||||
for path, file_ctx in context.files.items():
|
||||
# Extract imports
|
||||
import_pattern = r'^(?:from\s+(\S+)\s+)?import\s+(.+)$'
|
||||
for line in file_ctx.content.split('\n'):
|
||||
match = re.match(import_pattern, line.strip())
|
||||
if match:
|
||||
module = match.group(1) or match.group(2).split(',')[0].strip()
|
||||
context.all_imports.append(module)
|
||||
|
||||
# Check if it's a local import
|
||||
for other_path in context.files:
|
||||
other_module = other_path.replace('/', '.').replace('.py', '')
|
||||
if module.startswith(other_module) or other_module.endswith(module):
|
||||
if path not in context.cross_file_deps:
|
||||
context.cross_file_deps[path] = []
|
||||
context.cross_file_deps[path].append(other_path)
|
||||
|
||||
# Extract class and function names
|
||||
class_pattern = r'^class\s+(\w+)'
|
||||
func_pattern = r'^def\s+(\w+)'
|
||||
for line in file_ctx.content.split('\n'):
|
||||
match = re.match(class_pattern, line)
|
||||
if match:
|
||||
context.all_classes.append(match.group(1))
|
||||
match = re.match(func_pattern, line)
|
||||
if match:
|
||||
context.all_functions.append(match.group(1))
|
||||
|
||||
def _create_agents(self):
|
||||
"""Create the specialized migration agents."""
|
||||
# Lazy import to avoid circular dependencies
|
||||
from praisonaiagents import Agent
|
||||
from .migration_spec import get_default_spec, PRAISONAI_REFERENCE
|
||||
|
||||
self._spec = get_default_spec()
|
||||
spec_prompt = self._spec.to_prompt()
|
||||
|
||||
# Analyzer Agent
|
||||
analyzer = Agent(
|
||||
name="Analyzer",
|
||||
role="Code Analyzer",
|
||||
goal="Analyze source code to identify agent patterns and dependencies",
|
||||
instructions=f"""You are a code analysis expert. Analyze the provided source code to:
|
||||
1. Identify all agent-related patterns (Agent, Task, Team, Workflow definitions)
|
||||
2. Map dependencies between files
|
||||
3. Identify import patterns that need conversion
|
||||
4. List all classes and functions that are part of the agent system
|
||||
|
||||
Use this specification to identify patterns:
|
||||
{spec_prompt}
|
||||
|
||||
Output a structured analysis with:
|
||||
- List of detected patterns per file
|
||||
- Cross-file dependencies
|
||||
- Recommended conversion order
|
||||
""",
|
||||
llm=self.llm,
|
||||
)
|
||||
|
||||
# Converter Agent
|
||||
converter = Agent(
|
||||
name="Converter",
|
||||
role="Code Converter",
|
||||
goal="Convert source code to PraisonAI format",
|
||||
instructions=f"""You are a code conversion expert. Convert the provided source code to PraisonAI format.
|
||||
|
||||
Use this specification for conversion:
|
||||
{spec_prompt}
|
||||
|
||||
Reference for PraisonAI code:
|
||||
{PRAISONAI_REFERENCE}
|
||||
|
||||
Rules:
|
||||
1. Preserve all logic and behavior
|
||||
2. Convert imports to praisonaiagents
|
||||
3. Map parameters according to the spec
|
||||
4. Handle cross-file dependencies correctly
|
||||
5. Ensure the converted code is syntactically valid Python
|
||||
6. Do NOT include any framework names in comments
|
||||
|
||||
Output the complete converted code for each file.
|
||||
""",
|
||||
llm=self.llm,
|
||||
)
|
||||
|
||||
# Evaluator Agent (LLM-as-Judge)
|
||||
evaluator = Agent(
|
||||
name="Evaluator",
|
||||
role="Migration Evaluator",
|
||||
goal="Evaluate the quality of code migration",
|
||||
instructions="""You are a code quality evaluator using LLM-as-Judge methodology.
|
||||
|
||||
Evaluate the converted code on these criteria (score 1-10 each):
|
||||
1. **Syntax Correctness**: Is the code valid Python?
|
||||
2. **Import Completeness**: Are all necessary imports present?
|
||||
3. **Functional Equivalence**: Does it preserve the original behavior?
|
||||
4. **Pattern Accuracy**: Are agent patterns correctly converted?
|
||||
5. **Dependency Handling**: Are cross-file dependencies handled?
|
||||
|
||||
Output format:
|
||||
```json
|
||||
{
|
||||
"scores": {
|
||||
"syntax": 8,
|
||||
"imports": 9,
|
||||
"equivalence": 7,
|
||||
"patterns": 8,
|
||||
"dependencies": 9
|
||||
},
|
||||
"overall_score": 8.2,
|
||||
"passed": true,
|
||||
"issues": ["list of specific issues if any"],
|
||||
"suggestions": ["list of improvements if any"]
|
||||
}
|
||||
```
|
||||
|
||||
A score of 8.0 or higher means PASSED.
|
||||
""",
|
||||
llm=self.llm,
|
||||
)
|
||||
|
||||
# Error Agent
|
||||
error_agent = Agent(
|
||||
name="ErrorAnalyzer",
|
||||
role="Error Analyzer",
|
||||
goal="Analyze migration errors and suggest fixes",
|
||||
instructions="""You are an error analysis expert. When migration evaluation fails:
|
||||
|
||||
1. Analyze the specific errors reported
|
||||
2. Identify the root cause
|
||||
3. Suggest specific fixes
|
||||
4. Provide corrected code snippets
|
||||
|
||||
Output format:
|
||||
```json
|
||||
{
|
||||
"root_cause": "description of the main issue",
|
||||
"affected_files": ["list of files with issues"],
|
||||
"fixes": [
|
||||
{
|
||||
"file": "filename",
|
||||
"issue": "what's wrong",
|
||||
"fix": "how to fix it",
|
||||
"corrected_code": "the fixed code snippet"
|
||||
}
|
||||
],
|
||||
"retry_recommended": true
|
||||
}
|
||||
```
|
||||
""",
|
||||
llm=self.llm,
|
||||
)
|
||||
|
||||
return analyzer, converter, evaluator, error_agent
|
||||
|
||||
def run(self) -> MigrationResult:
|
||||
"""Run the migration flow."""
|
||||
result = MigrationResult(success=False)
|
||||
|
||||
# Gather all files
|
||||
logger.info(f"Gathering files from {self.source_path}")
|
||||
self._context = self._gather_files()
|
||||
|
||||
if not self._context.files:
|
||||
result.errors.append("No Python files found")
|
||||
return result
|
||||
|
||||
logger.info(f"Found {len(self._context.files)} files to analyze")
|
||||
|
||||
# Create agents
|
||||
analyzer, converter, evaluator, error_agent = self._create_agents()
|
||||
|
||||
# Build the combined context for all files
|
||||
all_code = []
|
||||
for path, file_ctx in self._context.files.items():
|
||||
all_code.append(f"# File: {path}\n{file_ctx.content}")
|
||||
combined_code = "\n\n---\n\n".join(all_code)
|
||||
|
||||
# Retry loop
|
||||
for iteration in range(self.max_retries):
|
||||
result.iterations = iteration + 1
|
||||
logger.info(f"Migration iteration {iteration + 1}/{self.max_retries}")
|
||||
|
||||
try:
|
||||
# Step 1: Analyze
|
||||
analysis_prompt = f"""Analyze this codebase for migration:
|
||||
|
||||
{self._context.to_prompt()}
|
||||
|
||||
Full code:
|
||||
{combined_code}
|
||||
"""
|
||||
analysis = analyzer.start(analysis_prompt)
|
||||
logger.info("Analysis complete")
|
||||
|
||||
# Step 2: Convert
|
||||
convert_prompt = f"""Convert this code to PraisonAI format.
|
||||
|
||||
Analysis results:
|
||||
{analysis}
|
||||
|
||||
Original code:
|
||||
{combined_code}
|
||||
|
||||
Convert ALL files and output the complete converted code for each file.
|
||||
Format: Start each file with "# FILE: filename.py" followed by the converted code.
|
||||
"""
|
||||
converted = converter.start(convert_prompt)
|
||||
logger.info("Conversion complete")
|
||||
|
||||
# Parse converted files
|
||||
self._parse_converted_output(converted, result)
|
||||
|
||||
# Step 3: Evaluate
|
||||
eval_prompt = f"""Evaluate this migration:
|
||||
|
||||
Original code:
|
||||
{combined_code}
|
||||
|
||||
Converted code:
|
||||
{converted}
|
||||
|
||||
Evaluate and score the migration quality.
|
||||
"""
|
||||
evaluation = evaluator.start(eval_prompt)
|
||||
logger.info("Evaluation complete")
|
||||
|
||||
# Parse evaluation result
|
||||
import json
|
||||
import re
|
||||
|
||||
# Try to extract JSON from evaluation
|
||||
json_match = re.search(r'\{[\s\S]*\}', evaluation)
|
||||
if json_match:
|
||||
try:
|
||||
eval_result = json.loads(json_match.group())
|
||||
result.evaluation_score = eval_result.get('overall_score', 0)
|
||||
|
||||
if eval_result.get('passed', False) or result.evaluation_score >= 8.0:
|
||||
result.success = True
|
||||
result.files_converted = len(result.converted_files)
|
||||
logger.info(f"Migration PASSED with score {result.evaluation_score}")
|
||||
break
|
||||
else:
|
||||
# Evaluation failed, run error analysis
|
||||
issues = eval_result.get('issues', [])
|
||||
result.warnings.extend(issues)
|
||||
|
||||
if iteration < self.max_retries - 1:
|
||||
error_prompt = f"""Migration evaluation failed.
|
||||
|
||||
Issues found:
|
||||
{issues}
|
||||
|
||||
Converted code:
|
||||
{converted}
|
||||
|
||||
Analyze the errors and suggest fixes.
|
||||
"""
|
||||
_ = error_agent.start(error_prompt)
|
||||
logger.info("Error analysis complete, retrying...")
|
||||
# The next iteration will use the error analysis context
|
||||
except json.JSONDecodeError:
|
||||
result.warnings.append("Could not parse evaluation result")
|
||||
else:
|
||||
result.warnings.append("No evaluation JSON found")
|
||||
|
||||
except Exception as e:
|
||||
result.errors.append(f"Iteration {iteration + 1} failed: {str(e)}")
|
||||
logger.error(f"Migration error: {e}")
|
||||
|
||||
if not result.success:
|
||||
result.errors.append(f"Migration failed after {self.max_retries} attempts")
|
||||
|
||||
# Save converted files if not dry run
|
||||
if not self.dry_run and result.success:
|
||||
self._save_converted_files(result)
|
||||
|
||||
return result
|
||||
|
||||
def _parse_converted_output(self, converted: str, result: MigrationResult) -> None:
|
||||
"""Parse the converted output into individual files."""
|
||||
import re
|
||||
|
||||
# Split by file markers
|
||||
file_pattern = r'#\s*FILE:\s*(\S+\.py)'
|
||||
parts = re.split(file_pattern, converted)
|
||||
|
||||
# parts[0] is before first file, then alternating filename, content
|
||||
for i in range(1, len(parts), 2):
|
||||
if i + 1 < len(parts):
|
||||
filename = parts[i].strip()
|
||||
content = parts[i + 1].strip()
|
||||
# Clean up code blocks
|
||||
content = re.sub(r'^```python\s*', '', content)
|
||||
content = re.sub(r'\s*```$', '', content)
|
||||
result.converted_files[filename] = content
|
||||
|
||||
def _save_converted_files(self, result: MigrationResult) -> None:
|
||||
"""Save converted files to output directory."""
|
||||
output_dir = Path(self.output_path)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for filename, content in result.converted_files.items():
|
||||
filepath = output_dir / filename
|
||||
filepath.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
logger.info(f"Saved: {filepath}")
|
||||
@@ -0,0 +1,276 @@
|
||||
"""
|
||||
Migration Specification for Agent-Driven Code Migration.
|
||||
|
||||
This module defines the feature mapping specification used by the migration agents
|
||||
to convert code from various agent framework patterns to PraisonAI format.
|
||||
|
||||
The spec is framework-agnostic - it describes patterns generically without
|
||||
explicitly naming source frameworks.
|
||||
|
||||
Design:
|
||||
- Pattern-based: Describes what to look for, not where it comes from
|
||||
- Dynamic: LLM agents use this spec to understand and convert code
|
||||
- Extensible: New patterns can be added without code changes
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List
|
||||
|
||||
|
||||
@dataclass
|
||||
class PatternSpec:
|
||||
"""Specification for a code pattern to detect and convert."""
|
||||
name: str
|
||||
description: str
|
||||
source_indicators: List[str] # What to look for in source code
|
||||
target_equivalent: str # PraisonAI equivalent
|
||||
parameter_mapping: Dict[str, str] # source_param -> praisonai_param
|
||||
notes: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class MigrationSpec:
|
||||
"""Complete migration specification for agent-driven conversion."""
|
||||
|
||||
# Agent patterns
|
||||
agent_patterns: List[PatternSpec] = field(default_factory=list)
|
||||
|
||||
# Task/Step patterns
|
||||
task_patterns: List[PatternSpec] = field(default_factory=list)
|
||||
|
||||
# Team/Orchestrator patterns
|
||||
team_patterns: List[PatternSpec] = field(default_factory=list)
|
||||
|
||||
# Workflow patterns
|
||||
workflow_patterns: List[PatternSpec] = field(default_factory=list)
|
||||
|
||||
# Import patterns
|
||||
import_patterns: Dict[str, str] = field(default_factory=dict)
|
||||
|
||||
# Method patterns
|
||||
method_patterns: Dict[str, str] = field(default_factory=dict)
|
||||
|
||||
def to_prompt(self) -> str:
|
||||
"""Convert spec to a prompt for LLM agents."""
|
||||
lines = [
|
||||
"# Code Migration Specification",
|
||||
"",
|
||||
"Use this specification to convert agent code to PraisonAI format.",
|
||||
"",
|
||||
"## Agent Patterns",
|
||||
""
|
||||
]
|
||||
|
||||
for p in self.agent_patterns:
|
||||
lines.append(f"### {p.name}")
|
||||
lines.append(f"Description: {p.description}")
|
||||
lines.append(f"Look for: {', '.join(p.source_indicators)}")
|
||||
lines.append(f"Convert to: {p.target_equivalent}")
|
||||
lines.append("Parameter mapping:")
|
||||
for src, tgt in p.parameter_mapping.items():
|
||||
lines.append(f" - {src} → {tgt}")
|
||||
if p.notes:
|
||||
lines.append(f"Notes: {p.notes}")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Task Patterns")
|
||||
lines.append("")
|
||||
for p in self.task_patterns:
|
||||
lines.append(f"### {p.name}")
|
||||
lines.append(f"Description: {p.description}")
|
||||
lines.append(f"Look for: {', '.join(p.source_indicators)}")
|
||||
lines.append(f"Convert to: {p.target_equivalent}")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Team/Orchestrator Patterns")
|
||||
lines.append("")
|
||||
for p in self.team_patterns:
|
||||
lines.append(f"### {p.name}")
|
||||
lines.append(f"Description: {p.description}")
|
||||
lines.append(f"Look for: {', '.join(p.source_indicators)}")
|
||||
lines.append(f"Convert to: {p.target_equivalent}")
|
||||
lines.append("Parameter mapping:")
|
||||
for src, tgt in p.parameter_mapping.items():
|
||||
lines.append(f" - {src} → {tgt}")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Import Conversions")
|
||||
lines.append("")
|
||||
for src, tgt in self.import_patterns.items():
|
||||
lines.append(f"- `{src}` → `{tgt}`")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Method Conversions")
|
||||
lines.append("")
|
||||
for src, tgt in self.method_patterns.items():
|
||||
lines.append(f"- `.{src}()` → `.{tgt}()`")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def get_default_spec() -> MigrationSpec:
|
||||
"""Get the default migration specification."""
|
||||
return MigrationSpec(
|
||||
agent_patterns=[
|
||||
PatternSpec(
|
||||
name="Role-Goal-Backstory Agent",
|
||||
description="Agent defined with role, goal, and backstory attributes",
|
||||
source_indicators=["role=", "goal=", "backstory=", "Agent("],
|
||||
target_equivalent="from praisonaiagents import Agent",
|
||||
parameter_mapping={
|
||||
"role": "role",
|
||||
"goal": "goal",
|
||||
"backstory": "backstory",
|
||||
"tools": "tools",
|
||||
"llm": "llm",
|
||||
"verbose": "verbose",
|
||||
},
|
||||
),
|
||||
PatternSpec(
|
||||
name="Name-Instructions Agent",
|
||||
description="Agent defined with name and instructions",
|
||||
source_indicators=["name=", "instructions=", "model=", "Agent("],
|
||||
target_equivalent="from praisonaiagents import Agent",
|
||||
parameter_mapping={
|
||||
"name": "name",
|
||||
"instructions": "instructions",
|
||||
"model": "llm", # Convert model object to llm string
|
||||
"tools": "tools",
|
||||
"markdown": "markdown",
|
||||
},
|
||||
notes="model=ModelClass(...) should become llm='provider/model-name'",
|
||||
),
|
||||
],
|
||||
task_patterns=[
|
||||
PatternSpec(
|
||||
name="Description-Output Task",
|
||||
description="Task with description and expected_output",
|
||||
source_indicators=["description=", "expected_output=", "Task("],
|
||||
target_equivalent="from praisonaiagents import Task",
|
||||
parameter_mapping={
|
||||
"description": "description",
|
||||
"expected_output": "expected_output",
|
||||
"agent": "agent",
|
||||
"context": "context",
|
||||
},
|
||||
),
|
||||
PatternSpec(
|
||||
name="Step Pattern",
|
||||
description="Workflow step with agent and description",
|
||||
source_indicators=["Step(", "agent=", "description="],
|
||||
target_equivalent="from praisonaiagents import Task",
|
||||
parameter_mapping={
|
||||
"name": "name",
|
||||
"agent": "agent",
|
||||
"description": "description",
|
||||
},
|
||||
),
|
||||
],
|
||||
team_patterns=[
|
||||
PatternSpec(
|
||||
name="Crew/Team Orchestrator",
|
||||
description="Multi-agent orchestrator with agents list",
|
||||
source_indicators=["Crew(", "Team(", "agents=", "tasks=", "members="],
|
||||
target_equivalent="from praisonaiagents import AgentTeam",
|
||||
parameter_mapping={
|
||||
"agents": "agents",
|
||||
"members": "agents", # members → agents
|
||||
"tasks": "tasks",
|
||||
"process": "process",
|
||||
"verbose": "verbose",
|
||||
},
|
||||
),
|
||||
PatternSpec(
|
||||
name="Workflow Orchestrator",
|
||||
description="Sequential workflow with steps",
|
||||
source_indicators=["Workflow(", "steps="],
|
||||
target_equivalent="from praisonaiagents import AgentFlow",
|
||||
parameter_mapping={
|
||||
"name": "name",
|
||||
"steps": "steps",
|
||||
"description": "description",
|
||||
},
|
||||
),
|
||||
],
|
||||
workflow_patterns=[],
|
||||
import_patterns={
|
||||
# Generic patterns - the LLM will match these
|
||||
"from X.agent import Agent": "from praisonaiagents import Agent",
|
||||
"from X import Agent": "from praisonaiagents import Agent",
|
||||
"from X import Task": "from praisonaiagents import Task",
|
||||
"from X.team import Team": "from praisonaiagents import AgentTeam",
|
||||
"from X import Crew": "from praisonaiagents import AgentTeam",
|
||||
"from X.workflow import Workflow": "from praisonaiagents import AgentFlow",
|
||||
"from X.models.Y import Z": "# Use llm parameter instead",
|
||||
"from X.db.Y import Z": "# Use memory parameter instead",
|
||||
},
|
||||
method_patterns={
|
||||
"kickoff": "start",
|
||||
"run": "start",
|
||||
"print_response": "start",
|
||||
"execute": "start",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# PraisonAI reference code for the LLM to understand target format
|
||||
PRAISONAI_REFERENCE = '''
|
||||
# PraisonAI Agent Framework Reference
|
||||
|
||||
## Basic Agent
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="assistant", # Agent name
|
||||
role="Helper", # Agent role
|
||||
goal="Help users", # Agent goal
|
||||
backstory="Expert helper", # Agent backstory
|
||||
instructions="Be helpful", # System instructions
|
||||
llm="gpt-4o-mini", # LLM model (provider/model format)
|
||||
tools=[my_tool], # List of tools
|
||||
memory=True, # Enable memory
|
||||
markdown=True, # Enable markdown output
|
||||
)
|
||||
|
||||
# Run the agent
|
||||
response = agent.start("Hello!")
|
||||
```
|
||||
|
||||
## Multi-Agent Team
|
||||
```python
|
||||
from praisonaiagents import Agent, AgentTeam
|
||||
|
||||
agent1 = Agent(name="researcher", role="Research")
|
||||
agent2 = Agent(name="writer", role="Write")
|
||||
|
||||
team = AgentTeam(
|
||||
agents=[agent1, agent2],
|
||||
process="sequential", # or "hierarchical"
|
||||
)
|
||||
|
||||
result = team.start("Research and write about AI")
|
||||
```
|
||||
|
||||
## AgentFlow (Workflow)
|
||||
```python
|
||||
from praisonaiagents import Agent, AgentFlow
|
||||
|
||||
flow = AgentFlow(
|
||||
name="my_flow",
|
||||
steps=[
|
||||
Agent(instructions="Step 1"),
|
||||
Agent(instructions="Step 2"),
|
||||
],
|
||||
)
|
||||
|
||||
result = flow.run("Start the workflow")
|
||||
```
|
||||
|
||||
## LLM Format
|
||||
Use "provider/model" format:
|
||||
- OpenAI: "gpt-4o-mini", "gpt-4o", "o1-mini"
|
||||
- Google: "gemini/gemini-2.0-flash", "gemini/gemini-pro"
|
||||
- Anthropic: "anthropic/claude-3-sonnet"
|
||||
- Ollama: "ollama/llama3"
|
||||
'''
|
||||
@@ -57,7 +57,7 @@ class CloudDeployer:
|
||||
file.write("FROM python:3.11-slim\n")
|
||||
file.write("WORKDIR /app\n")
|
||||
file.write("COPY . .\n")
|
||||
file.write("RUN pip install flask praisonai==4.2.2 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==4.3.0 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "4.2.2"
|
||||
__version__ = "4.3.0"
|
||||
@@ -12,7 +12,7 @@ dependencies = [
|
||||
"rich>=13.7",
|
||||
"markdown>=3.5",
|
||||
"pyparsing>=3.0.0",
|
||||
"praisonaiagents>=1.2.2",
|
||||
"praisonaiagents>=1.3.0",
|
||||
"python-dotenv>=0.19.0",
|
||||
"litellm>=1.81.0",
|
||||
"PyYAML>=6.0",
|
||||
@@ -40,6 +40,12 @@ api = [
|
||||
"uvicorn>=0.34.0",
|
||||
"sse-starlette>=1.6.0"
|
||||
]
|
||||
os = [
|
||||
"fastapi>=0.115.0",
|
||||
"uvicorn>=0.34.0",
|
||||
"PyJWT>=2.8.0",
|
||||
"sse-starlette>=1.6.0"
|
||||
]
|
||||
agentops = ["agentops>=0.3.12"]
|
||||
chat = [
|
||||
"chainlit>=2.8.5,<=2.9.4",
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
"""
|
||||
Unit tests for the migrate CLI feature.
|
||||
|
||||
Tests pattern detection and code conversion without exposing framework names.
|
||||
Uses generic pattern terminology for stealth approach.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class TestPatternDetection:
|
||||
"""Test pattern detection from Python code."""
|
||||
|
||||
def test_detect_agent_class_pattern_with_role_goal_backstory(self):
|
||||
"""Detect agent-like class with role, goal, backstory attributes."""
|
||||
from praisonai.cli.features.migrate import PatternDetector
|
||||
|
||||
code = '''
|
||||
class MyAgent:
|
||||
role = "Researcher"
|
||||
goal = "Find information"
|
||||
backstory = "Expert researcher"
|
||||
'''
|
||||
detector = PatternDetector()
|
||||
patterns = detector.detect_patterns(code)
|
||||
|
||||
assert len(patterns) >= 1
|
||||
agent_patterns = [p for p in patterns if p.pattern_type.value == "agent"]
|
||||
assert len(agent_patterns) == 1
|
||||
assert agent_patterns[0].name == "MyAgent"
|
||||
assert agent_patterns[0].confidence >= 0.8
|
||||
|
||||
def test_detect_task_class_pattern(self):
|
||||
"""Detect task-like class with description, expected_output."""
|
||||
from praisonai.cli.features.migrate import PatternDetector
|
||||
|
||||
code = '''
|
||||
class ResearchTask:
|
||||
description = "Research the topic"
|
||||
expected_output = "A detailed report"
|
||||
'''
|
||||
detector = PatternDetector()
|
||||
patterns = detector.detect_patterns(code)
|
||||
|
||||
task_patterns = [p for p in patterns if p.pattern_type.value == "task"]
|
||||
assert len(task_patterns) == 1
|
||||
assert task_patterns[0].name == "ResearchTask"
|
||||
|
||||
def test_detect_orchestrator_pattern(self):
|
||||
"""Detect orchestrator-like class with agents and tasks lists."""
|
||||
from praisonai.cli.features.migrate import PatternDetector
|
||||
|
||||
code = '''
|
||||
class MyOrchestrator:
|
||||
agents = [agent1, agent2]
|
||||
tasks = [task1, task2]
|
||||
|
||||
def kickoff(self):
|
||||
pass
|
||||
'''
|
||||
detector = PatternDetector()
|
||||
patterns = detector.detect_patterns(code)
|
||||
|
||||
orch_patterns = [p for p in patterns if p.pattern_type.value == "orchestrator"]
|
||||
assert len(orch_patterns) == 1
|
||||
assert orch_patterns[0].name == "MyOrchestrator"
|
||||
|
||||
def test_detect_decorated_agent_function(self):
|
||||
"""Detect @agent decorated functions."""
|
||||
from praisonai.cli.features.migrate import PatternDetector
|
||||
|
||||
code = '''
|
||||
@agent
|
||||
def researcher():
|
||||
return Agent(role="Researcher")
|
||||
'''
|
||||
detector = PatternDetector()
|
||||
patterns = detector.detect_patterns(code)
|
||||
|
||||
agent_patterns = [p for p in patterns if p.pattern_type.value == "agent"]
|
||||
assert len(agent_patterns) >= 1
|
||||
|
||||
def test_detect_pydantic_agent_model(self):
|
||||
"""Detect Pydantic BaseModel with agent fields."""
|
||||
from praisonai.cli.features.migrate import PatternDetector
|
||||
|
||||
code = '''
|
||||
class AgentConfig(BaseModel):
|
||||
role: str
|
||||
goal: str
|
||||
backstory: str = ""
|
||||
'''
|
||||
detector = PatternDetector()
|
||||
patterns = detector.detect_patterns(code)
|
||||
|
||||
agent_patterns = [p for p in patterns if p.pattern_type.value == "agent"]
|
||||
assert len(agent_patterns) >= 1
|
||||
|
||||
def test_confidence_scoring(self):
|
||||
"""Test that confidence scoring works correctly."""
|
||||
from praisonai.cli.features.migrate import PatternDetector
|
||||
|
||||
# High confidence: all agent attributes
|
||||
high_conf_code = '''
|
||||
class FullAgent:
|
||||
role = "Role"
|
||||
goal = "Goal"
|
||||
backstory = "Backstory"
|
||||
tools = []
|
||||
'''
|
||||
# Lower confidence: partial attributes
|
||||
low_conf_code = '''
|
||||
class PartialAgent:
|
||||
role = "Role"
|
||||
'''
|
||||
detector = PatternDetector()
|
||||
|
||||
high_patterns = detector.detect_patterns(high_conf_code)
|
||||
low_patterns = detector.detect_patterns(low_conf_code)
|
||||
|
||||
high_agent = [p for p in high_patterns if p.pattern_type.value == "agent"]
|
||||
low_agent = [p for p in low_patterns if p.pattern_type.value == "agent"]
|
||||
|
||||
if high_agent and low_agent:
|
||||
assert high_agent[0].confidence > low_agent[0].confidence
|
||||
|
||||
def test_no_patterns_in_regular_code(self):
|
||||
"""Regular Python code should not trigger false positives."""
|
||||
from praisonai.cli.features.migrate import PatternDetector
|
||||
|
||||
code = '''
|
||||
def hello():
|
||||
print("Hello world")
|
||||
|
||||
class Calculator:
|
||||
def add(self, a, b):
|
||||
return a + b
|
||||
'''
|
||||
detector = PatternDetector()
|
||||
patterns = detector.detect_patterns(code)
|
||||
|
||||
# Should have no agent/task/orchestrator patterns
|
||||
agent_patterns = [p for p in patterns if p.pattern_type.value in ("agent", "task", "orchestrator")]
|
||||
assert len(agent_patterns) == 0
|
||||
|
||||
|
||||
class TestCodeConversion:
|
||||
"""Test code conversion to PraisonAI format."""
|
||||
|
||||
def test_convert_agent_pattern_to_praisonai(self):
|
||||
"""Convert detected agent pattern to PraisonAI Agent."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
code = '''
|
||||
from some_framework import Agent
|
||||
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Find information",
|
||||
backstory="Expert researcher",
|
||||
tools=[search_tool]
|
||||
)
|
||||
'''
|
||||
converter = CodeConverter()
|
||||
result = converter.convert_code(code)
|
||||
|
||||
assert result.success
|
||||
assert "from praisonaiagents import Agent" in result.converted_code
|
||||
assert 'role="Researcher"' in result.converted_code
|
||||
|
||||
def test_convert_orchestrator_to_agent_team(self):
|
||||
"""Convert orchestrator pattern to AgentTeam."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
code = '''
|
||||
orchestrator = Orchestrator(
|
||||
agents=[agent1, agent2],
|
||||
tasks=[task1, task2]
|
||||
)
|
||||
result = orchestrator.kickoff()
|
||||
'''
|
||||
converter = CodeConverter()
|
||||
result = converter.convert_code(code)
|
||||
|
||||
assert result.success
|
||||
# Should convert to AgentTeam
|
||||
assert "AgentTeam" in result.converted_code or "team" in result.converted_code.lower()
|
||||
|
||||
def test_preserve_unknown_code(self):
|
||||
"""Unknown code should be preserved as-is."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
code = '''
|
||||
def helper_function():
|
||||
return "helper"
|
||||
|
||||
# Some comment
|
||||
x = 42
|
||||
'''
|
||||
converter = CodeConverter()
|
||||
result = converter.convert_code(code)
|
||||
|
||||
assert "helper_function" in result.converted_code
|
||||
assert "x = 42" in result.converted_code
|
||||
|
||||
def test_dry_run_does_not_write(self):
|
||||
"""Dry run should not write files."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
source = Path(tmpdir) / "source.py"
|
||||
source.write_text('agent = Agent(role="Test")')
|
||||
|
||||
converter = CodeConverter()
|
||||
result = converter.convert_file(str(source), dry_run=True)
|
||||
|
||||
assert result.success
|
||||
# No output file should be created in dry run
|
||||
output = Path(tmpdir) / "source_converted.py"
|
||||
assert not output.exists()
|
||||
|
||||
|
||||
class TestDirectoryScanning:
|
||||
"""Test directory scanning for migratable files."""
|
||||
|
||||
def test_scan_directory_finds_python_files(self):
|
||||
"""Scan directory should find all Python files."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
# Create test files
|
||||
(Path(tmpdir) / "agents.py").write_text('role = "Test"')
|
||||
(Path(tmpdir) / "tasks.py").write_text('description = "Test"')
|
||||
(Path(tmpdir) / "readme.txt").write_text("Not Python")
|
||||
|
||||
converter = CodeConverter()
|
||||
files = converter.scan_directory(tmpdir)
|
||||
|
||||
assert len(files) == 2
|
||||
assert all(f.endswith(".py") for f in files)
|
||||
|
||||
def test_scan_excludes_venv_and_pycache(self):
|
||||
"""Scan should exclude venv and __pycache__ directories."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
# Create test structure
|
||||
(Path(tmpdir) / "main.py").write_text('role = "Test"')
|
||||
venv = Path(tmpdir) / "venv"
|
||||
venv.mkdir()
|
||||
(venv / "lib.py").write_text('# venv file')
|
||||
pycache = Path(tmpdir) / "__pycache__"
|
||||
pycache.mkdir()
|
||||
(pycache / "cache.pyc").write_text('# cache')
|
||||
|
||||
converter = CodeConverter()
|
||||
files = converter.scan_directory(tmpdir)
|
||||
|
||||
assert len(files) == 1
|
||||
assert "venv" not in files[0]
|
||||
assert "__pycache__" not in files[0]
|
||||
|
||||
|
||||
class TestYAMLMigration:
|
||||
"""Test YAML config migration (existing functionality)."""
|
||||
|
||||
def test_yaml_migration_still_works(self):
|
||||
"""Existing YAML migration should still work."""
|
||||
from praisonai.cli.features.migrate import ConfigMigrator
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
source = Path(tmpdir) / "config.yaml"
|
||||
source.write_text('''
|
||||
agents:
|
||||
- role: Researcher
|
||||
goal: Find info
|
||||
backstory: Expert
|
||||
tasks:
|
||||
- description: Research topic
|
||||
expected_output: Report
|
||||
agent: researcher
|
||||
''')
|
||||
|
||||
migrator = ConfigMigrator()
|
||||
result = migrator.migrate(str(source))
|
||||
|
||||
assert result["success"]
|
||||
|
||||
def test_detect_format_without_framework_names_in_output(self):
|
||||
"""Format detection should work but not expose framework names in user output."""
|
||||
from praisonai.cli.features.migrate import ConfigMigrator
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
source = Path(tmpdir) / "config.yaml"
|
||||
source.write_text('''
|
||||
agents:
|
||||
- role: Test
|
||||
tasks:
|
||||
- description: Test task
|
||||
''')
|
||||
|
||||
migrator = ConfigMigrator()
|
||||
result = migrator.migrate(str(source))
|
||||
|
||||
# Result should succeed without exposing framework names
|
||||
assert result["success"]
|
||||
|
||||
|
||||
class TestCLIIntegration:
|
||||
"""Test CLI command integration."""
|
||||
|
||||
def test_migrate_help_is_generic(self):
|
||||
"""CLI help should use generic terminology."""
|
||||
import subprocess
|
||||
result = subprocess.run(
|
||||
["python", "-m", "praisonai", "migrate", "--help"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30
|
||||
)
|
||||
# Help text should be generic, not mention specific competitor frameworks
|
||||
help_text = result.stdout + result.stderr
|
||||
# Should have help content
|
||||
assert "migrate" in help_text.lower() or "usage" in help_text.lower() or result.returncode == 0
|
||||
|
||||
def test_migrate_dry_run_flag(self):
|
||||
"""--dry-run flag should work."""
|
||||
from praisonai.cli.features.migrate import handle_migrate_command
|
||||
import argparse
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
source = Path(tmpdir) / "test.py"
|
||||
source.write_text('agent = Agent(role="Test")')
|
||||
|
||||
# Create mock args
|
||||
args = argparse.Namespace(
|
||||
source=str(source),
|
||||
target=None,
|
||||
dry_run=True,
|
||||
output=None,
|
||||
from_format=None,
|
||||
to_format="praisonai"
|
||||
)
|
||||
|
||||
# Should not raise
|
||||
try:
|
||||
handle_migrate_command(args)
|
||||
except SystemExit:
|
||||
pass # CLI may exit
|
||||
|
||||
|
||||
class TestValidation:
|
||||
"""Test output validation."""
|
||||
|
||||
def test_converted_code_is_valid_python(self):
|
||||
"""Converted code should be valid Python."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
import ast
|
||||
|
||||
code = '''
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Find info"
|
||||
)
|
||||
'''
|
||||
converter = CodeConverter()
|
||||
result = converter.convert_code(code)
|
||||
|
||||
if result.success and result.converted_code:
|
||||
# Should parse without syntax errors
|
||||
try:
|
||||
ast.parse(result.converted_code)
|
||||
except SyntaxError:
|
||||
pytest.fail("Converted code has syntax errors")
|
||||
|
||||
def test_warnings_for_unsupported_patterns(self):
|
||||
"""Unsupported patterns should generate warnings."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
code = '''
|
||||
# Custom callback that can't be auto-converted
|
||||
@custom_decorator
|
||||
def special_callback():
|
||||
pass
|
||||
'''
|
||||
converter = CodeConverter()
|
||||
result = converter.convert_code(code)
|
||||
|
||||
# Should still succeed but may have warnings
|
||||
assert result.success or len(result.warnings) > 0
|
||||
|
||||
|
||||
class TestBackupCreation:
|
||||
"""Test backup file creation."""
|
||||
|
||||
def test_backup_created_when_overwriting(self):
|
||||
"""Backup should be created when overwriting files."""
|
||||
from praisonai.cli.features.migrate import CodeConverter
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
source = Path(tmpdir) / "agents.py"
|
||||
source.write_text('agent = Agent(role="Test")')
|
||||
|
||||
converter = CodeConverter()
|
||||
result = converter.convert_file(
|
||||
str(source),
|
||||
output=str(source), # Overwrite
|
||||
dry_run=False,
|
||||
backup=True
|
||||
)
|
||||
|
||||
if result.success:
|
||||
backup = Path(tmpdir) / "agents.py.bak"
|
||||
assert backup.exists()
|
||||
Generated
+15
-5
@@ -3977,6 +3977,12 @@ dev = [
|
||||
gradio = [
|
||||
{ name = "gradio" },
|
||||
]
|
||||
os = [
|
||||
{ name = "fastapi" },
|
||||
{ name = "pyjwt" },
|
||||
{ name = "sse-starlette" },
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
realtime = [
|
||||
{ name = "aiosqlite" },
|
||||
{ name = "chainlit" },
|
||||
@@ -4026,6 +4032,7 @@ requires-dist = [
|
||||
{ name = "fastapi", marker = "extra == 'all'", specifier = ">=0.115.0" },
|
||||
{ name = "fastapi", marker = "extra == 'api'", specifier = ">=0.115.0" },
|
||||
{ name = "fastapi", marker = "extra == 'call'", specifier = ">=0.95.0" },
|
||||
{ name = "fastapi", marker = "extra == 'os'", specifier = ">=0.115.0" },
|
||||
{ name = "flaml", extras = ["automl"], marker = "extra == 'call'", specifier = ">=2.3.1" },
|
||||
{ name = "flask", marker = "extra == 'all'", specifier = ">=3.0.0" },
|
||||
{ name = "flask", marker = "extra == 'api'", specifier = ">=3.0.0" },
|
||||
@@ -4047,8 +4054,9 @@ requires-dist = [
|
||||
{ name = "praisonai-tools", marker = "extra == 'autogen'", specifier = ">=0.1.0" },
|
||||
{ name = "praisonai-tools", marker = "extra == 'autogen-v4'", specifier = ">=0.1.0" },
|
||||
{ name = "praisonai-tools", marker = "extra == 'crewai'", specifier = ">=0.1.0" },
|
||||
{ name = "praisonaiagents", specifier = ">=1.2.2" },
|
||||
{ name = "praisonaiagents", specifier = ">=1.3.0" },
|
||||
{ name = "pyautogen", marker = "extra == 'autogen'", specifier = "==0.2.29" },
|
||||
{ name = "pyjwt", marker = "extra == 'os'", specifier = ">=2.8.0" },
|
||||
{ name = "pyngrok", marker = "extra == 'call'", specifier = ">=1.4.0" },
|
||||
{ name = "pyparsing", specifier = ">=3.0.0" },
|
||||
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0.0" },
|
||||
@@ -4067,6 +4075,7 @@ requires-dist = [
|
||||
{ name = "sqlalchemy", marker = "extra == 'ui'", specifier = ">=2.0.36" },
|
||||
{ name = "sse-starlette", marker = "extra == 'all'", specifier = ">=1.6.0" },
|
||||
{ name = "sse-starlette", marker = "extra == 'api'", specifier = ">=1.6.0" },
|
||||
{ name = "sse-starlette", marker = "extra == 'os'", specifier = ">=1.6.0" },
|
||||
{ name = "tavily-python", marker = "extra == 'all'", specifier = "==0.5.0" },
|
||||
{ name = "tavily-python", marker = "extra == 'chat'", specifier = "==0.5.0" },
|
||||
{ name = "tavily-python", marker = "extra == 'code'", specifier = "==0.5.0" },
|
||||
@@ -4078,13 +4087,14 @@ requires-dist = [
|
||||
{ name = "uvicorn", marker = "extra == 'all'", specifier = ">=0.34.0" },
|
||||
{ name = "uvicorn", marker = "extra == 'api'", specifier = ">=0.34.0" },
|
||||
{ name = "uvicorn", marker = "extra == 'call'", specifier = ">=0.20.0" },
|
||||
{ name = "uvicorn", marker = "extra == 'os'", specifier = ">=0.34.0" },
|
||||
{ name = "websockets", marker = "extra == 'all'", specifier = ">=12.0" },
|
||||
{ name = "websockets", marker = "extra == 'call'", specifier = ">=12.0" },
|
||||
{ name = "websockets", marker = "extra == 'realtime'", specifier = ">=12.0" },
|
||||
{ name = "yfinance", marker = "extra == 'all'", specifier = ">=0.2.44" },
|
||||
{ name = "yfinance", marker = "extra == 'realtime'", specifier = ">=0.2.44" },
|
||||
]
|
||||
provides-extras = ["ui", "gradio", "api", "agentops", "chat", "code", "realtime", "call", "train", "crewai", "autogen", "autogen-v4", "acp", "lite", "all", "bot", "dev"]
|
||||
provides-extras = ["ui", "gradio", "api", "os", "agentops", "chat", "code", "realtime", "call", "train", "crewai", "autogen", "autogen-v4", "acp", "lite", "all", "bot", "dev"]
|
||||
|
||||
[[package]]
|
||||
name = "praisonai-tools"
|
||||
@@ -4100,7 +4110,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "1.2.2"
|
||||
version = "1.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
@@ -4109,9 +4119,9 @@ dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "rich" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a5/fd/dc1591930e10108c04b21de9e620ef0910ad0d7c34ecb1a7616ce0ccc8c7/praisonaiagents-1.2.2.tar.gz", hash = "sha256:c790107dfd278a46c52a0191b77c13900f091fb5a7051195cb1926d9ca19e991", size = 1163165, upload-time = "2026-01-31T20:23:29.288Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3b/32/01d10458a43e1a1bcef34fabdd21da110b865b50ec0ae8519bb7581231a1/praisonaiagents-1.3.0.tar.gz", hash = "sha256:c0f9d19da5996918ee5e04e5faedffbf434603b2779d7bc5c9fd3ae7b6f68a56", size = 1170867, upload-time = "2026-02-02T10:01:28.817Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/21/406275ba1c6f1d7dcef710c7aa62a6fccb5cafbbb4883a39fe48715837ea/praisonaiagents-1.2.2-py3-none-any.whl", hash = "sha256:8732cdd90526b1fba0feb192c97b8c0b2387eda2827cf89d7d9867cd02aeaad8", size = 1156030, upload-time = "2026-01-31T20:23:27.414Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/fa/671163138e78d76af6f6e4c13f4ac3e6c422af250e917055761d85d91c53/praisonaiagents-1.3.0-py3-none-any.whl", hash = "sha256:86bfa0a24f3e69ea297fc8146291cddf1171a649e4dd83b7f8c52315701c0d91", size = 1164709, upload-time = "2026-02-02T10:01:21.644Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in new issue
Block a user