praisonaiagents 0.0.99__py3-none-any.whl → 0.0.100__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -619,12 +619,9 @@ Your Goal: {self.goal}
619
619
  while retry_count <= self.max_guardrail_retries:
620
620
  # Create TaskOutput object
621
621
  task_output = TaskOutput(
622
+ description="Agent response output",
622
623
  raw=current_response,
623
- output=current_response,
624
- pydantic=None,
625
- json_dict=None,
626
- name=f"{self.name}_output",
627
- description="Agent response output"
624
+ agent=self.name
628
625
  )
629
626
 
630
627
  # Process guardrail
@@ -0,0 +1,11 @@
1
+ """
2
+ Guardrails module for PraisonAI Agents.
3
+
4
+ This module provides validation and safety mechanisms for task outputs,
5
+ including both function-based and LLM-based guardrails.
6
+ """
7
+
8
+ from .guardrail_result import GuardrailResult
9
+ from .llm_guardrail import LLMGuardrail
10
+
11
+ __all__ = ["GuardrailResult", "LLMGuardrail"]
@@ -0,0 +1,43 @@
1
+ """
2
+ Guardrail result classes for PraisonAI Agents.
3
+
4
+ This module provides the result types for guardrail validation,
5
+ following the same pattern as CrewAI for consistency.
6
+ """
7
+
8
+ from typing import Any, Tuple, Union
9
+ from pydantic import BaseModel, Field
10
+ from ..main import TaskOutput
11
+
12
+
13
+ class GuardrailResult(BaseModel):
14
+ """Result of a guardrail validation."""
15
+
16
+ success: bool = Field(description="Whether the guardrail check passed")
17
+ result: Union[str, TaskOutput, None] = Field(description="The result if modified, or None if unchanged")
18
+ error: str = Field(default="", description="Error message if validation failed")
19
+
20
+ @classmethod
21
+ def from_tuple(cls, result: Tuple[bool, Any]) -> "GuardrailResult":
22
+ """Create a GuardrailResult from a tuple returned by a guardrail function.
23
+
24
+ Args:
25
+ result: Tuple of (success, result_or_error)
26
+
27
+ Returns:
28
+ GuardrailResult: The structured result
29
+ """
30
+ success, data = result
31
+
32
+ if success:
33
+ return cls(
34
+ success=True,
35
+ result=data,
36
+ error=""
37
+ )
38
+ else:
39
+ return cls(
40
+ success=False,
41
+ result=None,
42
+ error=str(data) if data else "Guardrail validation failed"
43
+ )
@@ -0,0 +1,88 @@
1
+ """
2
+ LLM-based guardrail implementation for PraisonAI Agents.
3
+
4
+ This module provides LLM-powered guardrails that can validate task outputs
5
+ using natural language descriptions, similar to CrewAI's implementation.
6
+ """
7
+
8
+ import logging
9
+ from typing import Any, Tuple, Union, Optional
10
+ from pydantic import BaseModel
11
+ from ..main import TaskOutput
12
+
13
+
14
+ class LLMGuardrail:
15
+ """An LLM-powered guardrail that validates task outputs using natural language."""
16
+
17
+ def __init__(self, description: str, llm: Any = None):
18
+ """Initialize the LLM guardrail.
19
+
20
+ Args:
21
+ description: Natural language description of what to validate
22
+ llm: The LLM instance to use for validation
23
+ """
24
+ self.description = description
25
+ self.llm = llm
26
+ self.logger = logging.getLogger(__name__)
27
+
28
+ def __call__(self, task_output: TaskOutput) -> Tuple[bool, Union[str, TaskOutput]]:
29
+ """Validate the task output using the LLM.
30
+
31
+ Args:
32
+ task_output: The task output to validate
33
+
34
+ Returns:
35
+ Tuple of (success, result) where result is the output or error message
36
+ """
37
+ try:
38
+ if not self.llm:
39
+ self.logger.warning("No LLM provided for guardrail validation")
40
+ return True, task_output
41
+
42
+ # Create validation prompt
43
+ validation_prompt = f"""
44
+ You are a quality assurance validator. Your task is to evaluate the following output against specific criteria.
45
+
46
+ Validation Criteria: {self.description}
47
+
48
+ Output to Validate:
49
+ {task_output.raw}
50
+
51
+ Please evaluate if this output meets the criteria. Respond with:
52
+ 1. "PASS" if the output meets all criteria
53
+ 2. "FAIL: [specific reason]" if the output does not meet criteria
54
+
55
+ Your response:"""
56
+
57
+ # Get LLM response
58
+ if hasattr(self.llm, 'chat'):
59
+ # For Agent's LLM interface
60
+ response = self.llm.chat(validation_prompt, temperature=0.1)
61
+ elif hasattr(self.llm, 'get_response'):
62
+ # For custom LLM instances
63
+ response = self.llm.get_response(validation_prompt, temperature=0.1)
64
+ elif callable(self.llm):
65
+ # For simple callable LLMs
66
+ response = self.llm(validation_prompt)
67
+ else:
68
+ self.logger.error(f"Unsupported LLM type: {type(self.llm)}")
69
+ return True, task_output
70
+
71
+ # Parse response
72
+ response = str(response).strip()
73
+
74
+ if response.upper().startswith("PASS"):
75
+ return True, task_output
76
+ elif response.upper().startswith("FAIL"):
77
+ # Extract the reason
78
+ reason = response[5:].strip(": ")
79
+ return False, f"Guardrail validation failed: {reason}"
80
+ else:
81
+ # Unclear response, log and pass through
82
+ self.logger.warning(f"Unclear guardrail response: {response}")
83
+ return True, task_output
84
+
85
+ except Exception as e:
86
+ self.logger.error(f"Error in LLM guardrail validation: {str(e)}")
87
+ # On error, pass through the original output
88
+ return True, task_output
@@ -0,0 +1,15 @@
1
+ """
2
+ Memory module for PraisonAI Agents
3
+
4
+ This module provides memory management capabilities including:
5
+ - Short-term memory (STM) for ephemeral context
6
+ - Long-term memory (LTM) for persistent knowledge
7
+ - Entity memory for structured data
8
+ - User memory for preferences/history
9
+ - Quality-based storage decisions
10
+ - Graph memory support via Mem0
11
+ """
12
+
13
+ from .memory import Memory
14
+
15
+ __all__ = ["Memory"]
@@ -910,11 +910,14 @@ class Memory:
910
910
  """
911
911
 
912
912
  try:
913
- # Use OpenAI client from main.py
914
- from ..main import client
913
+ # Use LiteLLM for consistency with the rest of the codebase
914
+ import litellm
915
915
 
916
- response = client.chat.completions.create(
917
- model=llm or "gpt-4o",
916
+ # Convert model name if it's in litellm format
917
+ model_name = llm or "gpt-4o-mini"
918
+
919
+ response = litellm.completion(
920
+ model=model_name,
918
921
  messages=[{
919
922
  "role": "user",
920
923
  "content": custom_prompt or default_prompt
@@ -308,7 +308,11 @@ class Task:
308
308
  if self.agent:
309
309
  if getattr(self.agent, '_using_custom_llm', False) and hasattr(self.agent, 'llm_instance'):
310
310
  # For custom LLM instances (like Ollama)
311
- llm_model = self.agent.llm_instance
311
+ # Extract the model name from the LLM instance
312
+ if hasattr(self.agent.llm_instance, 'model'):
313
+ llm_model = self.agent.llm_instance.model
314
+ else:
315
+ llm_model = "gpt-4o-mini" # Default fallback
312
316
  elif hasattr(self.agent, 'llm') and self.agent.llm:
313
317
  # For standard model strings
314
318
  llm_model = self.agent.llm
@@ -0,0 +1,94 @@
1
+ """SearxNG search functionality.
2
+
3
+ Usage:
4
+ from praisonaiagents.tools import searxng_search
5
+ results = searxng_search("AI news")
6
+
7
+ or
8
+ from praisonaiagents.tools import searxng
9
+ results = searxng("AI news")
10
+ """
11
+
12
+ from typing import List, Dict, Optional
13
+ import logging
14
+ from importlib import util
15
+
16
+ def searxng_search(
17
+ query: str,
18
+ max_results: int = 5,
19
+ searxng_url: Optional[str] = None
20
+ ) -> List[Dict]:
21
+ """Perform an internet search using SearxNG instance.
22
+
23
+ Args:
24
+ query: Search query string
25
+ max_results: Maximum number of results to return
26
+ searxng_url: SearxNG instance URL (defaults to localhost:32768)
27
+
28
+ Returns:
29
+ List[Dict]: Search results with title, url, and snippet keys
30
+ Returns error dict on failure
31
+ """
32
+ # Check if requests is available
33
+ if util.find_spec("requests") is None:
34
+ error_msg = "SearxNG search requires requests package. Install with: pip install requests"
35
+ logging.error(error_msg)
36
+ return [{"error": error_msg}]
37
+
38
+ try:
39
+ import requests
40
+
41
+ # Default URL for local SearxNG instance
42
+ url = searxng_url or "http://localhost:32768/search"
43
+
44
+ params = {
45
+ 'q': query,
46
+ 'format': 'json',
47
+ 'engines': 'google,bing,duckduckgo', # Multiple engines
48
+ 'safesearch': '1' # Safe search enabled
49
+ }
50
+
51
+ response = requests.get(url, params=params, timeout=10)
52
+ response.raise_for_status()
53
+
54
+ raw_results = response.json().get('results', [])
55
+
56
+ # Standardize to PraisonAI format
57
+ results = []
58
+ for i, result in enumerate(raw_results[:max_results]):
59
+ results.append({
60
+ "title": result.get("title", ""),
61
+ "url": result.get("url", ""),
62
+ "snippet": result.get("content", "")
63
+ })
64
+
65
+ return results
66
+
67
+ except requests.exceptions.ConnectionError:
68
+ error_msg = f"Could not connect to SearxNG at {url}. Ensure SearxNG is running."
69
+ logging.error(error_msg)
70
+ return [{"error": error_msg}]
71
+ except requests.exceptions.Timeout:
72
+ error_msg = "SearxNG search request timed out"
73
+ logging.error(error_msg)
74
+ return [{"error": error_msg}]
75
+ except requests.exceptions.RequestException as e:
76
+ error_msg = f"SearxNG search request failed: {e}"
77
+ logging.error(error_msg)
78
+ return [{"error": error_msg}]
79
+ except (ValueError, KeyError) as e:
80
+ error_msg = f"Error parsing SearxNG response: {e}"
81
+ logging.error(error_msg)
82
+ return [{"error": error_msg}]
83
+
84
+ def searxng(query: str, max_results: int = 5, searxng_url: Optional[str] = None) -> List[Dict]:
85
+ """Alias for searxng_search function."""
86
+ return searxng_search(query, max_results, searxng_url)
87
+
88
+ if __name__ == "__main__":
89
+ # Example usage
90
+ results = searxng_search("Python programming")
91
+ for result in results:
92
+ print(f"\nTitle: {result.get('title')}")
93
+ print(f"URL: {result.get('url')}")
94
+ print(f"Snippet: {result.get('snippet')}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: praisonaiagents
3
- Version: 0.0.99
3
+ Version: 0.0.100
4
4
  Summary: Praison AI agents for completing complex tasks with Self Reflection Agents
5
5
  Author: Mervin Praison
6
6
  Requires-Python: >=3.10
@@ -3,11 +3,14 @@ praisonaiagents/approval.py,sha256=UJ4OhfihpFGR5CAaMphqpSvqdZCHi5w2MGw1MByZ1FQ,9
3
3
  praisonaiagents/main.py,sha256=_-XE7_Y7ChvtLQMivfNFrrnAhv4wSSDhH9WJMWlkS0w,16315
4
4
  praisonaiagents/session.py,sha256=CI-ffCiOfmgB-1zFFik9daKCB5Sm41Q9ZOaq1-oSLW8,9250
5
5
  praisonaiagents/agent/__init__.py,sha256=j0T19TVNbfZcClvpbZDDinQxZ0oORgsMrMqx16jZ-bA,128
6
- praisonaiagents/agent/agent.py,sha256=gWTkPOhNHLosZbeZSWXp9sk4H9AN531EgclHmWeZVXk,97881
6
+ praisonaiagents/agent/agent.py,sha256=it38pIYzHQIn2qscIuuvfgWyC9gPLZFj-nN8tDI8x5A,97766
7
7
  praisonaiagents/agent/image_agent.py,sha256=-5MXG594HVwSpFMcidt16YBp7udtik-Cp7eXlzLE1fY,8696
8
8
  praisonaiagents/agents/__init__.py,sha256=_1d6Pqyk9EoBSo7E68sKyd1jDRlN1vxvVIRpoMc0Jcw,168
9
9
  praisonaiagents/agents/agents.py,sha256=C_yDdJB4XUuwKA9DrysAtAj3zSYT0IKtfCT4Pxo0oyI,63309
10
10
  praisonaiagents/agents/autoagents.py,sha256=Lc_b9mO2MeefBrsHkHoqFxEr5iRGrYuzDhslyybXwdw,13649
11
+ praisonaiagents/guardrails/__init__.py,sha256=HA8zhp-KRHTxo0194MUwXOUJjPyjOu7E3d7xUIKYVVY,310
12
+ praisonaiagents/guardrails/guardrail_result.py,sha256=2K1WIYRyT_s1H6vBGa-7HEHzXCFIyZXZVY4f0hnQyWc,1352
13
+ praisonaiagents/guardrails/llm_guardrail.py,sha256=MTTqmYDdZX-18QN9T17T5P_6H2qnV8GVgymJufW1WuM,3277
11
14
  praisonaiagents/knowledge/__init__.py,sha256=xL1Eh-a3xsHyIcU4foOWF-JdWYIYBALJH9bge0Ujuto,246
12
15
  praisonaiagents/knowledge/chunking.py,sha256=G6wyHa7_8V0_7VpnrrUXbEmUmptlT16ISJYaxmkSgmU,7678
13
16
  praisonaiagents/knowledge/knowledge.py,sha256=OKPar-XGyAp1ndmbOOdCgqFnTCqpOThYVSIZRxZyP58,15683
@@ -16,11 +19,12 @@ praisonaiagents/llm/llm.py,sha256=hoIxHzo9aNygeOiw9RtoPhpuSCVTUrKPe3OPvsT5qLc,98
16
19
  praisonaiagents/mcp/__init__.py,sha256=ibbqe3_7XB7VrIcUcetkZiUZS1fTVvyMy_AqCSFG8qc,240
17
20
  praisonaiagents/mcp/mcp.py,sha256=_gfp8hrSVT9aPqEDDfU8MiCdg0-3dVQpEQUE6AbrJlo,17243
18
21
  praisonaiagents/mcp/mcp_sse.py,sha256=DLh3F_aoVRM1X-7hgIOWOw4FQ1nGmn9YNbQTesykzn4,6792
19
- praisonaiagents/memory/memory.py,sha256=6tvsLWkpvyNU-t-8d6XpW7vOFUm1pNReW5B7rA8c04M,38612
22
+ praisonaiagents/memory/__init__.py,sha256=aEFdhgtTqDdMhc_JCWM-f4XI9cZIj7Wz5g_MUa-0amg,397
23
+ praisonaiagents/memory/memory.py,sha256=x6CEMYhgzvlJH6SGKHPLRDt6kF0DVFFSUQbgr1OK3JM,38729
20
24
  praisonaiagents/process/__init__.py,sha256=lkYbL7Hn5a0ldvJtkdH23vfIIZLIcanK-65C0MwaorY,52
21
25
  praisonaiagents/process/process.py,sha256=gxhMXG3s4CzaREyuwE5zxCMx2Wp_b_Wd53tDfkj8Qk8,66567
22
26
  praisonaiagents/task/__init__.py,sha256=VL5hXVmyGjINb34AalxpBMl-YW9m5EDcRkMTKkSSl7c,80
23
- praisonaiagents/task/task.py,sha256=60JE07JPpRowbEO420f4Ol49e_1AK856wSJDi_ricbg,20531
27
+ praisonaiagents/task/task.py,sha256=imqJ8wzZzVyUSym2EyF2tC-vAsV1UdfI_P3YM5mqAiw,20786
24
28
  praisonaiagents/tools/__init__.py,sha256=Rrgi7_3-yLHpfBB81WUi0-wD_wb_BsukwHVdjDYAF-0,9316
25
29
  praisonaiagents/tools/arxiv_tools.py,sha256=1stb31zTjLTon4jCnpZG5de9rKc9QWgC0leLegvPXWo,10528
26
30
  praisonaiagents/tools/calculator_tools.py,sha256=S1xPT74Geurvjm52QMMIG29zDXVEWJmM6nmyY7yF298,9571
@@ -33,6 +37,7 @@ praisonaiagents/tools/json_tools.py,sha256=ApUYNuQ1qnbmYNCxSlx6Tth_H1yo8mhWtZ7Rr
33
37
  praisonaiagents/tools/newspaper_tools.py,sha256=NyhojNPeyULBGcAWGOT1X70qVkh3FgZrpH-S7PEmrwI,12667
34
38
  praisonaiagents/tools/pandas_tools.py,sha256=yzCeY4jetKrFIRA15Tr5OQ5d94T8DaSpzglx2UiWfPs,11092
35
39
  praisonaiagents/tools/python_tools.py,sha256=puqLANl5YaG1YG8ixkl_MgWayF7uj5iXUEE15UYwIZE,13513
40
+ praisonaiagents/tools/searxng_tools.py,sha256=LzxFenzGlSBxnckEPwtEZYemAkU8FUflbFbHf5IZE7o,3159
36
41
  praisonaiagents/tools/shell_tools.py,sha256=6IlnFkNg04tVxQVM_fYgscIWLtcgIikpEi3olB1THuA,9431
37
42
  praisonaiagents/tools/spider_tools.py,sha256=lrZnT1V1BC46We-AzBrDB1Ryifr3KKGmYNntMsScU7w,15094
38
43
  praisonaiagents/tools/test.py,sha256=UHOTNrnMo0_H6I2g48re1WNZkrR7f6z25UnlWxiOSbM,1600
@@ -42,7 +47,7 @@ praisonaiagents/tools/xml_tools.py,sha256=iYTMBEk5l3L3ryQ1fkUnNVYK-Nnua2Kx2S0dxN
42
47
  praisonaiagents/tools/yaml_tools.py,sha256=uogAZrhXV9O7xvspAtcTfpKSQYL2nlOTvCQXN94-G9A,14215
43
48
  praisonaiagents/tools/yfinance_tools.py,sha256=s2PBj_1v7oQnOobo2fDbQBACEHl61ftG4beG6Z979ZE,8529
44
49
  praisonaiagents/tools/train/data/generatecot.py,sha256=H6bNh-E2hqL5MW6kX3hqZ05g9ETKN2-kudSjiuU_SD8,19403
45
- praisonaiagents-0.0.99.dist-info/METADATA,sha256=nwlbhRlDcuelH3q-qUQS1jaEPb_CeGL849Epd6NonJM,1452
46
- praisonaiagents-0.0.99.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
47
- praisonaiagents-0.0.99.dist-info/top_level.txt,sha256=_HsRddrJ23iDx5TTqVUVvXG2HeHBL5voshncAMDGjtA,16
48
- praisonaiagents-0.0.99.dist-info/RECORD,,
50
+ praisonaiagents-0.0.100.dist-info/METADATA,sha256=sP3J1zX6-LWPWRdLHRmy-Ca-ADgUxL3GR1-qsaiFO4Y,1453
51
+ praisonaiagents-0.0.100.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
52
+ praisonaiagents-0.0.100.dist-info/top_level.txt,sha256=_HsRddrJ23iDx5TTqVUVvXG2HeHBL5voshncAMDGjtA,16
53
+ praisonaiagents-0.0.100.dist-info/RECORD,,