mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-08 17:31:00 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5b6f8b91a | ||
|
|
823e46ca84 | ||
|
|
57040333a7 | ||
|
|
8c6800f876 | ||
|
|
0d701ae43c | ||
|
|
7a8c25621c | ||
|
|
218c5443b1 | ||
|
|
f56810341c | ||
|
|
4f601a573f | ||
|
|
43c03f4813 | ||
|
|
03856b74bf |
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
FROM python:3.11-slim
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN pip install flask praisonai==2.0.33 gunicorn markdown
|
||||
RUN pip install flask praisonai==2.0.37 gunicorn markdown
|
||||
EXPOSE 8080
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
|
||||
@@ -0,0 +1,6 @@
|
||||
Make it minimal change as possible
|
||||
|
||||
Firstly try not to make any modification to the existing code as possible
|
||||
|
||||
Only if its highly required, without that if it can't be done, then modify the existing.
|
||||
So by default try to add new code section and not modify the existing.
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import AutoAgents
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agents = AutoAgents(
|
||||
instructions="Search for information about AI Agents",
|
||||
tools=[duckduckgo],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
agents.start()
|
||||
@@ -1,74 +0,0 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from typing import List, Dict
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
# 1. Tool
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform a search using DuckDuckGo.
|
||||
|
||||
Args:
|
||||
query (str): The search query.
|
||||
|
||||
Returns:
|
||||
list: A list of search result titles, URLs, and snippets.
|
||||
"""
|
||||
try:
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=10):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during DuckDuckGo search: {e}")
|
||||
return []
|
||||
|
||||
# 2. Agent
|
||||
data_agent = Agent(
|
||||
name="DataCollector",
|
||||
role="Search Specialist",
|
||||
goal="Perform internet searches to collect relevant information.",
|
||||
backstory="Expert in finding and organising internet data.",
|
||||
tools=[internet_search_tool],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# 3. Tasks
|
||||
collect_task = Task(
|
||||
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
|
||||
expected_output="List of search results with titles, URLs, and snippets.",
|
||||
agent=data_agent,
|
||||
name="collect_data",
|
||||
is_start=True,
|
||||
next_tasks=["validate_data"]
|
||||
)
|
||||
|
||||
validate_task = Task(
|
||||
description="""Validate the collected data. Check if:
|
||||
1. At least 5 results are returned.
|
||||
2. Each result contains a title and a URL.
|
||||
Return validation_result as 'valid' or 'invalid' only no other text.""",
|
||||
expected_output="Validation result indicating if data is valid or invalid.",
|
||||
agent=data_agent,
|
||||
name="validate_data",
|
||||
task_type="decision",
|
||||
condition={
|
||||
"valid": [], # End the workflow on valid data
|
||||
"invalid": ["collect_data"] # Retry data collection on invalid data
|
||||
},
|
||||
)
|
||||
|
||||
# 4. Workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=[data_agent],
|
||||
tasks=[collect_task, validate_task],
|
||||
verbose=1,
|
||||
process="workflow"
|
||||
)
|
||||
|
||||
agents.start()
|
||||
@@ -0,0 +1,151 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from typing import List, Dict, Union
|
||||
from duckduckgo_search import DDGS
|
||||
from langchain_community.tools import YouTubeSearchTool
|
||||
from langchain_community.utilities import WikipediaAPIWrapper
|
||||
|
||||
# 1. Tool
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform a search using DuckDuckGo.
|
||||
|
||||
Args:
|
||||
query (str): The search query.
|
||||
|
||||
Returns:
|
||||
list: A list of search result titles, URLs, and snippets.
|
||||
"""
|
||||
try:
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=10):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during DuckDuckGo search: {e}")
|
||||
return []
|
||||
|
||||
def youtube_search_tool(query: str, inspect: bool = False, max_results: int = 2):
|
||||
"""
|
||||
Provide a custom wrapper around the YouTubeSearchTool.
|
||||
|
||||
Args:
|
||||
query (str): The search query for YouTube.
|
||||
inspect (bool): If True, returns tool inspection info instead of search results.
|
||||
max_results (int): Maximum number of results to return (default: 2).
|
||||
Returns:
|
||||
Union[List[str], dict]: List of YouTube video URLs or tool inspection info.
|
||||
"""
|
||||
yt = YouTubeSearchTool()
|
||||
|
||||
if inspect:
|
||||
inspection_info = {
|
||||
"type": type(yt),
|
||||
"attributes": [attr for attr in dir(yt) if not attr.startswith('_')],
|
||||
"methods": {
|
||||
"run": getattr(yt, 'run', None),
|
||||
"arun": getattr(yt, 'arun', None)
|
||||
},
|
||||
"properties": {
|
||||
"name": getattr(yt, 'name', 'youtube_search'),
|
||||
"description": getattr(yt, 'description', 'Search YouTube videos'),
|
||||
"return_direct": getattr(yt, 'return_direct', False)
|
||||
}
|
||||
}
|
||||
return inspection_info
|
||||
|
||||
# Format query with max_results
|
||||
formatted_query = f"{query}, {max_results}"
|
||||
return yt.run(formatted_query)
|
||||
|
||||
def wikipedia_search_tool(query: str, inspect: bool = False, max_chars: int = 4000, top_k: int = 3):
|
||||
"""
|
||||
Provide a custom wrapper around langchain_community's WikipediaAPIWrapper.
|
||||
|
||||
Args:
|
||||
query (str): A search query for Wikipedia.
|
||||
inspect (bool): If True, returns tool inspection info instead of search results.
|
||||
max_chars (int): Maximum characters to return (default: 4000).
|
||||
top_k (int): Number of top results to consider (default: 3).
|
||||
Returns:
|
||||
Union[str, dict]: Summary from Wikipedia or tool inspection info if inspect=True.
|
||||
"""
|
||||
w = WikipediaAPIWrapper(
|
||||
top_k_results=top_k,
|
||||
doc_content_chars_max=max_chars,
|
||||
lang='en'
|
||||
)
|
||||
|
||||
if inspect:
|
||||
inspection_info = {
|
||||
"type": type(w),
|
||||
"attributes": [attr for attr in dir(w) if not attr.startswith('_')],
|
||||
"methods": {
|
||||
"run": getattr(w, 'run', None),
|
||||
"arun": getattr(w, 'arun', None)
|
||||
},
|
||||
"properties": {
|
||||
"name": "wikipedia",
|
||||
"description": "Search and get summaries from Wikipedia",
|
||||
"top_k": w.top_k_results,
|
||||
"lang": w.lang,
|
||||
"max_chars": w.doc_content_chars_max
|
||||
}
|
||||
}
|
||||
return inspection_info
|
||||
|
||||
try:
|
||||
result = w.run(query)
|
||||
return result
|
||||
except Exception as e:
|
||||
return f"Error searching Wikipedia: {str(e)}"
|
||||
|
||||
# 2. Agent
|
||||
data_agent = Agent(
|
||||
name="DataCollector",
|
||||
role="Search Specialist",
|
||||
goal="Perform internet searches to collect relevant information.",
|
||||
backstory="Expert in finding and organizing internet data from multiple sources.",
|
||||
tools=[internet_search_tool, youtube_search_tool, wikipedia_search_tool],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# 3. Tasks
|
||||
collect_task = Task(
|
||||
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
|
||||
expected_output="List of search results with titles, URLs, and snippets.",
|
||||
agent=data_agent,
|
||||
name="collect_data",
|
||||
is_start=True,
|
||||
next_tasks=["validate_data"]
|
||||
)
|
||||
|
||||
validate_task = Task(
|
||||
description="""Validate the collected data. Check if:
|
||||
1. At least 5 results are returned.
|
||||
2. Each result contains a title and a URL.
|
||||
Return validation_result as 'valid' or 'invalid' only no other text.""",
|
||||
expected_output="Validation result indicating if data is valid or invalid.",
|
||||
agent=data_agent,
|
||||
name="validate_data",
|
||||
task_type="decision",
|
||||
condition={
|
||||
"valid": [], # End the workflow on valid data
|
||||
"invalid": ["collect_data"] # Retry data collection on invalid data
|
||||
},
|
||||
)
|
||||
|
||||
# 4. Workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=[data_agent],
|
||||
tasks=[collect_task, validate_task],
|
||||
verbose=1,
|
||||
process="workflow"
|
||||
)
|
||||
|
||||
agents.start()
|
||||
File renamed without changes.
@@ -0,0 +1,30 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from langchain_community.tools import YouTubeSearchTool
|
||||
from langchain_community.utilities import WikipediaAPIWrapper
|
||||
|
||||
# Create an agent with both tools
|
||||
agent = Agent(
|
||||
name="SearchAgent",
|
||||
role="Research Assistant",
|
||||
goal="Search for information from multiple sources",
|
||||
backstory="I am an AI assistant that can search YouTube and Wikipedia.",
|
||||
tools=[YouTubeSearchTool, WikipediaAPIWrapper],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create tasks to demonstrate both tools
|
||||
task = Task(
|
||||
name="search_task",
|
||||
description="Search for information about 'AI advancements' on both YouTube and Wikipedia",
|
||||
expected_output="Combined information from YouTube videos and Wikipedia articles",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Create and start the workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
agents.start()
|
||||
@@ -0,0 +1,73 @@
|
||||
from langchain_community.tools import YouTubeSearchTool
|
||||
from langchain_community.utilities import WikipediaAPIWrapper
|
||||
|
||||
def test_tools():
|
||||
"""Test both YouTube and Wikipedia tools"""
|
||||
|
||||
print("\n=== Testing YouTube Search ===")
|
||||
# Test YouTube
|
||||
yt = YouTubeSearchTool()
|
||||
|
||||
# Test basic search
|
||||
print("\nBasic YouTube Search:")
|
||||
query = "AI advancements 2024"
|
||||
print(f"Query: {query}")
|
||||
result = yt.run(query)
|
||||
print(f"Results: {result}")
|
||||
|
||||
# Test with max results
|
||||
print("\nYouTube Search with max results:")
|
||||
query = "AI advancements 2024, 3" # Format: query, max_results
|
||||
print(f"Query: {query}")
|
||||
result = yt.run(query)
|
||||
print(f"Results: {result}")
|
||||
|
||||
print("\n=== Testing Wikipedia Search ===")
|
||||
# Test Wikipedia
|
||||
wiki = WikipediaAPIWrapper(
|
||||
top_k_results=2,
|
||||
doc_content_chars_max=500
|
||||
)
|
||||
|
||||
# Test basic search
|
||||
print("\nBasic Wikipedia Search:")
|
||||
query = "Artificial Intelligence"
|
||||
print(f"Query: {query}")
|
||||
result = wiki.run(query)
|
||||
print(f"Results: {result[:200]}..." if result else "No result")
|
||||
|
||||
# Test with different parameters
|
||||
print("\nWikipedia Search with different language:")
|
||||
wiki_fr = WikipediaAPIWrapper(
|
||||
lang='fr',
|
||||
top_k_results=1,
|
||||
doc_content_chars_max=300
|
||||
)
|
||||
result = wiki_fr.run("Intelligence Artificielle")
|
||||
print(f"French Results: {result[:200]}..." if result else "No result")
|
||||
|
||||
def print_tool_info():
|
||||
"""Print detailed information about the tools"""
|
||||
|
||||
print("\n=== Tool Information ===")
|
||||
|
||||
# YouTube Tool Info
|
||||
print("\nYouTube Tool:")
|
||||
yt = YouTubeSearchTool()
|
||||
print("Type:", type(yt))
|
||||
print("Name:", getattr(yt, 'name', None))
|
||||
print("Description:", getattr(yt, 'description', None))
|
||||
print("Arguments:", getattr(yt, 'args', None))
|
||||
|
||||
# Wikipedia Tool Info
|
||||
print("\nWikipedia Tool:")
|
||||
wiki = WikipediaAPIWrapper()
|
||||
print("Type:", type(wiki))
|
||||
print("Available Settings:")
|
||||
print("- Language:", wiki.lang)
|
||||
print("- Top K Results:", wiki.top_k_results)
|
||||
print("- Max Characters:", wiki.doc_content_chars_max)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print_tool_info()
|
||||
test_tools()
|
||||
@@ -6,6 +6,7 @@ from .agent.agent import Agent
|
||||
from .agents.agents import PraisonAIAgents
|
||||
from .task.task import Task
|
||||
from .tools.tools import Tools
|
||||
from .agents.autoagents import AutoAgents
|
||||
from .main import (
|
||||
TaskOutput,
|
||||
ReflectionOutput,
|
||||
@@ -33,6 +34,7 @@ __all__ = [
|
||||
'Task',
|
||||
'TaskOutput',
|
||||
'ReflectionOutput',
|
||||
'AutoAgents',
|
||||
'display_interaction',
|
||||
'display_self_reflection',
|
||||
'display_instruction',
|
||||
|
||||
@@ -18,6 +18,7 @@ from ..main import (
|
||||
client,
|
||||
error_logs
|
||||
)
|
||||
import inspect
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..task.task import Task
|
||||
@@ -67,9 +68,24 @@ class Agent:
|
||||
return None
|
||||
|
||||
import inspect
|
||||
# Langchain tools
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
original_func = func
|
||||
func = func.run
|
||||
function_name = original_func.__name__
|
||||
|
||||
sig = inspect.signature(func)
|
||||
logging.debug(f"Function signature: {sig}")
|
||||
|
||||
# Skip self, *args, **kwargs, so they don't get passed in arguments
|
||||
parameters_list = []
|
||||
for name, param in sig.parameters.items():
|
||||
if name == "self":
|
||||
continue
|
||||
if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
|
||||
continue
|
||||
parameters_list.append((name, param))
|
||||
|
||||
parameters = {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
@@ -95,7 +111,7 @@ class Agent:
|
||||
|
||||
logging.debug(f"Parameter descriptions: {param_descriptions}")
|
||||
|
||||
for name, param in sig.parameters.items():
|
||||
for name, param in parameters_list:
|
||||
param_type = "string" # Default type
|
||||
if param.annotation != inspect.Parameter.empty:
|
||||
if param.annotation == int:
|
||||
@@ -249,25 +265,31 @@ Your Goal: {self.goal}
|
||||
# Try to find the function in the agent's tools list first
|
||||
func = None
|
||||
for tool in self.tools:
|
||||
if callable(tool) and getattr(tool, '__name__', '') == function_name:
|
||||
if (callable(tool) and getattr(tool, '__name__', '') == function_name) or \
|
||||
(inspect.isclass(tool) and tool.__name__ == function_name):
|
||||
func = tool
|
||||
break
|
||||
|
||||
logging.debug(f"Looking for {function_name} in agent tools: {func is not None}")
|
||||
|
||||
# If not found in tools, try globals and main
|
||||
if not func:
|
||||
if func is None:
|
||||
# If not found in tools, try globals and main
|
||||
func = globals().get(function_name)
|
||||
logging.debug(f"Looking for {function_name} in globals: {func is not None}")
|
||||
|
||||
if not func:
|
||||
import __main__
|
||||
func = getattr(__main__, function_name, None)
|
||||
logging.debug(f"Looking for {function_name} in __main__: {func is not None}")
|
||||
|
||||
if func and callable(func):
|
||||
if func:
|
||||
try:
|
||||
return func(**arguments)
|
||||
# If it's a class with run method, instantiate and call run
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
instance = func()
|
||||
# Extract only the parameters that run() expects
|
||||
run_params = {k: v for k, v in arguments.items()
|
||||
if k in inspect.signature(instance.run).parameters
|
||||
and k != 'self'}
|
||||
return instance.run(**run_params)
|
||||
# Otherwise treat as regular function
|
||||
elif callable(func):
|
||||
return func(**arguments)
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
logging.error(f"Error executing tool {function_name}: {error_msg}")
|
||||
@@ -711,4 +733,8 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
return None
|
||||
except Exception as e:
|
||||
display_error(f"Error in _achat_completion: {e}")
|
||||
return None
|
||||
return None
|
||||
|
||||
def run(self):
|
||||
"""Alias for start() method"""
|
||||
return self.start()
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Agents module for managing multiple AI agents"""
|
||||
from .agents import PraisonAIAgents
|
||||
from .autoagents import AutoAgents
|
||||
|
||||
__all__ = ['PraisonAIAgents']
|
||||
__all__ = ['PraisonAIAgents', 'AutoAgents']
|
||||
@@ -0,0 +1,335 @@
|
||||
"""
|
||||
AutoAgents - A class for automatically creating and managing AI agents and tasks.
|
||||
|
||||
This class provides a simplified interface for creating and running AI agents with tasks.
|
||||
It automatically handles agent creation, task setup, and execution flow.
|
||||
"""
|
||||
|
||||
from .agents import PraisonAIAgents
|
||||
from ..agent.agent import Agent
|
||||
from ..task.task import Task
|
||||
from typing import List, Any, Optional, Dict, Union
|
||||
import logging
|
||||
import os
|
||||
from pydantic import BaseModel, Field
|
||||
from ..main import display_instruction, display_tool_call, display_interaction, client
|
||||
|
||||
# Define Pydantic models for structured output
|
||||
class TaskConfig(BaseModel):
|
||||
name: str
|
||||
description: str
|
||||
expected_output: str
|
||||
tools: List[str]
|
||||
|
||||
class AgentConfig(BaseModel):
|
||||
name: str
|
||||
role: str
|
||||
goal: str
|
||||
backstory: str
|
||||
tools: List[str]
|
||||
tasks: List[TaskConfig]
|
||||
|
||||
class AutoAgentsConfig(BaseModel):
|
||||
main_instruction: str
|
||||
process_type: str
|
||||
agents: List[AgentConfig]
|
||||
|
||||
class AutoAgents(PraisonAIAgents):
|
||||
def __init__(
|
||||
self,
|
||||
instructions: str,
|
||||
tools: Optional[List[Any]] = None,
|
||||
verbose: bool = False,
|
||||
process: str = "sequential",
|
||||
manager_llm: Optional[str] = None,
|
||||
max_retries: int = 5,
|
||||
completion_checker: Optional[Any] = None,
|
||||
allow_code_execution: bool = False,
|
||||
memory: bool = True,
|
||||
markdown: bool = True,
|
||||
self_reflect: bool = False,
|
||||
max_reflect: int = 3,
|
||||
min_reflect: int = 1,
|
||||
llm: Optional[str] = None,
|
||||
function_calling_llm: Optional[str] = None,
|
||||
respect_context_window: bool = True,
|
||||
code_execution_mode: str = "safe",
|
||||
embedder_config: Optional[Dict[str, Any]] = None,
|
||||
knowledge_sources: Optional[List[Any]] = None,
|
||||
use_system_prompt: bool = True,
|
||||
cache: bool = True,
|
||||
allow_delegation: bool = False,
|
||||
step_callback: Optional[Any] = None,
|
||||
system_template: Optional[str] = None,
|
||||
prompt_template: Optional[str] = None,
|
||||
response_template: Optional[str] = None,
|
||||
max_rpm: Optional[int] = None,
|
||||
max_execution_time: Optional[int] = None,
|
||||
max_iter: int = 20,
|
||||
reflect_llm: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
api_key: Optional[str] = None,
|
||||
max_agents: int = 3 # New parameter for maximum number of agents
|
||||
):
|
||||
"""Initialize AutoAgents with configuration for automatic agent and task creation."""
|
||||
if max_agents < 1:
|
||||
raise ValueError("max_agents must be at least 1")
|
||||
if max_agents > 10:
|
||||
raise ValueError("max_agents cannot exceed 10")
|
||||
|
||||
# Store all configuration parameters first
|
||||
self.instructions = instructions
|
||||
self.tools = tools or []
|
||||
self.verbose = verbose # Store verbose parameter
|
||||
self.max_agents = max_agents # Store max_agents parameter
|
||||
self.allow_code_execution = allow_code_execution
|
||||
self.memory = memory
|
||||
self.markdown = markdown
|
||||
self.self_reflect = self_reflect
|
||||
self.max_reflect = max_reflect
|
||||
self.min_reflect = min_reflect
|
||||
self.llm = llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
self.function_calling_llm = function_calling_llm
|
||||
self.respect_context_window = respect_context_window
|
||||
self.code_execution_mode = code_execution_mode
|
||||
self.embedder_config = embedder_config
|
||||
self.knowledge_sources = knowledge_sources
|
||||
self.use_system_prompt = use_system_prompt
|
||||
self.cache = cache
|
||||
self.allow_delegation = allow_delegation
|
||||
self.step_callback = step_callback
|
||||
self.system_template = system_template
|
||||
self.prompt_template = prompt_template
|
||||
self.response_template = response_template
|
||||
self.max_rpm = max_rpm
|
||||
self.max_execution_time = max_execution_time
|
||||
self.max_iter = max_iter
|
||||
self.reflect_llm = reflect_llm
|
||||
|
||||
# Display initial instruction
|
||||
if self.verbose:
|
||||
display_instruction(f"🎯 Main Task: {self.instructions}")
|
||||
display_instruction(f"📊 Maximum Agents: {self.max_agents}")
|
||||
if self.tools:
|
||||
tool_names = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
|
||||
display_tool_call(f"🛠️ Available Tools: {', '.join(tool_names)}")
|
||||
|
||||
# Generate agents and tasks configuration
|
||||
config = self._generate_config()
|
||||
agents, tasks = self._create_agents_and_tasks(config)
|
||||
|
||||
# Display agents and their tasks
|
||||
if self.verbose:
|
||||
self._display_agents_and_tasks(agents, tasks)
|
||||
|
||||
# Initialize parent class with generated agents and tasks
|
||||
super().__init__(
|
||||
agents=agents,
|
||||
tasks=tasks,
|
||||
verbose=verbose,
|
||||
completion_checker=completion_checker,
|
||||
max_retries=max_retries,
|
||||
process=process,
|
||||
manager_llm=manager_llm
|
||||
)
|
||||
|
||||
def _display_agents_and_tasks(self, agents: List[Agent], tasks: List[Task]):
|
||||
"""Display the created agents and their assigned tasks"""
|
||||
display_instruction("\n🤖 Generated Agents and Tasks:")
|
||||
|
||||
# Create a mapping of agents to their tasks
|
||||
agent_tasks = {}
|
||||
for task in tasks:
|
||||
if task.agent not in agent_tasks:
|
||||
agent_tasks[task.agent] = []
|
||||
agent_tasks[task.agent].append(task)
|
||||
|
||||
# Display each agent and their tasks
|
||||
for agent in agents:
|
||||
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in agent.tools]
|
||||
display_interaction(
|
||||
f"\n👤 Agent: {agent.name}",
|
||||
f"""Role: {agent.role}
|
||||
Goal: {agent.goal}
|
||||
Tools: {', '.join(agent_tools)}"""
|
||||
)
|
||||
|
||||
# Display tasks for this agent
|
||||
if agent in agent_tasks:
|
||||
for i, task in enumerate(agent_tasks[agent], 1):
|
||||
task_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in task.tools]
|
||||
display_instruction(
|
||||
f""" 📋 Task {i}: {task.name}
|
||||
Description: {task.description}
|
||||
Expected Output: {task.expected_output}
|
||||
Tools: {', '.join(task_tools)}"""
|
||||
)
|
||||
|
||||
def _get_available_tools(self) -> List[str]:
|
||||
"""Get list of available tools"""
|
||||
if not self.tools:
|
||||
return []
|
||||
return [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
|
||||
|
||||
def _get_tool_by_name(self, tool_name: str) -> Optional[Any]:
|
||||
"""Get tool object by its name"""
|
||||
for tool in self.tools:
|
||||
if (hasattr(tool, '__name__') and tool.__name__ == tool_name) or str(tool) == tool_name:
|
||||
return tool
|
||||
return None
|
||||
|
||||
def _assign_tools_to_agent(self, agent_config: AgentConfig) -> List[Any]:
|
||||
"""
|
||||
Assign appropriate tools to an agent based on its role and tasks.
|
||||
|
||||
Args:
|
||||
agent_config: The agent configuration containing role and required tools
|
||||
|
||||
Returns:
|
||||
List of tool objects assigned to this agent
|
||||
"""
|
||||
assigned_tools = []
|
||||
tool_names = set(agent_config.tools)
|
||||
|
||||
# Also look at task requirements
|
||||
for task in agent_config.tasks:
|
||||
tool_names.update(task.tools)
|
||||
|
||||
# Assign tools that match the requirements
|
||||
for tool_name in tool_names:
|
||||
tool = self._get_tool_by_name(tool_name)
|
||||
if tool:
|
||||
assigned_tools.append(tool)
|
||||
|
||||
# If no specific tools matched but we have tools available,
|
||||
# assign all tools to ensure functionality
|
||||
if not assigned_tools and self.tools:
|
||||
assigned_tools = self.tools
|
||||
|
||||
return assigned_tools
|
||||
|
||||
def _generate_config(self) -> AutoAgentsConfig:
|
||||
"""Generate the configuration for agents and tasks"""
|
||||
prompt = f"""
|
||||
Generate a configuration for AI agents to accomplish this task: "{self.instructions}"
|
||||
|
||||
The configuration should include:
|
||||
1. A main instruction that clearly states the overall goal
|
||||
2. A process type (sequential, workflow, or hierarchical)
|
||||
3. A list of maximum {self.max_agents} agents (no more, no less), each with:
|
||||
- Name, role, goal, and backstory
|
||||
- List of required tools from: {self._get_available_tools()}
|
||||
- Only add tools that are needed for the agent to perform its task
|
||||
- Only one task per agent. Add more than one task if absolutely necessary.
|
||||
- List of specific tasks they need to perform
|
||||
- Whether they should self-reflect or allow delegation
|
||||
|
||||
Requirements:
|
||||
1. Each agent should have clear, focused responsibilities
|
||||
2. Tasks should be broken down into manageable steps
|
||||
3. Tool selection should be appropriate for each task
|
||||
4. The process type should match the task requirements
|
||||
5. Generate maximum {self.max_agents} agents to handle this task efficiently
|
||||
|
||||
Return the configuration in a structured JSON format matching the AutoAgentsConfig schema.
|
||||
"""
|
||||
|
||||
try:
|
||||
response = client.beta.chat.completions.parse(
|
||||
model=self.llm,
|
||||
response_format=AutoAgentsConfig,
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a helpful assistant designed to generate AI agent configurations."},
|
||||
{"role": "user", "content": prompt}
|
||||
]
|
||||
)
|
||||
|
||||
# Ensure we have exactly max_agents number of agents
|
||||
if len(response.choices[0].message.parsed.agents) > self.max_agents:
|
||||
response.choices[0].message.parsed.agents = response.choices[0].message.parsed.agents[:self.max_agents]
|
||||
elif len(response.choices[0].message.parsed.agents) < self.max_agents:
|
||||
logging.warning(f"Generated {len(response.choices[0].message.parsed.agents)} agents, expected {self.max_agents}")
|
||||
|
||||
return response.choices[0].message.parsed
|
||||
except Exception as e:
|
||||
logging.error(f"Error generating configuration: {e}")
|
||||
raise
|
||||
|
||||
def _create_agents_and_tasks(self, config: AutoAgentsConfig) -> tuple[List[Agent], List[Task]]:
|
||||
"""Create agents and tasks from configuration"""
|
||||
agents = []
|
||||
tasks = []
|
||||
|
||||
for agent_config in config.agents:
|
||||
# Get appropriate tools for this agent
|
||||
agent_tools = self._assign_tools_to_agent(agent_config)
|
||||
|
||||
# Create the agent with all parameters
|
||||
agent = Agent(
|
||||
name=agent_config.name,
|
||||
role=agent_config.role,
|
||||
goal=agent_config.goal,
|
||||
backstory=agent_config.backstory,
|
||||
tools=agent_tools, # Use assigned tools
|
||||
verbose=self.verbose >= 1,
|
||||
allow_code_execution=self.allow_code_execution,
|
||||
memory=self.memory,
|
||||
markdown=self.markdown,
|
||||
self_reflect=self.self_reflect,
|
||||
max_reflect=self.max_reflect,
|
||||
min_reflect=self.min_reflect,
|
||||
llm=self.llm,
|
||||
function_calling_llm=self.function_calling_llm,
|
||||
respect_context_window=self.respect_context_window,
|
||||
code_execution_mode=self.code_execution_mode,
|
||||
embedder_config=self.embedder_config,
|
||||
knowledge_sources=self.knowledge_sources,
|
||||
use_system_prompt=self.use_system_prompt,
|
||||
cache=self.cache,
|
||||
allow_delegation=self.allow_delegation,
|
||||
step_callback=self.step_callback,
|
||||
system_template=self.system_template,
|
||||
prompt_template=self.prompt_template,
|
||||
response_template=self.response_template,
|
||||
max_rpm=self.max_rpm,
|
||||
max_execution_time=self.max_execution_time,
|
||||
max_iter=self.max_iter,
|
||||
reflect_llm=self.reflect_llm
|
||||
)
|
||||
agents.append(agent)
|
||||
|
||||
# Create tasks for this agent
|
||||
for task_config in agent_config.tasks:
|
||||
# Get task-specific tools
|
||||
task_tools = [self._get_tool_by_name(t) for t in task_config.tools]
|
||||
task_tools = [t for t in task_tools if t] # Remove None values
|
||||
|
||||
# If no specific tools matched, use agent's tools
|
||||
if not task_tools:
|
||||
task_tools = agent_tools
|
||||
|
||||
task = Task(
|
||||
name=task_config.name,
|
||||
description=task_config.description,
|
||||
expected_output=task_config.expected_output,
|
||||
agent=agent,
|
||||
tools=task_tools # Use task-specific tools
|
||||
)
|
||||
tasks.append(task)
|
||||
|
||||
return agents, tasks
|
||||
|
||||
async def astart(self):
|
||||
"""
|
||||
Async version of start() method.
|
||||
Creates tasks based on the instructions, then starts execution.
|
||||
Returns the task status and results dictionary.
|
||||
"""
|
||||
return await super().astart()
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
Creates tasks based on the instructions, then starts execution.
|
||||
Returns the task status and results dictionary.
|
||||
"""
|
||||
return super().start()
|
||||
@@ -8,6 +8,59 @@ TOOL_MAPPINGS = {
|
||||
'internet_search': ('.duckduckgo_tools', None),
|
||||
'duckduckgo': ('.duckduckgo_tools', None),
|
||||
|
||||
# arXiv Tools
|
||||
'search_arxiv': ('.arxiv_tools', None),
|
||||
'get_arxiv_paper': ('.arxiv_tools', None),
|
||||
'get_papers_by_author': ('.arxiv_tools', None),
|
||||
'get_papers_by_category': ('.arxiv_tools', None),
|
||||
'arxiv_tools': ('.arxiv_tools', None),
|
||||
|
||||
# Wikipedia Tools
|
||||
'wiki_search': ('.wikipedia_tools', None),
|
||||
'wiki_summary': ('.wikipedia_tools', None),
|
||||
'wiki_page': ('.wikipedia_tools', None),
|
||||
'wiki_random': ('.wikipedia_tools', None),
|
||||
'wiki_language': ('.wikipedia_tools', None),
|
||||
'wikipedia_tools': ('.wikipedia_tools', None),
|
||||
|
||||
# Newspaper Tools
|
||||
'get_article': ('.newspaper_tools', None),
|
||||
'get_news_sources': ('.newspaper_tools', None),
|
||||
'get_articles_from_source': ('.newspaper_tools', None),
|
||||
'get_trending_topics': ('.newspaper_tools', None),
|
||||
'newspaper_tools': ('.newspaper_tools', None),
|
||||
|
||||
# Spider Tools
|
||||
'scrape_page': ('.spider_tools', None),
|
||||
'extract_links': ('.spider_tools', None),
|
||||
'crawl': ('.spider_tools', None),
|
||||
'extract_text': ('.spider_tools', None),
|
||||
'spider_tools': ('.spider_tools', None),
|
||||
|
||||
# DuckDB Tools
|
||||
'query': ('.duckdb_tools', None),
|
||||
'create_table': ('.duckdb_tools', None),
|
||||
'load_data': ('.duckdb_tools', None),
|
||||
'export_data': ('.duckdb_tools', None),
|
||||
'get_table_info': ('.duckdb_tools', None),
|
||||
'analyze_data': ('.duckdb_tools', None),
|
||||
'duckdb_tools': ('.duckdb_tools', None),
|
||||
|
||||
# Shell Tools
|
||||
'execute_command': ('.shell_tools', None),
|
||||
'list_processes': ('.shell_tools', None),
|
||||
'kill_process': ('.shell_tools', None),
|
||||
'get_system_info': ('.shell_tools', None),
|
||||
'shell_tools': ('.shell_tools', None),
|
||||
|
||||
# Calculator Tools
|
||||
'evaluate': ('.calculator_tools', None),
|
||||
'solve_equation': ('.calculator_tools', None),
|
||||
'convert_units': ('.calculator_tools', None),
|
||||
'calculate_statistics': ('.calculator_tools', None),
|
||||
'calculate_financial': ('.calculator_tools', None),
|
||||
'calculator_tools': ('.calculator_tools', None),
|
||||
|
||||
# Class methods from YFinance
|
||||
'get_stock_price': ('.yfinance_tools', 'YFinanceTools'),
|
||||
'get_stock_info': ('.yfinance_tools', 'YFinanceTools'),
|
||||
@@ -68,14 +121,6 @@ TOOL_MAPPINGS = {
|
||||
'transform_yaml': ('.yaml_tools', 'YAMLTools'),
|
||||
'yaml_tools': ('.yaml_tools', 'YAMLTools'),
|
||||
|
||||
# Calculator Tools
|
||||
'evaluate': ('.calculator_tools', 'CalculatorTools'),
|
||||
'solve_equation': ('.calculator_tools', 'CalculatorTools'),
|
||||
'convert_units': ('.calculator_tools', 'CalculatorTools'),
|
||||
'calculate_statistics': ('.calculator_tools', 'CalculatorTools'),
|
||||
'calculate_financial': ('.calculator_tools', 'CalculatorTools'),
|
||||
'calculator_tools': ('.calculator_tools', 'CalculatorTools'),
|
||||
|
||||
# Python Tools
|
||||
'execute_code': ('.python_tools', 'PythonTools'),
|
||||
'analyze_code': ('.python_tools', 'PythonTools'),
|
||||
@@ -90,51 +135,6 @@ TOOL_MAPPINGS = {
|
||||
'group_by': ('.pandas_tools', 'PandasTools'),
|
||||
'pivot_table': ('.pandas_tools', 'PandasTools'),
|
||||
'pandas_tools': ('.pandas_tools', 'PandasTools'),
|
||||
|
||||
# Wikipedia Tools
|
||||
'search': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'get_wikipedia_summary': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'get_wikipedia_page': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'get_random_wikipedia': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'set_wikipedia_language': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'wikipedia_tools': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
|
||||
# Newspaper Tools
|
||||
'get_article': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'get_news_sources': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'get_articles_from_source': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'get_trending_topics': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'newspaper_tools': ('.newspaper_tools', 'NewspaperTools'),
|
||||
|
||||
# arXiv Tools
|
||||
'search_arxiv': ('.arxiv_tools', 'ArxivTools'),
|
||||
'get_arxiv_paper': ('.arxiv_tools', 'ArxivTools'),
|
||||
'get_papers_by_author': ('.arxiv_tools', 'ArxivTools'),
|
||||
'get_papers_by_category': ('.arxiv_tools', 'ArxivTools'),
|
||||
'arxiv_tools': ('.arxiv_tools', 'ArxivTools'),
|
||||
|
||||
# Spider Tools
|
||||
'scrape_page': ('.spider_tools', 'SpiderTools'),
|
||||
'extract_links': ('.spider_tools', 'SpiderTools'),
|
||||
'crawl': ('.spider_tools', 'SpiderTools'),
|
||||
'extract_text': ('.spider_tools', 'SpiderTools'),
|
||||
'spider_tools': ('.spider_tools', 'SpiderTools'),
|
||||
|
||||
# DuckDB Tools
|
||||
'query': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'create_table': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'load_data': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'export_data': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'get_table_info': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'analyze_data': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'duckdb_tools': ('.duckdb_tools', 'DuckDBTools'),
|
||||
|
||||
# Shell Tools
|
||||
'execute_command': ('.shell_tools', 'ShellTools'),
|
||||
'list_processes': ('.shell_tools', 'ShellTools'),
|
||||
'kill_process': ('.shell_tools', 'ShellTools'),
|
||||
'get_system_info': ('.shell_tools', 'ShellTools'),
|
||||
'shell_tools': ('.shell_tools', 'ShellTools'),
|
||||
}
|
||||
|
||||
_instances = {} # Cache for class instances
|
||||
@@ -149,7 +149,18 @@ def __getattr__(name: str) -> Any:
|
||||
if class_name is None:
|
||||
# Direct function import
|
||||
module = import_module(module_path, __package__)
|
||||
if name in ['duckduckgo', 'file_tools', 'pandas_tools', 'wikipedia_tools',
|
||||
if name in [
|
||||
'duckduckgo', 'internet_search',
|
||||
'search_arxiv', 'get_arxiv_paper', 'get_papers_by_author', 'get_papers_by_category',
|
||||
'wiki_search', 'wiki_summary', 'wiki_page', 'wiki_random', 'wiki_language',
|
||||
'get_article', 'get_news_sources', 'get_articles_from_source', 'get_trending_topics',
|
||||
'scrape_page', 'extract_links', 'crawl', 'extract_text',
|
||||
'query', 'create_table', 'load_data', 'export_data', 'get_table_info', 'analyze_data',
|
||||
'execute_command', 'list_processes', 'kill_process', 'get_system_info',
|
||||
'evaluate', 'solve_equation', 'convert_units', 'calculate_statistics', 'calculate_financial'
|
||||
]:
|
||||
return getattr(module, name)
|
||||
if name in ['file_tools', 'pandas_tools', 'wikipedia_tools',
|
||||
'newspaper_tools', 'arxiv_tools', 'spider_tools', 'duckdb_tools', 'csv_tools', 'json_tools', 'excel_tools', 'xml_tools', 'yaml_tools', 'calculator_tools', 'python_tools', 'shell_tools']:
|
||||
return module # Returns the callable module
|
||||
return getattr(module, name)
|
||||
|
||||
@@ -12,7 +12,6 @@ results = duckduckgo("AI news")
|
||||
from typing import List, Dict
|
||||
import logging
|
||||
from importlib import util
|
||||
import sys
|
||||
|
||||
def internet_search(query: str) -> List[Dict]:
|
||||
"""Perform an internet search using DuckDuckGo."""
|
||||
@@ -40,8 +39,9 @@ def internet_search(query: str) -> List[Dict]:
|
||||
logging.error(error_msg)
|
||||
return [{"error": error_msg}]
|
||||
|
||||
# Make the module callable
|
||||
sys.modules[__name__].__call__ = internet_search
|
||||
def duckduckgo(query: str) -> List[Dict]:
|
||||
"""Alias for internet_search function."""
|
||||
return internet_search(query)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Tools module for PraisonAI Agents"""
|
||||
from .internet_search import internet_search
|
||||
from .duckduckgo_tools import internet_search
|
||||
|
||||
class Tools:
|
||||
"""Tools class for backward compatibility"""
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
Usage:
|
||||
from praisonaiagents.tools import wikipedia_tools
|
||||
summary = wikipedia_tools.get_summary("Python programming language")
|
||||
page = wikipedia_tools.get_page("Python programming language")
|
||||
results = wikipedia_tools.search("Python programming")
|
||||
summary = wikipedia_tools.wiki_summary("Python programming language")
|
||||
page = wikipedia_tools.wiki_page("Python programming language")
|
||||
results = wikipedia_tools.wiki_search("Python programming")
|
||||
|
||||
or
|
||||
from praisonaiagents.tools import get_wikipedia_summary, get_wikipedia_page
|
||||
summary = get_wikipedia_summary("Python programming language")
|
||||
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page
|
||||
summary = wiki_summary("Python programming language")
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -32,7 +32,7 @@ class WikipediaTools:
|
||||
# Set default language to English
|
||||
wikipedia.set_lang("en")
|
||||
|
||||
def search(
|
||||
def wiki_search(
|
||||
self,
|
||||
query: str,
|
||||
results: int = 10,
|
||||
@@ -63,7 +63,7 @@ class WikipediaTools:
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
def get_summary(
|
||||
def wiki_summary(
|
||||
self,
|
||||
title: str,
|
||||
sentences: int = 5,
|
||||
@@ -92,7 +92,7 @@ class WikipediaTools:
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
def get_page(
|
||||
def wiki_page(
|
||||
self,
|
||||
title: str,
|
||||
auto_suggest: bool = True
|
||||
@@ -168,7 +168,7 @@ class WikipediaTools:
|
||||
|
||||
return sections
|
||||
|
||||
def get_random(self, pages: int = 1) -> Union[List[str], Dict[str, str]]:
|
||||
def wiki_random(self, pages: int = 1) -> Union[List[str], Dict[str, str]]:
|
||||
"""
|
||||
Get random Wikipedia page titles.
|
||||
|
||||
@@ -185,7 +185,7 @@ class WikipediaTools:
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
def set_language(self, language: str) -> bool:
|
||||
def wiki_language(self, language: str) -> bool:
|
||||
"""
|
||||
Set the language for Wikipedia searches.
|
||||
|
||||
@@ -205,11 +205,11 @@ class WikipediaTools:
|
||||
|
||||
# Create instance for direct function access
|
||||
_wikipedia_tools = WikipediaTools()
|
||||
search = _wikipedia_tools.search
|
||||
get_summary = _wikipedia_tools.get_summary
|
||||
get_page = _wikipedia_tools.get_page
|
||||
get_random = _wikipedia_tools.get_random
|
||||
set_language = _wikipedia_tools.set_language
|
||||
wiki_search = _wikipedia_tools.wiki_search
|
||||
wiki_summary = _wikipedia_tools.wiki_summary
|
||||
wiki_page = _wikipedia_tools.wiki_page
|
||||
wiki_random = _wikipedia_tools.wiki_random
|
||||
wiki_language = _wikipedia_tools.wiki_language
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
@@ -220,7 +220,7 @@ if __name__ == "__main__":
|
||||
# 1. Search for a topic
|
||||
print("1. Searching Wikipedia")
|
||||
print("------------------------------")
|
||||
search_results = search("Python programming language")
|
||||
search_results = wiki_search("Python programming language")
|
||||
print("Search results:")
|
||||
print(json.dumps(search_results, indent=2))
|
||||
print()
|
||||
@@ -228,7 +228,7 @@ if __name__ == "__main__":
|
||||
# 2. Get a page summary
|
||||
print("2. Getting Page Summary")
|
||||
print("------------------------------")
|
||||
summary = get_summary("Python programming language", sentences=3)
|
||||
summary = wiki_summary("Python programming language", sentences=3)
|
||||
print("Summary:")
|
||||
print(summary)
|
||||
print()
|
||||
@@ -236,7 +236,7 @@ if __name__ == "__main__":
|
||||
# 3. Get detailed page information
|
||||
print("3. Getting Full Page Information")
|
||||
print("------------------------------")
|
||||
page = get_page("Python programming language")
|
||||
page = wiki_page("Python programming language")
|
||||
if isinstance(page, dict) and "error" not in page:
|
||||
print("Page sections:")
|
||||
for section in page["sections"]:
|
||||
@@ -252,7 +252,7 @@ if __name__ == "__main__":
|
||||
# 4. Get random pages
|
||||
print("4. Getting Random Pages")
|
||||
print("------------------------------")
|
||||
random_pages = get_random(3)
|
||||
random_pages = wiki_random(3)
|
||||
print("Random page titles:")
|
||||
print(json.dumps(random_pages, indent=2))
|
||||
print()
|
||||
@@ -260,9 +260,9 @@ if __name__ == "__main__":
|
||||
# 5. Try different language
|
||||
print("5. Changing Language")
|
||||
print("------------------------------")
|
||||
success = set_language("es")
|
||||
success = wiki_language("es")
|
||||
if success:
|
||||
summary = get_summary("Python (lenguaje de programación)", sentences=1)
|
||||
summary = wiki_summary("Python (lenguaje de programación)", sentences=1)
|
||||
print("Spanish summary:")
|
||||
print(summary)
|
||||
print()
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.24"
|
||||
version = "0.0.28"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
authors = [
|
||||
{ name="Mervin Praison" }
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
from praisonaiagents import Agent
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
|
||||
# Define structured output models
|
||||
class SearchResult(BaseModel):
|
||||
title: str
|
||||
url: Optional[str]
|
||||
snippet: str
|
||||
|
||||
class AnalysisReport(BaseModel):
|
||||
topic: str
|
||||
key_findings: List[str]
|
||||
search_results: List[SearchResult]
|
||||
summary: str
|
||||
confidence_score: float
|
||||
|
||||
def get_structured_analysis(query: str, verbose: bool = True) -> AnalysisReport:
|
||||
"""
|
||||
Performs a search and returns a structured analysis using an AI agent.
|
||||
|
||||
Args:
|
||||
query (str): The search query or topic to analyze
|
||||
verbose (bool): Whether to show detailed output
|
||||
|
||||
Returns:
|
||||
AnalysisReport: A structured report containing the analysis
|
||||
"""
|
||||
# Create an agent with search capabilities
|
||||
agent = Agent(
|
||||
name="StructuredAnalyst",
|
||||
role="Research Analyst",
|
||||
goal="Analyze topics and provide structured reports",
|
||||
backstory="Expert at gathering information and providing structured analysis",
|
||||
verbose=verbose,
|
||||
self_reflect=True, # Enable self-reflection for better quality
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# Create the analysis prompt
|
||||
prompt = f"""
|
||||
Analyze the following topic: "{query}"
|
||||
|
||||
Provide a structured analysis in JSON format that matches this schema:
|
||||
{{
|
||||
"topic": "string",
|
||||
"key_findings": ["string"],
|
||||
"search_results": [
|
||||
{{
|
||||
"title": "string",
|
||||
"url": "string",
|
||||
"snippet": "string"
|
||||
}}
|
||||
],
|
||||
"summary": "string",
|
||||
"confidence_score": float (0-1)
|
||||
}}
|
||||
|
||||
Requirements:
|
||||
1. Include at least 3 key findings
|
||||
2. Include at least 2 relevant search results
|
||||
3. Provide a comprehensive summary
|
||||
4. Set confidence score based on quality of sources (0-1)
|
||||
|
||||
Return ONLY the JSON object, no other text.
|
||||
"""
|
||||
|
||||
# Get structured response from agent
|
||||
response = agent.chat(
|
||||
prompt=prompt,
|
||||
output_json=AnalysisReport # This ensures response matches our model
|
||||
)
|
||||
|
||||
return AnalysisReport.parse_raw(response)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
analysis = get_structured_analysis("Latest developments in AI agents and autonomous systems")
|
||||
print(analysis)
|
||||
# Print the structured results
|
||||
print("\n=== Structured Analysis Report ===")
|
||||
print(f"Topic: {analysis.topic}")
|
||||
print("\nKey Findings:")
|
||||
for i, finding in enumerate(analysis.key_findings, 1):
|
||||
print(f"{i}. {finding}")
|
||||
|
||||
print("\nSearch Results:")
|
||||
for result in analysis.search_results:
|
||||
print(f"\nTitle: {result.title}")
|
||||
print(f"URL: {result.url}")
|
||||
print(f"Snippet: {result.snippet}")
|
||||
|
||||
print(f"\nSummary: {analysis.summary}")
|
||||
print(f"Confidence Score: {analysis.confidence_score:.2f}")
|
||||
@@ -0,0 +1,30 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import get_article, get_news_sources, get_articles_from_source, get_trending_topics
|
||||
|
||||
# Create Wikipedia agent
|
||||
news_agent = Agent(
|
||||
name="NewsAgent",
|
||||
role="News Analyst",
|
||||
goal="Collect and analyze news articles from various sources.",
|
||||
backstory="Expert in news gathering and content analysis.",
|
||||
tools=[get_article, get_news_sources, get_articles_from_source, get_trending_topics],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
|
||||
# Define research task
|
||||
news_task = Task(
|
||||
description="Analyze news articles about 'AI developments' from major tech news sources.",
|
||||
expected_output="Summary of key AI developments with source articles.",
|
||||
agent=news_agent,
|
||||
name="ai_news"
|
||||
)
|
||||
|
||||
|
||||
# Run agent
|
||||
agents = PraisonAIAgents(
|
||||
agents=[news_agent],
|
||||
tasks=[news_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
Generated
+1
-1
@@ -186,7 +186,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.24"
|
||||
version = "0.0.28"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "openai" },
|
||||
|
||||
@@ -110,7 +110,7 @@ Loads environment variables from .env file or system and sets them.</p>
|
||||
file.write("FROM python:3.11-slim\n")
|
||||
file.write("WORKDIR /app\n")
|
||||
file.write("COPY . .\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.33 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.37 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: "AutoAgents Module"
|
||||
description: "Documentation for the praisonaiagents.agents.autoagents module"
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
# Module praisonaiagents.agents.autoagents
|
||||
|
||||
The AutoAgents module provides automatic creation and management of AI agents and tasks based on high-level instructions.
|
||||
|
||||
## Classes
|
||||
|
||||
### AutoAgents
|
||||
The main class for automatically creating and managing AI agents and tasks.
|
||||
|
||||
#### Parameters
|
||||
- `instructions: str` - High-level task description for the agents
|
||||
- `tools: Optional[List[Any]] = None` - List of tools available to the agents
|
||||
- `verbose: bool = False` - Enable detailed logging
|
||||
- `process: str = "sequential"` - Process type (sequential or hierarchical)
|
||||
- `manager_llm: Optional[str] = None` - Language model for manager agent
|
||||
- `max_retries: int = 5` - Maximum retry attempts
|
||||
- `completion_checker: Optional[Any] = None` - Custom completion checker
|
||||
- `allow_code_execution: bool = False` - Allow code execution
|
||||
- `memory: bool = True` - Enable agent memory
|
||||
- `markdown: bool = True` - Enable markdown formatting
|
||||
- `self_reflect: bool = False` - Enable agent self-reflection
|
||||
- `max_reflect: int = 3` - Maximum reflection iterations
|
||||
- `min_reflect: int = 1` - Minimum reflection iterations
|
||||
- `llm: Optional[str] = None` - Language model for agents
|
||||
- `function_calling_llm: Optional[str] = None` - Language model for tool calling
|
||||
- `respect_context_window: bool = True` - Respect model context window
|
||||
- `code_execution_mode: str = "safe"` - Code execution mode (safe/unsafe)
|
||||
- `embedder_config: Optional[Dict[str, Any]] = None` - Embedder configuration
|
||||
- `knowledge_sources: Optional[List[Any]] = None` - Knowledge sources
|
||||
- `use_system_prompt: bool = True` - Use system prompts
|
||||
- `cache: bool = True` - Enable caching
|
||||
- `allow_delegation: bool = False` - Allow task delegation
|
||||
- `step_callback: Optional[Any] = None` - Callback for each step
|
||||
- `system_template: Optional[str] = None` - Custom system template
|
||||
- `prompt_template: Optional[str] = None` - Custom prompt template
|
||||
- `response_template: Optional[str] = None` - Custom response template
|
||||
- `max_rpm: Optional[int] = None` - Maximum requests per minute
|
||||
- `max_execution_time: Optional[int] = None` - Maximum execution time
|
||||
- `max_iter: int = 20` - Maximum iterations
|
||||
- `reflect_llm: Optional[str] = None` - Language model for reflection
|
||||
- `max_agents: int = 3` - Maximum number of agents to create
|
||||
|
||||
#### Methods
|
||||
|
||||
##### start()
|
||||
Start the agents synchronously.
|
||||
|
||||
```python
|
||||
def start(self):
|
||||
"""
|
||||
Creates tasks based on the instructions, then starts execution.
|
||||
Returns the task status and results dictionary.
|
||||
"""
|
||||
return super().start()
|
||||
```
|
||||
|
||||
##### astart()
|
||||
Start the agents asynchronously.
|
||||
|
||||
```python
|
||||
async def astart(self):
|
||||
"""
|
||||
Async version of start() method.
|
||||
Creates tasks based on the instructions, then starts execution.
|
||||
Returns the task status and results dictionary.
|
||||
"""
|
||||
return await super().astart()
|
||||
```
|
||||
|
||||
#### Internal Methods
|
||||
|
||||
##### _generate_config()
|
||||
Generate the configuration for agents and tasks.
|
||||
|
||||
```python
|
||||
def _generate_config(self) -> AutoAgentsConfig:
|
||||
"""
|
||||
Generate the configuration for agents and tasks based on instructions.
|
||||
Returns AutoAgentsConfig object containing agent and task configurations.
|
||||
"""
|
||||
```
|
||||
|
||||
##### _create_agents_and_tasks()
|
||||
Create agents and tasks from configuration.
|
||||
|
||||
```python
|
||||
def _create_agents_and_tasks(self, config: AutoAgentsConfig) -> tuple[List[Agent], List[Task]]:
|
||||
"""
|
||||
Create agents and tasks based on the generated configuration.
|
||||
Returns tuple of (agents, tasks).
|
||||
"""
|
||||
```
|
||||
|
||||
##### _assign_tools_to_agent()
|
||||
Assign appropriate tools to an agent.
|
||||
|
||||
```python
|
||||
def _assign_tools_to_agent(self, agent_config: AgentConfig) -> List[Any]:
|
||||
"""
|
||||
Assign tools to an agent based on its role and tasks.
|
||||
Returns list of assigned tools.
|
||||
"""
|
||||
```
|
||||
|
||||
## Pydantic Models
|
||||
|
||||
### TaskConfig
|
||||
Configuration for a task.
|
||||
|
||||
#### Attributes
|
||||
- `name: str` - Task name
|
||||
- `description: str` - Task description
|
||||
- `expected_output: str` - Expected output description
|
||||
- `tools: List[str]` - Required tools for the task
|
||||
|
||||
### AgentConfig
|
||||
Configuration for an agent.
|
||||
|
||||
#### Attributes
|
||||
- `name: str` - Agent name
|
||||
- `role: str` - Agent role
|
||||
- `goal: str` - Agent goal
|
||||
- `backstory: str` - Agent backstory
|
||||
- `tools: List[str]` - Required tools
|
||||
- `tasks: List[TaskConfig]` - Tasks assigned to the agent
|
||||
|
||||
### AutoAgentsConfig
|
||||
Overall configuration for AutoAgents.
|
||||
|
||||
#### Attributes
|
||||
- `main_instruction: str` - Main instruction for the agents
|
||||
- `process_type: str` - Process type (sequential/hierarchical)
|
||||
- `agents: List[AgentConfig]` - List of agent configurations
|
||||
|
||||
## Example Usage
|
||||
|
||||
### Basic Usage
|
||||
```python
|
||||
from praisonaiagents import AutoAgents
|
||||
from praisonaiagents.tools import SerperDevTool
|
||||
|
||||
agents = AutoAgents(
|
||||
instructions="Research recent AI developments",
|
||||
tools=[SerperDevTool()],
|
||||
verbose=True
|
||||
)
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
### Async Usage
|
||||
```python
|
||||
async def main():
|
||||
agents = AutoAgents(
|
||||
instructions="Research recent AI developments",
|
||||
tools=[SerperDevTool()],
|
||||
process="hierarchical"
|
||||
)
|
||||
result = await agents.astart()
|
||||
|
||||
import asyncio
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### Advanced Configuration
|
||||
```python
|
||||
agents = AutoAgents(
|
||||
instructions="Complex research task",
|
||||
tools=[SerperDevTool()],
|
||||
max_agents=5,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o",
|
||||
memory=True,
|
||||
allow_delegation=True,
|
||||
max_execution_time=600,
|
||||
self_reflect=True
|
||||
)
|
||||
```
|
||||
|
||||
<Note>
|
||||
For optimal results, provide clear instructions and appropriate tools for your use case.
|
||||
</Note>
|
||||
@@ -0,0 +1,281 @@
|
||||
---
|
||||
title: "AutoAgents"
|
||||
description: "AutoAgents automatically creates and manages AI agents and tasks based on high-level instructions."
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Project">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import AutoAgents
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create AutoAgents instance
|
||||
agents = AutoAgents(
|
||||
instructions="Search for information about AI Agents",
|
||||
tools=[duckduckgo],
|
||||
process="sequential",
|
||||
verbose=True,
|
||||
max_agents=3 # Maximum number of agents to create
|
||||
)
|
||||
|
||||
# Start the agents
|
||||
result = agents.start()
|
||||
print(result)
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Program">
|
||||
Run your AutoAgents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding AutoAgents
|
||||
|
||||
<Card title="What are AutoAgents?" icon="question">
|
||||
AutoAgents automatically:
|
||||
- Creates appropriate AI agents based on your instructions
|
||||
- Assigns relevant tools to each agent
|
||||
- Breaks down tasks into manageable steps
|
||||
- Manages execution flow between agents
|
||||
- Handles agent coordination and task delegation
|
||||
</Card>
|
||||
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
# Basic usage with default settings
|
||||
agents = AutoAgents(
|
||||
instructions="Your high-level task description",
|
||||
tools=[tool1, tool2]
|
||||
)
|
||||
```
|
||||
|
||||
```python Advanced
|
||||
# Advanced usage with custom settings
|
||||
agents = AutoAgents(
|
||||
instructions="Your task description",
|
||||
tools=[tool1, tool2],
|
||||
max_agents=3,
|
||||
process="hierarchical",
|
||||
verbose=True,
|
||||
memory=True,
|
||||
allow_delegation=True
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Automatic Agent Creation" icon="wand-magic-sparkles">
|
||||
Creates specialized agents based on task requirements.
|
||||
</Card>
|
||||
<Card title="Smart Tool Assignment" icon="toolbox">
|
||||
Automatically assigns relevant tools to each agent.
|
||||
</Card>
|
||||
<Card title="Task Management" icon="list-check">
|
||||
Breaks down complex tasks into manageable steps.
|
||||
</Card>
|
||||
<Card title="Process Optimization" icon="gauge-high">
|
||||
Chooses optimal execution process (sequential/hierarchical).
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
|
||||
# Create AutoAgents with advanced configuration
|
||||
agents = AutoAgents(
|
||||
instructions="Research and summarize recent AI developments",
|
||||
tools=[SerperDevTool, WikipediaTools],
|
||||
max_agents=3, # Maximum number of agents to create
|
||||
verbose=True, # Enable detailed logging
|
||||
process="hierarchical", # Use hierarchical process
|
||||
memory=True, # Enable memory for agents
|
||||
allow_delegation=True, # Allow task delegation
|
||||
max_rpm=60, # Maximum requests per minute
|
||||
max_execution_time=300, # Maximum execution time in seconds
|
||||
allow_code_execution=True, # Allow code execution
|
||||
code_execution_mode="safe", # Use safe mode for code execution
|
||||
self_reflect=True, # Enable agent self-reflection
|
||||
markdown=True # Enable markdown formatting
|
||||
)
|
||||
```
|
||||
|
||||
### Process Types
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Sequential Process">
|
||||
```python
|
||||
# Tasks are executed in sequence
|
||||
agents = AutoAgents(
|
||||
instructions="Your task",
|
||||
process="sequential"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Hierarchical Process">
|
||||
```python
|
||||
# Manager agent coordinates other agents
|
||||
agents = AutoAgents(
|
||||
instructions="Your task",
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o" # Specify LLM for manager
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Clear Instructions">
|
||||
```python
|
||||
# Good instruction example
|
||||
agents = AutoAgents(
|
||||
instructions="""
|
||||
Research the latest developments in AI for 2024:
|
||||
1. Focus on breakthrough technologies
|
||||
2. Include real-world applications
|
||||
3. Consider future implications
|
||||
"""
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Tool Selection">
|
||||
```python
|
||||
# Provide relevant tools for the task
|
||||
|
||||
agents = AutoAgents(
|
||||
instructions="Research task",
|
||||
tools=[
|
||||
SerperDevTool, # For web search
|
||||
WikipediaTools, # For background info
|
||||
CustomTool # Your custom tool
|
||||
]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Resource Management">
|
||||
|
||||
```python
|
||||
# Configure resource limits
|
||||
agents = AutoAgents(
|
||||
instructions="Your task",
|
||||
max_rpm=60, # Rate limiting
|
||||
max_execution_time=300, # Timeout
|
||||
max_agents=3 # Agent limit
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Tool Assignment Issues" icon="triangle-exclamation">
|
||||
If tools aren't being assigned correctly:
|
||||
- Check tool compatibility
|
||||
- Verify tool names
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Performance Issues" icon="gauge">
|
||||
If execution is slow:
|
||||
- Reduce max_agents
|
||||
- Adjust max_rpm
|
||||
- Consider process type
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## API Reference
|
||||
|
||||
### Main Parameters
|
||||
|
||||
<ResponseField name="instructions" type="str" required>
|
||||
High-level task description for the agents
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="tools" type="List[Any]">
|
||||
List of tools available to the agents
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="max_agents" type="int" default="3">
|
||||
Maximum number of agents to create
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="process" type="str" default="sequential">
|
||||
Process type: "sequential" or "hierarchical"
|
||||
</ResponseField>
|
||||
|
||||
### Optional Parameters
|
||||
|
||||
<ResponseField name="verbose" type="bool" default="False">
|
||||
Enable detailed logging
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="memory" type="bool" default="True">
|
||||
Enable agent memory
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="allow_delegation" type="bool" default="False">
|
||||
Allow agents to delegate tasks
|
||||
</ResponseField>
|
||||
|
||||
### Methods
|
||||
|
||||
<ResponseField name="start()" type="method">
|
||||
Start the agents synchronously
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="astart()" type="method">
|
||||
Start the agents asynchronously
|
||||
</ResponseField>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Examples" icon="code" href="./examples">
|
||||
Explore more examples in our examples directory
|
||||
</Card>
|
||||
<Card title="Custom Tools" icon="screwdriver-wrench" href="./tools">
|
||||
Learn how to create custom tools for your agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, provide clear instructions and appropriate tools for your use case.
|
||||
</Note>
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "Code Execution Agent"
|
||||
title: "Code Execution AI Agent"
|
||||
sidebarTitle: "Code Agent"
|
||||
description: "Learn how to create AI agents that can write and execute Python code safely using e2b code interpreter."
|
||||
icon: "code"
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
---
|
||||
title: "Math AI Agent"
|
||||
sidebarTitle: "Math Agent"
|
||||
description: "Learn how to create AI agents that can perform complex mathematical calculations, unit conversions, and financial computations."
|
||||
icon: "calculator"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Prerequisites**
|
||||
- Python 3.10 or higher
|
||||
- PraisonAI Agents package installed
|
||||
- Basic understanding of Python
|
||||
- sympy and pint packages (automatically installed when needed)
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
|
||||
Create AI agents that can perform complex mathematical calculations, unit conversions, and financial computations!
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the required package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Import Required Components">
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import (
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Math Agent">
|
||||
Set up your mathematical computation agent:
|
||||
```python
|
||||
math_agent = Agent(
|
||||
name="MathAssistant",
|
||||
description="Expert in mathematical calculations and analysis",
|
||||
tools=[
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
]
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Math Agents
|
||||
|
||||
<Card title="What are Math Agents?" icon="question">
|
||||
Math agents are specialized AI agents that can:
|
||||
- Evaluate mathematical expressions
|
||||
- Solve equations and systems of equations
|
||||
- Perform unit conversions
|
||||
- Calculate statistical metrics
|
||||
- Handle financial calculations
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Expression Evaluator" icon="function">
|
||||
Evaluates mathematical expressions
|
||||
```python
|
||||
evaluate("2 + 2 * 3")
|
||||
evaluate("sin(pi/2) + sqrt(16)")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Equation Solver" icon="equals">
|
||||
Solves mathematical equations
|
||||
```python
|
||||
solve_equation("2*x + 3 = 7")
|
||||
solve_equation("x^2 - 5*x + 6 = 0")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Unit Converter" icon="arrows-rotate">
|
||||
Converts between different units
|
||||
```python
|
||||
convert_units(100, "meters", "kilometers")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Statistical Calculator" icon="chart-simple">
|
||||
Calculates statistical metrics
|
||||
```python
|
||||
calculate_statistics([1, 2, 3, 4, 5])
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Calculations Example
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import evaluate, solve_equation
|
||||
|
||||
# Create agent
|
||||
math_agent = Agent(
|
||||
name="MathAssistant",
|
||||
description="Expert in mathematical calculations",
|
||||
tools=[evaluate, solve_equation]
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
calculation_task = Task(
|
||||
description="Calculate the value of: (3 + 4) * 2 - sqrt(16)",
|
||||
expected_output="The result of the mathematical expression",
|
||||
agent=math_agent
|
||||
)
|
||||
|
||||
equation_task = Task(
|
||||
description="Solve the equation: x^2 - 5x + 6 = 0",
|
||||
expected_output="The solutions to the quadratic equation",
|
||||
agent=math_agent
|
||||
)
|
||||
|
||||
# Initialize and run agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[math_agent],
|
||||
tasks=[calculation_task, equation_task]
|
||||
)
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
### Advanced Mathematical Operations
|
||||
|
||||
<CodeGroup>
|
||||
```python Statistical Analysis
|
||||
# Create a statistical analysis task
|
||||
stats_task = Task(
|
||||
description="""
|
||||
Calculate statistical metrics for the dataset:
|
||||
[12, 15, 18, 22, 25, 28, 32, 35, 38, 42]
|
||||
""",
|
||||
agent=math_agent
|
||||
)
|
||||
```
|
||||
|
||||
```python Financial Calculations
|
||||
# Create a financial calculation task
|
||||
finance_task = Task(
|
||||
description="""
|
||||
Calculate compound interest for:
|
||||
- Principal: $10,000
|
||||
- Rate: 5% annually
|
||||
- Time: 3 years
|
||||
- Compounding: Monthly
|
||||
""",
|
||||
agent=math_agent
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Expression Handling">
|
||||
Handle expressions safely:
|
||||
```python
|
||||
# Good - Using variables dictionary
|
||||
evaluate(
|
||||
"x^2 + y",
|
||||
variables={"x": 3, "y": 4}
|
||||
)
|
||||
|
||||
# Good - Setting precision
|
||||
evaluate(
|
||||
"pi + e",
|
||||
precision=5
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task Description">
|
||||
Write clear mathematical requirements:
|
||||
```python
|
||||
# Good
|
||||
Task(description="""
|
||||
Calculate the following:
|
||||
1. Area of a circle with radius 5
|
||||
2. Convert the result to square inches
|
||||
3. Round to 2 decimal places
|
||||
""")
|
||||
|
||||
# Too vague
|
||||
Task(description="Do some math")
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Multi-Step Calculations
|
||||
```python
|
||||
# Calculate area
|
||||
area_task = Task(
|
||||
description="Calculate the area of a circle with radius 5",
|
||||
agent=math_agent
|
||||
)
|
||||
|
||||
# Convert units
|
||||
conversion_task = Task(
|
||||
description="Convert the area from square meters to square feet",
|
||||
agent=math_agent
|
||||
)
|
||||
|
||||
# Format result
|
||||
formatting_task = Task(
|
||||
description="Round the result to 2 decimal places",
|
||||
agent=math_agent
|
||||
)
|
||||
```
|
||||
|
||||
### Statistical Analysis Pipeline
|
||||
```python
|
||||
# Gather data
|
||||
data_task = Task(
|
||||
description="Generate a dataset of 100 random numbers",
|
||||
agent=math_agent
|
||||
)
|
||||
|
||||
# Calculate statistics
|
||||
stats_task = Task(
|
||||
description="Calculate mean, median, mode, and standard deviation",
|
||||
agent=math_agent
|
||||
)
|
||||
|
||||
# Visualize results
|
||||
viz_task = Task(
|
||||
description="Create a summary of the statistical analysis",
|
||||
agent=math_agent
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Expression Errors" icon="triangle-exclamation">
|
||||
Check expression syntax and variable definitions:
|
||||
```python
|
||||
try:
|
||||
result = evaluate("x + y", variables={"x": 1})
|
||||
except Exception as e:
|
||||
print(f"Error: Missing variable 'y'")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Unit Conversion" icon="ruler">
|
||||
Ensure compatible unit types and valid unit names
|
||||
```python
|
||||
# Valid conversion
|
||||
convert_units(100, "celsius", "fahrenheit")
|
||||
|
||||
# Invalid conversion
|
||||
# convert_units(100, "meters", "celsius")
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Advanced Mathematics" icon="graduation-cap" href="./advanced-math">
|
||||
Learn about complex mathematical operations
|
||||
</Card>
|
||||
<Card title="Custom Math Tools" icon="wrench" href="./custom-tools">
|
||||
Create custom mathematical computation tools
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
Math agents provide a powerful way to perform complex mathematical operations, statistical analysis, and financial calculations. They're perfect for data analysis, scientific computing, and financial modeling tasks.
|
||||
</Note>
|
||||
@@ -46,6 +46,16 @@ Create multiple AI agents that can work together in just a few lines of code!
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
src="https://www.youtube.com/embed/OkvYp5aAGSg"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Understanding Mini AI Agents
|
||||
|
||||
<Card title="What are Mini AI Agents?" icon="question">
|
||||
|
||||
+35
-27
@@ -76,6 +76,21 @@
|
||||
"concepts/tools"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Features",
|
||||
"pages": [
|
||||
"features/autoagents",
|
||||
"features/selfreflection",
|
||||
"features/reasoning",
|
||||
"framework/multimodalagents",
|
||||
"features/async",
|
||||
"features/mini",
|
||||
"features/codeagent",
|
||||
"features/mathagent",
|
||||
"features/structured",
|
||||
"features/callbacks"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Getting Started (No Code)",
|
||||
"pages": [
|
||||
@@ -87,32 +102,6 @@
|
||||
"auto"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Features",
|
||||
"pages": [
|
||||
"features/selfreflection",
|
||||
"features/reasoning",
|
||||
"framework/multimodalagents",
|
||||
"features/async",
|
||||
"features/mini",
|
||||
"features/codeagent",
|
||||
"features/structured",
|
||||
"features/callbacks",
|
||||
"train",
|
||||
"framework/praisonaiagents",
|
||||
"framework/crewai",
|
||||
"framework/autogen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "User Interface",
|
||||
"pages": [
|
||||
"ui/ui",
|
||||
"ui/chat",
|
||||
"ui/code",
|
||||
"ui/realtime"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Models",
|
||||
"pages": [
|
||||
@@ -129,7 +118,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Tools (No Code)",
|
||||
"group": "Tools",
|
||||
"pages": [
|
||||
"tools/duckduckgo_tools",
|
||||
"tools/arxiv_tools",
|
||||
@@ -165,6 +154,24 @@
|
||||
"tools/googlecalendar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Other Features",
|
||||
"pages": [
|
||||
"train",
|
||||
"framework/crewai",
|
||||
"framework/autogen",
|
||||
"framework/praisonaiagents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "User Interface",
|
||||
"pages": [
|
||||
"ui/ui",
|
||||
"ui/chat",
|
||||
"ui/code",
|
||||
"ui/realtime"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Monitoring",
|
||||
"pages": ["monitoring/agentops"]
|
||||
@@ -187,6 +194,7 @@
|
||||
"api/praisonaiagents/index",
|
||||
"api/praisonaiagents/agent/agent",
|
||||
"api/praisonaiagents/agents/agents",
|
||||
"api/praisonaiagents/agents/autoagents",
|
||||
"api/praisonaiagents/task/task",
|
||||
"api/praisonaiagents/process/process"
|
||||
]
|
||||
|
||||
+219
-39
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "arXiv Tools"
|
||||
description: "Scientific paper search and retrieval tools for AI agents."
|
||||
icon: "book"
|
||||
title: "arXiv Agent"
|
||||
description: "arXiv research paper search and analysis tools for AI agents."
|
||||
icon: "book-open"
|
||||
---
|
||||
|
||||
<Note>
|
||||
@@ -11,9 +11,9 @@ icon: "book"
|
||||
- `arxiv` package installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## arXiv Tools
|
||||
|
||||
Use arXiv Tools to search and retrieve scientific papers with AI agents.
|
||||
Use arXiv Tools to search and analyze research papers with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
@@ -27,7 +27,7 @@ Use arXiv Tools to search and retrieve scientific papers with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import arxiv
|
||||
from praisonaiagents.tools import search_arxiv, get_arxiv_paper, get_papers_by_author, get_papers_by_category
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +39,7 @@ Use arXiv Tools to search and retrieve scientific papers with AI agents.
|
||||
role="Scientific Literature Specialist",
|
||||
goal="Find and analyze relevant scientific papers.",
|
||||
backstory="Expert in academic research and literature review.",
|
||||
tools=[arxiv],
|
||||
tools=[search_arxiv, get_arxiv_paper, get_papers_by_author, get_papers_by_category],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -81,34 +81,214 @@ Use arXiv Tools to search and retrieve scientific papers with AI agents.
|
||||
- PDF download options
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
## Available Functions
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Research Agent" icon="user-robot">
|
||||
Create specialized research agents:
|
||||
```python
|
||||
Agent(tools=[arxiv])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Research Task" icon="list-check">
|
||||
Define research tasks:
|
||||
```python
|
||||
Task(description="research_query")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Process Types" icon="arrows-split-up-and-left">
|
||||
Sequential or parallel processing:
|
||||
```python
|
||||
process="sequential"
|
||||
```
|
||||
</Card>
|
||||
<Card title="Search Options" icon="sliders">
|
||||
Customize search parameters:
|
||||
```python
|
||||
max_results=10, sort_by="relevance"
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
```python
|
||||
from praisonaiagents.tools import search_arxiv
|
||||
from praisonaiagents.tools import get_arxiv_paper
|
||||
from praisonaiagents.tools import get_papers_by_author
|
||||
from praisonaiagents.tools import get_papers_by_category
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### search_arxiv(query: str, max_results: int = 10, sort_by: str = "relevance", sort_order: str = "descending", include_fields: Optional[List[str]] = None)
|
||||
|
||||
Search arXiv for papers:
|
||||
- Flexible query support
|
||||
- Customizable results
|
||||
- Multiple sorting options
|
||||
- Field selection
|
||||
- Error handling
|
||||
|
||||
```python
|
||||
# Basic search
|
||||
papers = search_arxiv("quantum computing")
|
||||
|
||||
# Advanced search
|
||||
papers = search_arxiv(
|
||||
query="quantum computing",
|
||||
max_results=5,
|
||||
sort_by="submittedDate",
|
||||
sort_order="descending",
|
||||
include_fields=["title", "authors", "summary"]
|
||||
)
|
||||
|
||||
# Returns: List[Dict[str, Any]]
|
||||
# Example output:
|
||||
# [
|
||||
# {
|
||||
# "arxiv_id": "2401.00123",
|
||||
# "title": "Quantum Computing: A Survey",
|
||||
# "authors": ["John Doe", "Jane Smith"],
|
||||
# "summary": "This paper reviews...",
|
||||
# "published": "2024-01-01T00:00:00",
|
||||
# "updated": "2024-01-02T00:00:00"
|
||||
# },
|
||||
# ...
|
||||
# ]
|
||||
```
|
||||
|
||||
### get_arxiv_paper(paper_id: str, include_fields: Optional[List[str]] = None)
|
||||
|
||||
Get specific paper details:
|
||||
- Direct ID lookup
|
||||
- Full paper metadata
|
||||
- Customizable fields
|
||||
- PDF/Abstract links
|
||||
|
||||
```python
|
||||
# Get paper by ID
|
||||
paper = get_arxiv_paper("2401.00123")
|
||||
|
||||
# Get specific fields
|
||||
paper = get_arxiv_paper(
|
||||
paper_id="2401.00123",
|
||||
include_fields=["title", "authors", "pdf_url"]
|
||||
)
|
||||
|
||||
# Returns: Dict[str, Any]
|
||||
# Example output:
|
||||
# {
|
||||
# "arxiv_id": "2401.00123",
|
||||
# "title": "Quantum Computing: A Survey",
|
||||
# "authors": ["John Doe", "Jane Smith"],
|
||||
# "pdf_url": "https://arxiv.org/pdf/2401.00123",
|
||||
# "abstract_url": "https://arxiv.org/abs/2401.00123",
|
||||
# "published": "2024-01-01T00:00:00",
|
||||
# "updated": "2024-01-02T00:00:00"
|
||||
# }
|
||||
```
|
||||
|
||||
### get_papers_by_author(author: str, max_results: int = 10, sort_by: str = "submittedDate", sort_order: str = "descending", include_fields: Optional[List[str]] = None)
|
||||
|
||||
Search papers by author:
|
||||
- Author-specific search
|
||||
- Publication timeline
|
||||
- Sort options
|
||||
- Field selection
|
||||
|
||||
```python
|
||||
# Get author's papers
|
||||
papers = get_papers_by_author("Yoshua Bengio")
|
||||
|
||||
# Recent papers first
|
||||
papers = get_papers_by_author(
|
||||
author="Yoshua Bengio",
|
||||
max_results=5,
|
||||
sort_by="submittedDate",
|
||||
sort_order="descending"
|
||||
)
|
||||
|
||||
# Returns: List[Dict[str, Any]]
|
||||
# Example output:
|
||||
# [
|
||||
# {
|
||||
# "arxiv_id": "2401.00124",
|
||||
# "title": "Deep Learning Advances",
|
||||
# "authors": ["Yoshua Bengio", "Other Author"],
|
||||
# "published": "2024-01-01T00:00:00"
|
||||
# },
|
||||
# ...
|
||||
# ]
|
||||
```
|
||||
|
||||
### get_papers_by_category(category: str, max_results: int = 10, sort_by: str = "submittedDate", sort_order: str = "descending", include_fields: Optional[List[str]] = None)
|
||||
|
||||
Search papers by category:
|
||||
- Category-specific search
|
||||
- Latest publications
|
||||
- Sort options
|
||||
- Field selection
|
||||
|
||||
```python
|
||||
# Get papers in category
|
||||
papers = get_papers_by_category("cs.AI")
|
||||
|
||||
# Recent machine learning papers
|
||||
papers = get_papers_by_category(
|
||||
category="cs.LG",
|
||||
max_results=5,
|
||||
sort_by="submittedDate",
|
||||
sort_order="descending"
|
||||
)
|
||||
|
||||
# Returns: List[Dict[str, Any]]
|
||||
# Example output:
|
||||
# [
|
||||
# {
|
||||
# "arxiv_id": "2401.00125",
|
||||
# "title": "New ML Algorithm",
|
||||
# "categories": ["cs.LG", "cs.AI"],
|
||||
# "published": "2024-01-01T00:00:00"
|
||||
# },
|
||||
# ...
|
||||
# ]
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The arXiv tools require the following package:
|
||||
- arxiv: For accessing the arXiv API
|
||||
|
||||
This will be automatically installed when needed.
|
||||
|
||||
## Available Fields
|
||||
|
||||
When using `include_fields`, you can select from:
|
||||
- title: Paper title
|
||||
- authors: List of authors
|
||||
- summary: Abstract text
|
||||
- comment: Author comments
|
||||
- journal_ref: Journal reference
|
||||
- doi: Digital Object Identifier
|
||||
- primary_category: Main arXiv category
|
||||
- categories: All arXiv categories
|
||||
- links: PDF and abstract URLs
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. Literature Review:
|
||||
```python
|
||||
# Search multiple related topics
|
||||
topics = ["machine learning", "neural networks", "deep learning"]
|
||||
all_papers = []
|
||||
for topic in topics:
|
||||
papers = search_arxiv(
|
||||
topic,
|
||||
max_results=5,
|
||||
sort_by="relevance"
|
||||
)
|
||||
all_papers.extend(papers)
|
||||
```
|
||||
|
||||
2. Author Research:
|
||||
```python
|
||||
# Get recent papers by multiple authors
|
||||
authors = ["Yoshua Bengio", "Geoffrey Hinton", "Yann LeCun"]
|
||||
author_papers = {}
|
||||
for author in authors:
|
||||
papers = get_papers_by_author(
|
||||
author,
|
||||
max_results=3,
|
||||
sort_by="submittedDate"
|
||||
)
|
||||
author_papers[author] = papers
|
||||
```
|
||||
|
||||
3. Category Monitoring:
|
||||
```python
|
||||
# Monitor new papers in AI categories
|
||||
categories = ["cs.AI", "cs.LG", "cs.CL"]
|
||||
new_papers = {}
|
||||
for category in categories:
|
||||
papers = get_papers_by_category(
|
||||
category,
|
||||
max_results=5,
|
||||
sort_by="submittedDate"
|
||||
)
|
||||
new_papers[category] = papers
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -116,7 +296,7 @@ Use arXiv Tools to search and retrieve scientific papers with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import arxiv
|
||||
from praisonaiagents.tools import search_arxiv, get_arxiv_paper, get_papers_by_author, get_papers_by_category
|
||||
|
||||
# Create research agent
|
||||
research_agent = Agent(
|
||||
@@ -124,7 +304,7 @@ research_agent = Agent(
|
||||
role="Scientific Literature Specialist",
|
||||
goal="Find relevant scientific papers on specified topics.",
|
||||
backstory="Expert in academic research and literature analysis.",
|
||||
tools=[arxiv],
|
||||
tools=[search_arxiv, get_arxiv_paper, get_papers_by_author, get_papers_by_category],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -153,7 +333,7 @@ research_agent = Agent(
|
||||
name="Researcher",
|
||||
role="Literature Specialist",
|
||||
goal="Gather comprehensive scientific literature.",
|
||||
tools=[arxiv],
|
||||
tools=[search_arxiv, get_arxiv_paper, get_papers_by_author, get_papers_by_category],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -198,7 +378,7 @@ agents.start()
|
||||
name="Researcher",
|
||||
role="Literature Specialist",
|
||||
goal="Find relevant scientific papers",
|
||||
tools=[arxiv]
|
||||
tools=[search_arxiv, get_arxiv_paper, get_papers_by_author, get_papers_by_category]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +402,7 @@ agents.start()
|
||||
searcher = Agent(
|
||||
name="Searcher",
|
||||
role="Literature Specialist",
|
||||
tools=[arxiv]
|
||||
tools=[search_arxiv, get_arxiv_paper, get_papers_by_author, get_papers_by_category]
|
||||
)
|
||||
|
||||
# Review agent
|
||||
|
||||
+126
-160
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Calculator Tools"
|
||||
description: "Mathematical computation tools for AI agents."
|
||||
title: "Calculator Agent"
|
||||
description: "Mathematical calculation tools for AI agents."
|
||||
icon: "calculator"
|
||||
---
|
||||
|
||||
@@ -8,18 +8,18 @@ icon: "calculator"
|
||||
**Prerequisites**
|
||||
- Python 3.10 or higher
|
||||
- PraisonAI Agents package installed
|
||||
- Basic understanding of mathematical operations
|
||||
- `sympy` and `pint` packages installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Calculator Tools
|
||||
|
||||
Use Calculator Tools to perform mathematical computations with AI agents.
|
||||
Use Calculator Tools to perform mathematical calculations with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
First, install the required package:
|
||||
First, install the required packages:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
pip install praisonaiagents sympy pint
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -27,19 +27,25 @@ Use Calculator Tools to perform mathematical computations with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import calculator
|
||||
from praisonaiagents.tools import (
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agent">
|
||||
Create a calculator agent:
|
||||
```python
|
||||
calc_agent = Agent(
|
||||
name="Calculator",
|
||||
role="Mathematical Specialist",
|
||||
goal="Perform mathematical computations accurately.",
|
||||
backstory="Expert in mathematical calculations and analysis.",
|
||||
tools=[calculator],
|
||||
calculator_agent = Agent(
|
||||
name="MathAssistant",
|
||||
role="Mathematical Computation Specialist",
|
||||
goal="Perform accurate mathematical calculations and solve equations.",
|
||||
backstory="Expert in mathematical computations and problem-solving.",
|
||||
tools=[
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -49,10 +55,10 @@ Use Calculator Tools to perform mathematical computations with AI agents.
|
||||
Define the calculation task:
|
||||
```python
|
||||
calc_task = Task(
|
||||
description="Calculate financial metrics for quarterly report.",
|
||||
expected_output="Computed financial metrics with analysis.",
|
||||
agent=calc_agent,
|
||||
name="financial_calculations"
|
||||
description="Calculate the area of a circle with radius 5",
|
||||
expected_output="The area of the circle in square units",
|
||||
agent=calculator_agent,
|
||||
name="circle_area"
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
@@ -61,7 +67,7 @@ Use Calculator Tools to perform mathematical computations with AI agents.
|
||||
Initialize and run the agent:
|
||||
```python
|
||||
agents = PraisonAIAgents(
|
||||
agents=[calc_agent],
|
||||
agents=[calculator_agent],
|
||||
tasks=[calc_task],
|
||||
process="sequential"
|
||||
)
|
||||
@@ -73,178 +79,138 @@ Use Calculator Tools to perform mathematical computations with AI agents.
|
||||
## Understanding Calculator Tools
|
||||
|
||||
<Card title="What are Calculator Tools?" icon="question">
|
||||
Calculator Tools provide mathematical capabilities for AI agents:
|
||||
- Basic arithmetic
|
||||
- Advanced mathematics
|
||||
- Statistical calculations
|
||||
- Financial computations
|
||||
Calculator Tools provide mathematical computation capabilities for AI agents:
|
||||
- Expression evaluation
|
||||
- Equation solving
|
||||
- Unit conversions
|
||||
- Support for mathematical functions
|
||||
- Variable substitution
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Calculator Agent" icon="user-robot">
|
||||
Create specialized calculator agents:
|
||||
<Card title="Expression Evaluation" icon="function">
|
||||
Evaluate mathematical expressions:
|
||||
```python
|
||||
Agent(tools=[calculator])
|
||||
result = evaluate("2 + 2 * 3")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Calculator Task" icon="list-check">
|
||||
Define calculation tasks:
|
||||
<Card title="Equation Solving" icon="equals">
|
||||
Solve mathematical equations:
|
||||
```python
|
||||
Task(description="calculation_query")
|
||||
result = solve_equation("2*x + 3 = 7")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Process Types" icon="arrows-split-up-and-left">
|
||||
Sequential or parallel processing:
|
||||
<Card title="Unit Conversions" icon="exchange">
|
||||
Convert between units:
|
||||
```python
|
||||
process="sequential"
|
||||
result = convert_units(100, "meters", "kilometers")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Calculation Options" icon="sliders">
|
||||
Customize calculation parameters:
|
||||
<Card title="Statistical Calculations" icon="chart-line">
|
||||
Calculate statistical metrics:
|
||||
```python
|
||||
precision=2, format="decimal"
|
||||
result = calculate_statistics([1, 2, 3, 4, 5])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Financial Calculations" icon="chart-pie">
|
||||
Calculate financial metrics:
|
||||
```python
|
||||
result = calculate_financial(1000, 5, 2)
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Calculator Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import calculator
|
||||
|
||||
# Create calculator agent
|
||||
calc_agent = Agent(
|
||||
name="MathExpert",
|
||||
role="Mathematical Specialist",
|
||||
goal="Perform calculations accurately and efficiently.",
|
||||
backstory="Expert in mathematical computations and analysis.",
|
||||
tools=[calculator],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define calculation task
|
||||
calc_task = Task(
|
||||
description="Calculate investment returns and compound interest.",
|
||||
expected_output="Detailed investment calculations with analysis.",
|
||||
agent=calc_agent,
|
||||
name="investment_analysis"
|
||||
)
|
||||
|
||||
# Run agent
|
||||
agents = PraisonAIAgents(
|
||||
agents=[calc_agent],
|
||||
tasks=[calc_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
### Advanced Calculations with Multiple Agents
|
||||
|
||||
```python
|
||||
# Create calculation agent
|
||||
calculator_agent = Agent(
|
||||
name="Calculator",
|
||||
role="Math Calculator",
|
||||
goal="Perform complex calculations systematically.",
|
||||
tools=[calculator],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create analysis agent
|
||||
analysis_agent = Agent(
|
||||
name="Analyzer",
|
||||
role="Data Analyst",
|
||||
goal="Analyze and interpret calculation results.",
|
||||
backstory="Expert in data analysis and interpretation.",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
calculation_task = Task(
|
||||
description="Calculate statistical metrics for dataset.",
|
||||
agent=calculator_agent,
|
||||
name="statistical_analysis"
|
||||
)
|
||||
|
||||
analysis_task = Task(
|
||||
description="Analyze and interpret the statistical results.",
|
||||
agent=analysis_agent,
|
||||
name="result_analysis"
|
||||
)
|
||||
|
||||
# Run agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[calculator_agent, analysis_agent],
|
||||
tasks=[calculation_task, analysis_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## Advanced Usage
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Agent Configuration">
|
||||
Configure agents with clear calculation focus:
|
||||
<Accordion title="Expression Evaluation">
|
||||
Evaluate complex mathematical expressions with variables:
|
||||
```python
|
||||
Agent(
|
||||
name="Calculator",
|
||||
role="Mathematical Specialist",
|
||||
goal="Perform calculations accurately and efficiently",
|
||||
tools=[calculator]
|
||||
# Basic arithmetic
|
||||
result = evaluate("2 + 2 * 3")
|
||||
|
||||
# With mathematical functions
|
||||
result = evaluate("sin(pi/2) + sqrt(16)")
|
||||
|
||||
# With variables
|
||||
result = evaluate(
|
||||
"x^2 + y",
|
||||
variables={"x": 3, "y": 4}
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task Definition">
|
||||
Define specific calculation objectives:
|
||||
|
||||
<Accordion title="Equation Solving">
|
||||
Solve different types of equations:
|
||||
```python
|
||||
Task(
|
||||
description="Calculate financial metrics and growth rates",
|
||||
expected_output="Detailed financial analysis"
|
||||
)
|
||||
# Linear equation
|
||||
result = solve_equation("2*x + 3 = 7")
|
||||
|
||||
# With custom variable
|
||||
result = solve_equation("y^2 = 4", variable="y")
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Unit Conversions">
|
||||
Convert between different units:
|
||||
```python
|
||||
# Length conversion
|
||||
result = convert_units(100, "meters", "kilometers")
|
||||
|
||||
# Temperature conversion
|
||||
result = convert_units(32, "fahrenheit", "celsius")
|
||||
|
||||
# Time conversion
|
||||
result = convert_units(2.5, "hours", "minutes")
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Statistical Calculations">
|
||||
Calculate statistical metrics:
|
||||
```python
|
||||
result = calculate_statistics([1, 2, 3, 4, 5])
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Financial Calculations">
|
||||
Calculate financial metrics:
|
||||
```python
|
||||
result = calculate_financial(1000, 5, 2)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Common Patterns
|
||||
## Error Handling
|
||||
|
||||
### Calculation Pipeline
|
||||
```python
|
||||
# Calculator agent
|
||||
calculator = Agent(
|
||||
name="Calculator",
|
||||
role="Math Calculator",
|
||||
tools=[calculator]
|
||||
)
|
||||
<Card title="Error Management" icon="shield-check">
|
||||
The tools include comprehensive error handling:
|
||||
```python
|
||||
# Returns success result
|
||||
{"result": 8.0}
|
||||
|
||||
# Returns error message
|
||||
{"error": "Invalid expression"}
|
||||
```
|
||||
</Card>
|
||||
|
||||
# Analysis agent
|
||||
analyzer = Agent(
|
||||
name="Analyzer",
|
||||
role="Result Analyzer"
|
||||
)
|
||||
## Best Practices
|
||||
|
||||
# Define tasks
|
||||
calc_task = Task(
|
||||
description="Perform calculations",
|
||||
agent=calculator
|
||||
)
|
||||
|
||||
analysis_task = Task(
|
||||
description="Analyze results",
|
||||
agent=analyzer
|
||||
)
|
||||
|
||||
# Run workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=[calculator, analyzer],
|
||||
tasks=[calc_task, analysis_task]
|
||||
)
|
||||
```
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Precision Control" icon="ruler">
|
||||
Control calculation precision:
|
||||
```python
|
||||
evaluate(
|
||||
"pi",
|
||||
precision=5
|
||||
)
|
||||
```
|
||||
</Card>
|
||||
<Card title="Safe Execution" icon="shield">
|
||||
Uses safe evaluation environment with:
|
||||
- Restricted builtins
|
||||
- Mathematical functions only
|
||||
- Variable validation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
+147
-12
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "CSV Tools"
|
||||
title: "CSV Agent"
|
||||
description: "CSV file processing tools for AI agents."
|
||||
icon: "file-csv"
|
||||
---
|
||||
@@ -8,12 +8,12 @@ icon: "file-csv"
|
||||
**Prerequisites**
|
||||
- Python 3.10 or higher
|
||||
- PraisonAI Agents package installed
|
||||
- Basic understanding of CSV files
|
||||
- `pandas` package installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## CSV Tools
|
||||
|
||||
Use CSV Tools to process and manipulate CSV files with AI agents.
|
||||
Use CSV Tools to read, write, and manipulate CSV files with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
@@ -27,7 +27,7 @@ Use CSV Tools to process and manipulate CSV files with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import csv
|
||||
from praisonaiagents.tools import read_csv, write_csv, merge_csv
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +39,7 @@ Use CSV Tools to process and manipulate CSV files with AI agents.
|
||||
role="CSV Processing Specialist",
|
||||
goal="Process CSV files efficiently and accurately.",
|
||||
backstory="Expert in CSV file manipulation and analysis.",
|
||||
tools=[csv],
|
||||
tools=[read_csv, write_csv, merge_csv],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -87,7 +87,7 @@ Use CSV Tools to process and manipulate CSV files with AI agents.
|
||||
<Card title="CSV Agent" icon="user-robot">
|
||||
Create specialized CSV agents:
|
||||
```python
|
||||
Agent(tools=[csv])
|
||||
Agent(tools=[read_csv, write_csv, merge_csv])
|
||||
```
|
||||
</Card>
|
||||
<Card title="CSV Task" icon="list-check">
|
||||
@@ -110,13 +110,148 @@ Use CSV Tools to process and manipulate CSV files with AI agents.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import read_csv
|
||||
from praisonaiagents.tools import write_csv
|
||||
from praisonaiagents.tools import merge_csv
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### read_csv(filepath: str, encoding: str = 'utf-8', delimiter: str = ',', header: Union[int, List[int], None] = 0, usecols: Optional[List[str]] = None, dtype: Optional[Dict[str, str]] = None, parse_dates: Optional[List[str]] = None, na_values: Optional[List[str]] = None, nrows: Optional[int] = None)
|
||||
|
||||
Reads a CSV file with advanced options:
|
||||
- Supports multiple encodings (utf-8, ascii, etc.)
|
||||
- Configurable column delimiter
|
||||
- Flexible header row handling
|
||||
- Column selection and data type specification
|
||||
- Date parsing
|
||||
- Custom NA/NaN value handling
|
||||
- Row limit option
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
data = read_csv("data.csv")
|
||||
|
||||
# Advanced usage with options
|
||||
data = read_csv(
|
||||
"data.csv",
|
||||
encoding='utf-8',
|
||||
delimiter=',',
|
||||
header=0,
|
||||
usecols=['name', 'age', 'city'],
|
||||
dtype={'age': 'int32'},
|
||||
parse_dates=['birth_date'],
|
||||
na_values=['N/A', 'missing'],
|
||||
nrows=1000
|
||||
)
|
||||
# Returns: List[Dict[str, Any]]
|
||||
# Example: [{"name": "Alice", "age": 25, "city": "New York"}, ...]
|
||||
```
|
||||
|
||||
### write_csv(filepath: str, data: List[Dict[str, Any]], encoding: str = 'utf-8', delimiter: str = ',', index: bool = False, header: bool = True, float_format: Optional[str] = None, date_format: Optional[str] = None, mode: str = 'w')
|
||||
|
||||
Writes data to a CSV file with formatting options:
|
||||
- Supports different encodings
|
||||
- Configurable delimiter
|
||||
- Optional row indices
|
||||
- Optional headers
|
||||
- Custom float and date formatting
|
||||
- Append mode support
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
data = [
|
||||
{"name": "Alice", "age": 25, "city": "New York"},
|
||||
{"name": "Bob", "age": 30, "city": "San Francisco"}
|
||||
]
|
||||
success = write_csv("output.csv", data)
|
||||
|
||||
# Advanced usage with formatting
|
||||
success = write_csv(
|
||||
"output.csv",
|
||||
data,
|
||||
encoding='utf-8',
|
||||
delimiter=',',
|
||||
index=False,
|
||||
header=True,
|
||||
float_format='%.2f',
|
||||
date_format='%Y-%m-%d',
|
||||
mode='w'
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### merge_csv(files: List[str], output_file: str, how: str = 'inner', on: Optional[Union[str, List[str]]] = None, suffixes: Optional[tuple] = None)
|
||||
|
||||
Merges multiple CSV files with flexible join options:
|
||||
- Supports different join types (inner, outer, left, right)
|
||||
- Merge on single or multiple columns
|
||||
- Custom suffixes for overlapping columns
|
||||
- Automatic handling of column name conflicts
|
||||
|
||||
```python
|
||||
# Merge two files on a common column
|
||||
success = merge_csv(
|
||||
files=["employees.csv", "salaries.csv"],
|
||||
output_file="merged.csv",
|
||||
how='inner',
|
||||
on='employee_id'
|
||||
)
|
||||
|
||||
# Advanced merge with multiple columns and custom suffixes
|
||||
success = merge_csv(
|
||||
files=["data1.csv", "data2.csv", "data3.csv"],
|
||||
output_file="merged.csv",
|
||||
how='outer',
|
||||
on=['id', 'department'],
|
||||
suffixes=('_2022', '_2023')
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The CSV tools require the following Python packages:
|
||||
- pandas: For advanced CSV operations and data manipulation
|
||||
|
||||
These will be automatically installed when needed.
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import read_csv, write_csv, merge_csv
|
||||
|
||||
agent = Agent(
|
||||
name="CSVProcessor",
|
||||
description="An agent that processes CSV files",
|
||||
tools=[read_csv, write_csv, merge_csv]
|
||||
)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- File not found errors
|
||||
- Permission errors
|
||||
- Encoding errors
|
||||
- Data format errors
|
||||
- Missing dependency errors
|
||||
|
||||
Errors are logged and returned in a consistent format:
|
||||
- Success cases return the expected data type
|
||||
- Error cases return a dict with an "error" key containing the error message
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic CSV Processing Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import csv
|
||||
from praisonaiagents.tools import read_csv, write_csv, merge_csv
|
||||
|
||||
# Create CSV agent
|
||||
csv_agent = Agent(
|
||||
@@ -124,7 +259,7 @@ csv_agent = Agent(
|
||||
role="CSV Processing Specialist",
|
||||
goal="Process CSV files efficiently and accurately.",
|
||||
backstory="Expert in data processing and analysis.",
|
||||
tools=[csv],
|
||||
tools=[read_csv, write_csv, merge_csv],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -153,7 +288,7 @@ processor_agent = Agent(
|
||||
name="Processor",
|
||||
role="Data Processor",
|
||||
goal="Process CSV data systematically.",
|
||||
tools=[csv],
|
||||
tools=[read_csv, write_csv, merge_csv],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -198,7 +333,7 @@ agents.start()
|
||||
name="CSVProcessor",
|
||||
role="CSV Processing Specialist",
|
||||
goal="Process CSV files accurately and efficiently",
|
||||
tools=[csv]
|
||||
tools=[read_csv, write_csv, merge_csv]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +357,7 @@ agents.start()
|
||||
processor = Agent(
|
||||
name="Processor",
|
||||
role="CSV Processor",
|
||||
tools=[csv]
|
||||
tools=[read_csv, write_csv, merge_csv]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
|
||||
+184
-33
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "DuckDB Tools"
|
||||
title: "DuckDB Agent"
|
||||
description: "DuckDB database tools for AI agents."
|
||||
icon: "database"
|
||||
---
|
||||
@@ -12,7 +12,7 @@ icon: "database"
|
||||
- Basic understanding of SQL and databases
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## DuckDB Tools
|
||||
|
||||
Use DuckDB Tools to manage and query databases with AI agents.
|
||||
|
||||
@@ -28,7 +28,7 @@ Use DuckDB Tools to manage and query databases with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import duckdb
|
||||
from praisonaiagents.tools import execute_query, load_csv, export_csv
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -40,7 +40,7 @@ Use DuckDB Tools to manage and query databases with AI agents.
|
||||
role="Database Management Specialist",
|
||||
goal="Manage and query databases efficiently.",
|
||||
backstory="Expert in database operations and SQL.",
|
||||
tools=[duckdb],
|
||||
tools=[execute_query, load_csv, export_csv],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -71,6 +71,95 @@ Use DuckDB Tools to manage and query databases with AI agents.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import execute_query
|
||||
from praisonaiagents.tools import load_csv
|
||||
from praisonaiagents.tools import export_csv
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### execute_query(query: str, params: Optional[Union[tuple, dict]] = None, return_df: bool = True)
|
||||
|
||||
Executes SQL queries with advanced features:
|
||||
- Supports parameterized queries
|
||||
- Returns results as DataFrame records or raw tuples
|
||||
- Full SQL query support (SELECT, INSERT, UPDATE, DELETE, etc.)
|
||||
- Automatic connection management
|
||||
|
||||
```python
|
||||
# Basic SELECT query
|
||||
results = execute_query("SELECT * FROM employees")
|
||||
|
||||
# Parameterized query
|
||||
results = execute_query(
|
||||
"SELECT * FROM employees WHERE department = ? AND salary > ?",
|
||||
params=('Engineering', 75000)
|
||||
)
|
||||
|
||||
# Named parameters
|
||||
results = execute_query(
|
||||
"SELECT * FROM employees WHERE department = :dept",
|
||||
params={'dept': 'Engineering'}
|
||||
)
|
||||
# Returns: List[Dict[str, Any]]
|
||||
# Example: [{"id": 1, "name": "Alice", "department": "Engineering"}, ...]
|
||||
```
|
||||
|
||||
### load_csv(table_name: str, filepath: str, schema: Optional[Dict[str, str]] = None, if_exists: str = 'replace')
|
||||
|
||||
Loads CSV files into DuckDB tables:
|
||||
- Optional schema definition
|
||||
- Flexible table existence handling
|
||||
- Automatic type inference
|
||||
- Support for large files
|
||||
|
||||
```python
|
||||
# Basic usage - auto schema inference
|
||||
success = load_csv("employees", "employees.csv")
|
||||
|
||||
# With custom schema
|
||||
schema = {
|
||||
"id": "INTEGER PRIMARY KEY",
|
||||
"name": "VARCHAR",
|
||||
"salary": "DECIMAL(10,2)",
|
||||
"hire_date": "DATE"
|
||||
}
|
||||
success = load_csv(
|
||||
"employees",
|
||||
"employees.csv",
|
||||
schema=schema,
|
||||
if_exists='replace'
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### export_csv(query: str, filepath: str, params: Optional[Union[tuple, dict]] = None)
|
||||
|
||||
Exports query results to CSV files:
|
||||
- Supports parameterized queries
|
||||
- Automatic header generation
|
||||
- Configurable output formatting
|
||||
- Large result set handling
|
||||
|
||||
```python
|
||||
# Export simple query results
|
||||
success = export_csv(
|
||||
"SELECT * FROM employees",
|
||||
"exported_employees.csv"
|
||||
)
|
||||
|
||||
# Export filtered data with parameters
|
||||
success = export_csv(
|
||||
"SELECT * FROM employees WHERE department = ? AND year = ?",
|
||||
"eng_2023.csv",
|
||||
params=('Engineering', 2023)
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
## Understanding DuckDB Tools
|
||||
|
||||
<Card title="What are DuckDB Tools?" icon="question">
|
||||
@@ -88,7 +177,7 @@ Use DuckDB Tools to manage and query databases with AI agents.
|
||||
<Card title="DB Agent" icon="user-robot">
|
||||
Create specialized database agents:
|
||||
```python
|
||||
Agent(tools=[duckdb])
|
||||
Agent(tools=[execute_query, load_csv, export_csv])
|
||||
```
|
||||
</Card>
|
||||
<Card title="DB Task" icon="list-check">
|
||||
@@ -117,7 +206,7 @@ Use DuckDB Tools to manage and query databases with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import duckdb
|
||||
from praisonaiagents.tools import execute_query, load_csv, export_csv
|
||||
|
||||
# Create database agent
|
||||
db_agent = Agent(
|
||||
@@ -125,7 +214,7 @@ db_agent = Agent(
|
||||
role="Database Specialist",
|
||||
goal="Query and analyze data efficiently.",
|
||||
backstory="Expert in database management and SQL.",
|
||||
tools=[duckdb],
|
||||
tools=[execute_query, load_csv, export_csv],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -154,39 +243,101 @@ query_agent = Agent(
|
||||
name="QueryProcessor",
|
||||
role="SQL Query Specialist",
|
||||
goal="Execute SQL queries efficiently.",
|
||||
tools=[duckdb],
|
||||
tools=[execute_query],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create analysis agent
|
||||
analysis_agent = Agent(
|
||||
name="DataAnalyst",
|
||||
role="Data Analyst",
|
||||
goal="Analyze query results and generate insights.",
|
||||
backstory="Expert in data analysis and reporting.",
|
||||
# Create data import/export agent
|
||||
data_agent = Agent(
|
||||
name="DataProcessor",
|
||||
role="Data Import/Export Specialist",
|
||||
goal="Handle data import and export operations efficiently.",
|
||||
tools=[load_csv, export_csv],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
|
||||
# Define tasks
|
||||
query_task = Task(
|
||||
description="Execute complex SQL queries.",
|
||||
agent=query_agent,
|
||||
name="query_execution"
|
||||
)
|
||||
## Dependencies
|
||||
|
||||
analysis_task = Task(
|
||||
description="Analyze query results and trends.",
|
||||
agent=analysis_agent,
|
||||
name="result_analysis"
|
||||
)
|
||||
The DuckDB tools require the following Python packages:
|
||||
- duckdb: For database operations
|
||||
- pandas: For data manipulation and CSV handling
|
||||
|
||||
# Run agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[query_agent, analysis_agent],
|
||||
tasks=[query_task, analysis_task],
|
||||
process="sequential"
|
||||
These will be automatically installed when needed.
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import execute_query, load_csv, export_csv
|
||||
|
||||
agent = Agent(
|
||||
name="DBProcessor",
|
||||
description="An agent that works with DuckDB databases",
|
||||
tools=[execute_query, load_csv, export_csv]
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- Database connection errors
|
||||
- Query syntax errors
|
||||
- File I/O errors
|
||||
- Schema validation errors
|
||||
- Missing dependency errors
|
||||
|
||||
Errors are logged and returned in a consistent format:
|
||||
- Success cases return the expected data type
|
||||
- Error cases return a dict with an "error" key containing the error message
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. Data Analysis:
|
||||
```python
|
||||
# Load data
|
||||
load_csv("sales", "sales_data.csv")
|
||||
|
||||
# Analyze with SQL
|
||||
results = execute_query("""
|
||||
SELECT
|
||||
department,
|
||||
COUNT(*) as count,
|
||||
AVG(salary) as avg_salary
|
||||
FROM employees
|
||||
GROUP BY department
|
||||
HAVING count > 5
|
||||
ORDER BY avg_salary DESC
|
||||
""")
|
||||
```
|
||||
|
||||
2. Data Export:
|
||||
```python
|
||||
# Export filtered and aggregated data
|
||||
export_csv("""
|
||||
SELECT
|
||||
date_trunc('month', date) as month,
|
||||
SUM(amount) as total_sales
|
||||
FROM sales
|
||||
GROUP BY 1
|
||||
ORDER BY 1
|
||||
""", "monthly_sales.csv")
|
||||
```
|
||||
|
||||
3. Data Transformation:
|
||||
```python
|
||||
# Load and transform data
|
||||
load_csv("raw_data", "input.csv")
|
||||
execute_query("""
|
||||
CREATE TABLE transformed AS
|
||||
SELECT
|
||||
id,
|
||||
UPPER(name) as name,
|
||||
ROUND(amount, 2) as amount,
|
||||
DATE_TRUNC('day', timestamp) as date
|
||||
FROM raw_data
|
||||
""")
|
||||
export_csv("SELECT * FROM transformed", "transformed.csv")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
@@ -199,7 +350,7 @@ agents.start()
|
||||
name="DBProcessor",
|
||||
role="Database Specialist",
|
||||
goal="Process queries accurately and efficiently",
|
||||
tools=[duckdb]
|
||||
tools=[execute_query, load_csv, export_csv]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -223,7 +374,7 @@ agents.start()
|
||||
querier = Agent(
|
||||
name="Querier",
|
||||
role="SQL Specialist",
|
||||
tools=[duckdb]
|
||||
tools=[execute_query]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "DuckDuckGo Tools"
|
||||
title: "DuckDuckGo Agent"
|
||||
description: "Internet search tools using DuckDuckGo for AI agents."
|
||||
icon: "magnifying-glass"
|
||||
---
|
||||
@@ -11,7 +11,7 @@ icon: "magnifying-glass"
|
||||
- `duckduckgo-search` package installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## DuckDuckGo Tools
|
||||
|
||||
Use DuckDuckGo Tools to perform internet searches with AI agents.
|
||||
|
||||
|
||||
+204
-12
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "Excel Tools"
|
||||
title: "Excel Agent"
|
||||
description: "Excel file processing tools for AI agents."
|
||||
icon: "file-excel"
|
||||
---
|
||||
@@ -12,7 +12,7 @@ icon: "file-excel"
|
||||
- Basic understanding of Excel files
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Excel Tools
|
||||
|
||||
Use Excel Tools to process and manipulate Excel files with AI agents.
|
||||
|
||||
@@ -28,7 +28,7 @@ Use Excel Tools to process and manipulate Excel files with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import excel
|
||||
from praisonaiagents.tools import read_excel, write_excel, merge_excel
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -40,7 +40,7 @@ Use Excel Tools to process and manipulate Excel files with AI agents.
|
||||
role="Excel Processing Specialist",
|
||||
goal="Process Excel files efficiently and accurately.",
|
||||
backstory="Expert in Excel file manipulation and analysis.",
|
||||
tools=[excel],
|
||||
tools=[read_excel, write_excel, merge_excel],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -88,7 +88,7 @@ Use Excel Tools to process and manipulate Excel files with AI agents.
|
||||
<Card title="Excel Agent" icon="user-robot">
|
||||
Create specialized Excel agents:
|
||||
```python
|
||||
Agent(tools=[excel])
|
||||
Agent(tools=[read_excel, write_excel, merge_excel])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Excel Task" icon="list-check">
|
||||
@@ -111,13 +111,120 @@ Use Excel Tools to process and manipulate Excel files with AI agents.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import read_excel
|
||||
from praisonaiagents.tools import write_excel
|
||||
from praisonaiagents.tools import merge_excel
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### read_excel(filepath: str, sheet_name: Optional[Union[str, int, List[Union[str, int]]]] = 0, header: Optional[int] = 0, usecols: Optional[List[str]] = None, skiprows: Optional[Union[int, List[int]]] = None, na_values: Optional[List[str]] = None, dtype: Optional[Dict[str, str]] = None)
|
||||
|
||||
Reads Excel files with advanced options:
|
||||
- Support for multiple sheets
|
||||
- Flexible header handling
|
||||
- Column selection
|
||||
- Row skipping
|
||||
- Custom NA values
|
||||
- Data type specification
|
||||
|
||||
```python
|
||||
# Basic usage - read first sheet
|
||||
data = read_excel("data.xlsx")
|
||||
|
||||
# Read specific sheets
|
||||
data = read_excel(
|
||||
"data.xlsx",
|
||||
sheet_name=['Sheet1', 'Sheet2'],
|
||||
header=0,
|
||||
usecols=['A', 'B', 'C'],
|
||||
skiprows=[0, 1],
|
||||
na_values=['NA', 'missing'],
|
||||
dtype={'age': 'int32', 'salary': 'float64'}
|
||||
)
|
||||
# Returns: Dict[str, List[Dict[str, Any]]] for multiple sheets
|
||||
# Example: {
|
||||
# 'Sheet1': [{"name": "Alice", "age": 25}, ...],
|
||||
# 'Sheet2': [{"dept": "Engineering", "count": 10}, ...]
|
||||
# }
|
||||
```
|
||||
|
||||
### write_excel(filepath: str, data: Union[Dict[str, List[Dict[str, Any]]], List[Dict[str, Any]]], sheet_name: Optional[str] = None, index: bool = False, header: bool = True, mode: str = 'w')
|
||||
|
||||
Writes data to Excel files with formatting:
|
||||
- Multiple sheet support
|
||||
- Append mode for existing files
|
||||
- Optional row indices
|
||||
- Optional headers
|
||||
- Flexible data structure handling
|
||||
|
||||
```python
|
||||
# Write single sheet
|
||||
data = [
|
||||
{"name": "Alice", "age": 25, "city": "New York"},
|
||||
{"name": "Bob", "age": 30, "city": "San Francisco"}
|
||||
]
|
||||
success = write_excel("output.xlsx", data, sheet_name="Employees")
|
||||
|
||||
# Write multiple sheets
|
||||
data = {
|
||||
"Employees": [
|
||||
{"name": "Alice", "age": 25},
|
||||
{"name": "Bob", "age": 30}
|
||||
],
|
||||
"Departments": [
|
||||
{"name": "Engineering", "count": 50},
|
||||
{"name": "Sales", "count": 30}
|
||||
]
|
||||
}
|
||||
success = write_excel(
|
||||
"company.xlsx",
|
||||
data,
|
||||
index=False,
|
||||
header=True,
|
||||
mode='w'
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### merge_excel(files: List[str], output_file: str, how: str = 'inner', on: Optional[Union[str, List[str]]] = None, suffixes: Optional[Tuple[str, str]] = None)
|
||||
|
||||
Merges multiple Excel files:
|
||||
- Flexible join operations
|
||||
- Multiple key columns support
|
||||
- Custom column suffix handling
|
||||
- Preserves data types
|
||||
|
||||
```python
|
||||
# Merge two files on a common column
|
||||
success = merge_excel(
|
||||
files=["employees.xlsx", "salaries.xlsx"],
|
||||
output_file="merged.xlsx",
|
||||
how='inner',
|
||||
on='employee_id'
|
||||
)
|
||||
|
||||
# Advanced merge with multiple keys and custom suffixes
|
||||
success = merge_excel(
|
||||
files=["data2022.xlsx", "data2023.xlsx"],
|
||||
output_file="combined.xlsx",
|
||||
how='outer',
|
||||
on=['id', 'department'],
|
||||
suffixes=('_2022', '_2023')
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Excel Processing Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import excel
|
||||
from praisonaiagents.tools import read_excel, write_excel, merge_excel
|
||||
|
||||
# Create Excel agent
|
||||
excel_agent = Agent(
|
||||
@@ -125,7 +232,7 @@ excel_agent = Agent(
|
||||
role="Excel Processing Specialist",
|
||||
goal="Process Excel files efficiently and accurately.",
|
||||
backstory="Expert in spreadsheet manipulation and analysis.",
|
||||
tools=[excel],
|
||||
tools=[read_excel, write_excel, merge_excel],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -154,7 +261,7 @@ processor_agent = Agent(
|
||||
name="Processor",
|
||||
role="Data Processor",
|
||||
goal="Process Excel data systematically.",
|
||||
tools=[excel],
|
||||
tools=[read_excel, write_excel, merge_excel],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -199,7 +306,7 @@ agents.start()
|
||||
name="ExcelProcessor",
|
||||
role="Excel Processing Specialist",
|
||||
goal="Process Excel files accurately and efficiently",
|
||||
tools=[excel]
|
||||
tools=[read_excel, write_excel, merge_excel]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -208,8 +315,7 @@ agents.start()
|
||||
Define specific Excel operations:
|
||||
```python
|
||||
Task(
|
||||
description="Process sales data and generate reports",
|
||||
expected_output="Sales analysis report"
|
||||
description="Process sales data and generate reports"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -223,7 +329,7 @@ agents.start()
|
||||
processor = Agent(
|
||||
name="Processor",
|
||||
role="Excel Processor",
|
||||
tools=[excel]
|
||||
tools=[read_excel, write_excel, merge_excel]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
@@ -248,3 +354,89 @@ agents = PraisonAIAgents(
|
||||
agents=[processor, analyzer],
|
||||
tasks=[process_task, analyze_task]
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The Excel tools require the following Python packages:
|
||||
- pandas: For data manipulation
|
||||
- openpyxl: For Excel file operations
|
||||
|
||||
These will be automatically installed when needed.
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import read_excel, write_excel, merge_excel
|
||||
|
||||
agent = Agent(
|
||||
name="ExcelProcessor",
|
||||
description="An agent that processes Excel files",
|
||||
tools=[read_excel, write_excel, merge_excel]
|
||||
)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- File not found errors
|
||||
- Permission errors
|
||||
- Invalid sheet names
|
||||
- Data format errors
|
||||
- Missing dependency errors
|
||||
|
||||
Errors are logged and returned in a consistent format:
|
||||
- Success cases return the expected data type
|
||||
- Error cases return a dict with an "error" key containing the error message
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. Data Analysis:
|
||||
```python
|
||||
# Read and analyze employee data
|
||||
data = read_excel(
|
||||
"employees.xlsx",
|
||||
sheet_name="Salaries",
|
||||
usecols=["department", "salary"]
|
||||
)
|
||||
|
||||
# Write summary to new sheet
|
||||
summary = [
|
||||
{"department": dept, "avg_salary": sum(d["salary"] for d in dept_data) / len(dept_data)}
|
||||
for dept, dept_data in groupby(data, key=lambda x: x["department"])
|
||||
]
|
||||
write_excel("summary.xlsx", summary, sheet_name="Salary Summary")
|
||||
```
|
||||
|
||||
2. Data Consolidation:
|
||||
```python
|
||||
# Merge monthly reports
|
||||
monthly_files = ["jan.xlsx", "feb.xlsx", "mar.xlsx"]
|
||||
merge_excel(
|
||||
files=monthly_files,
|
||||
output_file="q1_report.xlsx",
|
||||
how='outer',
|
||||
on='transaction_id'
|
||||
)
|
||||
```
|
||||
|
||||
3. Multi-sheet Processing:
|
||||
```python
|
||||
# Read multiple sheets
|
||||
data = read_excel(
|
||||
"company_data.xlsx",
|
||||
sheet_name=None # Read all sheets
|
||||
)
|
||||
|
||||
# Process each sheet
|
||||
processed = {
|
||||
sheet: [process_record(record) for record in records]
|
||||
for sheet, records in data.items()
|
||||
}
|
||||
|
||||
# Write back to new file
|
||||
write_excel("processed_data.xlsx", processed)
|
||||
|
||||
```
|
||||
+263
-40
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "File Tools"
|
||||
description: "File system operations and management tools for AI agents."
|
||||
title: "File Agent"
|
||||
description: "File system operation tools for AI agents."
|
||||
icon: "folder"
|
||||
---
|
||||
|
||||
@@ -11,9 +11,9 @@ icon: "folder"
|
||||
- Basic understanding of file operations
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## File Tools
|
||||
|
||||
Use File Tools to manage files and directories with AI agents.
|
||||
Use File Tools to perform file system operations with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
@@ -27,7 +27,7 @@ Use File Tools to manage files and directories with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import file_tools
|
||||
from praisonaiagents.tools import read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +39,7 @@ Use File Tools to manage files and directories with AI agents.
|
||||
role="File System Specialist",
|
||||
goal="Manage files and directories efficiently.",
|
||||
backstory="Expert in file system operations and organization.",
|
||||
tools=[file_tools],
|
||||
tools=[read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -87,7 +87,7 @@ Use File Tools to manage files and directories with AI agents.
|
||||
<Card title="File Agent" icon="user-robot">
|
||||
Create specialized file agents:
|
||||
```python
|
||||
Agent(tools=[file_tools])
|
||||
Agent(tools=[read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file])
|
||||
```
|
||||
</Card>
|
||||
<Card title="File Task" icon="list-check">
|
||||
@@ -110,28 +110,249 @@ Use File Tools to manage files and directories with AI agents.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import read_file
|
||||
from praisonaiagents.tools import write_file
|
||||
from praisonaiagents.tools import list_files
|
||||
from praisonaiagents.tools import get_file_info
|
||||
from praisonaiagents.tools import copy_file
|
||||
from praisonaiagents.tools import move_file
|
||||
from praisonaiagents.tools import delete_file
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### read_file(filepath: str, encoding: str = 'utf-8')
|
||||
|
||||
Reads content from a file:
|
||||
- Supports different encodings
|
||||
- Error handling for missing files
|
||||
- Automatic encoding detection
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
content = read_file("example.txt")
|
||||
|
||||
# With specific encoding
|
||||
content = read_file("data.txt", encoding="latin-1")
|
||||
|
||||
# Returns: str (file content)
|
||||
# Error case: Returns error message as string
|
||||
```
|
||||
|
||||
### write_file(filepath: str, content: str, encoding: str = 'utf-8')
|
||||
|
||||
Writes content to a file:
|
||||
- Creates directories if they don't exist
|
||||
- Supports different encodings
|
||||
- Overwrites existing files
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
success = write_file("output.txt", "Hello World")
|
||||
|
||||
# With specific encoding and nested path
|
||||
success = write_file(
|
||||
"path/to/data/output.txt",
|
||||
"Content with special chars: áéíóú",
|
||||
encoding="utf-8"
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### list_files(directory: str, pattern: Optional[str] = None)
|
||||
|
||||
Lists files in a directory:
|
||||
- Optional pattern matching
|
||||
- Detailed file information
|
||||
- Recursive directory support
|
||||
|
||||
```python
|
||||
# List all files
|
||||
files = list_files("/path/to/directory")
|
||||
|
||||
# With pattern matching
|
||||
files = list_files("/path/to/directory", pattern="*.txt")
|
||||
|
||||
# Returns: List[Dict[str, Union[str, int]]]
|
||||
# Example: [
|
||||
# {
|
||||
# 'name': 'example.txt',
|
||||
# 'path': '/path/to/directory/example.txt',
|
||||
# 'size': 1024,
|
||||
# 'modified': 1609459200.0,
|
||||
# 'created': 1609459100.0
|
||||
# },
|
||||
# ...
|
||||
# ]
|
||||
```
|
||||
|
||||
### get_file_info(filepath: str)
|
||||
|
||||
Gets detailed information about a file:
|
||||
- File metadata
|
||||
- Size and timestamps
|
||||
- Type information
|
||||
- Path details
|
||||
|
||||
```python
|
||||
# Get file information
|
||||
info = get_file_info("example.txt")
|
||||
|
||||
# Returns: Dict[str, Union[str, int]]
|
||||
# Example: {
|
||||
# 'name': 'example.txt',
|
||||
# 'path': '/absolute/path/to/example.txt',
|
||||
# 'size': 1024,
|
||||
# 'modified': 1609459200.0,
|
||||
# 'created': 1609459100.0,
|
||||
# 'is_file': True,
|
||||
# 'is_dir': False,
|
||||
# 'extension': '.txt',
|
||||
# 'parent': '/absolute/path/to'
|
||||
# }
|
||||
```
|
||||
|
||||
### copy_file(src: str, dst: str)
|
||||
|
||||
Copies a file with metadata:
|
||||
- Preserves timestamps
|
||||
- Creates destination directories
|
||||
- Handles existing files
|
||||
|
||||
```python
|
||||
# Basic copy
|
||||
success = copy_file("source.txt", "destination.txt")
|
||||
|
||||
# Copy to new directory
|
||||
success = copy_file(
|
||||
"data.txt",
|
||||
"backup/2023/data_backup.txt"
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### move_file(src: str, dst: str)
|
||||
|
||||
Moves or renames a file:
|
||||
- Creates destination directories
|
||||
- Handles existing files
|
||||
- Cross-device moves
|
||||
|
||||
```python
|
||||
# Move file
|
||||
success = move_file("old/path/file.txt", "new/path/file.txt")
|
||||
|
||||
# Rename file
|
||||
success = move_file(
|
||||
"document.txt",
|
||||
"document_v2.txt"
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### delete_file(filepath: str)
|
||||
|
||||
Deletes a file:
|
||||
- Safe deletion
|
||||
- Error handling
|
||||
- Non-recursive (files only)
|
||||
|
||||
```python
|
||||
# Delete file
|
||||
success = delete_file("unwanted.txt")
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import (
|
||||
read_file, write_file, list_files,
|
||||
get_file_info, copy_file, move_file, delete_file
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
name="FileManager",
|
||||
description="An agent that manages files",
|
||||
tools=[
|
||||
read_file, write_file, list_files,
|
||||
get_file_info, copy_file, move_file, delete_file
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- File not found errors
|
||||
- Permission errors
|
||||
- Path errors
|
||||
- I/O errors
|
||||
- Encoding errors
|
||||
|
||||
Errors are handled consistently:
|
||||
- File operations return bool for success/failure
|
||||
- Information functions return error details in result
|
||||
- All errors are logged for debugging
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. File Organization:
|
||||
```python
|
||||
# List and organize files by extension
|
||||
files = list_files("downloads", pattern="*.*")
|
||||
for file in files:
|
||||
ext = file['extension']
|
||||
if ext:
|
||||
dst = f"organized/{ext[1:]}/{file['name']}"
|
||||
move_file(file['path'], dst)
|
||||
```
|
||||
|
||||
2. File Backup:
|
||||
```python
|
||||
# Create timestamped backups
|
||||
import time
|
||||
files = list_files("important_data")
|
||||
backup_time = time.strftime("%Y%m%d_%H%M%S")
|
||||
for file in files:
|
||||
dst = f"backup/{backup_time}/{file['name']}"
|
||||
copy_file(file['path'], dst)
|
||||
```
|
||||
|
||||
3. File Processing:
|
||||
```python
|
||||
# Read, process, and write files
|
||||
content = read_file("input.txt")
|
||||
processed = process_content(content) # Your processing function
|
||||
write_file("output.txt", processed)
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic File Management Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import file_tools
|
||||
from praisonaiagents.tools import read_file, write_file, list_files, get_file_info
|
||||
|
||||
# Create file management agent
|
||||
file_agent = Agent(
|
||||
name="FileOrganizer",
|
||||
role="File System Manager",
|
||||
goal="Organize and manage files efficiently.",
|
||||
backstory="Expert in file organization and system management.",
|
||||
tools=[file_tools],
|
||||
name="FileExpert",
|
||||
role="File Manager",
|
||||
goal="Process and organize files efficiently.",
|
||||
backstory="Expert in file system operations and organization.",
|
||||
tools=[read_file, write_file, list_files, get_file_info],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define file task
|
||||
file_task = Task(
|
||||
description="Sort documents by type and create backup copies.",
|
||||
expected_output="Organized file structure with backups.",
|
||||
description="Organize and process documents.",
|
||||
expected_output="Organized file structure.",
|
||||
agent=file_agent,
|
||||
name="file_organization"
|
||||
)
|
||||
@@ -145,44 +366,46 @@ agents = PraisonAIAgents(
|
||||
agents.start()
|
||||
```
|
||||
|
||||
### Advanced File Management with Multiple Agents
|
||||
### Advanced File Operations with Multiple Agents
|
||||
|
||||
```python
|
||||
# Create file organization agent
|
||||
organizer_agent = Agent(
|
||||
name="Organizer",
|
||||
role="File Organizer",
|
||||
goal="Sort and organize files systematically.",
|
||||
tools=[file_tools],
|
||||
# Create file IO agent
|
||||
io_agent = Agent(
|
||||
name="FileIO",
|
||||
role="File IO Specialist",
|
||||
goal="Handle file read/write operations efficiently.",
|
||||
tools=[read_file, write_file],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create backup agent
|
||||
backup_agent = Agent(
|
||||
name="Backup",
|
||||
role="Backup Manager",
|
||||
goal="Create and manage file backups.",
|
||||
backstory="Expert in data backup and recovery.",
|
||||
# Create file management agent
|
||||
management_agent = Agent(
|
||||
name="FileManager",
|
||||
role="File Management Specialist",
|
||||
goal="Handle file organization and movement.",
|
||||
tools=[list_files, get_file_info, copy_file, move_file, delete_file],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
organize_task = Task(
|
||||
description="Organize files by type and date.",
|
||||
agent=organizer_agent,
|
||||
name="organize_files"
|
||||
io_task = Task(
|
||||
description="Read and write files.",
|
||||
expected_output="File operations completed successfully.",
|
||||
agent=io_agent,
|
||||
name="file_io"
|
||||
)
|
||||
|
||||
backup_task = Task(
|
||||
description="Create backups of organized files.",
|
||||
agent=backup_agent,
|
||||
name="backup_files"
|
||||
management_task = Task(
|
||||
description="Organize and move files.",
|
||||
expected_output="File management completed successfully.",
|
||||
agent=management_agent,
|
||||
name="file_management"
|
||||
)
|
||||
|
||||
# Run agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[organizer_agent, backup_agent],
|
||||
tasks=[organize_task, backup_task],
|
||||
agents=[io_agent, management_agent],
|
||||
tasks=[io_task, management_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
@@ -198,7 +421,7 @@ agents.start()
|
||||
name="FileManager",
|
||||
role="File System Specialist",
|
||||
goal="Manage files efficiently and safely",
|
||||
tools=[file_tools]
|
||||
tools=[read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +445,7 @@ agents.start()
|
||||
organizer = Agent(
|
||||
name="Organizer",
|
||||
role="File Organizer",
|
||||
tools=[file_tools]
|
||||
tools=[read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file]
|
||||
)
|
||||
|
||||
# Cleanup agent
|
||||
|
||||
+388
-51
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "JSON Tools"
|
||||
description: "JSON file processing tools for AI agents."
|
||||
icon: "brackets-curly"
|
||||
title: "JSON Agent"
|
||||
description: "JSON data processing tools for AI agents."
|
||||
icon: "braces"
|
||||
---
|
||||
|
||||
<Note>
|
||||
@@ -11,7 +11,7 @@ icon: "brackets-curly"
|
||||
- Basic understanding of JSON format
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## JSON Tools
|
||||
|
||||
Use JSON Tools to process and manipulate JSON files with AI agents.
|
||||
|
||||
@@ -27,7 +27,10 @@ Use JSON Tools to process and manipulate JSON files with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import json
|
||||
from praisonaiagents.tools import (
|
||||
read_json, write_json, merge_json,
|
||||
validate_json, analyze_json, transform_json
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +42,10 @@ Use JSON Tools to process and manipulate JSON files with AI agents.
|
||||
role="JSON Processing Specialist",
|
||||
goal="Process JSON files efficiently and accurately.",
|
||||
backstory="Expert in JSON file manipulation and validation.",
|
||||
tools=[json],
|
||||
tools=[
|
||||
read_json, write_json, merge_json,
|
||||
validate_json, analyze_json, transform_json
|
||||
],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -74,11 +80,11 @@ Use JSON Tools to process and manipulate JSON files with AI agents.
|
||||
|
||||
<Card title="What are JSON Tools?" icon="question">
|
||||
JSON Tools provide JSON processing capabilities for AI agents:
|
||||
- JSON parsing
|
||||
- File validation
|
||||
- Data extraction
|
||||
- Structure manipulation
|
||||
- Format conversion
|
||||
- File reading and writing
|
||||
- Data validation
|
||||
- Schema validation
|
||||
- Data transformation
|
||||
- Structure analysis
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
@@ -87,7 +93,7 @@ Use JSON Tools to process and manipulate JSON files with AI agents.
|
||||
<Card title="JSON Agent" icon="user-robot">
|
||||
Create specialized JSON agents:
|
||||
```python
|
||||
Agent(tools=[json])
|
||||
Agent(tools=[read_json, write_json, merge_json, validate_json, analyze_json, transform_json])
|
||||
```
|
||||
</Card>
|
||||
<Card title="JSON Task" icon="list-check">
|
||||
@@ -103,9 +109,341 @@ Use JSON Tools to process and manipulate JSON files with AI agents.
|
||||
```
|
||||
</Card>
|
||||
<Card title="JSON Options" icon="sliders">
|
||||
Customize JSON parameters:
|
||||
Customize JSON operations:
|
||||
```python
|
||||
indent=2, encoding="utf-8"
|
||||
indent=2, sort_keys=True
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import read_json
|
||||
from praisonaiagents.tools import write_json
|
||||
from praisonaiagents.tools import merge_json
|
||||
from praisonaiagents.tools import validate_json
|
||||
from praisonaiagents.tools import analyze_json
|
||||
from praisonaiagents.tools import transform_json
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### read_json(filepath: str, encoding: str = 'utf-8', validate_schema: Optional[Dict[str, Any]] = None)
|
||||
|
||||
Reads JSON files with schema validation:
|
||||
- Optional schema validation
|
||||
- Custom encoding support
|
||||
- Error handling
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
data = read_json("config.json")
|
||||
|
||||
# With schema validation
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"age": {"type": "integer"}
|
||||
}
|
||||
}
|
||||
data = read_json(
|
||||
"user.json",
|
||||
encoding="utf-8",
|
||||
validate_schema=schema
|
||||
)
|
||||
|
||||
# Returns: Dict[str, Any] (JSON data)
|
||||
# Error case: Returns dict with 'error' key
|
||||
```
|
||||
|
||||
### write_json(data: Union[Dict[str, Any], List[Any]], filepath: str, encoding: str = 'utf-8', indent: int = 2, sort_keys: bool = False, ensure_ascii: bool = False)
|
||||
|
||||
Writes data to JSON files:
|
||||
- Pretty printing with indentation
|
||||
- Optional key sorting
|
||||
- Unicode support
|
||||
- Directory creation
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
data = {"name": "Alice", "age": 30}
|
||||
success = write_json(data, "output.json")
|
||||
|
||||
# With formatting options
|
||||
data = {
|
||||
"users": [
|
||||
{"name": "Alice", "age": 30},
|
||||
{"name": "Bob", "age": 25}
|
||||
]
|
||||
}
|
||||
success = write_json(
|
||||
data,
|
||||
"users.json",
|
||||
indent=4,
|
||||
sort_keys=True,
|
||||
ensure_ascii=False
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### merge_json(files: List[str], output_file: str, merge_arrays: bool = True, overwrite_duplicates: bool = True)
|
||||
|
||||
Merges multiple JSON files:
|
||||
- Deep merging of objects
|
||||
- Array handling options
|
||||
- Duplicate key handling
|
||||
- Nested structure support
|
||||
|
||||
```python
|
||||
# Merge configuration files
|
||||
success = merge_json(
|
||||
files=["config1.json", "config2.json"],
|
||||
output_file="merged_config.json"
|
||||
)
|
||||
|
||||
# Advanced merge with options
|
||||
success = merge_json(
|
||||
files=["base.json", "override.json"],
|
||||
output_file="final.json",
|
||||
merge_arrays=True,
|
||||
overwrite_duplicates=False
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### validate_json(data: Union[Dict[str, Any], str], schema: Dict[str, Any])
|
||||
|
||||
Validates JSON against a schema:
|
||||
- JSON Schema support
|
||||
- Detailed error messages
|
||||
- File or data validation
|
||||
|
||||
```python
|
||||
# Validate data
|
||||
schema = {
|
||||
"type": "object",
|
||||
"required": ["name", "email"],
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"email": {"type": "string", "format": "email"},
|
||||
"age": {"type": "integer", "minimum": 0}
|
||||
}
|
||||
}
|
||||
|
||||
# Validate data directly
|
||||
data = {"name": "Alice", "email": "[email protected]", "age": 25}
|
||||
is_valid, error = validate_json(data, schema)
|
||||
|
||||
# Validate file
|
||||
is_valid, error = validate_json("user.json", schema)
|
||||
# Returns: Tuple[bool, Optional[str]]
|
||||
```
|
||||
|
||||
### analyze_json(data: Union[Dict[str, Any], str], max_depth: int = 10)
|
||||
|
||||
Analyzes JSON structure:
|
||||
- Type information
|
||||
- Size metrics
|
||||
- Nested structure analysis
|
||||
- Sample data
|
||||
|
||||
```python
|
||||
# Analyze file
|
||||
analysis = analyze_json("data.json", max_depth=5)
|
||||
|
||||
# Analyze data structure
|
||||
data = {
|
||||
"users": [
|
||||
{"name": "Alice", "scores": [95, 87, 92]},
|
||||
{"name": "Bob", "scores": [88, 85, 90]}
|
||||
]
|
||||
}
|
||||
analysis = analyze_json(data)
|
||||
|
||||
# Returns: Dict[str, Any]
|
||||
# Example output:
|
||||
# {
|
||||
# 'analysis_time': '2023-01-01T12:00:00',
|
||||
# 'structure': {
|
||||
# 'type': 'dict',
|
||||
# 'size': 1,
|
||||
# 'keys': ['users'],
|
||||
# 'children': {
|
||||
# 'users': {
|
||||
# 'type': 'list',
|
||||
# 'length': 2,
|
||||
# 'element_types': ['dict'],
|
||||
# 'sample_elements': [...]
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
```
|
||||
|
||||
### transform_json(data: Union[Dict[str, Any], str], transformations: List[Dict[str, Any]])
|
||||
|
||||
Transforms JSON data:
|
||||
- Multiple operations
|
||||
- Path-based modifications
|
||||
- Nested transformations
|
||||
- Operation types: set, delete, rename, move
|
||||
|
||||
```python
|
||||
# Transform data
|
||||
transformations = [
|
||||
{
|
||||
"operation": "set",
|
||||
"path": "user.settings.theme",
|
||||
"value": "dark"
|
||||
},
|
||||
{
|
||||
"operation": "move",
|
||||
"path": "old.config",
|
||||
"value": "new.config"
|
||||
},
|
||||
{
|
||||
"operation": "delete",
|
||||
"path": "temporary.data"
|
||||
}
|
||||
]
|
||||
|
||||
# Transform file
|
||||
result = transform_json("config.json", transformations)
|
||||
|
||||
# Transform data directly
|
||||
data = {"user": {"name": "Alice"}}
|
||||
result = transform_json(data, transformations)
|
||||
# Returns: Dict[str, Any] (transformed data)
|
||||
```
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import (
|
||||
read_json, write_json, merge_json,
|
||||
validate_json, analyze_json, transform_json
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
name="JSONProcessor",
|
||||
description="An agent that processes JSON data",
|
||||
tools=[
|
||||
read_json, write_json, merge_json,
|
||||
validate_json, analyze_json, transform_json
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The JSON tools require the following Python packages:
|
||||
- jsonschema: For JSON schema validation
|
||||
|
||||
These will be automatically installed when needed.
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- File I/O errors
|
||||
- JSON parsing errors
|
||||
- Schema validation errors
|
||||
- Transformation errors
|
||||
|
||||
Errors are handled consistently:
|
||||
- File operations return bool for success/failure
|
||||
- Data operations return error details in result
|
||||
- All errors are logged for debugging
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. Configuration Management:
|
||||
```python
|
||||
# Merge multiple config files
|
||||
success = merge_json(
|
||||
["base_config.json", "env_config.json", "user_config.json"],
|
||||
"final_config.json",
|
||||
merge_arrays=True,
|
||||
overwrite_duplicates=True
|
||||
)
|
||||
|
||||
# Validate configuration
|
||||
schema = {
|
||||
"type": "object",
|
||||
"required": ["database", "api"],
|
||||
"properties": {
|
||||
"database": {
|
||||
"type": "object",
|
||||
"required": ["host", "port"]
|
||||
},
|
||||
"api": {
|
||||
"type": "object",
|
||||
"required": ["key"]
|
||||
}
|
||||
}
|
||||
}
|
||||
is_valid, error = validate_json("final_config.json", schema)
|
||||
```
|
||||
|
||||
2. Data Analysis:
|
||||
```python
|
||||
# Analyze data structure
|
||||
analysis = analyze_json("large_dataset.json", max_depth=3)
|
||||
print(f"Dataset size: {analysis['structure']['size']} entries")
|
||||
print(f"Available fields: {analysis['structure']['keys']}")
|
||||
```
|
||||
|
||||
3. Data Transformation:
|
||||
```python
|
||||
# Transform data format
|
||||
transformations = [
|
||||
{"operation": "rename", "path": "firstName", "value": "first_name"},
|
||||
{"operation": "rename", "path": "lastName", "value": "last_name"},
|
||||
{"operation": "move", "path": "address.zip", "value": "address.postal_code"},
|
||||
{"operation": "delete", "path": "temporary_data"}
|
||||
]
|
||||
result = transform_json("user_data.json", transformations)
|
||||
write_json(result, "transformed_data.json")
|
||||
```
|
||||
|
||||
## Understanding JSON Tools
|
||||
|
||||
<Card title="What are JSON Tools?" icon="question">
|
||||
JSON Tools provide JSON processing capabilities for AI agents:
|
||||
- File reading and writing
|
||||
- Data validation
|
||||
- Schema validation
|
||||
- Data transformation
|
||||
- Structure analysis
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="JSON Agent" icon="user-robot">
|
||||
Create specialized JSON agents:
|
||||
```python
|
||||
Agent(tools=[read_json, write_json, merge_json, validate_json, analyze_json, transform_json])
|
||||
```
|
||||
</Card>
|
||||
<Card title="JSON Task" icon="list-check">
|
||||
Define JSON tasks:
|
||||
```python
|
||||
Task(description="json_operation")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Process Types" icon="arrows-split-up-and-left">
|
||||
Sequential or parallel processing:
|
||||
```python
|
||||
process="sequential"
|
||||
```
|
||||
</Card>
|
||||
<Card title="JSON Options" icon="sliders">
|
||||
Customize JSON operations:
|
||||
```python
|
||||
indent=2, sort_keys=True
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -116,24 +454,24 @@ Use JSON Tools to process and manipulate JSON files with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import json
|
||||
from praisonaiagents.tools import read_json, write_json, validate_json
|
||||
|
||||
# Create JSON agent
|
||||
# Create JSON processing agent
|
||||
json_agent = Agent(
|
||||
name="JSONExpert",
|
||||
role="JSON Processing Specialist",
|
||||
goal="Process JSON files efficiently and accurately.",
|
||||
backstory="Expert in JSON file handling and validation.",
|
||||
tools=[json],
|
||||
role="JSON Processor",
|
||||
goal="Process and validate JSON data efficiently.",
|
||||
backstory="Expert in JSON processing and validation.",
|
||||
tools=[read_json, write_json, validate_json],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define JSON task
|
||||
json_task = Task(
|
||||
description="Parse and validate API configurations.",
|
||||
expected_output="Processed and validated JSON data.",
|
||||
description="Process and validate configuration files.",
|
||||
expected_output="Validated JSON configuration.",
|
||||
agent=json_agent,
|
||||
name="config_processing"
|
||||
name="config_validation"
|
||||
)
|
||||
|
||||
# Run agent
|
||||
@@ -145,44 +483,44 @@ agents = PraisonAIAgents(
|
||||
agents.start()
|
||||
```
|
||||
|
||||
### Advanced JSON Processing with Multiple Agents
|
||||
### Advanced JSON Operations with Multiple Agents
|
||||
|
||||
```python
|
||||
# Create JSON processing agent
|
||||
processor_agent = Agent(
|
||||
name="Processor",
|
||||
role="JSON Processor",
|
||||
goal="Process JSON files systematically.",
|
||||
tools=[json],
|
||||
# Create JSON validation agent
|
||||
validation_agent = Agent(
|
||||
name="Validator",
|
||||
role="JSON Validation Specialist",
|
||||
goal="Ensure JSON data integrity and schema compliance.",
|
||||
tools=[validate_json, analyze_json],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create validation agent
|
||||
validator_agent = Agent(
|
||||
name="Validator",
|
||||
role="Data Validator",
|
||||
goal="Validate JSON structure and content.",
|
||||
backstory="Expert in data validation and verification.",
|
||||
# Create JSON transformation agent
|
||||
transform_agent = Agent(
|
||||
name="Transformer",
|
||||
role="JSON Transformation Specialist",
|
||||
goal="Transform and merge JSON data structures.",
|
||||
tools=[transform_json, merge_json],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
processing_task = Task(
|
||||
description="Process and transform JSON configurations.",
|
||||
agent=processor_agent,
|
||||
name="json_processing"
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
description="Validate processed JSON data.",
|
||||
agent=validator_agent,
|
||||
name="data_validation"
|
||||
)
|
||||
description="Validate JSON data",
|
||||
agent=validation_agent,
|
||||
name="json_validation"
|
||||
)
|
||||
|
||||
transform_task = Task(
|
||||
description="Transform JSON data",
|
||||
agent=transform_agent,
|
||||
name="json_transformation"
|
||||
)
|
||||
|
||||
# Run agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[processor_agent, validator_agent],
|
||||
tasks=[processing_task, validation_task],
|
||||
agents=[validation_agent, transform_agent],
|
||||
tasks=[validation_task, transform_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
@@ -198,7 +536,7 @@ agents.start()
|
||||
name="JSONProcessor",
|
||||
role="JSON Processing Specialist",
|
||||
goal="Process JSON files accurately and safely",
|
||||
tools=[json]
|
||||
tools=[read_json, write_json, merge_json, validate_json, analyze_json, transform_json]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +560,7 @@ agents.start()
|
||||
processor = Agent(
|
||||
name="Processor",
|
||||
role="JSON Processor",
|
||||
tools=[json]
|
||||
tools=[read_json, write_json, merge_json, validate_json, analyze_json, transform_json]
|
||||
)
|
||||
|
||||
# Validation agent
|
||||
@@ -247,4 +585,3 @@ agents = PraisonAIAgents(
|
||||
agents=[processor, validator],
|
||||
tasks=[process_task, validate_task]
|
||||
)
|
||||
```
|
||||
+233
-18
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Newspaper Tools"
|
||||
description: "News article scraping and analysis tools for AI agents."
|
||||
title: "Newspaper Agent"
|
||||
description: "News article extraction tools for AI agents."
|
||||
icon: "newspaper"
|
||||
---
|
||||
|
||||
@@ -11,9 +11,9 @@ icon: "newspaper"
|
||||
- `newspaper3k` package installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Newspaper Tools
|
||||
|
||||
Use Newspaper Tools to scrape and analyze news articles with AI agents.
|
||||
Use Newspaper Tools to extract and analyze news articles with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
@@ -27,7 +27,7 @@ Use Newspaper Tools to scrape and analyze news articles with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import newspaper
|
||||
from praisonaiagents.tools import get_article, get_news_sources, get_articles_from_source, get_trending_topics
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +39,7 @@ Use Newspaper Tools to scrape and analyze news articles with AI agents.
|
||||
role="News Analyst",
|
||||
goal="Collect and analyze news articles from various sources.",
|
||||
backstory="Expert in news gathering and content analysis.",
|
||||
tools=[newspaper],
|
||||
tools=[get_article, get_news_sources, get_articles_from_source, get_trending_topics],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -87,7 +87,7 @@ Use Newspaper Tools to scrape and analyze news articles with AI agents.
|
||||
<Card title="News Agent" icon="user-robot">
|
||||
Create specialized news agents:
|
||||
```python
|
||||
Agent(tools=[newspaper])
|
||||
Agent(tools=[get_article, get_news_sources, get_articles_from_source, get_trending_topics])
|
||||
```
|
||||
</Card>
|
||||
<Card title="News Task" icon="list-check">
|
||||
@@ -110,30 +110,161 @@ Use Newspaper Tools to scrape and analyze news articles with AI agents.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import get_article
|
||||
from praisonaiagents.tools import get_news_sources
|
||||
from praisonaiagents.tools import get_articles_from_source
|
||||
from praisonaiagents.tools import get_trending_topics
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### get_article(url: str, language: str = 'en')
|
||||
|
||||
Extracts and parses news articles:
|
||||
- Full text extraction
|
||||
- Author detection
|
||||
- Date parsing
|
||||
- Image extraction
|
||||
- NLP processing
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
article = get_article("https://example.com/article")
|
||||
|
||||
# With language specification
|
||||
article = get_article(
|
||||
"https://lemonde.fr/article",
|
||||
language="fr"
|
||||
)
|
||||
|
||||
# Returns: Dict[str, Any]
|
||||
# Example output:
|
||||
# {
|
||||
# "url": "https://example.com/article",
|
||||
# "title": "Breaking News Story",
|
||||
# "text": "Full article text...",
|
||||
# "authors": ["John Doe", "Jane Smith"],
|
||||
# "publish_date": "2025-01-07T05:31:38",
|
||||
# "top_image": "https://example.com/image.jpg",
|
||||
# "images": ["https://example.com/image1.jpg", ...],
|
||||
# "movies": ["https://example.com/video1.mp4", ...],
|
||||
# "source_domain": "example.com",
|
||||
# "keywords": ["technology", "ai", ...],
|
||||
# "summary": "Article summary..."
|
||||
# }
|
||||
```
|
||||
|
||||
### get_news_sources(category: Optional[str] = None, language: str = 'en', country: Optional[str] = None)
|
||||
|
||||
Gets news sources by category:
|
||||
- Category filtering
|
||||
- Language support
|
||||
- Country filtering
|
||||
- Domain information
|
||||
|
||||
```python
|
||||
# Get all sources
|
||||
sources = get_news_sources()
|
||||
|
||||
# Get technology news sources
|
||||
tech_sources = get_news_sources(
|
||||
category="technology",
|
||||
language="en",
|
||||
country="us"
|
||||
)
|
||||
|
||||
# Returns: List[Dict[str, str]]
|
||||
# Example output:
|
||||
# [
|
||||
# {
|
||||
# "url": "https://techcrunch.com",
|
||||
# "domain": "techcrunch.com",
|
||||
# "name": "TechCrunch",
|
||||
# "category": "technology"
|
||||
# },
|
||||
# ...
|
||||
# ]
|
||||
```
|
||||
|
||||
### get_articles_from_source(source_url: str, limit: int = 10, language: str = 'en')
|
||||
|
||||
Gets recent articles from a source:
|
||||
- Configurable limit
|
||||
- Language support
|
||||
- Full article parsing
|
||||
- Error handling
|
||||
|
||||
```python
|
||||
# Get latest articles
|
||||
articles = get_articles_from_source(
|
||||
"https://techcrunch.com",
|
||||
limit=5
|
||||
)
|
||||
|
||||
# Get articles in specific language
|
||||
articles = get_articles_from_source(
|
||||
"https://lemonde.fr",
|
||||
limit=10,
|
||||
language="fr"
|
||||
)
|
||||
|
||||
# Returns: List[Dict[str, Any]]
|
||||
# Each article has the same structure as get_article()
|
||||
```
|
||||
|
||||
### get_trending_topics(sources: Optional[List[str]] = None, limit: int = 10, language: str = 'en')
|
||||
|
||||
Analyzes trending topics:
|
||||
- Cross-source analysis
|
||||
- Keyword extraction
|
||||
- Customizable sources
|
||||
- Topic ranking
|
||||
|
||||
```python
|
||||
# Get trending topics from default sources
|
||||
topics = get_trending_topics(limit=5)
|
||||
|
||||
# Get topics from specific sources
|
||||
topics = get_trending_topics(
|
||||
sources=[
|
||||
"https://techcrunch.com",
|
||||
"https://wired.com"
|
||||
],
|
||||
limit=10,
|
||||
language="en"
|
||||
)
|
||||
|
||||
# Returns: List[str]
|
||||
# Example: ["artificial intelligence", "climate change", ...]
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic News Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import newspaper
|
||||
from praisonaiagents.tools import get_article, get_news_sources, get_articles_from_source, get_trending_topics
|
||||
|
||||
# Create news agent
|
||||
news_agent = Agent(
|
||||
name="NewsCollector",
|
||||
name="NewsExpert",
|
||||
role="News Analyst",
|
||||
goal="Collect and analyze news articles on specific topics.",
|
||||
backstory="Expert in news gathering and content analysis.",
|
||||
tools=[newspaper],
|
||||
goal="Gather and analyze news content efficiently.",
|
||||
backstory="Expert in news analysis and content curation.",
|
||||
tools=[get_article, get_news_sources, get_articles_from_source, get_trending_topics],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define news task
|
||||
news_task = Task(
|
||||
description="Analyze recent tech news articles about 'artificial intelligence'.",
|
||||
expected_output="Summary of key AI developments with source articles.",
|
||||
description="Analyze tech news trends.",
|
||||
expected_output="Tech news analysis report.",
|
||||
agent=news_agent,
|
||||
name="tech_news"
|
||||
name="tech_news_analysis"
|
||||
)
|
||||
|
||||
# Run agent
|
||||
@@ -153,7 +284,7 @@ collector_agent = Agent(
|
||||
name="Collector",
|
||||
role="News Collector",
|
||||
goal="Gather comprehensive news coverage.",
|
||||
tools=[newspaper],
|
||||
tools=[get_article, get_news_sources, get_articles_from_source, get_trending_topics],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -198,7 +329,7 @@ agents.start()
|
||||
name="NewsAnalyst",
|
||||
role="News Specialist",
|
||||
goal="Analyze news content effectively",
|
||||
tools=[newspaper]
|
||||
tools=[get_article, get_news_sources, get_articles_from_source, get_trending_topics]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +353,7 @@ agents.start()
|
||||
monitor = Agent(
|
||||
name="Monitor",
|
||||
role="News Monitor",
|
||||
tools=[newspaper]
|
||||
tools=[get_article, get_news_sources, get_articles_from_source, get_trending_topics]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
@@ -247,3 +378,87 @@ agents = PraisonAIAgents(
|
||||
agents=[monitor, analyst],
|
||||
tasks=[monitor_task, analysis_task]
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import (
|
||||
get_article, get_news_sources,
|
||||
get_articles_from_source, get_trending_topics
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
name="NewsAnalyzer",
|
||||
description="An agent that analyzes news articles",
|
||||
tools=[
|
||||
get_article, get_news_sources,
|
||||
get_articles_from_source, get_trending_topics
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The newspaper tools require the following Python packages:
|
||||
- newspaper3k: For article extraction and parsing
|
||||
- nltk: For NLP processing (automatically installed with newspaper3k)
|
||||
|
||||
These will be automatically installed when needed.
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- Network errors
|
||||
- Parsing errors
|
||||
- Language errors
|
||||
- Source availability errors
|
||||
|
||||
Errors are handled consistently:
|
||||
- Success cases return the expected data type
|
||||
- Error cases return a dict with an "error" key
|
||||
- All errors are logged for debugging
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. News Monitoring:
|
||||
```python
|
||||
# Monitor tech news
|
||||
sources = get_news_sources(category="technology")
|
||||
for source in sources:
|
||||
articles = get_articles_from_source(
|
||||
source["url"],
|
||||
limit=5
|
||||
)
|
||||
for article in articles:
|
||||
if "ai" in article.get("keywords", []):
|
||||
print(f"AI article found: {article['title']}")
|
||||
```
|
||||
|
||||
2. Trend Analysis:
|
||||
```python
|
||||
# Analyze trending topics
|
||||
topics = get_trending_topics(limit=10)
|
||||
print("Current hot topics:")
|
||||
for i, topic in enumerate(topics, 1):
|
||||
print(f"{i}. {topic}")
|
||||
```
|
||||
|
||||
3. Content Aggregation:
|
||||
```python
|
||||
# Aggregate news from multiple sources
|
||||
def aggregate_news(categories):
|
||||
all_articles = []
|
||||
for category in categories:
|
||||
sources = get_news_sources(category=category)
|
||||
for source in sources[:3]: # Top 3 sources per category
|
||||
articles = get_articles_from_source(
|
||||
source["url"],
|
||||
limit=3
|
||||
)
|
||||
all_articles.extend(articles)
|
||||
return all_articles
|
||||
|
||||
news = aggregate_news(["technology", "business", "science"])
|
||||
+371
-37
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Pandas Tools"
|
||||
description: "Data manipulation and analysis tools for AI agents using pandas."
|
||||
title: "Pandas Agent"
|
||||
description: "Pandas data manipulation tools for AI agents."
|
||||
icon: "table"
|
||||
---
|
||||
|
||||
@@ -11,7 +11,7 @@ icon: "table"
|
||||
- `pandas` package installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Pandas Tools
|
||||
|
||||
Use Pandas Tools to manipulate and analyze data with AI agents.
|
||||
|
||||
@@ -27,7 +27,7 @@ Use Pandas Tools to manipulate and analyze data with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import pandas_tools
|
||||
from praisonaiagents.tools import read_csv, read_excel, write_csv, write_excel, filter_data, get_summary, group_by, pivot_table
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +39,7 @@ Use Pandas Tools to manipulate and analyze data with AI agents.
|
||||
role="Data Analysis Specialist",
|
||||
goal="Analyze and transform data efficiently.",
|
||||
backstory="Expert in data manipulation and statistical analysis.",
|
||||
tools=[pandas_tools],
|
||||
tools=[read_csv, read_excel, write_csv, write_excel, filter_data, get_summary, group_by, pivot_table],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -87,7 +87,7 @@ Use Pandas Tools to manipulate and analyze data with AI agents.
|
||||
<Card title="Data Agent" icon="user-robot">
|
||||
Create specialized data agents:
|
||||
```python
|
||||
Agent(tools=[pandas_tools])
|
||||
Agent(tools=[read_csv, read_excel, write_csv, write_excel, filter_data, get_summary, group_by, pivot_table])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Analysis Task" icon="list-check">
|
||||
@@ -110,30 +110,365 @@ Use Pandas Tools to manipulate and analyze data with AI agents.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import read_csv
|
||||
from praisonaiagents.tools import read_excel
|
||||
from praisonaiagents.tools import write_csv
|
||||
from praisonaiagents.tools import write_excel
|
||||
from praisonaiagents.tools import filter_data
|
||||
from praisonaiagents.tools import get_summary
|
||||
from praisonaiagents.tools import group_by
|
||||
from praisonaiagents.tools import pivot_table
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### read_csv(filepath: str, **kwargs)
|
||||
|
||||
Reads CSV files into pandas DataFrames:
|
||||
- Flexible data import
|
||||
- Error handling
|
||||
- Additional pandas options
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
df = read_csv("data.csv")
|
||||
|
||||
# With additional options
|
||||
df = read_csv(
|
||||
"data.csv",
|
||||
encoding="utf-8",
|
||||
sep=",",
|
||||
header=0,
|
||||
usecols=["name", "age", "salary"]
|
||||
)
|
||||
|
||||
# Returns: pd.DataFrame
|
||||
# Error case: Returns dict with 'error' key
|
||||
```
|
||||
|
||||
### read_excel(filepath: str, **kwargs)
|
||||
|
||||
Reads Excel files into pandas DataFrames:
|
||||
- Multiple sheet support
|
||||
- Error handling
|
||||
- Additional pandas options
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
df = read_excel("data.xlsx")
|
||||
|
||||
# With sheet specification
|
||||
df = read_excel(
|
||||
"data.xlsx",
|
||||
sheet_name="Sheet1",
|
||||
header=0,
|
||||
usecols="A:D"
|
||||
)
|
||||
|
||||
# Returns: pd.DataFrame
|
||||
# Error case: Returns dict with 'error' key
|
||||
```
|
||||
|
||||
### write_csv(df: pd.DataFrame, filepath: str, **kwargs)
|
||||
|
||||
Writes DataFrames to CSV files:
|
||||
- Directory creation
|
||||
- Error handling
|
||||
- Formatting options
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
success = write_csv(df, "output.csv")
|
||||
|
||||
# With formatting options
|
||||
success = write_csv(
|
||||
df,
|
||||
"output.csv",
|
||||
index=False,
|
||||
encoding="utf-8",
|
||||
sep=",",
|
||||
date_format="%Y-%m-%d"
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### write_excel(df: pd.DataFrame, filepath: str, **kwargs)
|
||||
|
||||
Writes DataFrames to Excel files:
|
||||
- Directory creation
|
||||
- Error handling
|
||||
- Excel-specific options
|
||||
|
||||
```python
|
||||
# Basic usage
|
||||
success = write_excel(df, "output.xlsx")
|
||||
|
||||
# With formatting options
|
||||
success = write_excel(
|
||||
df,
|
||||
"output.xlsx",
|
||||
sheet_name="Data",
|
||||
index=False,
|
||||
freeze_panes=(1,0)
|
||||
)
|
||||
# Returns: bool (True if successful)
|
||||
```
|
||||
|
||||
### filter_data(df: pd.DataFrame, query: str)
|
||||
|
||||
Filters DataFrames using query strings:
|
||||
- SQL-like syntax
|
||||
- Complex conditions
|
||||
- Efficient filtering
|
||||
|
||||
```python
|
||||
# Basic filtering
|
||||
filtered_df = filter_data(df, "age > 25")
|
||||
|
||||
# Complex conditions
|
||||
filtered_df = filter_data(
|
||||
df,
|
||||
"age > 25 and salary >= 50000 and city == 'New York'"
|
||||
)
|
||||
|
||||
# Returns: pd.DataFrame
|
||||
# Error case: Returns dict with 'error' key
|
||||
```
|
||||
|
||||
### get_summary(df: pd.DataFrame)
|
||||
|
||||
Generates comprehensive data summaries:
|
||||
- Basic statistics
|
||||
- Data types
|
||||
- Memory usage
|
||||
- Null counts
|
||||
|
||||
```python
|
||||
# Get data summary
|
||||
summary = get_summary(df)
|
||||
|
||||
# Returns: Dict[str, Any]
|
||||
# Example output:
|
||||
# {
|
||||
# "shape": [1000, 5],
|
||||
# "columns": ["name", "age", "salary", "city"],
|
||||
# "dtypes": {
|
||||
# "name": "object",
|
||||
# "age": "int64",
|
||||
# "salary": "float64",
|
||||
# "city": "object"
|
||||
# },
|
||||
# "null_counts": {
|
||||
# "name": 0,
|
||||
# "age": 2,
|
||||
# "salary": 1,
|
||||
# "city": 0
|
||||
# },
|
||||
# "numeric_summary": {
|
||||
# "age": {
|
||||
# "count": 998,
|
||||
# "mean": 35.5,
|
||||
# "std": 12.3,
|
||||
# "min": 18,
|
||||
# "25%": 28,
|
||||
# "50%": 35,
|
||||
# "75%": 45,
|
||||
# "max": 65
|
||||
# },
|
||||
# ...
|
||||
# },
|
||||
# "memory_usage": 40960
|
||||
# }
|
||||
```
|
||||
|
||||
### group_by(df: pd.DataFrame, columns: Union[str, List[str]], agg_dict: Dict[str, Union[str, List[str]]])
|
||||
|
||||
Groups and aggregates data:
|
||||
- Multiple grouping columns
|
||||
- Multiple aggregations
|
||||
- Custom functions
|
||||
|
||||
```python
|
||||
# Basic grouping
|
||||
grouped_df = group_by(
|
||||
df,
|
||||
columns="city",
|
||||
agg_dict={"salary": "mean"}
|
||||
)
|
||||
|
||||
# Complex grouping
|
||||
grouped_df = group_by(
|
||||
df,
|
||||
columns=["city", "department"],
|
||||
agg_dict={
|
||||
"salary": ["mean", "sum", "count"],
|
||||
"age": ["min", "max", "mean"]
|
||||
}
|
||||
)
|
||||
|
||||
# Returns: pd.DataFrame
|
||||
# Error case: Returns dict with 'error' key
|
||||
```
|
||||
|
||||
### pivot_table(df: pd.DataFrame, index: Union[str, List[str]], columns: Optional[Union[str, List[str]]] = None, values: Optional[Union[str, List[str]]] = None, aggfunc: str = "mean")
|
||||
|
||||
Creates pivot tables:
|
||||
- Multiple index levels
|
||||
- Column pivoting
|
||||
- Custom aggregations
|
||||
- Flexible reshaping
|
||||
|
||||
```python
|
||||
# Basic pivot
|
||||
pivot_df = pivot_table(
|
||||
df,
|
||||
index="city",
|
||||
columns="department",
|
||||
values="salary"
|
||||
)
|
||||
|
||||
# Complex pivot
|
||||
pivot_df = pivot_table(
|
||||
df,
|
||||
index=["city", "department"],
|
||||
columns="year",
|
||||
values=["salary", "headcount"],
|
||||
aggfunc={
|
||||
"salary": "mean",
|
||||
"headcount": "sum"
|
||||
}
|
||||
)
|
||||
|
||||
# Returns: pd.DataFrame
|
||||
# Error case: Returns dict with 'error' key
|
||||
```
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import (
|
||||
read_csv, read_excel, write_csv, write_excel,
|
||||
filter_data, get_summary, group_by, pivot_table
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
name="DataAnalyzer",
|
||||
description="An agent that analyzes data using pandas",
|
||||
tools=[
|
||||
read_csv, read_excel, write_csv, write_excel,
|
||||
filter_data, get_summary, group_by, pivot_table
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The pandas tools require the following Python packages:
|
||||
- pandas: For data manipulation and analysis
|
||||
- numpy: For numerical operations (automatically installed with pandas)
|
||||
- openpyxl: For Excel file support (optional)
|
||||
|
||||
These will be automatically installed when needed.
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- File I/O errors
|
||||
- Data format errors
|
||||
- Query syntax errors
|
||||
- Memory errors
|
||||
|
||||
Errors are handled consistently:
|
||||
- File operations return bool for success/failure
|
||||
- Data operations return error details in result
|
||||
- All errors are logged for debugging
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. Data Analysis:
|
||||
```python
|
||||
# Load and analyze sales data
|
||||
df = read_csv("sales_data.csv")
|
||||
summary = get_summary(df)
|
||||
print(f"Total records: {summary['shape'][0]}")
|
||||
print(f"Missing values: {summary['null_counts']}")
|
||||
|
||||
# Filter high-value transactions
|
||||
high_value = filter_data(df, "amount > 10000")
|
||||
write_excel(high_value, "high_value_sales.xlsx")
|
||||
```
|
||||
|
||||
2. Sales Reporting:
|
||||
```python
|
||||
# Create sales summary by region and product
|
||||
sales_summary = group_by(
|
||||
df,
|
||||
columns=["region", "product"],
|
||||
agg_dict={
|
||||
"amount": ["sum", "mean", "count"],
|
||||
"profit": ["sum", "mean"]
|
||||
}
|
||||
)
|
||||
|
||||
# Create pivot table for quarterly analysis
|
||||
quarterly_sales = pivot_table(
|
||||
df,
|
||||
index="product",
|
||||
columns="quarter",
|
||||
values="amount",
|
||||
aggfunc="sum"
|
||||
)
|
||||
```
|
||||
|
||||
3. Data Transformation:
|
||||
```python
|
||||
# Load and clean customer data
|
||||
customers = read_excel("customers.xlsx")
|
||||
filtered = filter_data(
|
||||
customers,
|
||||
"age >= 18 and status == 'active'"
|
||||
)
|
||||
|
||||
# Group by demographics
|
||||
demographics = group_by(
|
||||
filtered,
|
||||
columns=["age_group", "region"],
|
||||
agg_dict={
|
||||
"spending": ["mean", "sum"],
|
||||
"visits": "count"
|
||||
}
|
||||
)
|
||||
write_csv(demographics, "demographic_analysis.csv")
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Data Analysis Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import pandas_tools
|
||||
from praisonaiagents.tools import read_csv, filter_data, get_summary, group_by
|
||||
|
||||
# Create data analysis agent
|
||||
data_agent = Agent(
|
||||
name="DataAnalyst",
|
||||
role="Data Analysis Specialist",
|
||||
goal="Perform comprehensive data analysis.",
|
||||
backstory="Expert in statistical analysis and data visualization.",
|
||||
tools=[pandas_tools],
|
||||
name="DataExpert",
|
||||
role="Data Analyst",
|
||||
goal="Process and analyze data efficiently.",
|
||||
backstory="Expert in data analysis and statistical methods.",
|
||||
tools=[read_csv, filter_data, get_summary, group_by],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define analysis task
|
||||
analysis_task = Task(
|
||||
description="Analyze customer demographics and purchase patterns.",
|
||||
expected_output="Customer segmentation analysis with insights.",
|
||||
description="Analyze sales performance data.",
|
||||
expected_output="Sales analysis report.",
|
||||
agent=data_agent,
|
||||
name="customer_analysis"
|
||||
name="sales_analysis"
|
||||
)
|
||||
|
||||
# Run agent
|
||||
@@ -145,44 +480,44 @@ agents = PraisonAIAgents(
|
||||
agents.start()
|
||||
```
|
||||
|
||||
### Advanced Analysis with Multiple Agents
|
||||
### Advanced Data Operations with Multiple Agents
|
||||
|
||||
```python
|
||||
# Create data preparation agent
|
||||
prep_agent = Agent(
|
||||
name="DataPrep",
|
||||
role="Data Preparation Specialist",
|
||||
goal="Clean and prepare data for analysis.",
|
||||
tools=[pandas_tools],
|
||||
# Create data import/export agent
|
||||
io_agent = Agent(
|
||||
name="DataIO",
|
||||
role="Data IO Specialist",
|
||||
goal="Handle data import and export operations.",
|
||||
tools=[read_csv, read_excel, write_csv, write_excel],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create analysis agent
|
||||
analysis_agent = Agent(
|
||||
name="Analyzer",
|
||||
role="Statistical Analyst",
|
||||
goal="Perform advanced statistical analysis.",
|
||||
backstory="Expert in statistical modeling and interpretation.",
|
||||
role="Data Analysis Specialist",
|
||||
goal="Perform complex data analysis.",
|
||||
tools=[filter_data, get_summary, group_by, pivot_table],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
prep_task = Task(
|
||||
description="Clean and prepare sales data for analysis.",
|
||||
agent=prep_agent,
|
||||
name="data_prep"
|
||||
io_task = Task(
|
||||
description="Import and export data",
|
||||
agent=io_agent,
|
||||
name="data_io"
|
||||
)
|
||||
|
||||
analysis_task = Task(
|
||||
description="Perform statistical analysis and generate insights.",
|
||||
description="Analyze data",
|
||||
agent=analysis_agent,
|
||||
name="statistical_analysis"
|
||||
)
|
||||
name="data_analysis"
|
||||
)
|
||||
|
||||
# Run agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[prep_agent, analysis_agent],
|
||||
tasks=[prep_task, analysis_task],
|
||||
agents=[io_agent, analysis_agent],
|
||||
tasks=[io_task, analysis_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
@@ -198,7 +533,7 @@ agents.start()
|
||||
name="DataScientist",
|
||||
role="Data Analysis Specialist",
|
||||
goal="Extract meaningful insights from data",
|
||||
tools=[pandas_tools]
|
||||
tools=[read_csv, read_excel, write_csv, write_excel, filter_data, get_summary, group_by, pivot_table]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +557,7 @@ agents.start()
|
||||
prep_agent = Agent(
|
||||
name="Preparer",
|
||||
role="Data Preparation",
|
||||
tools=[pandas_tools]
|
||||
tools=[read_csv, read_excel, write_csv, write_excel, filter_data, get_summary, group_by, pivot_table]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
@@ -247,4 +582,3 @@ agents = PraisonAIAgents(
|
||||
agents=[prep_agent, analyst],
|
||||
tasks=[prep_task, analysis_task]
|
||||
)
|
||||
```
|
||||
+318
-39
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "Python Tools"
|
||||
title: "Python Agent"
|
||||
description: "Python code execution tools for AI agents."
|
||||
icon: "python"
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
<Note>
|
||||
@@ -11,7 +11,7 @@ icon: "python"
|
||||
- Basic understanding of Python programming
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Python Tools
|
||||
|
||||
Use Python Tools to execute and manage Python code with AI agents.
|
||||
|
||||
@@ -27,7 +27,10 @@ Use Python Tools to execute and manage Python code with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import python
|
||||
from praisonaiagents.tools import (
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +42,10 @@ Use Python Tools to execute and manage Python code with AI agents.
|
||||
role="Python Code Specialist",
|
||||
goal="Execute Python code efficiently and safely.",
|
||||
backstory="Expert in Python programming and code execution.",
|
||||
tools=[python],
|
||||
tools=[
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -70,6 +76,293 @@ Use Python Tools to execute and manage Python code with AI agents.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import execute_code
|
||||
from praisonaiagents.tools import analyze_code
|
||||
from praisonaiagents.tools import format_code
|
||||
from praisonaiagents.tools import lint_code
|
||||
from praisonaiagents.tools import disassemble_code
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### execute_code(code: str, globals_dict: Optional[Dict[str, Any]] = None, locals_dict: Optional[Dict[str, Any]] = None, timeout: int = 30, max_output_size: int = 10000)
|
||||
|
||||
Safely executes Python code:
|
||||
- Isolated execution environment
|
||||
- Output capture
|
||||
- Error handling
|
||||
- Timeout protection
|
||||
- Output size limits
|
||||
|
||||
```python
|
||||
# Basic execution
|
||||
result = execute_code("print('Hello, World!')")
|
||||
|
||||
# With custom environment
|
||||
result = execute_code(
|
||||
"""
|
||||
x = 10
|
||||
y = 20
|
||||
print(f'Sum: {x + y}')
|
||||
""",
|
||||
globals_dict={'__builtins__': __builtins__},
|
||||
timeout=5
|
||||
)
|
||||
|
||||
# Returns: Dict[str, Any]
|
||||
# Example output:
|
||||
# {
|
||||
# 'result': None,
|
||||
# 'stdout': 'Hello, World!\n',
|
||||
# 'stderr': '',
|
||||
# 'success': True
|
||||
# }
|
||||
```
|
||||
|
||||
### analyze_code(code: str)
|
||||
|
||||
Analyzes Python code structure:
|
||||
- Import statements
|
||||
- Function definitions
|
||||
- Class definitions
|
||||
- Variable usage
|
||||
- Code complexity
|
||||
|
||||
```python
|
||||
# Analyze code structure
|
||||
analysis = analyze_code("""
|
||||
def greet(name):
|
||||
return f"Hello, {name}!"
|
||||
|
||||
class Person:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
""")
|
||||
|
||||
# Returns: Dict[str, Any]
|
||||
# Example output:
|
||||
# {
|
||||
# 'imports': [],
|
||||
# 'functions': [
|
||||
# {
|
||||
# 'name': 'greet',
|
||||
# 'args': ['name'],
|
||||
# 'decorators': []
|
||||
# }
|
||||
# ],
|
||||
# 'classes': [
|
||||
# {
|
||||
# 'name': 'Person',
|
||||
# 'bases': [],
|
||||
# 'decorators': []
|
||||
# }
|
||||
# ],
|
||||
# 'variables': ['name'],
|
||||
# 'complexity': {
|
||||
# 'lines': 6,
|
||||
# 'functions': 2,
|
||||
# 'classes': 1,
|
||||
# 'branches': 0
|
||||
# }
|
||||
# }
|
||||
```
|
||||
|
||||
### format_code(code: str, style: str = 'black', line_length: int = 88)
|
||||
|
||||
Formats Python code:
|
||||
- Multiple style options
|
||||
- Line length control
|
||||
- PEP 8 compliance
|
||||
- Consistent formatting
|
||||
|
||||
```python
|
||||
# Format with black
|
||||
formatted = format_code("""
|
||||
def messy_function(x,y, z):
|
||||
if x>0:
|
||||
return y+z
|
||||
else:
|
||||
return y-z
|
||||
""")
|
||||
|
||||
# Format with PEP 8
|
||||
formatted = format_code(
|
||||
"""
|
||||
def messy_function(x,y, z):
|
||||
if x>0:
|
||||
return y+z
|
||||
else:
|
||||
return y-z
|
||||
""",
|
||||
style='pep8',
|
||||
line_length=79
|
||||
)
|
||||
|
||||
# Returns: str
|
||||
# Example output:
|
||||
# def messy_function(x, y, z):
|
||||
# if x > 0:
|
||||
# return y + z
|
||||
# else:
|
||||
# return y - z
|
||||
```
|
||||
|
||||
### lint_code(code: str)
|
||||
|
||||
Lints Python code for issues:
|
||||
- Code quality checks
|
||||
- Style violations
|
||||
- Potential bugs
|
||||
- Best practices
|
||||
|
||||
```python
|
||||
# Lint code for issues
|
||||
results = lint_code("""
|
||||
def bad_function():
|
||||
unused_var = 42
|
||||
return 'result'
|
||||
""")
|
||||
|
||||
# Returns: Dict[str, List[Dict[str, Any]]]
|
||||
# Example output:
|
||||
# {
|
||||
# 'errors': [],
|
||||
# 'warnings': [
|
||||
# {
|
||||
# 'type': 'warning',
|
||||
# 'module': 'bad_function',
|
||||
# 'obj': 'unused_var',
|
||||
# 'line': 2,
|
||||
# 'column': 4,
|
||||
# 'path': '<string>',
|
||||
# 'symbol': 'unused-variable',
|
||||
# 'message': 'Unused variable "unused_var"',
|
||||
# 'message-id': 'W0612'
|
||||
# }
|
||||
# ],
|
||||
# 'conventions': []
|
||||
# }
|
||||
```
|
||||
|
||||
### disassemble_code(code: str)
|
||||
|
||||
Disassembles Python code to bytecode:
|
||||
- Bytecode inspection
|
||||
- Performance analysis
|
||||
- Code optimization
|
||||
- Debugging support
|
||||
|
||||
```python
|
||||
# Disassemble code to bytecode
|
||||
bytecode = disassemble_code("""
|
||||
def add(a, b):
|
||||
return a + b
|
||||
""")
|
||||
|
||||
# Returns: str
|
||||
# Example output:
|
||||
# 1 0 LOAD_CONST 0 (<code object add at ...>)
|
||||
# 2 LOAD_CONST 1 ('add')
|
||||
# 4 MAKE_FUNCTION 0
|
||||
# 6 STORE_NAME 0 (add)
|
||||
# 8 LOAD_CONST 2 (None)
|
||||
# 10 RETURN_VALUE
|
||||
```
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import (
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
name="PythonDeveloper",
|
||||
description="An agent that helps with Python development",
|
||||
tools=[
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The Python tools require the following packages:
|
||||
- black: For code formatting (black style)
|
||||
- autopep8: For code formatting (PEP 8 style)
|
||||
- pylint: For code linting
|
||||
|
||||
These will be automatically installed when needed.
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- Code execution errors
|
||||
- Syntax errors
|
||||
- Import errors
|
||||
- Timeout errors
|
||||
- Memory errors
|
||||
|
||||
Errors are handled consistently:
|
||||
- Success cases return expected data type
|
||||
- Error cases return None or error details
|
||||
- All errors are logged for debugging
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. Code Testing:
|
||||
```python
|
||||
# Test code execution
|
||||
test_code = """
|
||||
def factorial(n):
|
||||
return 1 if n <= 1 else n * factorial(n - 1)
|
||||
|
||||
result = factorial(5)
|
||||
print(f"Factorial: {result}")
|
||||
"""
|
||||
result = execute_code(test_code)
|
||||
print(f"Output: {result['stdout']}")
|
||||
```
|
||||
|
||||
2. Code Quality:
|
||||
```python
|
||||
# Check code quality
|
||||
code = """
|
||||
def process_data(data):
|
||||
processed = []
|
||||
for item in data:
|
||||
if item > 0:
|
||||
processed.append(item * 2)
|
||||
return processed
|
||||
"""
|
||||
analysis = analyze_code(code)
|
||||
lint_results = lint_code(code)
|
||||
formatted = format_code(code)
|
||||
```
|
||||
|
||||
3. Code Analysis:
|
||||
```python
|
||||
# Analyze code structure
|
||||
code = """
|
||||
class DataProcessor:
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
|
||||
def process(self):
|
||||
return [x * 2 for x in self.data]
|
||||
"""
|
||||
structure = analyze_code(code)
|
||||
bytecode = disassemble_code(code)
|
||||
print(f"Classes: {structure['classes']}")
|
||||
print(f"Functions: {structure['functions']}")
|
||||
```
|
||||
|
||||
## Understanding Python Tools
|
||||
|
||||
<Card title="What are Python Tools?" icon="question">
|
||||
@@ -81,42 +374,16 @@ Use Python Tools to execute and manage Python code with AI agents.
|
||||
- Environment control
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Python Agent" icon="user-robot">
|
||||
Create specialized Python agents:
|
||||
```python
|
||||
Agent(tools=[python])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Python Task" icon="list-check">
|
||||
Define Python tasks:
|
||||
```python
|
||||
Task(description="python_operation")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Process Types" icon="arrows-split-up-and-left">
|
||||
Sequential or parallel processing:
|
||||
```python
|
||||
process="sequential"
|
||||
```
|
||||
</Card>
|
||||
<Card title="Python Options" icon="sliders">
|
||||
Customize execution parameters:
|
||||
```python
|
||||
timeout=30, capture_output=True
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Python Execution Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import python
|
||||
from praisonaiagents.tools import (
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
)
|
||||
|
||||
# Create Python agent
|
||||
python_agent = Agent(
|
||||
@@ -124,7 +391,10 @@ python_agent = Agent(
|
||||
role="Code Execution Specialist",
|
||||
goal="Execute Python code efficiently and safely.",
|
||||
backstory="Expert in Python programming and execution.",
|
||||
tools=[python],
|
||||
tools=[
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -153,7 +423,10 @@ executor_agent = Agent(
|
||||
name="CodeExecutor",
|
||||
role="Code Execution Specialist",
|
||||
goal="Execute Python code efficiently.",
|
||||
tools=[python],
|
||||
tools=[
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -198,7 +471,10 @@ agents.start()
|
||||
name="PythonExecutor",
|
||||
role="Code Execution Specialist",
|
||||
goal="Execute code safely and efficiently",
|
||||
tools=[python]
|
||||
tools=[
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +498,10 @@ agents.start()
|
||||
executor = Agent(
|
||||
name="Executor",
|
||||
role="Code Executor",
|
||||
tools=[python]
|
||||
tools=[
|
||||
execute_code, analyze_code, format_code,
|
||||
lint_code, disassemble_code
|
||||
]
|
||||
)
|
||||
|
||||
# Monitor agent
|
||||
|
||||
+257
-18
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Shell Tools"
|
||||
description: "Command-line interface tools for AI agents."
|
||||
title: "Shell Agent"
|
||||
description: "Shell command execution tools for AI agents."
|
||||
icon: "terminal"
|
||||
---
|
||||
|
||||
@@ -11,9 +11,9 @@ icon: "terminal"
|
||||
- Basic understanding of shell commands
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Shell Tools
|
||||
|
||||
Use Shell Tools to execute and manage shell commands with AI agents.
|
||||
Use Shell Tools to execute shell commands with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
@@ -27,7 +27,7 @@ Use Shell Tools to execute and manage shell commands with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import shell
|
||||
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +39,7 @@ Use Shell Tools to execute and manage shell commands with AI agents.
|
||||
role="Shell Command Specialist",
|
||||
goal="Execute shell commands efficiently and safely.",
|
||||
backstory="Expert in command-line operations and automation.",
|
||||
tools=[shell],
|
||||
tools=[execute_command, list_processes, kill_process, get_system_info],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -87,13 +87,13 @@ Use Shell Tools to execute and manage shell commands with AI agents.
|
||||
<Card title="Shell Agent" icon="user-robot">
|
||||
Create specialized shell agents:
|
||||
```python
|
||||
Agent(tools=[shell])
|
||||
Agent(tools=[execute_command, list_processes, kill_process, get_system_info])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Shell Task" icon="list-check">
|
||||
Define shell tasks:
|
||||
```python
|
||||
Task(description="shell_command")
|
||||
Task(description="shell_operation")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Process Types" icon="arrows-split-up-and-left">
|
||||
@@ -103,20 +103,16 @@ Use Shell Tools to execute and manage shell commands with AI agents.
|
||||
```
|
||||
</Card>
|
||||
<Card title="Shell Options" icon="sliders">
|
||||
Customize shell parameters:
|
||||
Customize shell operations:
|
||||
```python
|
||||
timeout=30, shell=True
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Shell Command Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import shell
|
||||
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info
|
||||
|
||||
# Create shell agent
|
||||
shell_agent = Agent(
|
||||
@@ -124,7 +120,7 @@ shell_agent = Agent(
|
||||
role="Shell Command Specialist",
|
||||
goal="Execute shell commands efficiently and safely.",
|
||||
backstory="Expert in command-line operations and scripting.",
|
||||
tools=[shell],
|
||||
tools=[execute_command, list_processes, kill_process, get_system_info],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -153,7 +149,7 @@ command_agent = Agent(
|
||||
name="Commander",
|
||||
role="Command Executor",
|
||||
goal="Execute shell commands systematically.",
|
||||
tools=[shell],
|
||||
tools=[execute_command, list_processes, kill_process, get_system_info],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -188,6 +184,249 @@ agents = PraisonAIAgents(
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Available Functions
|
||||
|
||||
```python
|
||||
from praisonaiagents.tools import execute_command
|
||||
from praisonaiagents.tools import list_processes
|
||||
from praisonaiagents.tools import kill_process
|
||||
from praisonaiagents.tools import get_system_info
|
||||
```
|
||||
|
||||
## Function Details
|
||||
|
||||
### execute_command(command: str, cwd: Optional[str] = None, timeout: int = 30, shell: bool = False, env: Optional[Dict[str, str]] = None, max_output_size: int = 10000)
|
||||
|
||||
Safely executes shell commands:
|
||||
- Timeout protection
|
||||
- Output capture
|
||||
- Error handling
|
||||
- Environment control
|
||||
- Working directory control
|
||||
|
||||
```python
|
||||
# Basic command execution
|
||||
result = execute_command("ls -la")
|
||||
|
||||
# Advanced execution
|
||||
result = execute_command(
|
||||
"python script.py",
|
||||
cwd="/path/to/scripts",
|
||||
timeout=60,
|
||||
env={"PYTHONPATH": "/custom/path"},
|
||||
shell=True
|
||||
)
|
||||
|
||||
# Returns: Dict[str, Union[str, int, bool]]
|
||||
# Example output:
|
||||
# {
|
||||
# 'stdout': 'command output...',
|
||||
# 'stderr': 'error output if any',
|
||||
# 'exit_code': 0,
|
||||
# 'success': True,
|
||||
# 'execution_time': 0.123
|
||||
# }
|
||||
```
|
||||
|
||||
### list_processes()
|
||||
|
||||
Lists running system processes:
|
||||
- Process details
|
||||
- Resource usage
|
||||
- User information
|
||||
- Performance metrics
|
||||
|
||||
```python
|
||||
# Get list of running processes
|
||||
processes = list_processes()
|
||||
|
||||
# Sort by CPU usage
|
||||
cpu_intensive = sorted(
|
||||
processes,
|
||||
key=lambda x: x['cpu_percent'],
|
||||
reverse=True
|
||||
)[:5]
|
||||
|
||||
# Returns: List[Dict[str, Union[int, str, float]]]
|
||||
# Example output:
|
||||
# [
|
||||
# {
|
||||
# 'pid': 1234,
|
||||
# 'name': 'python',
|
||||
# 'username': 'user',
|
||||
# 'memory_percent': 2.5,
|
||||
# 'cpu_percent': 15.3
|
||||
# },
|
||||
# ...
|
||||
# ]
|
||||
```
|
||||
|
||||
### kill_process(pid: int, force: bool = False)
|
||||
|
||||
Terminates system processes:
|
||||
- Graceful termination
|
||||
- Force kill option
|
||||
- Error handling
|
||||
- Access control
|
||||
|
||||
```python
|
||||
# Graceful termination
|
||||
result = kill_process(1234)
|
||||
|
||||
# Force kill
|
||||
result = kill_process(
|
||||
pid=1234,
|
||||
force=True # Use SIGKILL
|
||||
)
|
||||
|
||||
# Returns: Dict[str, Union[bool, str]]
|
||||
# Example output:
|
||||
# {
|
||||
# 'success': True,
|
||||
# 'message': 'Process 1234 killed successfully'
|
||||
# }
|
||||
# or
|
||||
# {
|
||||
# 'success': False,
|
||||
# 'message': 'Access denied to kill process 1234'
|
||||
# }
|
||||
```
|
||||
|
||||
### get_system_info()
|
||||
|
||||
Retrieves system information:
|
||||
- CPU statistics
|
||||
- Memory usage
|
||||
- Disk space
|
||||
- Platform details
|
||||
- Boot time
|
||||
|
||||
```python
|
||||
# Get system information
|
||||
info = get_system_info()
|
||||
|
||||
# Access specific metrics
|
||||
print(f"CPU Usage: {info['cpu']['percent']}%")
|
||||
print(f"Memory Free: {info['memory']['free']} bytes")
|
||||
|
||||
# Returns: Dict[str, Union[float, int, str, Dict]]
|
||||
# Example output:
|
||||
# {
|
||||
# 'cpu': {
|
||||
# 'percent': 45.2,
|
||||
# 'cores': 8,
|
||||
# 'physical_cores': 4
|
||||
# },
|
||||
# 'memory': {
|
||||
# 'total': 16000000000,
|
||||
# 'available': 8000000000,
|
||||
# 'percent': 50.0,
|
||||
# 'used': 8000000000,
|
||||
# 'free': 4000000000
|
||||
# },
|
||||
# 'disk': {
|
||||
# 'total': 500000000000,
|
||||
# 'used': 250000000000,
|
||||
# 'free': 250000000000,
|
||||
# 'percent': 50.0
|
||||
# },
|
||||
# 'boot_time': 1641544800,
|
||||
# 'platform': 'Darwin'
|
||||
# }
|
||||
```
|
||||
|
||||
## Example Agent Configuration
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import (
|
||||
execute_command, list_processes,
|
||||
kill_process, get_system_info
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
name="SystemManager",
|
||||
description="An agent that manages system processes and executes commands",
|
||||
tools=[
|
||||
execute_command, list_processes,
|
||||
kill_process, get_system_info
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
The shell tools require the following package:
|
||||
- psutil: For system and process information
|
||||
|
||||
This will be automatically installed when needed.
|
||||
|
||||
## Error Handling
|
||||
|
||||
All functions include comprehensive error handling:
|
||||
- Command execution errors
|
||||
- Process access errors
|
||||
- Permission errors
|
||||
- Timeout errors
|
||||
- Resource errors
|
||||
|
||||
Errors are handled consistently:
|
||||
- Success cases return expected data type
|
||||
- Error cases return error details in result
|
||||
- All errors are logged for debugging
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. System Monitoring:
|
||||
```python
|
||||
# Monitor system resources
|
||||
info = get_system_info()
|
||||
if info['cpu']['percent'] > 90:
|
||||
print("High CPU usage detected!")
|
||||
if info['memory']['percent'] > 80:
|
||||
print("Low memory warning!")
|
||||
|
||||
# List resource-intensive processes
|
||||
processes = sorted(
|
||||
list_processes(),
|
||||
key=lambda x: x['memory_percent'],
|
||||
reverse=True
|
||||
)[:5]
|
||||
print("Top memory users:", processes)
|
||||
```
|
||||
|
||||
2. Process Management:
|
||||
```python
|
||||
# Find and kill zombie processes
|
||||
for process in list_processes():
|
||||
if process['name'] == 'zombie_process':
|
||||
result = kill_process(
|
||||
process['pid'],
|
||||
force=True
|
||||
)
|
||||
print(f"Kill result: {result['message']}")
|
||||
```
|
||||
|
||||
3. Command Execution:
|
||||
```python
|
||||
# Run a series of maintenance commands
|
||||
commands = [
|
||||
"apt-get update",
|
||||
"apt-get upgrade -y",
|
||||
"apt-get autoremove -y"
|
||||
]
|
||||
for cmd in commands:
|
||||
result = execute_command(
|
||||
cmd,
|
||||
timeout=300,
|
||||
shell=True
|
||||
)
|
||||
if result['success']:
|
||||
print(f"Command succeeded: {cmd}")
|
||||
else:
|
||||
print(f"Command failed: {result['stderr']}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
<AccordionGroup>
|
||||
@@ -198,7 +437,7 @@ agents.start()
|
||||
name="ShellManager",
|
||||
role="Command Line Specialist",
|
||||
goal="Execute shell commands safely and efficiently",
|
||||
tools=[shell]
|
||||
tools=[execute_command, list_processes, kill_process, get_system_info]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,7 +461,7 @@ agents.start()
|
||||
commander = Agent(
|
||||
name="Commander",
|
||||
role="Shell Commander",
|
||||
tools=[shell]
|
||||
tools=[execute_command]
|
||||
)
|
||||
|
||||
# Monitor agent
|
||||
|
||||
+35
-34
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Spider Tools"
|
||||
description: "Web scraping and crawling tools for AI agents."
|
||||
title: "Spider Agent"
|
||||
description: "Web scraping tools for AI agents."
|
||||
icon: "spider"
|
||||
---
|
||||
|
||||
@@ -8,19 +8,18 @@ icon: "spider"
|
||||
**Prerequisites**
|
||||
- Python 3.10 or higher
|
||||
- PraisonAI Agents package installed
|
||||
- `beautifulsoup4` package installed
|
||||
- `requests` package installed
|
||||
- `scrapy` package installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Spider Tools
|
||||
|
||||
Use Spider Tools to scrape and crawl web content with AI agents.
|
||||
Use Spider Tools to crawl and scrape web content with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
First, install the required packages:
|
||||
```bash
|
||||
pip install praisonaiagents beautifulsoup4 requests
|
||||
pip install praisonaiagents scrapy
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -28,7 +27,7 @@ Use Spider Tools to scrape and crawl web content with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import spider
|
||||
from praisonaiagents.tools import scrape_page, extract_links, crawl, extract_text
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -40,7 +39,7 @@ Use Spider Tools to scrape and crawl web content with AI agents.
|
||||
role="Web Scraping Specialist",
|
||||
goal="Extract and analyze web content efficiently.",
|
||||
backstory="Expert in web scraping and content extraction.",
|
||||
tools=[spider],
|
||||
tools=[scrape_page, extract_links, crawl, extract_text],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -75,11 +74,11 @@ Use Spider Tools to scrape and crawl web content with AI agents.
|
||||
|
||||
<Card title="What are Spider Tools?" icon="question">
|
||||
Spider Tools provide web scraping capabilities for AI agents:
|
||||
- Web page scraping
|
||||
- Content extraction
|
||||
- Link crawling
|
||||
- HTML parsing
|
||||
- Data structuring
|
||||
- Page scraping and downloading
|
||||
- Content extraction and filtering
|
||||
- Link discovery and crawling
|
||||
- HTML parsing and cleaning
|
||||
- Data structuring and formatting
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
@@ -88,7 +87,7 @@ Use Spider Tools to scrape and crawl web content with AI agents.
|
||||
<Card title="Spider Agent" icon="user-robot">
|
||||
Create specialized scraping agents:
|
||||
```python
|
||||
Agent(tools=[spider])
|
||||
Agent(tools=[scrape_page, extract_content, crawl_links, parse_html, structure_data])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Spider Task" icon="list-check">
|
||||
@@ -117,30 +116,30 @@ Use Spider Tools to scrape and crawl web content with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import spider
|
||||
from praisonaiagents.tools import scrape_page, extract_links, crawl, extract_text
|
||||
|
||||
# Create scraping agent
|
||||
spider_agent = Agent(
|
||||
# Create search agent
|
||||
agent = Agent(
|
||||
name="WebCrawler",
|
||||
role="Web Scraping Specialist",
|
||||
goal="Extract web content efficiently and ethically.",
|
||||
backstory="Expert in web crawling and data extraction.",
|
||||
tools=[spider],
|
||||
goal="Extract and analyze web content efficiently.",
|
||||
backstory="Expert in web scraping and content extraction.",
|
||||
tools=[scrape_page, extract_links, crawl, extract_text],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Define scraping task
|
||||
scraping_task = Task(
|
||||
description="Extract article content from news websites.",
|
||||
expected_output="Structured article data with text and metadata.",
|
||||
agent=spider_agent,
|
||||
name="news_scraping"
|
||||
# Define task
|
||||
task = Task(
|
||||
description="Scrape and analyze the content from 'https://example.com'",
|
||||
expected_output="Extracted content with links and text analysis",
|
||||
agent=agent,
|
||||
name="web_scraping"
|
||||
)
|
||||
|
||||
# Run agent
|
||||
agents = PraisonAIAgents(
|
||||
agents=[spider_agent],
|
||||
tasks=[scraping_task],
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
@@ -154,7 +153,7 @@ scraper_agent = Agent(
|
||||
name="Scraper",
|
||||
role="Content Scraper",
|
||||
goal="Extract web content systematically.",
|
||||
tools=[spider],
|
||||
tools=[scrape_page, crawl_links, parse_html],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -164,6 +163,7 @@ analysis_agent = Agent(
|
||||
role="Content Analyst",
|
||||
goal="Analyze and structure scraped content.",
|
||||
backstory="Expert in data analysis and organization.",
|
||||
tools=[extract_content, structure_data],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -199,7 +199,7 @@ agents.start()
|
||||
name="WebScraper",
|
||||
role="Content Extraction Specialist",
|
||||
goal="Extract web content ethically and efficiently",
|
||||
tools=[spider]
|
||||
tools=[scrape_page, extract_content, crawl_links, parse_html, structure_data]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -223,13 +223,14 @@ agents.start()
|
||||
scraper = Agent(
|
||||
name="Scraper",
|
||||
role="Web Scraper",
|
||||
tools=[spider]
|
||||
tools=[scrape_page, crawl_links, parse_html]
|
||||
)
|
||||
|
||||
# Processing agent
|
||||
processor = Agent(
|
||||
name="Processor",
|
||||
role="Data Processor"
|
||||
role="Data Processor",
|
||||
tools=[extract_content, structure_data]
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
@@ -247,4 +248,4 @@ process_task = Task(
|
||||
agents = PraisonAIAgents(
|
||||
agents=[scraper, processor],
|
||||
tasks=[scrape_task, process_task]
|
||||
)
|
||||
)
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "Wikipedia Tools"
|
||||
title: "Wikipedia Agent"
|
||||
description: "Wikipedia data retrieval tools for AI agents."
|
||||
icon: "book"
|
||||
---
|
||||
@@ -12,7 +12,7 @@ icon: "book"
|
||||
- Basic understanding of Wikipedia APIs
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## Wikipedia Tools
|
||||
|
||||
Use Wikipedia Tools to retrieve and analyze Wikipedia content with AI agents.
|
||||
|
||||
@@ -28,7 +28,7 @@ Use Wikipedia Tools to retrieve and analyze Wikipedia content with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import wikipedia
|
||||
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -40,7 +40,7 @@ Use Wikipedia Tools to retrieve and analyze Wikipedia content with AI agents.
|
||||
role="Wikipedia Research Specialist",
|
||||
goal="Research and analyze Wikipedia content efficiently.",
|
||||
backstory="Expert in information retrieval and content analysis.",
|
||||
tools=[wikipedia],
|
||||
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -75,11 +75,11 @@ Use Wikipedia Tools to retrieve and analyze Wikipedia content with AI agents.
|
||||
|
||||
<Card title="What are Wikipedia Tools?" icon="question">
|
||||
Wikipedia Tools provide research capabilities for AI agents:
|
||||
- Article retrieval
|
||||
- Content search
|
||||
- Information extraction
|
||||
- Summary generation
|
||||
- Reference collection
|
||||
- Article search and retrieval
|
||||
- Content summary generation
|
||||
- Full page information access
|
||||
- Random article discovery
|
||||
- Multi-language support
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
@@ -88,7 +88,7 @@ Use Wikipedia Tools to retrieve and analyze Wikipedia content with AI agents.
|
||||
<Card title="Wiki Agent" icon="user-robot">
|
||||
Create specialized research agents:
|
||||
```python
|
||||
Agent(tools=[wikipedia])
|
||||
Agent(tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Wiki Task" icon="list-check">
|
||||
@@ -117,7 +117,7 @@ Use Wikipedia Tools to retrieve and analyze Wikipedia content with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import wikipedia
|
||||
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language
|
||||
|
||||
# Create Wikipedia agent
|
||||
wiki_agent = Agent(
|
||||
@@ -125,7 +125,7 @@ wiki_agent = Agent(
|
||||
role="Research Specialist",
|
||||
goal="Research topics efficiently and accurately.",
|
||||
backstory="Expert in information gathering and analysis.",
|
||||
tools=[wikipedia],
|
||||
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -144,6 +144,7 @@ agents = PraisonAIAgents(
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
|
||||
```
|
||||
|
||||
### Advanced Research with Multiple Agents
|
||||
@@ -154,7 +155,7 @@ researcher_agent = Agent(
|
||||
name="Researcher",
|
||||
role="Content Researcher",
|
||||
goal="Research topics systematically.",
|
||||
tools=[wikipedia],
|
||||
tools=[wiki_search, wiki_summary, wiki_page],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -164,6 +165,7 @@ analysis_agent = Agent(
|
||||
role="Content Analyst",
|
||||
goal="Analyze and summarize research findings.",
|
||||
backstory="Expert in content analysis and synthesis.",
|
||||
tools=[wiki_summary, wiki_page],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -199,7 +201,7 @@ agents.start()
|
||||
name="WikiResearcher",
|
||||
role="Research Specialist",
|
||||
goal="Research topics accurately and efficiently",
|
||||
tools=[wikipedia]
|
||||
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -223,13 +225,14 @@ agents.start()
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Wiki Researcher",
|
||||
tools=[wikipedia]
|
||||
tools=[wiki_search, wiki_summary, wiki_page]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
analyzer = Agent(
|
||||
name="Analyzer",
|
||||
role="Content Analyzer"
|
||||
role="Content Analyzer",
|
||||
tools=[wiki_summary, wiki_page]
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
@@ -247,4 +250,4 @@ analyze_task = Task(
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, analyzer],
|
||||
tasks=[research_task, analyze_task]
|
||||
)
|
||||
)
|
||||
+21
-19
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "XML Tools"
|
||||
description: "XML file processing tools for AI agents."
|
||||
title: "XML Agent"
|
||||
description: "XML data processing tools for AI agents."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
@@ -8,12 +8,12 @@ icon: "code"
|
||||
**Prerequisites**
|
||||
- Python 3.10 or higher
|
||||
- PraisonAI Agents package installed
|
||||
- Basic understanding of XML format
|
||||
- `lxml` package installed
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## XML Tools
|
||||
|
||||
Use XML Tools to process and manipulate XML files with AI agents.
|
||||
Use XML Tools to read, write, and manipulate XML data with AI agents.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
@@ -27,7 +27,7 @@ Use XML Tools to process and manipulate XML files with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import xml
|
||||
from praisonaiagents.tools import read_xml, write_xml, transform_xml, validate_xml, xml_to_dict, dict_to_xml
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -39,7 +39,7 @@ Use XML Tools to process and manipulate XML files with AI agents.
|
||||
role="XML Processing Specialist",
|
||||
goal="Process XML files efficiently and accurately.",
|
||||
backstory="Expert in XML file manipulation and validation.",
|
||||
tools=[xml],
|
||||
tools=[read_xml, write_xml, transform_xml, validate_xml, xml_to_dict, dict_to_xml],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -74,11 +74,11 @@ Use XML Tools to process and manipulate XML files with AI agents.
|
||||
|
||||
<Card title="What are XML Tools?" icon="question">
|
||||
XML Tools provide XML processing capabilities for AI agents:
|
||||
- XML parsing
|
||||
- File validation
|
||||
- Data extraction
|
||||
- XML parsing and reading
|
||||
- File writing and validation
|
||||
- Data transformation
|
||||
- Dictionary conversion
|
||||
- Structure manipulation
|
||||
- Format conversion
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
@@ -87,7 +87,7 @@ Use XML Tools to process and manipulate XML files with AI agents.
|
||||
<Card title="XML Agent" icon="user-robot">
|
||||
Create specialized XML agents:
|
||||
```python
|
||||
Agent(tools=[xml])
|
||||
Agent(tools=[read_xml, write_xml, transform_xml, validate_xml, xml_to_dict, dict_to_xml])
|
||||
```
|
||||
</Card>
|
||||
<Card title="XML Task" icon="list-check">
|
||||
@@ -116,7 +116,7 @@ Use XML Tools to process and manipulate XML files with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import xml
|
||||
from praisonaiagents.tools import read_xml, write_xml, transform_xml, validate_xml, xml_to_dict, dict_to_xml
|
||||
|
||||
# Create XML agent
|
||||
xml_agent = Agent(
|
||||
@@ -124,7 +124,7 @@ xml_agent = Agent(
|
||||
role="XML Processing Specialist",
|
||||
goal="Process XML files efficiently and accurately.",
|
||||
backstory="Expert in XML file handling and validation.",
|
||||
tools=[xml],
|
||||
tools=[read_xml, write_xml, transform_xml, validate_xml, xml_to_dict, dict_to_xml],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -153,7 +153,7 @@ processor_agent = Agent(
|
||||
name="Processor",
|
||||
role="XML Processor",
|
||||
goal="Process XML files systematically.",
|
||||
tools=[xml],
|
||||
tools=[read_xml, write_xml, transform_xml],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -163,6 +163,7 @@ validator_agent = Agent(
|
||||
role="Data Validator",
|
||||
goal="Validate XML structure and content.",
|
||||
backstory="Expert in data validation and verification.",
|
||||
tools=[validate_xml, xml_to_dict, dict_to_xml],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -198,7 +199,7 @@ agents.start()
|
||||
name="XMLProcessor",
|
||||
role="XML Processing Specialist",
|
||||
goal="Process XML files accurately and safely",
|
||||
tools=[xml]
|
||||
tools=[read_xml, write_xml, transform_xml, validate_xml, xml_to_dict, dict_to_xml]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -222,13 +223,14 @@ agents.start()
|
||||
processor = Agent(
|
||||
name="Processor",
|
||||
role="XML Processor",
|
||||
tools=[xml]
|
||||
tools=[read_xml, write_xml, transform_xml]
|
||||
)
|
||||
|
||||
# Validation agent
|
||||
validator = Agent(
|
||||
name="Validator",
|
||||
role="Data Validator"
|
||||
role="Data Validator",
|
||||
tools=[validate_xml, xml_to_dict, dict_to_xml]
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
@@ -246,4 +248,4 @@ validate_task = Task(
|
||||
agents = PraisonAIAgents(
|
||||
agents=[processor, validator],
|
||||
tasks=[process_task, validate_task]
|
||||
)
|
||||
)
|
||||
+21
-19
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "YAML Tools"
|
||||
description: "YAML file processing tools for AI agents."
|
||||
icon: "file-code"
|
||||
title: "YAML Agent"
|
||||
description: "YAML data processing tools for AI agents."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
<Note>
|
||||
@@ -12,7 +12,7 @@ icon: "file-code"
|
||||
- Basic understanding of YAML format
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## YAML Tools
|
||||
|
||||
Use YAML Tools to process and manipulate YAML files with AI agents.
|
||||
|
||||
@@ -28,7 +28,7 @@ Use YAML Tools to process and manipulate YAML files with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import yaml
|
||||
from praisonaiagents.tools import read_yaml, write_yaml, validate_yaml, merge_yaml, convert_yaml
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -40,7 +40,7 @@ Use YAML Tools to process and manipulate YAML files with AI agents.
|
||||
role="YAML Processing Specialist",
|
||||
goal="Process YAML files efficiently and accurately.",
|
||||
backstory="Expert in YAML file manipulation and validation.",
|
||||
tools=[yaml],
|
||||
tools=[read_yaml, write_yaml, validate_yaml, merge_yaml, convert_yaml],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -75,11 +75,11 @@ Use YAML Tools to process and manipulate YAML files with AI agents.
|
||||
|
||||
<Card title="What are YAML Tools?" icon="question">
|
||||
YAML Tools provide YAML processing capabilities for AI agents:
|
||||
- YAML parsing
|
||||
- File validation
|
||||
- Data extraction
|
||||
- Structure manipulation
|
||||
- Format conversion
|
||||
- Reading YAML files
|
||||
- Writing YAML data
|
||||
- Validating YAML structure
|
||||
- Merging YAML files
|
||||
- Converting between formats
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
@@ -88,7 +88,7 @@ Use YAML Tools to process and manipulate YAML files with AI agents.
|
||||
<Card title="YAML Agent" icon="user-robot">
|
||||
Create specialized YAML agents:
|
||||
```python
|
||||
Agent(tools=[yaml])
|
||||
Agent(tools=[read_yaml, write_yaml, validate_yaml, merge_yaml, convert_yaml])
|
||||
```
|
||||
</Card>
|
||||
<Card title="YAML Task" icon="list-check">
|
||||
@@ -117,7 +117,7 @@ Use YAML Tools to process and manipulate YAML files with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import yaml
|
||||
from praisonaiagents.tools import read_yaml, write_yaml, validate_yaml, merge_yaml, convert_yaml
|
||||
|
||||
# Create YAML agent
|
||||
yaml_agent = Agent(
|
||||
@@ -125,7 +125,7 @@ yaml_agent = Agent(
|
||||
role="YAML Processing Specialist",
|
||||
goal="Process YAML files efficiently and accurately.",
|
||||
backstory="Expert in YAML file handling and validation.",
|
||||
tools=[yaml],
|
||||
tools=[read_yaml, write_yaml, validate_yaml, merge_yaml, convert_yaml],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -154,7 +154,7 @@ processor_agent = Agent(
|
||||
name="Processor",
|
||||
role="YAML Processor",
|
||||
goal="Process YAML files systematically.",
|
||||
tools=[yaml],
|
||||
tools=[read_yaml, write_yaml, convert_yaml],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -164,6 +164,7 @@ validator_agent = Agent(
|
||||
role="Data Validator",
|
||||
goal="Validate YAML structure and content.",
|
||||
backstory="Expert in data validation and verification.",
|
||||
tools=[validate_yaml, merge_yaml],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -199,7 +200,7 @@ agents.start()
|
||||
name="YAMLProcessor",
|
||||
role="YAML Processing Specialist",
|
||||
goal="Process YAML files accurately and safely",
|
||||
tools=[yaml]
|
||||
tools=[read_yaml, write_yaml, validate_yaml, merge_yaml, convert_yaml]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -223,13 +224,14 @@ agents.start()
|
||||
processor = Agent(
|
||||
name="Processor",
|
||||
role="YAML Processor",
|
||||
tools=[yaml]
|
||||
tools=[read_yaml, write_yaml, convert_yaml]
|
||||
)
|
||||
|
||||
# Validation agent
|
||||
validator = Agent(
|
||||
name="Validator",
|
||||
role="Data Validator"
|
||||
role="Data Validator",
|
||||
tools=[validate_yaml, merge_yaml]
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
@@ -247,4 +249,4 @@ validate_task = Task(
|
||||
agents = PraisonAIAgents(
|
||||
agents=[processor, validator],
|
||||
tasks=[process_task, validate_task]
|
||||
)
|
||||
)
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "YFinance Tools"
|
||||
title: "YFinance Agent"
|
||||
description: "Yahoo Finance data retrieval tools for AI agents."
|
||||
icon: "chart-line"
|
||||
---
|
||||
@@ -12,7 +12,7 @@ icon: "chart-line"
|
||||
- Basic understanding of financial data
|
||||
</Note>
|
||||
|
||||
## Quick Start
|
||||
## YFinance Tools
|
||||
|
||||
Use YFinance Tools to retrieve and analyze financial data with AI agents.
|
||||
|
||||
@@ -28,7 +28,7 @@ Use YFinance Tools to retrieve and analyze financial data with AI agents.
|
||||
Import the necessary components:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import yfinance
|
||||
from praisonaiagents.tools import get_stock_price, get_stock_info, get_historical_data
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -40,7 +40,7 @@ Use YFinance Tools to retrieve and analyze financial data with AI agents.
|
||||
role="Financial Data Specialist",
|
||||
goal="Retrieve and analyze financial data efficiently.",
|
||||
backstory="Expert in financial data analysis and market research.",
|
||||
tools=[yfinance],
|
||||
tools=[get_stock_price, get_stock_info, get_historical_data],
|
||||
self_reflect=False
|
||||
)
|
||||
```
|
||||
@@ -75,11 +75,11 @@ Use YFinance Tools to retrieve and analyze financial data with AI agents.
|
||||
|
||||
<Card title="What are YFinance Tools?" icon="question">
|
||||
YFinance Tools provide financial data capabilities for AI agents:
|
||||
- Stock data retrieval
|
||||
- Market analysis
|
||||
- Historical data
|
||||
- Company information
|
||||
- Financial metrics
|
||||
- Real-time stock prices
|
||||
- Detailed company information
|
||||
- Historical market data
|
||||
- Financial metrics and ratios
|
||||
- Market performance analysis
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
@@ -88,7 +88,7 @@ Use YFinance Tools to retrieve and analyze financial data with AI agents.
|
||||
<Card title="Finance Agent" icon="user-robot">
|
||||
Create specialized finance agents:
|
||||
```python
|
||||
Agent(tools=[yfinance])
|
||||
Agent(tools=[get_stock_price, get_stock_info, get_historical_data])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Finance Task" icon="list-check">
|
||||
@@ -117,7 +117,7 @@ Use YFinance Tools to retrieve and analyze financial data with AI agents.
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import yfinance
|
||||
from praisonaiagents.tools import get_stock_price, get_stock_info, get_historical_data
|
||||
|
||||
# Create finance agent
|
||||
finance_agent = Agent(
|
||||
@@ -125,7 +125,7 @@ finance_agent = Agent(
|
||||
role="Financial Data Specialist",
|
||||
goal="Analyze market data efficiently and accurately.",
|
||||
backstory="Expert in financial analysis and market research.",
|
||||
tools=[yfinance],
|
||||
tools=[get_stock_price, get_stock_info, get_historical_data],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -154,7 +154,7 @@ data_agent = Agent(
|
||||
name="DataCollector",
|
||||
role="Market Data Collector",
|
||||
goal="Retrieve financial data systematically.",
|
||||
tools=[yfinance],
|
||||
tools=[get_stock_price, get_historical_data],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -164,6 +164,7 @@ analysis_agent = Agent(
|
||||
role="Market Analyst",
|
||||
goal="Analyze market trends and patterns.",
|
||||
backstory="Expert in financial market analysis.",
|
||||
tools=[get_stock_info],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
@@ -199,7 +200,7 @@ agents.start()
|
||||
name="FinanceAnalyst",
|
||||
role="Market Analysis Specialist",
|
||||
goal="Analyze financial data accurately and efficiently",
|
||||
tools=[yfinance]
|
||||
tools=[get_stock_price, get_stock_info, get_historical_data]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
@@ -223,13 +224,14 @@ agents.start()
|
||||
collector = Agent(
|
||||
name="Collector",
|
||||
role="Data Collector",
|
||||
tools=[yfinance]
|
||||
tools=[get_stock_price, get_historical_data]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
analyst = Agent(
|
||||
name="Analyst",
|
||||
role="Market Analyst"
|
||||
role="Market Analyst",
|
||||
tools=[get_stock_info]
|
||||
)
|
||||
|
||||
# Define tasks
|
||||
@@ -247,4 +249,4 @@ analyze_task = Task(
|
||||
agents = PraisonAIAgents(
|
||||
agents=[collector, analyst],
|
||||
tasks=[collect_task, analyze_task]
|
||||
)
|
||||
)
|
||||
Generated
-8837
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -3,7 +3,7 @@ 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/2.0.33.tar.gz"
|
||||
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/2.0.37.tar.gz"
|
||||
sha256 "1828fb9227d10f991522c3f24f061943a254b667196b40b1a3e4a54a8d30ce32" # Replace with actual SHA256 checksum
|
||||
license "MIT"
|
||||
|
||||
|
||||
+1
-1
@@ -56,7 +56,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==2.0.33 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.37 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "PraisonAI"
|
||||
version = "2.0.33"
|
||||
version = "2.0.37"
|
||||
description = "PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human–agent collaboration."
|
||||
readme = "README.md"
|
||||
license = ""
|
||||
@@ -12,7 +12,7 @@ dependencies = [
|
||||
"rich>=13.7",
|
||||
"markdown>=3.5",
|
||||
"pyparsing>=3.0.0",
|
||||
"praisonaiagents>=0.0.24",
|
||||
"praisonaiagents>=0.0.28",
|
||||
"python-dotenv>=0.19.0",
|
||||
"instructor>=1.3.3",
|
||||
"PyYAML>=6.0",
|
||||
@@ -84,7 +84,7 @@ autogen = ["pyautogen>=0.2.19", "praisonai-tools>=0.0.7", "crewai"]
|
||||
|
||||
[tool.poetry]
|
||||
name = "PraisonAI"
|
||||
version = "2.0.33"
|
||||
version = "2.0.37"
|
||||
description = "PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human–agent collaboration."
|
||||
authors = ["Mervin Praison"]
|
||||
license = ""
|
||||
@@ -102,7 +102,7 @@ python = ">=3.10,<3.13"
|
||||
rich = ">=13.7"
|
||||
markdown = ">=3.5"
|
||||
pyparsing = ">=3.0.0"
|
||||
praisonaiagents = ">=0.0.24"
|
||||
praisonaiagents = ">=0.0.28"
|
||||
python-dotenv = ">=0.19.0"
|
||||
instructor = ">=1.3.3"
|
||||
PyYAML = ">=6.0"
|
||||
|
||||
@@ -3061,7 +3061,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonai"
|
||||
version = "2.0.33"
|
||||
version = "2.0.37"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "instructor" },
|
||||
@@ -3198,7 +3198,7 @@ requires-dist = [
|
||||
{ name = "plotly", marker = "extra == 'realtime'", specifier = ">=5.24.0" },
|
||||
{ name = "praisonai-tools", marker = "extra == 'autogen'", specifier = ">=0.0.7" },
|
||||
{ name = "praisonai-tools", marker = "extra == 'crewai'", specifier = ">=0.0.7" },
|
||||
{ name = "praisonaiagents", specifier = ">=0.0.23" },
|
||||
{ name = "praisonaiagents", specifier = ">=0.0.28" },
|
||||
{ name = "pyautogen", marker = "extra == 'autogen'", specifier = ">=0.2.19" },
|
||||
{ name = "pydantic", marker = "extra == 'chat'", specifier = "<=2.10.1" },
|
||||
{ name = "pydantic", marker = "extra == 'code'", specifier = "<=2.10.1" },
|
||||
@@ -3251,16 +3251,16 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.23"
|
||||
version = "0.0.28"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "openai" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "rich" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a8/87/08ff2ac7c365251fa07973fded3e68c2edc1173d8514e6fd90fc8ee7b131/praisonaiagents-0.0.23.tar.gz", hash = "sha256:1814d537b2625a5c7d4b61d07f5d5bd043f0ad8afc31fe9d4eb99a5ca54101bf", size = 25375 }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/18/8d/f65e7df81b2f14a14cce47164dc4e7431f56f84a3a14ac4cd8adde97b86a/praisonaiagents-0.0.28.tar.gz", hash = "sha256:e736c970023d5e92a9080f5f9e8a6a6c30d00bc0d5e94d9feb6c903240068d45", size = 64693 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/56/75/c3a1cf2adaf0811ab538029054fa993e82caffba2853546f41766b7e0aab/praisonaiagents-0.0.23-py3-none-any.whl", hash = "sha256:d6aaa406fc993ccd0a763aa426b7139c955e1cd99e6b204b06817ebc1a5855e3", size = 31734 },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/db/35663967eb53be8c60ceb3f128bd45be33321f31dff7ba29757c3870bf35/praisonaiagents-0.0.28-py3-none-any.whl", hash = "sha256:4274cfbe1cb20cc8d541e00bb2d9cebc310f86f03a68a6e02090f54b2c29e508", size = 84483 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in new issue
Block a user