mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-08 01:08:39 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f49ad9fbc2 | ||
|
|
c086c60fd6 | ||
|
|
4f8f4f2036 | ||
|
|
8e91c20967 | ||
|
|
6f092c1507 | ||
|
|
8f553d3a54 | ||
|
|
2d647e25b5 | ||
|
|
039bb772f5 | ||
|
|
459c2f2b70 | ||
|
|
ee59706357 | ||
|
|
2a51644773 | ||
|
|
cce908fa22 | ||
|
|
acf476f715 | ||
|
|
e5d77de79c | ||
|
|
9ab444b54c |
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.47 gunicorn markdown
|
||||
RUN pip install flask praisonai==2.0.50 gunicorn markdown
|
||||
EXPOSE 8080
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
|
||||
@@ -0,0 +1,53 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
|
||||
class CVAnalysisReport(BaseModel):
|
||||
overall_score: int
|
||||
key_strengths: List[str]
|
||||
areas_for_improvement: List[str]
|
||||
market_fit: str
|
||||
recommendations: List[str]
|
||||
technical_skills: List[str]
|
||||
soft_skills: List[str]
|
||||
skill_gaps: List[str]
|
||||
key_achievements: List[str]
|
||||
impact_metrics: List[Dict[str, str]]
|
||||
areas_of_expertise: List[str]
|
||||
|
||||
# Create single CV analysis agent
|
||||
cv_analyzer = Agent(
|
||||
role="CV Analysis Expert",
|
||||
goal="Provide comprehensive CV evaluation and recommendations",
|
||||
backstory="""You are an expert CV analyst with deep knowledge of industry requirements,
|
||||
market trends, and talent assessment. You excel at evaluating skills, experience,
|
||||
and providing actionable recommendations.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Single comprehensive analysis task
|
||||
cv_analysis_task = Task(
|
||||
description="""Analyze the CV comprehensively including:
|
||||
1. Technical and soft skills assessment
|
||||
2. Experience and achievements evaluation
|
||||
3. Overall CV evaluation with recommendations
|
||||
Provide detailed insights and actionable recommendations.""",
|
||||
expected_output="Complete CV analysis report",
|
||||
agent=cv_analyzer,
|
||||
output_pydantic=CVAnalysisReport
|
||||
)
|
||||
|
||||
# Create and run the agent
|
||||
agents = PraisonAIAgents(
|
||||
agents=[cv_analyzer],
|
||||
tasks=[cv_analysis_task]
|
||||
)
|
||||
|
||||
# Read and pass CV content through start()
|
||||
with open('cv.txt', 'r') as file:
|
||||
cv_content = file.read()
|
||||
|
||||
# Start the analysis by passing CV content
|
||||
result = agents.start(cv_content)
|
||||
|
||||
print(result)
|
||||
@@ -0,0 +1,61 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
|
||||
class CVAnalysisReport(BaseModel):
|
||||
overall_score: int
|
||||
key_strengths: List[str]
|
||||
areas_for_improvement: List[str]
|
||||
market_fit: str
|
||||
recommendations: List[str]
|
||||
technical_skills: List[str]
|
||||
soft_skills: List[str]
|
||||
skill_gaps: List[str]
|
||||
key_achievements: List[str]
|
||||
impact_metrics: List[Dict[str, str]]
|
||||
areas_of_expertise: List[str]
|
||||
|
||||
# Create single CV analysis agent
|
||||
cv_analyzer = Agent(
|
||||
role="CV Analysis Expert",
|
||||
goal="Provide comprehensive CV evaluation and recommendations",
|
||||
backstory="""You are an expert CV analyst with deep knowledge of industry requirements,
|
||||
market trends, and talent assessment. You excel at evaluating skills, experience,
|
||||
and providing actionable recommendations.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Read CV content first
|
||||
with open('cv.txt', 'r') as file:
|
||||
cv_content = file.read()
|
||||
|
||||
cv_key_strengths = Task(
|
||||
description="List the key strengths to look",
|
||||
expected_output="List of key strengths",
|
||||
agent=cv_analyzer,
|
||||
)
|
||||
|
||||
# Single comprehensive analysis task with CV content in context
|
||||
cv_analysis_task = Task(
|
||||
description="""Analyze the CV comprehensively including:
|
||||
1. Technical and soft skills assessment
|
||||
2. Experience and achievements evaluation
|
||||
3. Overall CV evaluation with recommendations
|
||||
Provide detailed insights and actionable recommendations.""",
|
||||
expected_output="Complete CV analysis report",
|
||||
agent=cv_analyzer,
|
||||
output_pydantic=CVAnalysisReport,
|
||||
context=[cv_content, cv_key_strengths] # Pass CV content directly in task context
|
||||
)
|
||||
|
||||
# Create and run the agent
|
||||
agents = PraisonAIAgents(
|
||||
agents=[cv_analyzer],
|
||||
tasks=[cv_key_strengths,cv_analysis_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Start the analysis - no need to pass content again since it's in task context
|
||||
result = agents.start()
|
||||
|
||||
print(result)
|
||||
@@ -0,0 +1,27 @@
|
||||
# example tools.py
|
||||
from duckduckgo_search import DDGS
|
||||
from praisonai_tools import BaseTool
|
||||
|
||||
class InternetSearchTool(BaseTool):
|
||||
name: str = "InternetSearchTool"
|
||||
description: str = "Search Internet for relevant information based on a query or latest news"
|
||||
|
||||
def _run(self, query: str):
|
||||
ddgs = DDGS()
|
||||
results = ddgs.text(keywords=query, region='wt-wt', safesearch='moderate', max_results=5)
|
||||
return results
|
||||
|
||||
# Example agent
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents import PraisonAIAgents
|
||||
agent = Agent(
|
||||
name="Internet Search Agent",
|
||||
tools=[InternetSearchTool],
|
||||
instructions="""
|
||||
You are an agent that can search the internet for relevant information based on a query or latest news.
|
||||
"""
|
||||
)
|
||||
|
||||
# Run the agent
|
||||
result = PraisonAIAgents(agents=[agent], verbose=10).start()
|
||||
print(result)
|
||||
@@ -0,0 +1,57 @@
|
||||
Name: Alex Johnson
|
||||
Location: London, UK
|
||||
|
||||
Professional Summary
|
||||
Dynamic and results-oriented leader with a proven track record of driving innovation, scaling operations, and achieving transformational growth. Over 15 years of experience in engineering, strategic management, and executive leadership in the automotive and renewable energy sectors. Passionate about sustainable technologies and visionary leadership.
|
||||
|
||||
Professional Experience
|
||||
Chief Operating Officer (COO)
|
||||
NextGen Mobility Ltd. | Palo Alto, CA | 2020 – Present
|
||||
|
||||
Spearheaded global operations for an electric vehicle company, scaling production by 200% in three years.
|
||||
Introduced automation-driven supply chain strategies, reducing costs by 15%.
|
||||
Collaborated with R&D to launch three new EV models, driving 25% revenue growth annually.
|
||||
Vice President of Engineering
|
||||
ElectroDrive Systems | San Francisco, CA | 2015 – 2020
|
||||
|
||||
Led a team of 500+ engineers in developing next-generation EV batteries, achieving a 30% increase in energy efficiency.
|
||||
Secured $50M in government funding for sustainable energy innovation.
|
||||
Drove cross-functional collaboration, aligning product development with market needs.
|
||||
Director of Renewable Energy Initiatives
|
||||
GreenTech Innovations | London, UK | 2011 – 2015
|
||||
|
||||
Oversaw £100M projects in solar and wind energy deployment across Europe.
|
||||
Established partnerships with policymakers to influence renewable energy legislation.
|
||||
Pioneered a smart energy grid system, enhancing energy distribution efficiency by 40%.
|
||||
Senior Project Manager
|
||||
Innovate Auto Ltd. | Munich, Germany | 2008 – 2011
|
||||
|
||||
Managed R&D projects for autonomous driving technologies.
|
||||
Delivered projects 20% under budget through strategic resource allocation.
|
||||
Filed 10+ patents in automotive AI and renewable integration.
|
||||
Mechanical Engineer
|
||||
AutoFusion Technologies | Berlin, Germany | 2005 – 2008
|
||||
|
||||
Designed core systems for EV powertrains, optimising energy consumption by 15%.
|
||||
Collaborated with suppliers to improve material efficiency, cutting costs by £5M annually.
|
||||
Education
|
||||
MBA in Strategic Management
|
||||
Harvard Business School | Cambridge, MA | 2015
|
||||
|
||||
MSc in Renewable Energy Engineering
|
||||
Imperial College London | London, UK | 2007
|
||||
|
||||
BSc in Mechanical Engineering
|
||||
Technical University of Munich | Munich, Germany | 2005
|
||||
|
||||
Skills
|
||||
Strategic Leadership & Visionary Thinking
|
||||
Electric Vehicle Engineering
|
||||
Renewable Energy Systems
|
||||
Global Operations Management
|
||||
Policy Advocacy & Government Relations
|
||||
Supply Chain Optimisation
|
||||
Achievements
|
||||
Featured in Forbes 30 Under 40 for innovations in EV technology.
|
||||
Author of The Future of Sustainable Mobility.
|
||||
Keynote speaker at World Energy Summit, 2023.
|
||||
@@ -13,7 +13,7 @@ config = {
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"],
|
||||
knowledge=["large.pdf"],
|
||||
knowledge_config=config
|
||||
)
|
||||
|
||||
|
||||
@@ -71,10 +71,15 @@ class Agent:
|
||||
|
||||
import inspect
|
||||
# Langchain tools
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
if inspect.isclass(func) and hasattr(func, 'run') and not hasattr(func, '_run'):
|
||||
original_func = func
|
||||
func = func.run
|
||||
function_name = original_func.__name__
|
||||
# CrewAI tools
|
||||
elif 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}")
|
||||
@@ -313,14 +318,22 @@ Your Goal: {self.goal}
|
||||
|
||||
if func:
|
||||
try:
|
||||
# If it's a class with run method, instantiate and call run
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
# Langchain: If it's a class with run but not _run, instantiate and call run
|
||||
if inspect.isclass(func) and hasattr(func, 'run') and not 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'}
|
||||
if k in inspect.signature(instance.run).parameters
|
||||
and k != 'self'}
|
||||
return instance.run(**run_params)
|
||||
|
||||
# CrewAI: If it's a class with an _run method, instantiate and call _run
|
||||
elif inspect.isclass(func) and hasattr(func, '_run'):
|
||||
instance = func()
|
||||
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)
|
||||
@@ -472,9 +485,9 @@ Your Role: {self.role}\n
|
||||
Your Goal: {self.goal}
|
||||
"""
|
||||
if output_json:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_json.model_json_schema())}"
|
||||
elif output_pydantic:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_pydantic.model_json_schema())}"
|
||||
else:
|
||||
system_prompt = None
|
||||
|
||||
@@ -664,9 +677,9 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
# Build system prompt
|
||||
system_prompt = self.system_prompt
|
||||
if output_json:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_json.model_json_schema())}"
|
||||
elif output_pydantic:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_pydantic.model_json_schema())}"
|
||||
|
||||
# Build messages
|
||||
if isinstance(prompt, str):
|
||||
|
||||
@@ -229,15 +229,28 @@ You need to do the following task: {task.description}.
|
||||
Expected Output: {task.expected_output}.
|
||||
"""
|
||||
if task.context:
|
||||
context_results = ""
|
||||
for context_task in task.context:
|
||||
if context_task.result:
|
||||
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
|
||||
else:
|
||||
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
|
||||
context_results = [] # Use list to avoid duplicates
|
||||
for context_item in task.context:
|
||||
if isinstance(context_item, str):
|
||||
context_results.append(f"Input Content:\n{context_item}")
|
||||
elif isinstance(context_item, list):
|
||||
context_results.append(f"Input Content: {' '.join(str(x) for x in context_item)}")
|
||||
elif hasattr(context_item, 'result'): # Task object
|
||||
if context_item.result:
|
||||
context_results.append(
|
||||
f"Result of previous task {context_item.name if context_item.name else context_item.description}:\n{context_item.result.raw}"
|
||||
)
|
||||
else:
|
||||
context_results.append(
|
||||
f"Previous task {context_item.name if context_item.name else context_item.description} has no result yet."
|
||||
)
|
||||
|
||||
# Join unique context results
|
||||
unique_contexts = list(dict.fromkeys(context_results)) # Remove duplicates
|
||||
task_prompt += f"""
|
||||
Here are the results of previous tasks that might be useful:\n
|
||||
{context_results}
|
||||
Context:
|
||||
|
||||
{' '.join(unique_contexts)}
|
||||
"""
|
||||
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
|
||||
|
||||
@@ -427,8 +440,16 @@ Here are the results of previous tasks that might be useful:\n
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
|
||||
async def astart(self):
|
||||
async def astart(self, content=None, **kwargs):
|
||||
"""Async version of start method"""
|
||||
if content:
|
||||
# Add content to context of all tasks
|
||||
for task in self.tasks.values():
|
||||
if isinstance(content, (str, list)):
|
||||
if not task.context:
|
||||
task.context = []
|
||||
task.context.append(content)
|
||||
|
||||
await self.arun_all_tasks()
|
||||
return {
|
||||
"task_status": self.get_all_tasks_status(),
|
||||
@@ -485,16 +506,30 @@ You need to do the following task: {task.description}.
|
||||
Expected Output: {task.expected_output}.
|
||||
"""
|
||||
if task.context:
|
||||
context_results = ""
|
||||
for context_task in task.context:
|
||||
if context_task.result:
|
||||
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
|
||||
else:
|
||||
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
|
||||
context_results = [] # Use list to avoid duplicates
|
||||
for context_item in task.context:
|
||||
if isinstance(context_item, str):
|
||||
context_results.append(f"Input Content:\n{context_item}")
|
||||
elif isinstance(context_item, list):
|
||||
context_results.append(f"Input Content: {' '.join(str(x) for x in context_item)}")
|
||||
elif hasattr(context_item, 'result'): # Task object
|
||||
if context_item.result:
|
||||
context_results.append(
|
||||
f"Result of previous task {context_item.name if context_item.name else context_item.description}:\n{context_item.result.raw}"
|
||||
)
|
||||
else:
|
||||
context_results.append(
|
||||
f"Previous task {context_item.name if context_item.name else context_item.description} has no result yet."
|
||||
)
|
||||
|
||||
# Join unique context results
|
||||
unique_contexts = list(dict.fromkeys(context_results)) # Remove duplicates
|
||||
task_prompt += f"""
|
||||
Here are the results of previous tasks that might be useful:\n
|
||||
{context_results}
|
||||
Context:
|
||||
|
||||
{' '.join(unique_contexts)}
|
||||
"""
|
||||
|
||||
# Add memory context if available
|
||||
if task.memory:
|
||||
try:
|
||||
@@ -714,12 +749,24 @@ Here are the results of previous tasks that might be useful:\n
|
||||
return str(agent[0])
|
||||
return None
|
||||
|
||||
def start(self):
|
||||
def start(self, content=None, **kwargs):
|
||||
"""Start agent execution with optional content and config"""
|
||||
if content:
|
||||
# Add content to context of all tasks
|
||||
for task in self.tasks.values():
|
||||
if isinstance(content, (str, list)):
|
||||
# If context is empty, initialize it
|
||||
if not task.context:
|
||||
task.context = []
|
||||
# Add content to context
|
||||
task.context.append(content)
|
||||
|
||||
# Run tasks as before
|
||||
self.run_all_tasks()
|
||||
return {
|
||||
"task_status": self.get_all_tasks_status(),
|
||||
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
|
||||
}
|
||||
}
|
||||
|
||||
def set_state(self, key: str, value: Any) -> None:
|
||||
"""Set a state value"""
|
||||
|
||||
@@ -4,6 +4,7 @@ import uuid
|
||||
import time
|
||||
from .chunking import Chunking
|
||||
from functools import cached_property
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -274,14 +275,26 @@ class Knowledge:
|
||||
# Treat as raw text content only if no file extension
|
||||
memories = [self.normalize_content(input_path)]
|
||||
|
||||
# Store memories
|
||||
# Create progress display
|
||||
progress = Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
transient=True
|
||||
)
|
||||
|
||||
# Store memories with progress bar
|
||||
all_results = []
|
||||
for memory in memories:
|
||||
if memory:
|
||||
memory_result = self.store(memory, user_id=user_id, agent_id=agent_id,
|
||||
run_id=run_id, metadata=metadata)
|
||||
if memory_result:
|
||||
all_results.extend(memory_result.get('results', []))
|
||||
with progress:
|
||||
store_task = progress.add_task(f"Adding to Knowledge from {os.path.basename(input_path)}", total=len(memories))
|
||||
for memory in memories:
|
||||
if memory:
|
||||
memory_result = self.store(memory, user_id=user_id, agent_id=agent_id,
|
||||
run_id=run_id, metadata=metadata)
|
||||
if memory_result:
|
||||
all_results.extend(memory_result.get('results', []))
|
||||
progress.advance(store_task)
|
||||
|
||||
return {'results': all_results, 'relations': []}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ class Task:
|
||||
agent: Optional[Agent] = None,
|
||||
name: Optional[str] = None,
|
||||
tools: Optional[List[Any]] = None,
|
||||
context: Optional[List["Task"]] = None,
|
||||
context: Optional[List[Union[str, List, 'Task']]] = None,
|
||||
async_execution: Optional[bool] = False,
|
||||
config: Optional[Dict[str, Any]] = None,
|
||||
output_file: Optional[str] = None,
|
||||
@@ -219,4 +219,33 @@ class Task:
|
||||
self.callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Task {self.id}: Failed to execute callback: {e}")
|
||||
logger.exception(e)
|
||||
logger.exception(e)
|
||||
|
||||
task_prompt = f"""
|
||||
You need to do the following task: {self.description}.
|
||||
Expected Output: {self.expected_output}.
|
||||
"""
|
||||
if self.context:
|
||||
context_results = [] # Use list to avoid duplicates
|
||||
for context_item in self.context:
|
||||
if isinstance(context_item, str):
|
||||
context_results.append(f"Input Content:\n{context_item}")
|
||||
elif isinstance(context_item, list):
|
||||
context_results.append(f"Input Content: {' '.join(str(x) for x in context_item)}")
|
||||
elif hasattr(context_item, 'result'): # Task object
|
||||
if context_item.result:
|
||||
context_results.append(
|
||||
f"Result of previous task {context_item.name if context_item.name else context_item.description}:\n{context_item.result.raw}"
|
||||
)
|
||||
else:
|
||||
context_results.append(
|
||||
f"Previous task {context_item.name if context_item.name else context_item.description} has no result yet."
|
||||
)
|
||||
|
||||
# Join unique context results
|
||||
unique_contexts = list(dict.fromkeys(context_results)) # Remove duplicates
|
||||
task_prompt += f"""
|
||||
Context:
|
||||
|
||||
{' '.join(unique_contexts)}
|
||||
"""
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.38"
|
||||
version = "0.0.41"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
authors = [
|
||||
{ name="Mervin Praison" }
|
||||
|
||||
Generated
+1
-1
@@ -1558,7 +1558,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.38"
|
||||
version = "0.0.41"
|
||||
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.47 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.50 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
+13
-27
@@ -4,11 +4,8 @@ description: "Understanding Agents in PraisonAI"
|
||||
icon: "user"
|
||||
---
|
||||
|
||||
<Note>
|
||||
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
|
||||
</Note>
|
||||
|
||||
# Understanding Agents
|
||||
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
@@ -19,45 +16,34 @@ graph LR
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[" "]
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
|
||||
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Agent2[" "]
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
|
||||
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Style for agent containers
|
||||
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Start,Output,Task1,Task2 input
|
||||
class Process,AgentIcon1,AgentIcon2 process
|
||||
class Tools1,Tools2 tools
|
||||
class Agent1,Agent2 transparent
|
||||
```
|
||||
|
||||
## Key Components
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
title: "Knowledge"
|
||||
title: "AI Agents with Knowledge"
|
||||
sidebarTitle: "Knowledge"
|
||||
description: "Learn how to create AI agents with custom knowledge bases"
|
||||
icon: "book"
|
||||
---
|
||||
@@ -13,7 +14,7 @@ flowchart LR
|
||||
end
|
||||
|
||||
subgraph Router[Vector Store]
|
||||
DB[(Chroma)]
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
subgraph Out[Agents]
|
||||
@@ -32,6 +33,14 @@ flowchart LR
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|
||||
|---------|--------------------------------|---------------------------|
|
||||
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
|
||||
| Purpose | Provide static reference information | Store dynamic context and interactions |
|
||||
| Storage | Read-only knowledge base | Read-write memory store |
|
||||
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
|
||||
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
|
||||
+43
-12
@@ -5,6 +5,48 @@ description: "Learn how to create AI agents with memory capabilities for maintai
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Memory
|
||||
direction TB
|
||||
STM[Short Term]
|
||||
LTM[Long Term]
|
||||
end
|
||||
|
||||
subgraph Store
|
||||
direction TB
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
Input[Input] ---> Agents
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
Agents ---> Output[Output]
|
||||
|
||||
Memory <--> Store
|
||||
Store <--> A1
|
||||
Store <--> A2
|
||||
Store <--> A3
|
||||
|
||||
style Memory fill:#189AB4,color:#fff
|
||||
style Store fill:#2E8B57,color:#fff
|
||||
style Agents fill:#8B0000,color:#fff
|
||||
style Input fill:#8B0000,color:#fff
|
||||
style Output fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|
||||
|---------|--------------------------------|---------------------------|
|
||||
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
|
||||
| Purpose | Provide static reference information | Store dynamic context and interactions |
|
||||
| Storage | Read-only knowledge base | Read-write memory store |
|
||||
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
|
||||
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
@@ -396,16 +438,6 @@ PraisonAI's memory system includes several types of memory:
|
||||
- Semantic search capabilities with RAG
|
||||
- Quality-based storage decisions
|
||||
</Card>
|
||||
<Card title="Entity Memory" icon="diagram-project">
|
||||
- Store information about specific entities
|
||||
- Track relationships and attributes
|
||||
- Specialized search for entity information
|
||||
</Card>
|
||||
<Card title="User Memory" icon="user">
|
||||
- Store user-specific information
|
||||
- Personalized context for each user
|
||||
- Persistent across sessions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### Memory Quality Control
|
||||
@@ -437,5 +469,4 @@ results = agents.memory.search_long_term(
|
||||
query="search query",
|
||||
min_quality=0.8, # Only return high-quality matches
|
||||
limit=5 # Maximum number of results
|
||||
)
|
||||
```
|
||||
)
|
||||
@@ -36,6 +36,24 @@ Process types in PraisonAI define how tasks are executed and how agents collabor
|
||||
|
||||
## Sequential Process
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] --> A1
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
|
||||
end
|
||||
A3 --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class A1,A2,A3 process
|
||||
class Agents transparent
|
||||
```
|
||||
|
||||
The simplest form of task execution where tasks are performed one after another.
|
||||
|
||||
<Card>
|
||||
@@ -57,6 +75,39 @@ The simplest form of task execution where tasks are performed one after another.
|
||||
|
||||
## Hierarchical Process
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
Input[Input] --> Manager
|
||||
|
||||
subgraph Agents
|
||||
Manager[Manager Agent]
|
||||
|
||||
subgraph Workers
|
||||
direction LR
|
||||
W1[Worker 1]
|
||||
W2[Worker 2]
|
||||
W3[Worker 3]
|
||||
end
|
||||
|
||||
Manager --> W1
|
||||
Manager --> W2
|
||||
Manager --> W3
|
||||
end
|
||||
|
||||
W1 --> Manager
|
||||
W2 --> Manager
|
||||
W3 --> Manager
|
||||
Manager --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class Manager,W1,W2,W3 process
|
||||
class Agents,Workers transparent
|
||||
```
|
||||
|
||||
Uses a manager agent to coordinate task execution and agent assignments.
|
||||
|
||||
<Card>
|
||||
@@ -79,6 +130,33 @@ Uses a manager agent to coordinate task execution and agent assignments.
|
||||
|
||||
## Workflow Process
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] --> Start
|
||||
|
||||
subgraph Workflow
|
||||
direction LR
|
||||
Start[Start] --> C1{Condition}
|
||||
C1 --> |Yes| A1[Agent 1]
|
||||
C1 --> |No| A2[Agent 2]
|
||||
A1 --> Join
|
||||
A2 --> Join
|
||||
Join --> A3[Agent 3]
|
||||
end
|
||||
|
||||
A3 --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef decision fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class Start,A1,A2,A3,Join process
|
||||
class C1 decision
|
||||
class Workflow transparent
|
||||
```
|
||||
|
||||
Advanced process type supporting complex task relationships and conditional execution.
|
||||
|
||||
<Card>
|
||||
|
||||
+30
-3
@@ -4,9 +4,36 @@ description: "Understanding Tasks in PraisonAI"
|
||||
icon: "list-check"
|
||||
---
|
||||
|
||||
<Note>
|
||||
Tasks are the fundamental units of work in PraisonAI, defining what needs to be done, how it should be done, and who should do it.
|
||||
</Note>
|
||||
# Understanding Tasks
|
||||
Tasks are units of work that agents execute. Each task has a clear goal, input requirements, and expected outputs.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] ---> Task
|
||||
|
||||
subgraph Task
|
||||
direction LR
|
||||
Role[Role]
|
||||
Goal[Goal]
|
||||
Story[Backstory]
|
||||
Expected[Expected Output]
|
||||
|
||||
Role --> Goal
|
||||
Goal --> Story
|
||||
Story --> Expected
|
||||
end
|
||||
|
||||
Task ---> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class Role,Goal,Story,Expected process
|
||||
class Task transparent
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
|
||||
+41
-4
@@ -1,12 +1,49 @@
|
||||
---
|
||||
title: "Tools"
|
||||
description: "Understanding Tools in PraisonAI"
|
||||
title: "AI Agents with Tools"
|
||||
sidebarTitle: "Tools"
|
||||
description: "Learn how to create AI agents that can use tools to interact with external systems and perform actions."
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
# Understanding Tools
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Tools
|
||||
direction TB
|
||||
T3[Internet Search]
|
||||
T1[Code Execution]
|
||||
T2[Formatting]
|
||||
end
|
||||
|
||||
Tools in PraisonAI are functions that agents can use to interact with external systems, perform computations, or access data. They extend the capabilities of agents beyond just language processing.
|
||||
Input[Input] ---> Agents
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
Agents ---> Output[Output]
|
||||
|
||||
T3 --> A1
|
||||
T1 --> A2
|
||||
T2 --> A3
|
||||
|
||||
style Tools fill:#189AB4,color:#fff
|
||||
style Agents fill:#8B0000,color:#fff
|
||||
style Input fill:#8B0000,color:#fff
|
||||
style Output fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
| Feature | [Knowledge](/concepts/knowledge) | [Tools](/concepts/tools) |
|
||||
|---------|--------------------------------|---------------------------|
|
||||
| Purpose | Static reference information | Dynamic interaction capabilities |
|
||||
| Access | Read-only reference | Execute actions and commands |
|
||||
| Updates | Manual through files | Real-time through tool calls |
|
||||
| Storage | Knowledge base | Assigned to specific agents |
|
||||
| Persistence | Permanent until changed | Available during agent execution |
|
||||
|
||||
## Quick Start
|
||||
|
||||
Tools are functions that agents can use to interact with external systems and perform actions. They are essential for creating agents that can do more than just process text.
|
||||
|
||||
## Creating Custom Tool
|
||||
<Steps>
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
---
|
||||
title: "Climate Impact"
|
||||
description: "Learn how to create AI agents for climate impact analysis and adaptation strategies."
|
||||
icon: "cloud-sun"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Monitor[Environmental Monitor]
|
||||
Monitor --> Urban[Urban Analyzer]
|
||||
Urban --> Climate[Climate Modeler]
|
||||
Climate --> Impact[Impact Predictor]
|
||||
Impact --> Strategy[Strategy Generator]
|
||||
Strategy --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Monitor fill:#2E8B57,color:#fff
|
||||
style Urban fill:#2E8B57,color:#fff
|
||||
style Climate fill:#2E8B57,color:#fff
|
||||
style Impact fill:#2E8B57,color:#fff
|
||||
style Strategy fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Climate Impact Analysis?
|
||||
|
||||
Climate Impact Analysis is a systematic process of collecting environmental data, analyzing urban factors, modeling microclimates, predicting impacts, and generating adaptation strategies. This helps cities and communities understand and prepare for climate change effects, ensuring sustainable urban development and public health.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Environmental Monitoring" icon="temperature-high">
|
||||
Collection of temperature, humidity, and air quality data with trend analysis.
|
||||
</Card>
|
||||
<Card title="Urban Analysis" icon="city">
|
||||
Assessment of building density, green spaces, traffic flow, and heat islands.
|
||||
</Card>
|
||||
<Card title="Climate Modeling" icon="chart-line">
|
||||
Microclimate modeling for different urban locations with temperature and air quality impacts.
|
||||
</Card>
|
||||
<Card title="Impact Prediction" icon="chart-mixed">
|
||||
Prediction of health impacts, energy consumption, and livability scores.
|
||||
</Card>
|
||||
<Card title="Adaptation Strategies" icon="leaf">
|
||||
Generation of location-specific strategies for climate adaptation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def collect_environmental_data():
|
||||
"""Simulates environmental data collection"""
|
||||
data = {
|
||||
"temperature": {
|
||||
"current": 25 + (time.time() % 10),
|
||||
"historical": [24, 25, 26, 24, 23],
|
||||
"trend": "increasing"
|
||||
},
|
||||
"humidity": {
|
||||
"current": 60 + (time.time() % 20),
|
||||
"historical": [65, 62, 58, 63, 61],
|
||||
"trend": "stable"
|
||||
},
|
||||
"air_quality": {
|
||||
"pm25": 35 + (time.time() % 15),
|
||||
"co2": 415 + (time.time() % 30),
|
||||
"trend": "deteriorating"
|
||||
}
|
||||
}
|
||||
return data
|
||||
|
||||
def analyze_urban_factors():
|
||||
"""Simulates urban environment analysis"""
|
||||
factors = {
|
||||
"building_density": 75 + (time.time() % 20),
|
||||
"green_spaces": 25 + (time.time() % 10),
|
||||
"traffic_flow": {
|
||||
"peak_hours": [8, 17],
|
||||
"congestion_level": "high"
|
||||
},
|
||||
"heat_islands": [
|
||||
{"location": "downtown", "intensity": "high"},
|
||||
{"location": "industrial", "intensity": "medium"}
|
||||
]
|
||||
}
|
||||
return factors
|
||||
|
||||
def model_microclimate(env_data: Dict, urban_factors: Dict):
|
||||
"""Models microclimate conditions"""
|
||||
models = []
|
||||
locations = ["downtown", "residential", "industrial", "parks"]
|
||||
|
||||
for location in locations:
|
||||
models.append({
|
||||
"location": location,
|
||||
"temperature_delta": 2 + (time.time() % 3),
|
||||
"air_quality_impact": "moderate" if "park" in location else "significant",
|
||||
"humidity_variation": 5 + (time.time() % 5)
|
||||
})
|
||||
return models
|
||||
|
||||
def predict_impacts(models: List[Dict]):
|
||||
"""Predicts climate impacts"""
|
||||
predictions = []
|
||||
for model in models:
|
||||
predictions.append({
|
||||
"location": model["location"],
|
||||
"health_impact": "high" if model["air_quality_impact"] == "significant" else "medium",
|
||||
"energy_consumption": {
|
||||
"cooling_need": model["temperature_delta"] * 10,
|
||||
"trend": "increasing" if model["temperature_delta"] > 2.5 else "stable"
|
||||
},
|
||||
"livability_score": 70 - (model["temperature_delta"] * 5)
|
||||
})
|
||||
return predictions
|
||||
|
||||
def generate_adaptation_strategies(predictions: List[Dict]):
|
||||
"""Generates adaptation strategies"""
|
||||
strategies = []
|
||||
for pred in predictions:
|
||||
if pred["health_impact"] == "high":
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"increase_green_spaces",
|
||||
"traffic_reduction",
|
||||
"building_retrofitting"
|
||||
],
|
||||
"priority": "immediate",
|
||||
"cost_estimate": "high"
|
||||
})
|
||||
else:
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"tree_planting",
|
||||
"cool_roofs"
|
||||
],
|
||||
"priority": "medium",
|
||||
"cost_estimate": "moderate"
|
||||
})
|
||||
return strategies
|
||||
|
||||
# Create specialized agents
|
||||
environmental_monitor = Agent(
|
||||
name="Environmental Monitor",
|
||||
role="Data Collection",
|
||||
goal="Collect environmental data",
|
||||
instructions="Monitor and collect climate data",
|
||||
tools=[collect_environmental_data]
|
||||
)
|
||||
|
||||
urban_analyzer = Agent(
|
||||
name="Urban Analyzer",
|
||||
role="Urban Analysis",
|
||||
goal="Analyze urban environment",
|
||||
instructions="Assess urban factors affecting climate",
|
||||
tools=[analyze_urban_factors]
|
||||
)
|
||||
|
||||
climate_modeler = Agent(
|
||||
name="Climate Modeler",
|
||||
role="Climate Modeling",
|
||||
goal="Model microclimate conditions",
|
||||
instructions="Create detailed climate models",
|
||||
tools=[model_microclimate]
|
||||
)
|
||||
|
||||
impact_predictor = Agent(
|
||||
name="Impact Predictor",
|
||||
role="Impact Analysis",
|
||||
goal="Predict climate impacts",
|
||||
instructions="Assess potential climate impacts",
|
||||
tools=[predict_impacts]
|
||||
)
|
||||
|
||||
strategy_generator = Agent(
|
||||
name="Strategy Generator",
|
||||
role="Strategy Development",
|
||||
goal="Generate adaptation strategies",
|
||||
instructions="Develop climate adaptation strategies",
|
||||
tools=[generate_adaptation_strategies]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
monitoring_task = Task(
|
||||
name="collect_data",
|
||||
description="Collect environmental data",
|
||||
expected_output="Environmental measurements",
|
||||
agent=environmental_monitor,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_urban"]
|
||||
)
|
||||
|
||||
urban_task = Task(
|
||||
name="analyze_urban",
|
||||
description="Analyze urban factors",
|
||||
expected_output="Urban analysis",
|
||||
agent=urban_analyzer,
|
||||
next_tasks=["model_climate"]
|
||||
)
|
||||
|
||||
modeling_task = Task(
|
||||
name="model_climate",
|
||||
description="Model microclimate",
|
||||
expected_output="Climate models",
|
||||
agent=climate_modeler,
|
||||
context=[monitoring_task, urban_task],
|
||||
next_tasks=["predict_impacts"]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_impacts",
|
||||
description="Predict climate impacts",
|
||||
expected_output="Impact predictions",
|
||||
agent=impact_predictor,
|
||||
next_tasks=["generate_strategies"]
|
||||
)
|
||||
|
||||
strategy_task = Task(
|
||||
name="generate_strategies",
|
||||
description="Generate adaptation strategies",
|
||||
expected_output="Adaptation strategies",
|
||||
agent=strategy_generator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"immediate": ["collect_data"], # Continuous monitoring for high priority
|
||||
"medium": "", # End workflow for medium priority
|
||||
"low": "" # End workflow for low priority
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[environmental_monitor, urban_analyzer, climate_modeler,
|
||||
impact_predictor, strategy_generator],
|
||||
tasks=[monitoring_task, urban_task, modeling_task,
|
||||
prediction_task, strategy_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Climate Impact Prediction Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nClimate Impact Analysis Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,316 @@
|
||||
---
|
||||
title: "Crypto Validator"
|
||||
description: "Learn how to create AI agents for post-quantum cryptographic scheme validation and security analysis."
|
||||
icon: "key"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Crypto Analyzer]
|
||||
Analyzer --> Quantum[Attack Simulator]
|
||||
Analyzer --> Perf[Performance Benchmarker]
|
||||
Quantum --> Security[Implementation Assessor]
|
||||
Perf --> Security
|
||||
Security --> Compliance[Compliance Validator]
|
||||
Compliance --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Quantum fill:#2E8B57,color:#fff
|
||||
style Perf fill:#2E8B57,color:#fff
|
||||
style Security fill:#2E8B57,color:#fff
|
||||
style Compliance fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Post-Quantum Cryptography?
|
||||
|
||||
Post-quantum cryptography focuses on developing cryptographic systems that are secure against both quantum and classical computers. This involves analyzing cryptographic schemes, simulating quantum attacks, and ensuring compliance with security standards.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Cryptographic Analysis" icon="shield-check">
|
||||
Analyze quantum-resistant cryptographic schemes including lattice-based encryption and multivariate signatures.
|
||||
</Card>
|
||||
<Card title="Attack Simulation" icon="bug">
|
||||
Test resistance against quantum attacks including Grover's algorithm and Shor's algorithm.
|
||||
</Card>
|
||||
<Card title="Performance Testing" icon="gauge-high">
|
||||
Benchmark key generation, encryption/decryption speeds, and throughput metrics.
|
||||
</Card>
|
||||
<Card title="Security Assessment" icon="lock">
|
||||
Evaluate implementation security including side-channel resistance and hardening measures.
|
||||
</Card>
|
||||
<Card title="Compliance Validation" icon="certificate">
|
||||
Verify compliance with NIST PQC, Common Criteria, and FIPS standards.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_cryptographic_scheme():
|
||||
"""Simulates cryptographic scheme analysis"""
|
||||
schemes = [
|
||||
{
|
||||
"name": "lattice_based",
|
||||
"type": "encryption",
|
||||
"key_size": 2048,
|
||||
"security_level": "AES-256 equivalent",
|
||||
"parameters": {
|
||||
"lattice_dimension": 1024,
|
||||
"modulus": "q = 2^32 - 1",
|
||||
"error_distribution": "discrete_gaussian"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "multivariate",
|
||||
"type": "signature",
|
||||
"key_size": 4096,
|
||||
"security_level": "SHA-384 equivalent",
|
||||
"parameters": {
|
||||
"variables": 128,
|
||||
"equations": 128,
|
||||
"field_size": "2^8"
|
||||
}
|
||||
}
|
||||
]
|
||||
return schemes[int(time.time()) % 2]
|
||||
|
||||
def simulate_quantum_attacks(scheme: Dict):
|
||||
"""Simulates quantum attack scenarios"""
|
||||
attacks = {
|
||||
"grover_search": {
|
||||
"effectiveness": "reduced",
|
||||
"quantum_speedup": "quadratic",
|
||||
"estimated_qubits": 2048,
|
||||
"time_complexity": "O(2^n/2)"
|
||||
},
|
||||
"shor_algorithm": {
|
||||
"effectiveness": "ineffective",
|
||||
"quantum_speedup": "none",
|
||||
"vulnerability": "resistant",
|
||||
"classical_hardness": "maintained"
|
||||
},
|
||||
"quantum_hidden_subgroup": {
|
||||
"effectiveness": "partial",
|
||||
"applicability": "limited",
|
||||
"mitigation": "parameter_adjustment"
|
||||
}
|
||||
}
|
||||
return attacks
|
||||
|
||||
def benchmark_performance(scheme: Dict):
|
||||
"""Benchmarks cryptographic performance"""
|
||||
benchmarks = {
|
||||
"key_generation": {
|
||||
"time": 0.5 + (time.time() % 1) / 10, # seconds
|
||||
"memory": 128 + (int(time.time()) % 64) # MB
|
||||
},
|
||||
"encryption_speed": {
|
||||
"small_message": 0.001 + (time.time() % 1) / 1000, # seconds
|
||||
"large_message": 0.1 + (time.time() % 1) / 10 # seconds
|
||||
},
|
||||
"decryption_speed": {
|
||||
"small_message": 0.002 + (time.time() % 1) / 1000,
|
||||
"large_message": 0.15 + (time.time() % 1) / 10
|
||||
},
|
||||
"throughput": {
|
||||
"encryption": 100 + (int(time.time()) % 50), # MB/s
|
||||
"decryption": 80 + (int(time.time()) % 40) # MB/s
|
||||
}
|
||||
}
|
||||
return benchmarks
|
||||
|
||||
def assess_implementation(scheme: Dict, benchmarks: Dict):
|
||||
"""Assesses implementation security"""
|
||||
assessment = {
|
||||
"side_channel_resistance": {
|
||||
"timing_attacks": "protected",
|
||||
"power_analysis": "partial_vulnerability",
|
||||
"cache_attacks": "mitigated"
|
||||
},
|
||||
"implementation_hardening": {
|
||||
"constant_time": True,
|
||||
"memory_protection": True,
|
||||
"error_handling": "secure"
|
||||
},
|
||||
"compiler_optimizations": {
|
||||
"safety": "verified",
|
||||
"performance_impact": -0.05 + (time.time() % 1) / 10
|
||||
}
|
||||
}
|
||||
return assessment
|
||||
|
||||
def validate_compliance(scheme: Dict, assessment: Dict):
|
||||
"""Validates compliance and standards"""
|
||||
compliance = {
|
||||
"nist_pqc": {
|
||||
"status": "submitted",
|
||||
"round": 3,
|
||||
"requirements_met": True
|
||||
},
|
||||
"common_criteria": {
|
||||
"evaluation_level": "EAL4+",
|
||||
"protection_profile": "compliant"
|
||||
},
|
||||
"fips_140_3": {
|
||||
"security_level": 3,
|
||||
"validation_status": "in_process"
|
||||
}
|
||||
}
|
||||
return compliance
|
||||
|
||||
# Create specialized agents
|
||||
crypto_analyzer = Agent(
|
||||
name="Crypto Analyzer",
|
||||
role="Cryptographic Analysis",
|
||||
goal="Analyze cryptographic schemes",
|
||||
instructions="Evaluate quantum-resistant cryptographic schemes",
|
||||
tools=[analyze_cryptographic_scheme]
|
||||
)
|
||||
|
||||
attack_simulator = Agent(
|
||||
name="Attack Simulator",
|
||||
role="Attack Simulation",
|
||||
goal="Simulate quantum attacks",
|
||||
instructions="Test resistance against quantum attacks",
|
||||
tools=[simulate_quantum_attacks]
|
||||
)
|
||||
|
||||
performance_benchmarker = Agent(
|
||||
name="Performance Benchmarker",
|
||||
role="Performance Testing",
|
||||
goal="Benchmark cryptographic performance",
|
||||
instructions="Measure performance metrics",
|
||||
tools=[benchmark_performance]
|
||||
)
|
||||
|
||||
implementation_assessor = Agent(
|
||||
name="Implementation Assessor",
|
||||
role="Implementation Assessment",
|
||||
goal="Assess implementation security",
|
||||
instructions="Evaluate implementation security",
|
||||
tools=[assess_implementation]
|
||||
)
|
||||
|
||||
compliance_validator = Agent(
|
||||
name="Compliance Validator",
|
||||
role="Compliance Validation",
|
||||
goal="Validate standards compliance",
|
||||
instructions="Verify compliance with standards",
|
||||
tools=[validate_compliance]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_crypto",
|
||||
description="Analyze cryptographic scheme",
|
||||
expected_output="Cryptographic analysis",
|
||||
agent=crypto_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["simulate_attacks", "benchmark_performance"]
|
||||
)
|
||||
|
||||
attack_task = Task(
|
||||
name="simulate_attacks",
|
||||
description="Simulate quantum attacks",
|
||||
expected_output="Attack simulation results",
|
||||
agent=attack_simulator,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
benchmark_task = Task(
|
||||
name="benchmark_performance",
|
||||
description="Benchmark performance",
|
||||
expected_output="Performance benchmarks",
|
||||
agent=performance_benchmarker,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
assessment_task = Task(
|
||||
name="assess_implementation",
|
||||
description="Assess implementation",
|
||||
expected_output="Implementation assessment",
|
||||
agent=implementation_assessor,
|
||||
context=[attack_task, benchmark_task],
|
||||
next_tasks=["validate_compliance"]
|
||||
)
|
||||
|
||||
compliance_task = Task(
|
||||
name="validate_compliance",
|
||||
description="Validate compliance",
|
||||
expected_output="Compliance validation",
|
||||
agent=compliance_validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"compliant": "", # End workflow if compliant
|
||||
"non_compliant": ["assess_implementation"] # Reassess if non-compliant
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[crypto_analyzer, attack_simulator, performance_benchmarker,
|
||||
implementation_assessor, compliance_validator],
|
||||
tasks=[analysis_task, attack_task, benchmark_task,
|
||||
assessment_task, compliance_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Quantum-Resistant Cryptography Validation Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nCryptography Validation Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,302 @@
|
||||
---
|
||||
title: "DeFi Market Maker"
|
||||
description: "Learn how to create AI agents for decentralized finance market making and arbitrage."
|
||||
icon: "chart-line"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Market[Market Analyzer]
|
||||
Market --> Arbitrage[Arbitrage Detector]
|
||||
Market --> Liquidity[Liquidity Optimizer]
|
||||
Arbitrage --> Risk[Risk Assessor]
|
||||
Liquidity --> Risk
|
||||
Risk --> Executor[Trade Executor]
|
||||
Executor --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Market fill:#2E8B57,color:#fff
|
||||
style Arbitrage fill:#2E8B57,color:#fff
|
||||
style Liquidity fill:#2E8B57,color:#fff
|
||||
style Risk fill:#2E8B57,color:#fff
|
||||
style Executor fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is DeFi Market Making?
|
||||
|
||||
Decentralized Finance (DeFi) market making involves providing liquidity to decentralized exchanges and automatically executing trades to capture arbitrage opportunities. This requires real-time analysis of market conditions, optimization of liquidity positions, and risk management.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Market Analysis" icon="chart-candlestick">
|
||||
Real-time analysis of liquidity pools, market volatility, trading volumes, and gas prices.
|
||||
</Card>
|
||||
<Card title="Arbitrage Detection" icon="magnifying-glass-dollar">
|
||||
Identification of profitable trading opportunities across different liquidity pools.
|
||||
</Card>
|
||||
<Card title="Liquidity Optimization" icon="water">
|
||||
Optimization of liquidity distribution and pool ratios for maximum efficiency.
|
||||
</Card>
|
||||
<Card title="Risk Assessment" icon="shield-halved">
|
||||
Comprehensive risk analysis including impermanent loss and smart contract risks.
|
||||
</Card>
|
||||
<Card title="Trade Execution" icon="money-bill-transfer">
|
||||
Automated execution of optimized trades with performance monitoring.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_market_conditions():
|
||||
"""Simulates market analysis"""
|
||||
conditions = {
|
||||
"liquidity_pools": {
|
||||
"pool_A": {
|
||||
"token_0": {"balance": 1000000, "price": 1.0},
|
||||
"token_1": {"balance": 500000, "price": 2.0},
|
||||
"total_value_locked": 2000000
|
||||
},
|
||||
"pool_B": {
|
||||
"token_0": {"balance": 800000, "price": 1.0},
|
||||
"token_1": {"balance": 400000, "price": 2.0},
|
||||
"total_value_locked": 1600000
|
||||
}
|
||||
},
|
||||
"market_volatility": 0.15 + (time.time() % 10) / 100,
|
||||
"trading_volume_24h": 5000000 + (time.time() % 1000000),
|
||||
"gas_prices": 50 + (time.time() % 30)
|
||||
}
|
||||
return conditions
|
||||
|
||||
def detect_arbitrage():
|
||||
"""Simulates arbitrage opportunity detection"""
|
||||
opportunities = [
|
||||
{
|
||||
"path": ["pool_A", "pool_B"],
|
||||
"profit_potential": 0.02 + (time.time() % 5) / 100,
|
||||
"required_capital": 10000,
|
||||
"execution_cost": 50,
|
||||
"risk_level": "low"
|
||||
},
|
||||
{
|
||||
"path": ["pool_B", "pool_C"],
|
||||
"profit_potential": 0.03 + (time.time() % 5) / 100,
|
||||
"required_capital": 20000,
|
||||
"execution_cost": 75,
|
||||
"risk_level": "medium"
|
||||
}
|
||||
]
|
||||
return opportunities[int(time.time()) % 2]
|
||||
|
||||
def optimize_liquidity(market_conditions: Dict):
|
||||
"""Optimizes liquidity distribution"""
|
||||
optimizations = {
|
||||
"pool_A": {
|
||||
"target_ratio": 2.0,
|
||||
"suggested_actions": [
|
||||
{
|
||||
"action": "rebalance",
|
||||
"token": "token_1",
|
||||
"amount": 10000,
|
||||
"direction": "add"
|
||||
}
|
||||
],
|
||||
"expected_improvement": 0.05
|
||||
},
|
||||
"pool_B": {
|
||||
"target_ratio": 1.8,
|
||||
"suggested_actions": [
|
||||
{
|
||||
"action": "rebalance",
|
||||
"token": "token_0",
|
||||
"amount": 5000,
|
||||
"direction": "remove"
|
||||
}
|
||||
],
|
||||
"expected_improvement": 0.03
|
||||
}
|
||||
}
|
||||
return optimizations
|
||||
|
||||
def assess_risks(arbitrage: Dict, optimizations: Dict):
|
||||
"""Assesses potential risks"""
|
||||
risk_assessment = {
|
||||
"impermanent_loss_risk": 0.1 + (time.time() % 5) / 100,
|
||||
"smart_contract_risk": "low",
|
||||
"market_manipulation_risk": "medium" if arbitrage["profit_potential"] > 0.025 else "low",
|
||||
"gas_price_risk": "high" if arbitrage["execution_cost"] > 60 else "medium",
|
||||
"mitigation_strategies": [
|
||||
"implement_slippage_protection",
|
||||
"set_maximum_gas_price",
|
||||
"use_multiple_liquidity_sources"
|
||||
]
|
||||
}
|
||||
return risk_assessment
|
||||
|
||||
def execute_trades(arbitrage: Dict, risks: Dict):
|
||||
"""Simulates trade execution"""
|
||||
execution_results = {
|
||||
"status": "success" if time.time() % 2 == 0 else "failed",
|
||||
"executed_volume": arbitrage["required_capital"] * 0.95,
|
||||
"actual_profit": arbitrage["profit_potential"] * 0.9,
|
||||
"gas_used": arbitrage["execution_cost"] * 1.1,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
return execution_results
|
||||
|
||||
# Create specialized agents
|
||||
market_analyzer = Agent(
|
||||
name="Market Analyzer",
|
||||
role="Market Analysis",
|
||||
goal="Analyze market conditions",
|
||||
instructions="Monitor and analyze DeFi market conditions",
|
||||
tools=[analyze_market_conditions]
|
||||
)
|
||||
|
||||
arbitrage_detector = Agent(
|
||||
name="Arbitrage Detector",
|
||||
role="Arbitrage Detection",
|
||||
goal="Detect arbitrage opportunities",
|
||||
instructions="Identify profitable trading opportunities",
|
||||
tools=[detect_arbitrage]
|
||||
)
|
||||
|
||||
liquidity_optimizer = Agent(
|
||||
name="Liquidity Optimizer",
|
||||
role="Liquidity Optimization",
|
||||
goal="Optimize liquidity distribution",
|
||||
instructions="Optimize pool liquidity ratios",
|
||||
tools=[optimize_liquidity]
|
||||
)
|
||||
|
||||
risk_assessor = Agent(
|
||||
name="Risk Assessor",
|
||||
role="Risk Assessment",
|
||||
goal="Assess trading risks",
|
||||
instructions="Evaluate potential risks and mitigation strategies",
|
||||
tools=[assess_risks]
|
||||
)
|
||||
|
||||
trade_executor = Agent(
|
||||
name="Trade Executor",
|
||||
role="Trade Execution",
|
||||
goal="Execute optimized trades",
|
||||
instructions="Execute trades based on analysis",
|
||||
tools=[execute_trades]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
market_task = Task(
|
||||
name="analyze_market",
|
||||
description="Analyze market conditions",
|
||||
expected_output="Market analysis",
|
||||
agent=market_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["detect_arbitrage", "optimize_liquidity"]
|
||||
)
|
||||
|
||||
arbitrage_task = Task(
|
||||
name="detect_arbitrage",
|
||||
description="Detect arbitrage opportunities",
|
||||
expected_output="Arbitrage opportunities",
|
||||
agent=arbitrage_detector,
|
||||
next_tasks=["assess_risks"]
|
||||
)
|
||||
|
||||
liquidity_task = Task(
|
||||
name="optimize_liquidity",
|
||||
description="Optimize liquidity",
|
||||
expected_output="Liquidity optimization",
|
||||
agent=liquidity_optimizer,
|
||||
context=[market_task],
|
||||
next_tasks=["assess_risks"]
|
||||
)
|
||||
|
||||
risk_task = Task(
|
||||
name="assess_risks",
|
||||
description="Assess trading risks",
|
||||
expected_output="Risk assessment",
|
||||
agent=risk_assessor,
|
||||
context=[arbitrage_task, liquidity_task],
|
||||
next_tasks=["execute_trades"]
|
||||
)
|
||||
|
||||
execution_task = Task(
|
||||
name="execute_trades",
|
||||
description="Execute trades",
|
||||
expected_output="Trade execution results",
|
||||
agent=trade_executor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"success": ["analyze_market"], # Continue monitoring if successful
|
||||
"failed": ["optimize_liquidity"] # Reoptimize if failed
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[market_analyzer, arbitrage_detector, liquidity_optimizer,
|
||||
risk_assessor, trade_executor],
|
||||
tasks=[market_task, arbitrage_task, liquidity_task,
|
||||
risk_task, execution_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting DeFi Market Making Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nMarket Making Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -87,6 +87,86 @@ icon: "code"
|
||||
>
|
||||
Learn how to create AI agents for multilingual content generation and cultural adaptation.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Climate Impact"
|
||||
icon="cloud-sun"
|
||||
href="/examples/climate-impact"
|
||||
>
|
||||
Learn how to create AI agents for climate impact analysis and adaptation strategies.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Space Mission"
|
||||
icon="rocket"
|
||||
href="/examples/space-mission"
|
||||
>
|
||||
Learn how to create AI agents for space mission planning and resource optimization.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Neural Architecture"
|
||||
icon="network-wired"
|
||||
href="/examples/neural-architecture"
|
||||
>
|
||||
Learn how to create AI agents for neural architecture search and optimization.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="DeFi Market Maker"
|
||||
icon="money-bill-trend-up"
|
||||
href="/examples/defi-market-maker"
|
||||
>
|
||||
Learn how to create AI agents for decentralized finance market making and liquidity provision.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Quantum Optimiser"
|
||||
icon="atom"
|
||||
href="/examples/quantum-optimiser"
|
||||
>
|
||||
Learn how to create AI agents for quantum computing optimization and algorithm design.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Medicine Protocol"
|
||||
icon="prescription-bottle-medical"
|
||||
href="/examples/medicine-protocol"
|
||||
>
|
||||
Learn how to create AI agents for medical protocol optimization and drug discovery.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Crypto Validator"
|
||||
icon="key"
|
||||
href="/examples/crypto-validator"
|
||||
>
|
||||
Learn how to create AI agents for cryptocurrency validation and blockchain security.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Research Assistant"
|
||||
icon="microscope"
|
||||
href="/examples/research-assistant"
|
||||
>
|
||||
Learn how to create AI agents for research analysis and experiment design.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Vulnerability Detection"
|
||||
icon="shield-check"
|
||||
href="/examples/vulnerability-detection"
|
||||
>
|
||||
Learn how to create AI agents for vulnerability detection and analysis.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Healthcare Diagnosis"
|
||||
icon="stethoscope"
|
||||
href="/examples/healthcare-diagnosis"
|
||||
>
|
||||
Learn how to create AI agents for medical diagnosis and treatment recommendations.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## What's Next?
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
---
|
||||
title: "Medicine Protocol"
|
||||
description: "Learn how to create AI agents for personalized medicine protocol generation and analysis."
|
||||
icon: "stethoscope"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Genetic[Genetic Analyzer]
|
||||
In --> History[Patient History]
|
||||
Genetic --> Interaction[Drug Interaction]
|
||||
History --> Interaction
|
||||
Interaction --> Protocol[Protocol Generator]
|
||||
Protocol --> Simulation[Effectiveness Simulator]
|
||||
Simulation --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Genetic fill:#2E8B57,color:#fff
|
||||
style History fill:#2E8B57,color:#fff
|
||||
style Interaction fill:#2E8B57,color:#fff
|
||||
style Protocol fill:#2E8B57,color:#fff
|
||||
style Simulation fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Personalized Medicine?
|
||||
|
||||
Personalized medicine is an approach that tailors medical treatment to individual characteristics of each patient. It involves analyzing genetic markers, patient history, and drug interactions to create optimized treatment protocols.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Genetic Analysis" icon="dna">
|
||||
Deep analysis of genetic markers including metabolism genes, risk factors, and drug response markers.
|
||||
</Card>
|
||||
<Card title="Patient History" icon="notes-medical">
|
||||
Comprehensive evaluation of medical conditions, medications, allergies, and family history.
|
||||
</Card>
|
||||
<Card title="Drug Interaction" icon="pills">
|
||||
Analysis of potential drug interactions based on genetic data and patient history.
|
||||
</Card>
|
||||
<Card title="Protocol Generation" icon="file-medical">
|
||||
Creation of personalized treatment protocols with dosage adjustments and monitoring plans.
|
||||
</Card>
|
||||
<Card title="Treatment Simulation" icon="chart-line">
|
||||
Prediction of treatment effectiveness, side effects, and adherence probability.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_genetic_markers():
|
||||
"""Simulates genetic marker analysis"""
|
||||
markers = {
|
||||
"metabolism_genes": {
|
||||
"CYP2D6": "rapid_metabolizer",
|
||||
"CYP2C19": "normal_metabolizer",
|
||||
"DPYD": "poor_metabolizer"
|
||||
},
|
||||
"risk_factors": {
|
||||
"cardiovascular": "elevated",
|
||||
"diabetes": "low",
|
||||
"autoimmune": "moderate"
|
||||
},
|
||||
"drug_response_markers": {
|
||||
"TPMT": "high_sensitivity",
|
||||
"HLA-B*5701": "negative",
|
||||
"UGT1A1": "normal"
|
||||
}
|
||||
}
|
||||
return markers
|
||||
|
||||
def evaluate_patient_history():
|
||||
"""Simulates patient history evaluation"""
|
||||
history = {
|
||||
"conditions": [
|
||||
{"name": "hypertension", "duration": "5_years", "severity": "moderate"},
|
||||
{"name": "arthritis", "duration": "2_years", "severity": "mild"}
|
||||
],
|
||||
"medications": [
|
||||
{"name": "lisinopril", "response": "good", "side_effects": "minimal"},
|
||||
{"name": "methotrexate", "response": "moderate", "side_effects": "mild"}
|
||||
],
|
||||
"allergies": ["penicillin", "sulfa"],
|
||||
"family_history": ["diabetes", "heart_disease"]
|
||||
}
|
||||
return history
|
||||
|
||||
def analyze_drug_interactions(genetic_data: Dict, patient_history: Dict):
|
||||
"""Analyzes potential drug interactions"""
|
||||
interactions = []
|
||||
medications = [med["name"] for med in patient_history["medications"]]
|
||||
|
||||
for med in medications:
|
||||
interactions.append({
|
||||
"medication": med,
|
||||
"genetic_impact": "significant" if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer" else "normal",
|
||||
"risk_level": "high" if med in patient_history["allergies"] else "low",
|
||||
"monitoring_needed": True if genetic_data["metabolism_genes"]["DPYD"] == "poor_metabolizer" else False
|
||||
})
|
||||
return interactions
|
||||
|
||||
def generate_protocol(genetic_data: Dict, interactions: List[Dict]):
|
||||
"""Generates treatment protocol"""
|
||||
protocol = {
|
||||
"primary_treatment": {
|
||||
"medication": "custom_formulation_A",
|
||||
"dosage": "adjusted_based_on_metabolism",
|
||||
"frequency": "twice_daily",
|
||||
"monitoring": {
|
||||
"type": "blood_levels",
|
||||
"frequency": "weekly"
|
||||
}
|
||||
},
|
||||
"alternatives": [
|
||||
{
|
||||
"medication": "custom_formulation_B",
|
||||
"conditions": ["genetic_compatibility", "no_interactions"]
|
||||
}
|
||||
],
|
||||
"precautions": []
|
||||
}
|
||||
|
||||
if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer":
|
||||
protocol["precautions"].append("increase_monitoring_frequency")
|
||||
|
||||
if any(i["risk_level"] == "high" for i in interactions):
|
||||
protocol["precautions"].append("alternative_medication_needed")
|
||||
|
||||
return protocol
|
||||
|
||||
def simulate_effectiveness(protocol: Dict):
|
||||
"""Simulates treatment effectiveness"""
|
||||
simulation = {
|
||||
"efficacy_prediction": 0.85 + (time.time() % 2) / 10,
|
||||
"side_effect_risk": 0.15 + (time.time() % 1) / 10,
|
||||
"adherence_probability": 0.9 + (time.time() % 1) / 10,
|
||||
"expected_outcomes": [
|
||||
"symptom_reduction_80_percent",
|
||||
"minimal_side_effects",
|
||||
"good_tolerance"
|
||||
]
|
||||
}
|
||||
return simulation
|
||||
|
||||
# Create specialized agents
|
||||
genetic_analyzer = Agent(
|
||||
name="Genetic Analyzer",
|
||||
role="Genetic Analysis",
|
||||
goal="Analyze genetic markers",
|
||||
instructions="Evaluate genetic markers and variants",
|
||||
tools=[analyze_genetic_markers]
|
||||
)
|
||||
|
||||
history_analyzer = Agent(
|
||||
name="History Analyzer",
|
||||
role="History Analysis",
|
||||
goal="Analyze patient history",
|
||||
instructions="Evaluate medical history and conditions",
|
||||
tools=[evaluate_patient_history]
|
||||
)
|
||||
|
||||
interaction_analyzer = Agent(
|
||||
name="Interaction Analyzer",
|
||||
role="Drug Interaction",
|
||||
goal="Analyze drug interactions",
|
||||
instructions="Evaluate potential drug interactions",
|
||||
tools=[analyze_drug_interactions]
|
||||
)
|
||||
|
||||
protocol_generator = Agent(
|
||||
name="Protocol Generator",
|
||||
role="Protocol Generation",
|
||||
goal="Generate treatment protocol",
|
||||
instructions="Create personalized treatment protocol",
|
||||
tools=[generate_protocol]
|
||||
)
|
||||
|
||||
effectiveness_simulator = Agent(
|
||||
name="Effectiveness Simulator",
|
||||
role="Treatment Simulation",
|
||||
goal="Simulate treatment effectiveness",
|
||||
instructions="Predict treatment outcomes",
|
||||
tools=[simulate_effectiveness]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
genetic_task = Task(
|
||||
name="analyze_genetics",
|
||||
description="Analyze genetic markers",
|
||||
expected_output="Genetic analysis",
|
||||
agent=genetic_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_history"]
|
||||
)
|
||||
|
||||
history_task = Task(
|
||||
name="analyze_history",
|
||||
description="Analyze patient history",
|
||||
expected_output="History analysis",
|
||||
agent=history_analyzer,
|
||||
next_tasks=["analyze_interactions"]
|
||||
)
|
||||
|
||||
interaction_task = Task(
|
||||
name="analyze_interactions",
|
||||
description="Analyze drug interactions",
|
||||
expected_output="Interaction analysis",
|
||||
agent=interaction_analyzer,
|
||||
context=[genetic_task, history_task],
|
||||
next_tasks=["generate_protocol"]
|
||||
)
|
||||
|
||||
protocol_task = Task(
|
||||
name="generate_protocol",
|
||||
description="Generate treatment protocol",
|
||||
expected_output="Treatment protocol",
|
||||
agent=protocol_generator,
|
||||
context=[genetic_task, interaction_task],
|
||||
next_tasks=["simulate_effectiveness"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_effectiveness",
|
||||
description="Simulate treatment effectiveness",
|
||||
expected_output="Effectiveness simulation",
|
||||
agent=effectiveness_simulator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": "", # End workflow if high effectiveness
|
||||
"medium": ["generate_protocol"], # Adjust protocol if medium
|
||||
"low": ["analyze_interactions"] # Reanalyze if low
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[genetic_analyzer, history_analyzer, interaction_analyzer,
|
||||
protocol_generator, effectiveness_simulator],
|
||||
tasks=[genetic_task, history_task, interaction_task,
|
||||
protocol_task, simulation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Personalized Medicine Protocol Generation...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nProtocol Generation Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,284 @@
|
||||
---
|
||||
title: "Neural Architecture"
|
||||
description: "Learn how to create AI agents for neural architecture search and optimization."
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Hardware[Hardware Analyzer]
|
||||
Hardware --> Generator[Architecture Generator]
|
||||
Generator --> Hyperparams[Hyperparameter Optimizer]
|
||||
Hyperparams --> Performance[Performance Estimator]
|
||||
Performance --> Deployment[Deployment Optimizer]
|
||||
Deployment --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Hardware fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Hyperparams fill:#2E8B57,color:#fff
|
||||
style Performance fill:#2E8B57,color:#fff
|
||||
style Deployment fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Neural Architecture Search?
|
||||
|
||||
Neural Architecture Search (NAS) is an automated process for designing optimal neural network architectures. It involves analyzing hardware constraints, generating candidate architectures, optimizing hyperparameters, and configuring deployment settings to create efficient and performant models.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Hardware Analysis" icon="microchip">
|
||||
Analysis of GPU memory, compute capability, bandwidth, and thermal constraints.
|
||||
</Card>
|
||||
<Card title="Architecture Generation" icon="diagram-project">
|
||||
Creation of candidate architectures including transformers and CNNs with optimized structures.
|
||||
</Card>
|
||||
<Card title="Hyperparameter Tuning" icon="sliders">
|
||||
Optimization of learning rates, batch sizes, optimizers, and regularization parameters.
|
||||
</Card>
|
||||
<Card title="Performance Estimation" icon="gauge-high">
|
||||
Prediction of model accuracy, training time, memory requirements, and FLOPS.
|
||||
</Card>
|
||||
<Card title="Deployment Optimization" icon="rocket">
|
||||
Configuration of quantization, pruning, and batching for efficient deployment.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_hardware_constraints():
|
||||
"""Simulates hardware analysis"""
|
||||
constraints = {
|
||||
"gpu_memory": 16 * 1024, # MB
|
||||
"compute_capability": "7.5",
|
||||
"memory_bandwidth": 900, # GB/s
|
||||
"tensor_cores": True,
|
||||
"max_power_consumption": 300, # Watts
|
||||
"thermal_limits": 85 # Celsius
|
||||
}
|
||||
return constraints
|
||||
|
||||
def generate_architecture_candidates():
|
||||
"""Generates candidate architectures"""
|
||||
candidates = [
|
||||
{
|
||||
"type": "transformer",
|
||||
"layers": 12 + (int(time.time()) % 6),
|
||||
"attention_heads": 8,
|
||||
"embedding_dim": 512,
|
||||
"estimated_params": 125_000_000
|
||||
},
|
||||
{
|
||||
"type": "cnn",
|
||||
"layers": 50 + (int(time.time()) % 50),
|
||||
"filters": [64, 128, 256, 512],
|
||||
"estimated_params": 25_000_000
|
||||
}
|
||||
]
|
||||
return candidates[int(time.time()) % 2]
|
||||
|
||||
def optimize_hyperparameters(architecture: Dict):
|
||||
"""Optimizes hyperparameters"""
|
||||
optimization = {
|
||||
"learning_rate": 0.001 + (time.time() % 9) / 10000,
|
||||
"batch_size": 32 * (1 + int(time.time()) % 4),
|
||||
"optimizer": "adam",
|
||||
"weight_decay": 0.0001,
|
||||
"dropout_rate": 0.1 + (time.time() % 3) / 10,
|
||||
"activation": "gelu" if architecture["type"] == "transformer" else "relu"
|
||||
}
|
||||
return optimization
|
||||
|
||||
def estimate_performance(architecture: Dict, hyperparams: Dict):
|
||||
"""Estimates model performance"""
|
||||
performance = {
|
||||
"estimated_accuracy": 0.85 + (time.time() % 10) / 100,
|
||||
"estimated_training_time": {
|
||||
"hours": 24 + (int(time.time()) % 24),
|
||||
"gpu_hours": 96
|
||||
},
|
||||
"memory_requirements": {
|
||||
"training": architecture["estimated_params"] * 4 / (1024 * 1024), # GB
|
||||
"inference": architecture["estimated_params"] * 2 / (1024 * 1024) # GB
|
||||
},
|
||||
"flops_count": architecture["estimated_params"] * 2
|
||||
}
|
||||
return performance
|
||||
|
||||
def optimize_deployment(architecture: Dict, performance: Dict):
|
||||
"""Optimizes deployment configuration"""
|
||||
deployment = {
|
||||
"quantization": {
|
||||
"method": "dynamic",
|
||||
"precision": "int8",
|
||||
"estimated_speedup": 2.5
|
||||
},
|
||||
"pruning": {
|
||||
"method": "magnitude",
|
||||
"target_sparsity": 0.3,
|
||||
"estimated_size_reduction": 0.6
|
||||
},
|
||||
"batching": {
|
||||
"max_batch_size": 32,
|
||||
"dynamic_batching": True
|
||||
}
|
||||
}
|
||||
return deployment
|
||||
|
||||
# Create specialized agents
|
||||
hardware_analyzer = Agent(
|
||||
name="Hardware Analyzer",
|
||||
role="Hardware Analysis",
|
||||
goal="Analyze hardware constraints",
|
||||
instructions="Evaluate available hardware resources",
|
||||
tools=[analyze_hardware_constraints]
|
||||
)
|
||||
|
||||
architecture_generator = Agent(
|
||||
name="Architecture Generator",
|
||||
role="Architecture Generation",
|
||||
goal="Generate neural architectures",
|
||||
instructions="Create candidate neural architectures",
|
||||
tools=[generate_architecture_candidates]
|
||||
)
|
||||
|
||||
hyperparameter_optimizer = Agent(
|
||||
name="Hyperparameter Optimizer",
|
||||
role="Hyperparameter Optimization",
|
||||
goal="Optimize hyperparameters",
|
||||
instructions="Find optimal hyperparameter settings",
|
||||
tools=[optimize_hyperparameters]
|
||||
)
|
||||
|
||||
performance_estimator = Agent(
|
||||
name="Performance Estimator",
|
||||
role="Performance Estimation",
|
||||
goal="Estimate model performance",
|
||||
instructions="Predict model performance metrics",
|
||||
tools=[estimate_performance]
|
||||
)
|
||||
|
||||
deployment_optimizer = Agent(
|
||||
name="Deployment Optimizer",
|
||||
role="Deployment Optimization",
|
||||
goal="Optimize deployment settings",
|
||||
instructions="Configure optimal deployment",
|
||||
tools=[optimize_deployment]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
hardware_task = Task(
|
||||
name="analyze_hardware",
|
||||
description="Analyze hardware constraints",
|
||||
expected_output="Hardware analysis",
|
||||
agent=hardware_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["generate_architecture"]
|
||||
)
|
||||
|
||||
architecture_task = Task(
|
||||
name="generate_architecture",
|
||||
description="Generate architecture candidates",
|
||||
expected_output="Architecture candidates",
|
||||
agent=architecture_generator,
|
||||
next_tasks=["optimize_hyperparameters"]
|
||||
)
|
||||
|
||||
hyperparameter_task = Task(
|
||||
name="optimize_hyperparameters",
|
||||
description="Optimize hyperparameters",
|
||||
expected_output="Hyperparameter settings",
|
||||
agent=hyperparameter_optimizer,
|
||||
context=[architecture_task],
|
||||
next_tasks=["estimate_performance"]
|
||||
)
|
||||
|
||||
performance_task = Task(
|
||||
name="estimate_performance",
|
||||
description="Estimate performance",
|
||||
expected_output="Performance estimates",
|
||||
agent=performance_estimator,
|
||||
context=[architecture_task, hyperparameter_task],
|
||||
next_tasks=["optimize_deployment"]
|
||||
)
|
||||
|
||||
deployment_task = Task(
|
||||
name="optimize_deployment",
|
||||
description="Optimize deployment",
|
||||
expected_output="Deployment configuration",
|
||||
agent=deployment_optimizer,
|
||||
context=[architecture_task, performance_task],
|
||||
task_type="decision",
|
||||
condition={
|
||||
"success": ["generate_architecture"], # Try new architecture
|
||||
"failure": ["optimize_hyperparameters"] # Reoptimize hyperparameters
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[hardware_analyzer, architecture_generator, hyperparameter_optimizer,
|
||||
performance_estimator, deployment_optimizer],
|
||||
tasks=[hardware_task, architecture_task, hyperparameter_task,
|
||||
performance_task, deployment_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Neural Architecture Search Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nArchitecture Search Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,279 @@
|
||||
---
|
||||
title: "Quantum Optimiser"
|
||||
description: "Learn how to create AI agents for quantum circuit optimization and performance analysis."
|
||||
icon: "atom"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Circuit Analyzer]
|
||||
Analyzer --> Finder[Optimization Finder]
|
||||
Finder --> Optimizer[Circuit Optimizer]
|
||||
Optimizer --> Benchmarker[Performance Benchmarker]
|
||||
Benchmarker --> Validator[Results Validator]
|
||||
Validator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Finder fill:#2E8B57,color:#fff
|
||||
style Optimizer fill:#2E8B57,color:#fff
|
||||
style Benchmarker fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Quantum Circuit Optimization?
|
||||
|
||||
Quantum circuit optimization is the process of improving quantum algorithms by reducing circuit depth, minimizing gate count, and enhancing execution efficiency while maintaining computational fidelity. This is crucial for making quantum algorithms practical on real quantum hardware.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Circuit Analysis" icon="microchip">
|
||||
Deep analysis of quantum circuit metrics including depth, gate counts, and qubit usage.
|
||||
</Card>
|
||||
<Card title="Optimization Detection" icon="magnifying-glass">
|
||||
Identification of optimization opportunities through gate reduction and parallel execution.
|
||||
</Card>
|
||||
<Card title="Performance Simulation" icon="gauge-high">
|
||||
Simulation of optimization results with improvement metrics and success probabilities.
|
||||
</Card>
|
||||
<Card title="Benchmark Testing" icon="chart-line">
|
||||
Comprehensive benchmarking of execution time, fidelity, and resource usage.
|
||||
</Card>
|
||||
<Card title="Result Validation" icon="check-double">
|
||||
Validation of optimization results ensuring performance gains and fidelity maintenance.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_quantum_circuit():
|
||||
"""Simulates quantum circuit analysis"""
|
||||
circuit_metrics = {
|
||||
"depth": 15 + (int(time.time()) % 10),
|
||||
"gates": {
|
||||
"single_qubit": 25 + (int(time.time()) % 15),
|
||||
"two_qubit": 10 + (int(time.time()) % 8),
|
||||
"measurement": 5 + (int(time.time()) % 3)
|
||||
},
|
||||
"qubits": 8 + (int(time.time()) % 4)
|
||||
}
|
||||
return circuit_metrics
|
||||
|
||||
def identify_optimization_opportunities(metrics: Dict):
|
||||
"""Identifies potential optimization areas"""
|
||||
opportunities = []
|
||||
if metrics["depth"] > 20:
|
||||
opportunities.append({
|
||||
"type": "depth_reduction",
|
||||
"potential": "high",
|
||||
"technique": "parallel_gates"
|
||||
})
|
||||
if metrics["gates"]["two_qubit"] > 15:
|
||||
opportunities.append({
|
||||
"type": "gate_reduction",
|
||||
"potential": "medium",
|
||||
"technique": "gate_decomposition"
|
||||
})
|
||||
return opportunities
|
||||
|
||||
def simulate_optimization(opportunities: List[Dict]):
|
||||
"""Simulates optimization results"""
|
||||
results = []
|
||||
for opt in opportunities:
|
||||
improvement = {
|
||||
"high": 0.3 + (time.time() % 2) / 10,
|
||||
"medium": 0.2 + (time.time() % 2) / 10,
|
||||
"low": 0.1 + (time.time() % 2) / 10
|
||||
}
|
||||
results.append({
|
||||
"type": opt["type"],
|
||||
"improvement": improvement[opt["potential"]],
|
||||
"success_probability": 0.8 + (time.time() % 2) / 10
|
||||
})
|
||||
return results
|
||||
|
||||
def benchmark_performance(original: Dict, optimized: List[Dict]):
|
||||
"""Benchmarks optimization performance"""
|
||||
benchmarks = {
|
||||
"execution_time": {
|
||||
"original": 100 + (int(time.time()) % 50),
|
||||
"optimized": 70 + (int(time.time()) % 30)
|
||||
},
|
||||
"fidelity": {
|
||||
"original": 0.9 + (time.time() % 1) / 10,
|
||||
"optimized": 0.85 + (time.time() % 1) / 10
|
||||
},
|
||||
"resource_usage": {
|
||||
"original": original["qubits"],
|
||||
"optimized": original["qubits"] - len(optimized)
|
||||
}
|
||||
}
|
||||
return benchmarks
|
||||
|
||||
def validate_results(benchmarks: Dict):
|
||||
"""Validates optimization results"""
|
||||
validations = {
|
||||
"performance_gain": (benchmarks["execution_time"]["original"] -
|
||||
benchmarks["execution_time"]["optimized"]) /
|
||||
benchmarks["execution_time"]["original"],
|
||||
"fidelity_maintained": benchmarks["fidelity"]["optimized"] > 0.8,
|
||||
"resource_efficient": benchmarks["resource_usage"]["optimized"] <
|
||||
benchmarks["resource_usage"]["original"]
|
||||
}
|
||||
return validations
|
||||
|
||||
# Create specialized agents
|
||||
circuit_analyzer = Agent(
|
||||
name="Circuit Analyzer",
|
||||
role="Circuit Analysis",
|
||||
goal="Analyze quantum circuit structure",
|
||||
instructions="Evaluate quantum circuit metrics",
|
||||
tools=[analyze_quantum_circuit]
|
||||
)
|
||||
|
||||
optimization_finder = Agent(
|
||||
name="Optimization Finder",
|
||||
role="Optimization Discovery",
|
||||
goal="Identify optimization opportunities",
|
||||
instructions="Find potential optimization techniques",
|
||||
tools=[identify_optimization_opportunities]
|
||||
)
|
||||
|
||||
optimizer = Agent(
|
||||
name="Circuit Optimizer",
|
||||
role="Circuit Optimization",
|
||||
goal="Optimize quantum circuit",
|
||||
instructions="Apply optimization techniques",
|
||||
tools=[simulate_optimization]
|
||||
)
|
||||
|
||||
benchmarker = Agent(
|
||||
name="Performance Benchmarker",
|
||||
role="Performance Analysis",
|
||||
goal="Benchmark optimization results",
|
||||
instructions="Measure performance improvements",
|
||||
tools=[benchmark_performance]
|
||||
)
|
||||
|
||||
validator = Agent(
|
||||
name="Results Validator",
|
||||
role="Validation",
|
||||
goal="Validate optimization results",
|
||||
instructions="Ensure optimization quality",
|
||||
tools=[validate_results]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_circuit",
|
||||
description="Analyze quantum circuit",
|
||||
expected_output="Circuit metrics",
|
||||
agent=circuit_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["find_optimizations"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="find_optimizations",
|
||||
description="Find optimization opportunities",
|
||||
expected_output="Optimization opportunities",
|
||||
agent=optimization_finder,
|
||||
next_tasks=["optimize_circuit"]
|
||||
)
|
||||
|
||||
optimization_execution_task = Task(
|
||||
name="optimize_circuit",
|
||||
description="Execute circuit optimization",
|
||||
expected_output="Optimization results",
|
||||
agent=optimizer,
|
||||
next_tasks=["benchmark_performance"]
|
||||
)
|
||||
|
||||
benchmark_task = Task(
|
||||
name="benchmark_performance",
|
||||
description="Benchmark optimization",
|
||||
expected_output="Performance metrics",
|
||||
agent=benchmarker,
|
||||
next_tasks=["validate_results"],
|
||||
context=[analysis_task, optimization_execution_task]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_results",
|
||||
description="Validate optimization results",
|
||||
expected_output="Validation results",
|
||||
agent=validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"True": "", # End workflow if validation passes
|
||||
"False": ["find_optimizations"] # Retry optimization if validation fails
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[circuit_analyzer, optimization_finder, optimizer,
|
||||
benchmarker, validator],
|
||||
tasks=[analysis_task, optimization_task, optimization_execution_task,
|
||||
benchmark_task, validation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Quantum Algorithm Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nOptimization Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,274 @@
|
||||
---
|
||||
title: "Research Assistant"
|
||||
description: "Learn how to create AI agents for research analysis and experiment design."
|
||||
icon: "microscope"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Paper Analyzer]
|
||||
Analyzer --> Gap[Gap Identifier]
|
||||
Gap --> Designer[Experiment Designer]
|
||||
Designer --> Validator[Methodology Validator]
|
||||
Validator --> Impact[Impact Predictor]
|
||||
Impact --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Gap fill:#2E8B57,color:#fff
|
||||
style Designer fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Impact fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Research Analysis?
|
||||
|
||||
Research Analysis is a systematic process of analyzing scientific papers, identifying knowledge gaps, designing experiments, validating methodologies, and predicting research impact. This helps researchers make informed decisions about their research direction and experimental design.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Paper Analysis" icon="book">
|
||||
Analysis of research papers with topic identification and impact assessment.
|
||||
</Card>
|
||||
<Card title="Gap Identification" icon="magnifying-glass">
|
||||
Discovery of research gaps with significance and potential evaluation.
|
||||
</Card>
|
||||
<Card title="Experiment Design" icon="flask">
|
||||
Creation of experimental methodologies with resource planning.
|
||||
</Card>
|
||||
<Card title="Methodology Validation" icon="check-double">
|
||||
Validation of experimental design with statistical power and feasibility checks.
|
||||
</Card>
|
||||
<Card title="Impact Prediction" icon="chart-line">
|
||||
Prediction of research impact with novelty and breakthrough probability.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_research_papers():
|
||||
"""Simulates research paper analysis"""
|
||||
papers = [
|
||||
{
|
||||
"topic": "quantum_computing",
|
||||
"gaps": ["error_correction", "scalability"],
|
||||
"methodology": "experimental",
|
||||
"impact_factor": 8.5
|
||||
},
|
||||
{
|
||||
"topic": "machine_learning",
|
||||
"gaps": ["interpretability", "robustness"],
|
||||
"methodology": "theoretical",
|
||||
"impact_factor": 7.8
|
||||
}
|
||||
]
|
||||
return papers[int(time.time()) % 2]
|
||||
|
||||
def identify_knowledge_gaps(papers: Dict):
|
||||
"""Identifies research gaps"""
|
||||
gaps = []
|
||||
for gap in papers["gaps"]:
|
||||
gaps.append({
|
||||
"area": gap,
|
||||
"significance": "high" if papers["impact_factor"] > 8 else "medium",
|
||||
"research_potential": 0.8 + (time.time() % 2) / 10
|
||||
})
|
||||
return gaps
|
||||
|
||||
def design_experiment(gaps: List[Dict]):
|
||||
"""Designs experimental methodology"""
|
||||
experiments = []
|
||||
for gap in gaps:
|
||||
experiments.append({
|
||||
"area": gap["area"],
|
||||
"methodology": {
|
||||
"type": "quantitative",
|
||||
"duration": "3_months",
|
||||
"resources_needed": ["equipment_A", "dataset_B"],
|
||||
"expected_outcome": "validation_metrics"
|
||||
},
|
||||
"priority": gap["significance"]
|
||||
})
|
||||
return experiments
|
||||
|
||||
def validate_methodology(experiments: List[Dict]):
|
||||
"""Validates experimental design"""
|
||||
validations = []
|
||||
for exp in experiments:
|
||||
validations.append({
|
||||
"area": exp["area"],
|
||||
"statistical_power": 0.9 + (time.time() % 1) / 10,
|
||||
"resource_feasibility": 0.8 + (time.time() % 1) / 10,
|
||||
"ethical_compliance": True,
|
||||
"recommendations": []
|
||||
})
|
||||
return validations
|
||||
|
||||
def predict_impact(experiments: List[Dict], validations: List[Dict]):
|
||||
"""Predicts research impact"""
|
||||
predictions = []
|
||||
for exp, val in zip(experiments, validations):
|
||||
predictions.append({
|
||||
"area": exp["area"],
|
||||
"potential_impact": val["statistical_power"] * 10,
|
||||
"novelty_score": 0.7 + (time.time() % 3) / 10,
|
||||
"breakthrough_probability": 0.5 + (time.time() % 4) / 10
|
||||
})
|
||||
return predictions
|
||||
|
||||
# Create specialized agents
|
||||
paper_analyzer = Agent(
|
||||
name="Paper Analyzer",
|
||||
role="Research Analysis",
|
||||
goal="Analyze research papers",
|
||||
instructions="Review and analyze scientific papers",
|
||||
tools=[analyze_research_papers]
|
||||
)
|
||||
|
||||
gap_identifier = Agent(
|
||||
name="Gap Identifier",
|
||||
role="Gap Analysis",
|
||||
goal="Identify knowledge gaps",
|
||||
instructions="Identify research opportunities",
|
||||
tools=[identify_knowledge_gaps]
|
||||
)
|
||||
|
||||
experiment_designer = Agent(
|
||||
name="Experiment Designer",
|
||||
role="Experimental Design",
|
||||
goal="Design research experiments",
|
||||
instructions="Create experimental methodologies",
|
||||
tools=[design_experiment]
|
||||
)
|
||||
|
||||
methodology_validator = Agent(
|
||||
name="Methodology Validator",
|
||||
role="Validation",
|
||||
goal="Validate experimental design",
|
||||
instructions="Ensure methodology validity",
|
||||
tools=[validate_methodology]
|
||||
)
|
||||
|
||||
impact_predictor = Agent(
|
||||
name="Impact Predictor",
|
||||
role="Impact Analysis",
|
||||
goal="Predict research impact",
|
||||
instructions="Assess potential impact",
|
||||
tools=[predict_impact]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_papers",
|
||||
description="Analyze research papers",
|
||||
expected_output="Paper analysis results",
|
||||
agent=paper_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["identify_gaps"]
|
||||
)
|
||||
|
||||
gap_task = Task(
|
||||
name="identify_gaps",
|
||||
description="Identify knowledge gaps",
|
||||
expected_output="Research gaps",
|
||||
agent=gap_identifier,
|
||||
next_tasks=["design_experiments"]
|
||||
)
|
||||
|
||||
design_task = Task(
|
||||
name="design_experiments",
|
||||
description="Design experiments",
|
||||
expected_output="Experimental designs",
|
||||
agent=experiment_designer,
|
||||
next_tasks=["validate_methodology"]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_methodology",
|
||||
description="Validate methodology",
|
||||
expected_output="Validation results",
|
||||
agent=methodology_validator,
|
||||
next_tasks=["predict_impact"]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_impact",
|
||||
description="Predict research impact",
|
||||
expected_output="Impact predictions",
|
||||
agent=impact_predictor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": "", # End workflow if high impact
|
||||
"medium": ["design_experiments"], # Refine if medium impact
|
||||
"low": ["identify_gaps"] # Restart if low impact
|
||||
},
|
||||
context=[design_task, validation_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[paper_analyzer, gap_identifier, experiment_designer,
|
||||
methodology_validator, impact_predictor],
|
||||
tasks=[analysis_task, gap_task, design_task,
|
||||
validation_task, prediction_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Research Assistant Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nResearch Analysis Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,313 @@
|
||||
---
|
||||
title: "Space Mission"
|
||||
description: "Learn how to create AI agents for space mission planning and resource optimization."
|
||||
icon: "rocket"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Mission[Mission Analyzer]
|
||||
Mission --> Resources[Resource Calculator]
|
||||
Resources --> Contingency[Contingency Planner]
|
||||
Contingency --> Optimizer[Resource Optimizer]
|
||||
Optimizer --> Simulator[Scenario Simulator]
|
||||
Simulator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Mission fill:#2E8B57,color:#fff
|
||||
style Resources fill:#2E8B57,color:#fff
|
||||
style Contingency fill:#2E8B57,color:#fff
|
||||
style Optimizer fill:#2E8B57,color:#fff
|
||||
style Simulator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Space Mission Planning?
|
||||
|
||||
Space Mission Planning is a complex process that involves analyzing mission parameters, calculating resource requirements, planning contingencies, optimizing resource allocation, and simulating various scenarios. This ensures the safety and success of space missions by carefully managing resources and preparing for potential emergencies.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mission Analysis" icon="satellite">
|
||||
Analysis of mission duration, crew size, orbital parameters, and objectives.
|
||||
</Card>
|
||||
<Card title="Resource Calculation" icon="calculator">
|
||||
Computation of life support, power, and propellant requirements.
|
||||
</Card>
|
||||
<Card title="Contingency Planning" icon="shield">
|
||||
Planning for power failures, life support malfunctions, and other emergencies.
|
||||
</Card>
|
||||
<Card title="Resource Optimization" icon="chart-line">
|
||||
Optimization of resource allocation with buffers for contingencies.
|
||||
</Card>
|
||||
<Card title="Scenario Simulation" icon="vr-cardboard">
|
||||
Simulation of nominal operations and emergency scenarios.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_mission_parameters():
|
||||
"""Simulates mission parameter analysis"""
|
||||
parameters = {
|
||||
"duration": 180, # days
|
||||
"crew_size": 4,
|
||||
"orbital_parameters": {
|
||||
"altitude": 400, # km
|
||||
"inclination": 51.6, # degrees
|
||||
"period": 92.68 # minutes
|
||||
},
|
||||
"mission_objectives": [
|
||||
"scientific_research",
|
||||
"satellite_deployment",
|
||||
"space_station_maintenance"
|
||||
]
|
||||
}
|
||||
return parameters
|
||||
|
||||
def calculate_resource_requirements(params: Dict):
|
||||
"""Calculates required resources"""
|
||||
requirements = {
|
||||
"life_support": {
|
||||
"oxygen": params["duration"] * params["crew_size"] * 0.84, # kg
|
||||
"water": params["duration"] * params["crew_size"] * 2.5, # liters
|
||||
"food": params["duration"] * params["crew_size"] * 1.8 # kg
|
||||
},
|
||||
"power": {
|
||||
"daily_consumption": 30 + (params["crew_size"] * 5), # kWh
|
||||
"peak_demand": 45 + (params["crew_size"] * 8), # kW
|
||||
"backup_capacity": 72 # hours
|
||||
},
|
||||
"propellant": {
|
||||
"main_engine": 2000, # kg
|
||||
"attitude_control": 500, # kg
|
||||
"reserve": 300 # kg
|
||||
}
|
||||
}
|
||||
return requirements
|
||||
|
||||
def plan_contingencies(requirements: Dict):
|
||||
"""Plans contingency scenarios"""
|
||||
contingencies = [
|
||||
{
|
||||
"scenario": "power_failure",
|
||||
"probability": 0.05,
|
||||
"impact": "critical",
|
||||
"resources_needed": {
|
||||
"backup_power": requirements["power"]["daily_consumption"] * 3,
|
||||
"repair_equipment": ["solar_panel_kit", "power_distribution_unit"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "life_support_malfunction",
|
||||
"probability": 0.03,
|
||||
"impact": "severe",
|
||||
"resources_needed": {
|
||||
"oxygen_reserve": requirements["life_support"]["oxygen"] * 0.2,
|
||||
"repair_parts": ["filter_system", "pressure_regulators"]
|
||||
}
|
||||
}
|
||||
]
|
||||
return contingencies[int(time.time()) % 2]
|
||||
|
||||
def optimize_allocation(requirements: Dict, contingencies: Dict):
|
||||
"""Optimizes resource allocation"""
|
||||
allocation = {
|
||||
"primary_resources": {
|
||||
"life_support": {
|
||||
"nominal": requirements["life_support"],
|
||||
"buffer": 0.15 # 15% buffer
|
||||
},
|
||||
"power": {
|
||||
"nominal": requirements["power"],
|
||||
"buffer": 0.2 # 20% buffer
|
||||
}
|
||||
},
|
||||
"contingency_resources": {
|
||||
"type": contingencies["scenario"],
|
||||
"allocation": contingencies["resources_needed"],
|
||||
"priority": "high" if contingencies["impact"] == "critical" else "medium"
|
||||
}
|
||||
}
|
||||
return allocation
|
||||
|
||||
def simulate_mission_scenarios(allocation: Dict):
|
||||
"""Simulates various mission scenarios"""
|
||||
scenarios = {
|
||||
"nominal_operations": {
|
||||
"success_rate": 0.95,
|
||||
"resource_utilization": 0.85,
|
||||
"efficiency_rating": 0.9
|
||||
},
|
||||
"emergency_scenarios": [
|
||||
{
|
||||
"type": "power_reduction",
|
||||
"duration": 48, # hours
|
||||
"impact": "moderate",
|
||||
"resolution_success": 0.88
|
||||
},
|
||||
{
|
||||
"type": "life_support_adjustment",
|
||||
"duration": 24, # hours
|
||||
"impact": "minor",
|
||||
"resolution_success": 0.92
|
||||
}
|
||||
]
|
||||
}
|
||||
return scenarios
|
||||
|
||||
# Create specialized agents
|
||||
mission_analyzer = Agent(
|
||||
name="Mission Analyzer",
|
||||
role="Mission Analysis",
|
||||
goal="Analyze mission parameters",
|
||||
instructions="Evaluate mission requirements and constraints",
|
||||
tools=[analyze_mission_parameters]
|
||||
)
|
||||
|
||||
resource_calculator = Agent(
|
||||
name="Resource Calculator",
|
||||
role="Resource Calculation",
|
||||
goal="Calculate resource requirements",
|
||||
instructions="Determine required resources for mission",
|
||||
tools=[calculate_resource_requirements]
|
||||
)
|
||||
|
||||
contingency_planner = Agent(
|
||||
name="Contingency Planner",
|
||||
role="Contingency Planning",
|
||||
goal="Plan for contingencies",
|
||||
instructions="Develop contingency scenarios and plans",
|
||||
tools=[plan_contingencies]
|
||||
)
|
||||
|
||||
resource_optimizer = Agent(
|
||||
name="Resource Optimizer",
|
||||
role="Resource Optimization",
|
||||
goal="Optimize resource allocation",
|
||||
instructions="Optimize resource distribution",
|
||||
tools=[optimize_allocation]
|
||||
)
|
||||
|
||||
scenario_simulator = Agent(
|
||||
name="Scenario Simulator",
|
||||
role="Scenario Simulation",
|
||||
goal="Simulate mission scenarios",
|
||||
instructions="Simulate various mission scenarios",
|
||||
tools=[simulate_mission_scenarios]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
mission_task = Task(
|
||||
name="analyze_mission",
|
||||
description="Analyze mission parameters",
|
||||
expected_output="Mission parameters",
|
||||
agent=mission_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["calculate_resources"]
|
||||
)
|
||||
|
||||
resource_task = Task(
|
||||
name="calculate_resources",
|
||||
description="Calculate resource requirements",
|
||||
expected_output="Resource requirements",
|
||||
agent=resource_calculator,
|
||||
next_tasks=["plan_contingencies"]
|
||||
)
|
||||
|
||||
contingency_task = Task(
|
||||
name="plan_contingencies",
|
||||
description="Plan contingencies",
|
||||
expected_output="Contingency plans",
|
||||
agent=contingency_planner,
|
||||
context=[resource_task],
|
||||
next_tasks=["optimize_resources"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="optimize_resources",
|
||||
description="Optimize resource allocation",
|
||||
expected_output="Resource allocation",
|
||||
agent=resource_optimizer,
|
||||
context=[resource_task, contingency_task],
|
||||
next_tasks=["simulate_scenarios"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_scenarios",
|
||||
description="Simulate scenarios",
|
||||
expected_output="Simulation results",
|
||||
agent=scenario_simulator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"nominal_operations": "", # End workflow if nominal
|
||||
"emergency_scenarios": ["optimize_resources"] # Reoptimize if emergency
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[mission_analyzer, resource_calculator, contingency_planner,
|
||||
resource_optimizer, scenario_simulator],
|
||||
tasks=[mission_task, resource_task, contingency_task,
|
||||
optimization_task, simulation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Space Mission Resource Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nResource Optimization Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,277 @@
|
||||
---
|
||||
title: "Vulnerability Detection"
|
||||
description: "Learn how to create AI agents for vulnerability detection and analysis."
|
||||
icon: "shield-check"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Scanner[Pattern Scanner]
|
||||
Scanner --> Vector[Vector Analyzer]
|
||||
Vector --> Simulator[Exploit Simulator]
|
||||
Simulator --> Generator[Signature Generator]
|
||||
Generator --> Validator[Finding Validator]
|
||||
Validator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Scanner fill:#2E8B57,color:#fff
|
||||
style Vector fill:#2E8B57,color:#fff
|
||||
style Simulator fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Vulnerability Detection?
|
||||
|
||||
Vulnerability Detection is a systematic process of identifying, analyzing, and validating security vulnerabilities in code. It involves pattern scanning, attack vector analysis, exploitation simulation, signature generation, and finding validation to ensure robust security measures are in place.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Pattern Scanning" icon="magnifying-glass">
|
||||
Detection of buffer overflows, SQL injections, and race conditions.
|
||||
</Card>
|
||||
<Card title="Attack Vector Analysis" icon="route">
|
||||
Analysis of attack paths, complexity, and CVSS scores.
|
||||
</Card>
|
||||
<Card title="Exploit Simulation" icon="bug">
|
||||
Simulation of exploitation attempts with success rate and detection time.
|
||||
</Card>
|
||||
<Card title="Signature Generation" icon="fingerprint">
|
||||
Creation of vulnerability signatures with reliability metrics.
|
||||
</Card>
|
||||
<Card title="Finding Validation" icon="check-double">
|
||||
Validation of findings with confidence and reproducibility scores.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def scan_code_patterns():
|
||||
"""Simulates code pattern scanning"""
|
||||
patterns = [
|
||||
{
|
||||
"type": "buffer_overflow",
|
||||
"severity": "critical",
|
||||
"location": "memory_management",
|
||||
"frequency": 3
|
||||
},
|
||||
{
|
||||
"type": "sql_injection",
|
||||
"severity": "high",
|
||||
"location": "database_interface",
|
||||
"frequency": 2
|
||||
},
|
||||
{
|
||||
"type": "race_condition",
|
||||
"severity": "medium",
|
||||
"location": "thread_handling",
|
||||
"frequency": 1
|
||||
}
|
||||
]
|
||||
return patterns[int(time.time()) % 3]
|
||||
|
||||
def analyze_attack_vectors(pattern: Dict):
|
||||
"""Analyzes potential attack vectors"""
|
||||
vectors = []
|
||||
severity_scores = {"critical": 9.5, "high": 8.0, "medium": 6.5}
|
||||
base_score = severity_scores[pattern["type"]]
|
||||
|
||||
vectors.append({
|
||||
"type": pattern["type"],
|
||||
"attack_path": f"exploit_{pattern['location']}",
|
||||
"complexity": "high" if pattern["frequency"] < 2 else "medium",
|
||||
"cvss_score": base_score + (time.time() % 1)
|
||||
})
|
||||
return vectors
|
||||
|
||||
def simulate_exploitation(vectors: List[Dict]):
|
||||
"""Simulates exploitation attempts"""
|
||||
results = []
|
||||
for vector in vectors:
|
||||
results.append({
|
||||
"vector": vector["type"],
|
||||
"success_rate": 0.7 + (time.time() % 3) / 10,
|
||||
"detection_time": 100 + (int(time.time()) % 50),
|
||||
"mitigation_possible": vector["complexity"] != "high"
|
||||
})
|
||||
return results
|
||||
|
||||
def generate_signatures(results: List[Dict]):
|
||||
"""Generates vulnerability signatures"""
|
||||
signatures = []
|
||||
for result in results:
|
||||
signatures.append({
|
||||
"pattern": f"signature_{result['vector']}",
|
||||
"reliability": result['success_rate'],
|
||||
"false_positive_rate": 0.1 + (time.time() % 2) / 10,
|
||||
"detection_speed": result['detection_time']
|
||||
})
|
||||
return signatures
|
||||
|
||||
def validate_findings(signatures: List[Dict]):
|
||||
"""Validates vulnerability findings"""
|
||||
validations = []
|
||||
for sig in signatures:
|
||||
validations.append({
|
||||
"signature": sig["pattern"],
|
||||
"confidence": sig["reliability"] * (1 - sig["false_positive_rate"]),
|
||||
"reproducibility": 0.8 + (time.time() % 2) / 10,
|
||||
"severity": "critical" if sig["reliability"] > 0.8 else "high"
|
||||
})
|
||||
return validations
|
||||
|
||||
# Create specialized agents
|
||||
pattern_scanner = Agent(
|
||||
name="Pattern Scanner",
|
||||
role="Code Analysis",
|
||||
goal="Scan for suspicious patterns",
|
||||
instructions="Analyze code for potential vulnerabilities",
|
||||
tools=[scan_code_patterns]
|
||||
)
|
||||
|
||||
vector_analyzer = Agent(
|
||||
name="Vector Analyzer",
|
||||
role="Attack Vector Analysis",
|
||||
goal="Analyze attack vectors",
|
||||
instructions="Identify potential attack paths",
|
||||
tools=[analyze_attack_vectors]
|
||||
)
|
||||
|
||||
exploit_simulator = Agent(
|
||||
name="Exploit Simulator",
|
||||
role="Exploitation Testing",
|
||||
goal="Simulate exploitation attempts",
|
||||
instructions="Test potential vulnerabilities",
|
||||
tools=[simulate_exploitation]
|
||||
)
|
||||
|
||||
signature_generator = Agent(
|
||||
name="Signature Generator",
|
||||
role="Signature Creation",
|
||||
goal="Generate vulnerability signatures",
|
||||
instructions="Create detection signatures",
|
||||
tools=[generate_signatures]
|
||||
)
|
||||
|
||||
finding_validator = Agent(
|
||||
name="Finding Validator",
|
||||
role="Validation",
|
||||
goal="Validate findings",
|
||||
instructions="Verify vulnerability findings",
|
||||
tools=[validate_findings]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
scanning_task = Task(
|
||||
name="scan_patterns",
|
||||
description="Scan code patterns",
|
||||
expected_output="Suspicious patterns",
|
||||
agent=pattern_scanner,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_vectors"]
|
||||
)
|
||||
|
||||
vector_task = Task(
|
||||
name="analyze_vectors",
|
||||
description="Analyze attack vectors",
|
||||
expected_output="Attack vectors",
|
||||
agent=vector_analyzer,
|
||||
next_tasks=["simulate_exploits"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_exploits",
|
||||
description="Simulate exploits",
|
||||
expected_output="Exploitation results",
|
||||
agent=exploit_simulator,
|
||||
next_tasks=["generate_signatures"]
|
||||
)
|
||||
|
||||
signature_task = Task(
|
||||
name="generate_signatures",
|
||||
description="Generate signatures",
|
||||
expected_output="Vulnerability signatures",
|
||||
agent=signature_generator,
|
||||
next_tasks=["validate_findings"]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_findings",
|
||||
description="Validate findings",
|
||||
expected_output="Validation results",
|
||||
agent=finding_validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"critical": ["scan_patterns"], # Continue scanning if critical
|
||||
"high": ["analyze_vectors"], # Reanalyze if high
|
||||
"medium": "" # End workflow if medium
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[pattern_scanner, vector_analyzer, exploit_simulator,
|
||||
signature_generator, finding_validator],
|
||||
tasks=[scanning_task, vector_task, simulation_task,
|
||||
signature_task, validation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Vulnerability Detection Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nVulnerability Detection Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
+13
-26
@@ -6,9 +6,7 @@ icon: "book-open"
|
||||
|
||||
## What is PraisonAI?
|
||||
|
||||
<Note>
|
||||
PraisonAI is a powerful Multi-Agent Framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
|
||||
</Note>
|
||||
PraisonAI is a powerful Multi-Agent Framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Welcome to PraisonAI" icon="wand-magic-sparkles">
|
||||
Build powerful autonomous agents that understand, decide, and execute with unprecedented capability.
|
||||
@@ -26,45 +24,34 @@ graph LR
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[" "]
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
|
||||
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Agent2[" "]
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
|
||||
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Style for agent containers
|
||||
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Start,Output,Task1,Task2 input
|
||||
class Process,AgentIcon1,AgentIcon2 process
|
||||
class Tools1,Tools2 tools
|
||||
class Agent1,Agent2 transparent
|
||||
```
|
||||
<br />
|
||||
<CardGroup cols={2}>
|
||||
|
||||
+16
-3
@@ -70,6 +70,10 @@
|
||||
{
|
||||
"name": "UI",
|
||||
"url": "/ui"
|
||||
},
|
||||
{
|
||||
"name": "Tools",
|
||||
"url": "/tools"
|
||||
}
|
||||
],
|
||||
"navigation": [
|
||||
@@ -151,7 +155,16 @@
|
||||
"examples/customer-service",
|
||||
"examples/smart-city",
|
||||
"examples/multilingual-content",
|
||||
"examples/adaptive-learning"
|
||||
"examples/adaptive-learning",
|
||||
"examples/crypto-validator",
|
||||
"examples/space-mission",
|
||||
"examples/neural-architecture",
|
||||
"examples/defi-market-maker",
|
||||
"examples/medicine-protocol",
|
||||
"examples/climate-impact",
|
||||
"examples/vulnerability-detection",
|
||||
"examples/research-assistant",
|
||||
"examples/quantum-optimiser"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -177,6 +190,8 @@
|
||||
{
|
||||
"group": "Tools",
|
||||
"pages": [
|
||||
"tools/tools",
|
||||
"tools/langchain_tools",
|
||||
"tools/duckduckgo_tools",
|
||||
"tools/arxiv_tools",
|
||||
"tools/calculator_tools",
|
||||
@@ -194,7 +209,6 @@
|
||||
"tools/xml_tools",
|
||||
"tools/yaml_tools",
|
||||
"tools/yfinance_tools",
|
||||
"tools",
|
||||
"tools/custom",
|
||||
"tools/tools_class",
|
||||
"tools/gpt",
|
||||
@@ -239,7 +253,6 @@
|
||||
{
|
||||
"group": "Developers",
|
||||
"pages": [
|
||||
"examples",
|
||||
"developers/test",
|
||||
"developers/agents-playbook",
|
||||
"developers/wrapper",
|
||||
|
||||
+138
-4
@@ -1,9 +1,143 @@
|
||||
---
|
||||
title: Quick Start
|
||||
description: Build your first AI agent with PraisonAI
|
||||
icon: bolt
|
||||
title: "Quick Start"
|
||||
description: "Create AI Agents and make them work for you in just a few lines of code."
|
||||
icon: "bolt"
|
||||
---
|
||||
|
||||
# Basic
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys).
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agents">
|
||||
Create `app.py`:
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Create a simple agent
|
||||
summarise_agent = Agent(instructions="Summarise Photosynthesis")
|
||||
|
||||
# Run the agent
|
||||
agents = PraisonAIAgents(agents=[summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
|
||||
```python Multiple Agents
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Create agents with specific roles
|
||||
diet_agent = Agent(
|
||||
instructions="Give me 5 healthy food recipes",
|
||||
)
|
||||
|
||||
blog_agent = Agent(
|
||||
instructions="Write a blog post about the food recipes",
|
||||
)
|
||||
|
||||
# Run multiple agents
|
||||
agents = PraisonAIAgents(agents=[diet_agent, blog_agent])
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Run Agents">
|
||||
Execute your script:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
You'll see:
|
||||
- Agent initialization
|
||||
- Task execution progress
|
||||
- Final results
|
||||
|
||||
<Tip>
|
||||
You have successfully CreatedAI Agents and made them work for you!
|
||||
</Tip>
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install the No Code PraisonAI Package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Config">
|
||||
Create `agents.yaml`:
|
||||
|
||||
<CodeGroup>
|
||||
```yaml Single Agent
|
||||
roles:
|
||||
summarise_agent:
|
||||
instructions: Summarise Photosynthesis
|
||||
```
|
||||
|
||||
```yaml Multiple Agents
|
||||
roles:
|
||||
diet_agent:
|
||||
instructions: Give me 5 healthy food recipes
|
||||
blog_agent:
|
||||
instructions: Write a blog post about the food recipes
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Note>
|
||||
You can automatically create `agents.yaml` using:
|
||||
```bash
|
||||
praisonai --init "your task description"
|
||||
```
|
||||
</Note>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Run Agents">
|
||||
Execute your config:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Note>
|
||||
**Prerequisites**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key (get it [here](https://platform.openai.com/api-keys))
|
||||
- For other LLM providers, see [Models](/models)
|
||||
</Note>
|
||||
|
||||
# Advanced
|
||||
|
||||
## Providing Detailed Tasks to Agents (Optional)
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
@@ -180,7 +314,7 @@ praisonai --init create movie script about cat in mars
|
||||
</Tabs>
|
||||
|
||||
|
||||
## Creating Custom Tool for Agents
|
||||
## Creating Custom Tool for Agents (Optional)
|
||||
|
||||
<Info>
|
||||
Tools makes the Agent powerful.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
title: "Create Custom Tools"
|
||||
title: "Low Code Custom Tools"
|
||||
sidebarTitle: "Low Code Custom Tools"
|
||||
description: "Step-by-step guide for creating and implementing custom tools in PraisonAI, including examples and configuration instructions"
|
||||
icon: "wrench"
|
||||
---
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
---
|
||||
title: "LangChain Agent"
|
||||
sidebarTitle: "LangChain Agent"
|
||||
description: "Learn how to use LangChain tools and utilities with PraisonAI agents."
|
||||
icon: "link-simple"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the required packages:
|
||||
```bash
|
||||
pip install praisonaiagents langchain-community wikipedia
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
<CodeGroup>
|
||||
```python Single Tool
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from langchain_community.utilities import WikipediaAPIWrapper
|
||||
|
||||
# Create an agent with Wikipedia tool
|
||||
agent = Agent(
|
||||
name="WikiAgent",
|
||||
role="Research Assistant",
|
||||
goal="Search Wikipedia for accurate information",
|
||||
backstory="I am an AI assistant specialized in Wikipedia research",
|
||||
tools=[WikipediaAPIWrapper],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create a research task
|
||||
task = Task(
|
||||
name="wiki_search",
|
||||
description="Research 'Artificial Intelligence' on Wikipedia",
|
||||
expected_output="Comprehensive information from Wikipedia articles",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Create and start the workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
|
||||
```python Multiple Tools
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from langchain_community.tools import YouTubeSearchTool
|
||||
from langchain_community.utilities import WikipediaAPIWrapper
|
||||
|
||||
# Create YouTube search agent
|
||||
agent = Agent(
|
||||
name="SearchAgent",
|
||||
role="Research Assistant",
|
||||
goal="Search for information from YouTube",
|
||||
backstory="I am an AI assistant that can search YouTube for relevant videos.",
|
||||
tools=[YouTubeSearchTool],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create Wikipedia research agent
|
||||
agent2 = Agent(
|
||||
name="WikiAgent",
|
||||
role="Research Assistant",
|
||||
goal="Search for information from Wikipedia",
|
||||
backstory="I am an AI assistant that can search Wikipedia for accurate information.",
|
||||
tools=[WikipediaAPIWrapper],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create YouTube search task
|
||||
task = Task(
|
||||
name="search_task",
|
||||
description="Search for information about 'AI advancements' on YouTube",
|
||||
expected_output="Relevant information from YouTube videos",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Create Wikipedia research task
|
||||
task2 = Task(
|
||||
name="wiki_task",
|
||||
description="Search for information about 'AI advancements' on Wikipedia",
|
||||
expected_output="Comprehensive information from Wikipedia articles",
|
||||
agent=agent2
|
||||
)
|
||||
|
||||
# Create and start the workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent, agent2],
|
||||
tasks=[task, task2],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
(Upcoming Feature)
|
||||
Install the PraisonAI package:
|
||||
```bash
|
||||
pip install "praisonai"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create a file">
|
||||
Create a new file `agents.yaml` with the basic setup:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
roles:
|
||||
researcher:
|
||||
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:
|
||||
- youtube_search
|
||||
- wikipedia
|
||||
tasks:
|
||||
search_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
|
||||
```
|
||||
</Step>
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys)
|
||||
- LangChain compatible tools and utilities
|
||||
</Note>
|
||||
|
||||
## Understanding LangChain Integration
|
||||
|
||||
<Card title="What is LangChain Integration?" icon="question">
|
||||
LangChain integration enables agents to:
|
||||
- Use LangChain's extensive tool ecosystem
|
||||
- Access various data sources and APIs
|
||||
- Leverage pre-built utilities and wrappers
|
||||
- Combine multiple tools in a single agent
|
||||
- Extend agent capabilities with community tools
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Tool Integration" icon="plug">
|
||||
Seamlessly use LangChain tools with PraisonAI agents.
|
||||
</Card>
|
||||
<Card title="Multiple Sources" icon="database">
|
||||
Access various data sources through LangChain utilities.
|
||||
</Card>
|
||||
<Card title="Community Tools" icon="users">
|
||||
Leverage the extensive LangChain community ecosystem.
|
||||
</Card>
|
||||
<Card title="Custom Tools" icon="wrench">
|
||||
Create and integrate custom LangChain tools.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Memory Integration" icon="brain" href="../concepts/memory">
|
||||
Learn how to combine LangChain tools with agent memory
|
||||
</Card>
|
||||
<Card title="Custom Tools" icon="wrench" href="./tools">
|
||||
Create your own custom tools for agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure all required dependencies are installed and API keys are properly configured for each tool.
|
||||
</Note>
|
||||
@@ -0,0 +1,647 @@
|
||||
---
|
||||
title: "AI Agents with Tools"
|
||||
sidebarTitle: "Tools"
|
||||
description: "Learn how to create AI agents that can use tools to interact with external systems and perform actions."
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Tools
|
||||
direction TB
|
||||
T3[Internet Search]
|
||||
T1[Code Execution]
|
||||
T2[Formatting]
|
||||
end
|
||||
|
||||
Input[Input] ---> Agents
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
Agents ---> Output[Output]
|
||||
|
||||
T3 --> A1
|
||||
T1 --> A2
|
||||
T2 --> A3
|
||||
|
||||
style Tools fill:#189AB4,color:#fff
|
||||
style Agents fill:#8B0000,color:#fff
|
||||
style Input fill:#8B0000,color:#fff
|
||||
style Output fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
| Feature | [Knowledge](/concepts/knowledge) | [Tools](/concepts/tools) |
|
||||
|---------|--------------------------------|---------------------------|
|
||||
| Purpose | Static reference information | Dynamic interaction capabilities |
|
||||
| Access | Read-only reference | Execute actions and commands |
|
||||
| Updates | Manual through files | Real-time through tool calls |
|
||||
| Storage | Knowledge base | Assigned to specific agents |
|
||||
| Persistence | Permanent until changed | Available during agent execution |
|
||||
|
||||
## Quick Start
|
||||
|
||||
Tools are functions that agents can use to interact with external systems and perform actions. They are essential for creating agents that can do more than just process text.
|
||||
|
||||
## Creating Custom Tool
|
||||
<Steps>
|
||||
<Step>
|
||||
Create any function that you want to use as a tool, that performs a specific task.
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# Tool Implementation
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search using DuckDuckGo
|
||||
|
||||
Args:
|
||||
query (str): The search query string
|
||||
|
||||
Returns:
|
||||
List[Dict]: List of search results containing title, URL, and snippet
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
Assign the tool to an agent
|
||||
```python
|
||||
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], ## Add the tool to the agent i.e the function name
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Card title="That's it!">
|
||||
<Check>You have created a custom tool and assigned it to an agent.</Check>
|
||||
</Card>
|
||||
|
||||
## Implementing Tools Full Code Example
|
||||
<Tabs>
|
||||
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents duckduckgo-search
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agent with Tool">
|
||||
Create `app.py`
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# 1. Tool Implementation
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search using DuckDuckGo
|
||||
|
||||
Args:
|
||||
query (str): The search query string
|
||||
|
||||
Returns:
|
||||
List[Dict]: List of search results containing title, URL, and snippet
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
# 2. Assign the tool to an 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. Task Definition
|
||||
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",
|
||||
)
|
||||
|
||||
# 4. Start Agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[data_agent],
|
||||
tasks=[collect_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package and duckduckgo_search package:
|
||||
```bash Terminal
|
||||
pip install praisonai duckduckgo_search
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Custom Tool">
|
||||
<Info>
|
||||
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
|
||||
</Info>
|
||||
Create a new file `tools.py` with the following content:
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# 1. Tool
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Agent">
|
||||
|
||||
Create a new file `agents.yaml` with the following content:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
topic: create movie script about cat in mars
|
||||
roles:
|
||||
scriptwriter:
|
||||
backstory: Expert in dialogue and script structure, translating concepts into
|
||||
scripts.
|
||||
goal: Write a movie script about a cat in Mars
|
||||
role: Scriptwriter
|
||||
tools:
|
||||
- internet_search_tool # <-- Tool assigned to Agent here
|
||||
tasks:
|
||||
scriptwriting_task:
|
||||
description: Turn the story concept into a production-ready movie script,
|
||||
including dialogue and scene details.
|
||||
expected_output: Final movie script with dialogue and scene details.
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## In-build Tools in PraisonAI
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Search Tools" icon="magnifying-glass" href="/tools/search">
|
||||
Tools for searching and retrieving information from various sources
|
||||
</Card>
|
||||
<Card title="Python Tools" icon="python" href="/tools/python_tools">
|
||||
Essential Python utilities for data manipulation and scripting
|
||||
</Card>
|
||||
<Card title="Spider Tools" icon="spider" href="/tools/spider_tools">
|
||||
Web crawling and scraping capabilities for data extraction
|
||||
</Card>
|
||||
<Card title="Arxiv Tools" icon="book" href="/tools/arxiv_tools">
|
||||
Access and search academic papers from arXiv repository
|
||||
</Card>
|
||||
<Card title="Newspaper Tools" icon="newspaper" href="/tools/newspaper_tools">
|
||||
Extract and parse content from news articles and websites
|
||||
</Card>
|
||||
<Card title="DuckDB Tools" icon="database" href="/tools/duckdb_tools">
|
||||
Fast analytical SQL database operations and queries
|
||||
</Card>
|
||||
<Card title="DuckDuckGo Tools" icon="duck" href="/tools/duckduckgo_tools">
|
||||
Web search functionality using DuckDuckGo's API
|
||||
</Card>
|
||||
<Card title="Calculator Tools" icon="calculator" href="/tools/calculator_tools">
|
||||
Perform mathematical calculations and conversions
|
||||
</Card>
|
||||
<Card title="YAML Tools" icon="file-code" href="/tools/yaml_tools">
|
||||
Parse and manipulate YAML format data
|
||||
</Card>
|
||||
<Card title="JSON Tools" icon="brackets-curly" href="/tools/json_tools">
|
||||
Handle JSON data structures and operations
|
||||
</Card>
|
||||
<Card title="Pandas Tools" icon="table" href="/tools/pandas_tools">
|
||||
Data analysis and manipulation using Pandas
|
||||
</Card>
|
||||
<Card title="YFinance Tools" icon="chart-line" href="/tools/yfinance_tools">
|
||||
Fetch financial market data from Yahoo Finance
|
||||
</Card>
|
||||
<Card title="Shell Tools" icon="terminal" href="/tools/shell_tools">
|
||||
Execute shell commands and system operations
|
||||
</Card>
|
||||
<Card title="Wikipedia Tools" icon="book-open" href="/tools/wikipedia_tools">
|
||||
Access and search Wikipedia articles and data
|
||||
</Card>
|
||||
<Card title="XML Tools" icon="code" href="/tools/xml_tools">
|
||||
Process and manipulate XML format data
|
||||
</Card>
|
||||
<Card title="File Tools" icon="file" href="/tools/file_tools">
|
||||
File system operations and management utilities
|
||||
</Card>
|
||||
<Card title="Excel Tools" icon="file-excel" href="/tools/excel_tools">
|
||||
Work with Excel spreadsheets and workbooks
|
||||
</Card>
|
||||
<Card title="CSV Tools" icon="file-csv" href="/tools/csv_tools">
|
||||
Handle CSV file operations and transformations
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Tools Overview
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card
|
||||
title="Search Tools"
|
||||
icon="magnifying-glass"
|
||||
iconType="solid"
|
||||
>
|
||||
Tools for searching and retrieving information from various sources
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="File Tools"
|
||||
icon="file"
|
||||
iconType="solid"
|
||||
>
|
||||
Tools for reading, writing, and manipulating files
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="API Tools"
|
||||
icon="code"
|
||||
iconType="solid"
|
||||
>
|
||||
Tools for interacting with external APIs and services
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Advanced Tool Features
|
||||
|
||||
### Tool Configuration
|
||||
<Frame>
|
||||
```python
|
||||
def configured_tool(
|
||||
query: str,
|
||||
max_results: int = 5,
|
||||
timeout: int = 10
|
||||
) -> List[Dict]:
|
||||
"""
|
||||
Example of a configurable tool
|
||||
|
||||
Args:
|
||||
query (str): Search query
|
||||
max_results (int): Maximum number of results
|
||||
timeout (int): Request timeout in seconds
|
||||
|
||||
Returns:
|
||||
List[Dict]: Search results
|
||||
"""
|
||||
# Tool implementation
|
||||
pass
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Chaining
|
||||
<Frame>
|
||||
```python
|
||||
def chain_tools(input_data: str) -> Dict:
|
||||
"""
|
||||
Example of chaining multiple tools
|
||||
|
||||
Args:
|
||||
input_data (str): Input data
|
||||
|
||||
Returns:
|
||||
Dict: Processed results
|
||||
"""
|
||||
# 1. Search for data
|
||||
search_results = internet_search_tool(input_data)
|
||||
|
||||
# 2. Process results
|
||||
processed_data = process_tool(search_results)
|
||||
|
||||
# 3. Format output
|
||||
return format_tool(processed_data)
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Categories
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Data Collection Tools">
|
||||
- Web scraping
|
||||
- API integration
|
||||
- Database queries
|
||||
</Card>
|
||||
|
||||
<Card title="Processing Tools">
|
||||
- Data transformation
|
||||
- Text analysis
|
||||
- Image processing
|
||||
</Card>
|
||||
|
||||
<Card title="Output Tools">
|
||||
- File generation
|
||||
- Report creation
|
||||
- Data visualization
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Tool Integration
|
||||
|
||||
### Adding Tools to Agents
|
||||
<Frame>
|
||||
```python
|
||||
# Multiple tools
|
||||
agent = Agent(
|
||||
name="MultiTool Agent",
|
||||
tools=[
|
||||
internet_search_tool,
|
||||
file_processing_tool,
|
||||
api_integration_tool
|
||||
]
|
||||
)
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Dependencies
|
||||
<Frame>
|
||||
```python
|
||||
# Tool with dependencies
|
||||
def advanced_tool(data: Dict) -> Dict:
|
||||
"""
|
||||
Tool that depends on external libraries
|
||||
|
||||
Args:
|
||||
data (Dict): Input data
|
||||
|
||||
Returns:
|
||||
Dict: Processed data
|
||||
"""
|
||||
try:
|
||||
import required_library
|
||||
# Tool implementation
|
||||
return processed_result
|
||||
except ImportError:
|
||||
raise Exception("Required library not installed")
|
||||
```
|
||||
</Frame>
|
||||
|
||||
## Tool Guidelines
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Best Practices">
|
||||
1. **Type Hints**
|
||||
- Use Python type hints
|
||||
- Define clear input/output types
|
||||
- Document complex types
|
||||
|
||||
2. **Documentation**
|
||||
- Write clear docstrings
|
||||
- Explain parameters
|
||||
- Provide usage examples
|
||||
|
||||
3. **Error Handling**
|
||||
- Handle exceptions gracefully
|
||||
- Return meaningful errors
|
||||
- Validate inputs
|
||||
</Card>
|
||||
|
||||
<Card title="Tool Types">
|
||||
1. **Search Tools**
|
||||
- Web search
|
||||
- Database queries
|
||||
- Document search
|
||||
|
||||
2. **File Tools**
|
||||
- Read/write operations
|
||||
- File conversion
|
||||
- Data extraction
|
||||
|
||||
3. **API Tools**
|
||||
- REST API calls
|
||||
- GraphQL queries
|
||||
- Service integration
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Best Practices Summary
|
||||
|
||||
<Note>
|
||||
Following these best practices will help you create robust, efficient, and secure tools in PraisonAI.
|
||||
</Note>
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Design Principles" icon="compass-drafting" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Single Responsibility">
|
||||
Each tool should have one clear purpose and do it well. Avoid creating tools that try to do too many things.
|
||||
```python
|
||||
# Good Example
|
||||
def process_image(image: np.array) -> np.array:
|
||||
return processed_image
|
||||
|
||||
# Avoid
|
||||
def process_and_save_and_upload(image):
|
||||
# Too many responsibilities
|
||||
pass
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Clear Interfaces">
|
||||
Define explicit input/output types and maintain consistent parameter naming.
|
||||
```python
|
||||
def search_tool(
|
||||
query: str,
|
||||
max_results: int = 10
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Search for information with clear parameters
|
||||
"""
|
||||
pass
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Documentation">
|
||||
Always include detailed docstrings and type hints.
|
||||
```python
|
||||
def analyze_text(
|
||||
text: str,
|
||||
language: str = "en"
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
Analyze text sentiment and emotions.
|
||||
|
||||
Args:
|
||||
text: Input text to analyze
|
||||
language: ISO language code
|
||||
|
||||
Returns:
|
||||
Dict with sentiment scores
|
||||
"""
|
||||
pass
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<br />
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Performance Optimization" icon="bolt" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Efficient Processing">
|
||||
Optimize resource usage and processing time.
|
||||
```python
|
||||
# Use generators for large datasets
|
||||
def process_large_data():
|
||||
for chunk in data_generator():
|
||||
yield process_chunk(chunk)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Resource Management">
|
||||
Properly handle resource allocation and cleanup.
|
||||
```python
|
||||
async with aiohttp.ClientSession() as session:
|
||||
# Resource automatically managed
|
||||
await process_data(session)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Caching">
|
||||
Implement caching for frequently accessed data.
|
||||
```python
|
||||
@cache.memoize(timeout=300)
|
||||
def expensive_operation(data: str) -> Dict:
|
||||
return process_expensive(data)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Async Operations">
|
||||
Use async/await for I/O-bound operations.
|
||||
```python
|
||||
async def fetch_data(urls: List[str]):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
tasks = [fetch_url(session, url) for url in urls]
|
||||
return await asyncio.gather(*tasks)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<br />
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Security Best Practices" icon="shield-check" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Input Validation">
|
||||
Always validate and sanitize inputs to prevent security vulnerabilities.
|
||||
```python
|
||||
def process_user_input(data: str) -> str:
|
||||
if not isinstance(data, str):
|
||||
raise ValueError("Input must be string")
|
||||
return sanitize_input(data.strip())
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Rate Limiting">
|
||||
Implement rate limiting for API calls to prevent abuse.
|
||||
```python
|
||||
@rate_limit(calls=100, period=60)
|
||||
async def api_call():
|
||||
return await make_request()
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="API Key Management">
|
||||
Securely handle API keys and credentials using environment variables.
|
||||
```python
|
||||
# Use environment variables
|
||||
api_key = os.getenv('API_KEY')
|
||||
if not api_key:
|
||||
raise ConfigError("API key not found")
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Error Masking">
|
||||
Hide sensitive information in error messages to prevent information leakage.
|
||||
```python
|
||||
try:
|
||||
result = process_sensitive_data()
|
||||
except Exception as e:
|
||||
# Log detailed error internally
|
||||
logger.error(f"Detailed error: {str(e)}")
|
||||
# Return sanitized error to user
|
||||
raise PublicError("Processing failed")
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<br />
|
||||
|
||||
<Tip>
|
||||
**Pro Tip**: Start with these practices from the beginning of your project. It's easier to maintain good practices than to retrofit them later.
|
||||
</Tip>
|
||||
@@ -0,0 +1,108 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
|
||||
# Define structured output models
|
||||
class SkillAnalysis(BaseModel):
|
||||
technical_skills: List[str]
|
||||
soft_skills: List[str]
|
||||
skill_gaps: List[str]
|
||||
recommendations: List[str]
|
||||
|
||||
class ExperienceAnalysis(BaseModel):
|
||||
key_achievements: List[str]
|
||||
impact_metrics: List[Dict[str, str]]
|
||||
areas_of_expertise: List[str]
|
||||
improvement_suggestions: List[str]
|
||||
|
||||
class CVAnalysisReport(BaseModel):
|
||||
overall_score: int
|
||||
key_strengths: List[str]
|
||||
areas_for_improvement: List[str]
|
||||
market_fit: str
|
||||
recommendations: List[str]
|
||||
skill_analysis: SkillAnalysis
|
||||
experience_analysis: ExperienceAnalysis
|
||||
|
||||
# Create specialized agents
|
||||
skill_analyst = Agent(
|
||||
role="Skills Analysis Expert",
|
||||
goal="Analyze technical and soft skills in CV",
|
||||
backstory="""You are an experienced skills analyst with deep knowledge of industry requirements
|
||||
and current market trends. You excel at identifying valuable skills and potential skill gaps.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
experience_analyst = Agent(
|
||||
role="Experience Analysis Expert",
|
||||
goal="Analyze professional experience and achievements",
|
||||
backstory="""You are an expert in evaluating professional experience and achievements.
|
||||
You can identify impactful contributions and quantifiable results.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
cv_evaluator = Agent(
|
||||
role="Senior CV Evaluator",
|
||||
goal="Provide comprehensive CV evaluation and recommendations",
|
||||
backstory="""You are a senior CV evaluation expert with years of experience in talent assessment.
|
||||
You provide detailed analysis and actionable recommendations for CV improvement.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create tasks with structured outputs
|
||||
skills_analysis_task = Task(
|
||||
description="""Analyze the CV's technical and soft skills. Identify skill gaps and provide recommendations
|
||||
for skill development based on current market trends.""",
|
||||
expected_output="Detailed analysis of skills with recommendations",
|
||||
agent=skill_analyst,
|
||||
output_pydantic=SkillAnalysis,
|
||||
context=["test"],
|
||||
)
|
||||
|
||||
experience_analysis_task = Task(
|
||||
description="""Evaluate professional experience, achievements, and impact.
|
||||
Identify key accomplishments and areas of expertise.""",
|
||||
expected_output="Comprehensive analysis of professional experience",
|
||||
agent=experience_analyst,
|
||||
output_pydantic=ExperienceAnalysis
|
||||
)
|
||||
|
||||
final_evaluation_task = Task(
|
||||
description="""Review all analyses and provide a comprehensive evaluation of the CV.
|
||||
Include overall assessment, key strengths, areas for improvement, and specific recommendations.""",
|
||||
expected_output="Final CV evaluation report",
|
||||
agent=cv_evaluator,
|
||||
context=[skills_analysis_task, experience_analysis_task],
|
||||
output_pydantic=CVAnalysisReport
|
||||
)
|
||||
|
||||
# Create and run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[skill_analyst, experience_analyst, cv_evaluator],
|
||||
tasks=[skills_analysis_task, experience_analysis_task, final_evaluation_task],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Start the analysis
|
||||
result = agents.start()
|
||||
|
||||
# Access the structured results
|
||||
print("\nCV Analysis Results:")
|
||||
print(f"\nOverall Score: {result.pydantic.overall_score}/100")
|
||||
print("\nKey Strengths:")
|
||||
for strength in result.pydantic.key_strengths:
|
||||
print(f"- {strength}")
|
||||
|
||||
print("\nSkill Analysis:")
|
||||
print("\nTechnical Skills:")
|
||||
for skill in result.pydantic.skill_analysis.technical_skills:
|
||||
print(f"- {skill}")
|
||||
|
||||
print("\nExperience Highlights:")
|
||||
for achievement in result.pydantic.experience_analysis.key_achievements:
|
||||
print(f"- {achievement}")
|
||||
|
||||
print("\nRecommendations:")
|
||||
for recommendation in result.pydantic.recommendations:
|
||||
print(f"- {recommendation}")
|
||||
@@ -0,0 +1,215 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def collect_environmental_data():
|
||||
"""Simulates environmental data collection"""
|
||||
data = {
|
||||
"temperature": {
|
||||
"current": 25 + (time.time() % 10),
|
||||
"historical": [24, 25, 26, 24, 23],
|
||||
"trend": "increasing"
|
||||
},
|
||||
"humidity": {
|
||||
"current": 60 + (time.time() % 20),
|
||||
"historical": [65, 62, 58, 63, 61],
|
||||
"trend": "stable"
|
||||
},
|
||||
"air_quality": {
|
||||
"pm25": 35 + (time.time() % 15),
|
||||
"co2": 415 + (time.time() % 30),
|
||||
"trend": "deteriorating"
|
||||
}
|
||||
}
|
||||
return data
|
||||
|
||||
def analyze_urban_factors():
|
||||
"""Simulates urban environment analysis"""
|
||||
factors = {
|
||||
"building_density": 75 + (time.time() % 20),
|
||||
"green_spaces": 25 + (time.time() % 10),
|
||||
"traffic_flow": {
|
||||
"peak_hours": [8, 17],
|
||||
"congestion_level": "high"
|
||||
},
|
||||
"heat_islands": [
|
||||
{"location": "downtown", "intensity": "high"},
|
||||
{"location": "industrial", "intensity": "medium"}
|
||||
]
|
||||
}
|
||||
return factors
|
||||
|
||||
def model_microclimate(env_data: Dict, urban_factors: Dict):
|
||||
"""Models microclimate conditions"""
|
||||
models = []
|
||||
locations = ["downtown", "residential", "industrial", "parks"]
|
||||
|
||||
for location in locations:
|
||||
models.append({
|
||||
"location": location,
|
||||
"temperature_delta": 2 + (time.time() % 3),
|
||||
"air_quality_impact": "moderate" if "park" in location else "significant",
|
||||
"humidity_variation": 5 + (time.time() % 5)
|
||||
})
|
||||
return models
|
||||
|
||||
def predict_impacts(models: List[Dict]):
|
||||
"""Predicts climate impacts"""
|
||||
predictions = []
|
||||
for model in models:
|
||||
predictions.append({
|
||||
"location": model["location"],
|
||||
"health_impact": "high" if model["air_quality_impact"] == "significant" else "medium",
|
||||
"energy_consumption": {
|
||||
"cooling_need": model["temperature_delta"] * 10,
|
||||
"trend": "increasing" if model["temperature_delta"] > 2.5 else "stable"
|
||||
},
|
||||
"livability_score": 70 - (model["temperature_delta"] * 5)
|
||||
})
|
||||
return predictions
|
||||
|
||||
def generate_adaptation_strategies(predictions: List[Dict]):
|
||||
"""Generates adaptation strategies"""
|
||||
strategies = []
|
||||
for pred in predictions:
|
||||
if pred["health_impact"] == "high":
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"increase_green_spaces",
|
||||
"traffic_reduction",
|
||||
"building_retrofitting"
|
||||
],
|
||||
"priority": "immediate",
|
||||
"cost_estimate": "high"
|
||||
})
|
||||
else:
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"tree_planting",
|
||||
"cool_roofs"
|
||||
],
|
||||
"priority": "medium",
|
||||
"cost_estimate": "moderate"
|
||||
})
|
||||
return strategies
|
||||
|
||||
# Create specialized agents
|
||||
environmental_monitor = Agent(
|
||||
name="Environmental Monitor",
|
||||
role="Data Collection",
|
||||
goal="Collect environmental data",
|
||||
instructions="Monitor and collect climate data",
|
||||
tools=[collect_environmental_data]
|
||||
)
|
||||
|
||||
urban_analyzer = Agent(
|
||||
name="Urban Analyzer",
|
||||
role="Urban Analysis",
|
||||
goal="Analyze urban environment",
|
||||
instructions="Assess urban factors affecting climate",
|
||||
tools=[analyze_urban_factors]
|
||||
)
|
||||
|
||||
climate_modeler = Agent(
|
||||
name="Climate Modeler",
|
||||
role="Climate Modeling",
|
||||
goal="Model microclimate conditions",
|
||||
instructions="Create detailed climate models",
|
||||
tools=[model_microclimate]
|
||||
)
|
||||
|
||||
impact_predictor = Agent(
|
||||
name="Impact Predictor",
|
||||
role="Impact Analysis",
|
||||
goal="Predict climate impacts",
|
||||
instructions="Assess potential climate impacts",
|
||||
tools=[predict_impacts]
|
||||
)
|
||||
|
||||
strategy_generator = Agent(
|
||||
name="Strategy Generator",
|
||||
role="Strategy Development",
|
||||
goal="Generate adaptation strategies",
|
||||
instructions="Develop climate adaptation strategies",
|
||||
tools=[generate_adaptation_strategies]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
monitoring_task = Task(
|
||||
name="collect_data",
|
||||
description="Collect environmental data",
|
||||
expected_output="Environmental measurements",
|
||||
agent=environmental_monitor,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_urban"]
|
||||
)
|
||||
|
||||
urban_task = Task(
|
||||
name="analyze_urban",
|
||||
description="Analyze urban factors",
|
||||
expected_output="Urban analysis",
|
||||
agent=urban_analyzer,
|
||||
next_tasks=["model_climate"]
|
||||
)
|
||||
|
||||
modeling_task = Task(
|
||||
name="model_climate",
|
||||
description="Model microclimate",
|
||||
expected_output="Climate models",
|
||||
agent=climate_modeler,
|
||||
context=[monitoring_task, urban_task],
|
||||
next_tasks=["predict_impacts"]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_impacts",
|
||||
description="Predict climate impacts",
|
||||
expected_output="Impact predictions",
|
||||
agent=impact_predictor,
|
||||
next_tasks=["generate_strategies"]
|
||||
)
|
||||
|
||||
strategy_task = Task(
|
||||
name="generate_strategies",
|
||||
description="Generate adaptation strategies",
|
||||
expected_output="Adaptation strategies",
|
||||
agent=strategy_generator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"immediate": ["collect_data"], # Continuous monitoring for high priority
|
||||
"medium": "", # End workflow for medium priority
|
||||
"low": "" # End workflow for low priority
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[environmental_monitor, urban_analyzer, climate_modeler,
|
||||
impact_predictor, strategy_generator],
|
||||
tasks=[monitoring_task, urban_task, modeling_task,
|
||||
prediction_task, strategy_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Climate Impact Prediction Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nClimate Impact Analysis Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,233 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_cryptographic_scheme():
|
||||
"""Simulates cryptographic scheme analysis"""
|
||||
schemes = [
|
||||
{
|
||||
"name": "lattice_based",
|
||||
"type": "encryption",
|
||||
"key_size": 2048,
|
||||
"security_level": "AES-256 equivalent",
|
||||
"parameters": {
|
||||
"lattice_dimension": 1024,
|
||||
"modulus": "q = 2^32 - 1",
|
||||
"error_distribution": "discrete_gaussian"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "multivariate",
|
||||
"type": "signature",
|
||||
"key_size": 4096,
|
||||
"security_level": "SHA-384 equivalent",
|
||||
"parameters": {
|
||||
"variables": 128,
|
||||
"equations": 128,
|
||||
"field_size": "2^8"
|
||||
}
|
||||
}
|
||||
]
|
||||
return schemes[int(time.time()) % 2]
|
||||
|
||||
def simulate_quantum_attacks(scheme: Dict):
|
||||
"""Simulates quantum attack scenarios"""
|
||||
attacks = {
|
||||
"grover_search": {
|
||||
"effectiveness": "reduced",
|
||||
"quantum_speedup": "quadratic",
|
||||
"estimated_qubits": 2048,
|
||||
"time_complexity": "O(2^n/2)"
|
||||
},
|
||||
"shor_algorithm": {
|
||||
"effectiveness": "ineffective",
|
||||
"quantum_speedup": "none",
|
||||
"vulnerability": "resistant",
|
||||
"classical_hardness": "maintained"
|
||||
},
|
||||
"quantum_hidden_subgroup": {
|
||||
"effectiveness": "partial",
|
||||
"applicability": "limited",
|
||||
"mitigation": "parameter_adjustment"
|
||||
}
|
||||
}
|
||||
return attacks
|
||||
|
||||
def benchmark_performance(scheme: Dict):
|
||||
"""Benchmarks cryptographic performance"""
|
||||
benchmarks = {
|
||||
"key_generation": {
|
||||
"time": 0.5 + (time.time() % 1) / 10, # seconds
|
||||
"memory": 128 + (int(time.time()) % 64) # MB
|
||||
},
|
||||
"encryption_speed": {
|
||||
"small_message": 0.001 + (time.time() % 1) / 1000, # seconds
|
||||
"large_message": 0.1 + (time.time() % 1) / 10 # seconds
|
||||
},
|
||||
"decryption_speed": {
|
||||
"small_message": 0.002 + (time.time() % 1) / 1000,
|
||||
"large_message": 0.15 + (time.time() % 1) / 10
|
||||
},
|
||||
"throughput": {
|
||||
"encryption": 100 + (int(time.time()) % 50), # MB/s
|
||||
"decryption": 80 + (int(time.time()) % 40) # MB/s
|
||||
}
|
||||
}
|
||||
return benchmarks
|
||||
|
||||
def assess_implementation(scheme: Dict, benchmarks: Dict):
|
||||
"""Assesses implementation security"""
|
||||
assessment = {
|
||||
"side_channel_resistance": {
|
||||
"timing_attacks": "protected",
|
||||
"power_analysis": "partial_vulnerability",
|
||||
"cache_attacks": "mitigated"
|
||||
},
|
||||
"implementation_hardening": {
|
||||
"constant_time": True,
|
||||
"memory_protection": True,
|
||||
"error_handling": "secure"
|
||||
},
|
||||
"compiler_optimizations": {
|
||||
"safety": "verified",
|
||||
"performance_impact": -0.05 + (time.time() % 1) / 10
|
||||
}
|
||||
}
|
||||
return assessment
|
||||
|
||||
def validate_compliance(scheme: Dict, assessment: Dict):
|
||||
"""Validates compliance and standards"""
|
||||
compliance = {
|
||||
"nist_pqc": {
|
||||
"status": "submitted",
|
||||
"round": 3,
|
||||
"requirements_met": True
|
||||
},
|
||||
"common_criteria": {
|
||||
"evaluation_level": "EAL4+",
|
||||
"protection_profile": "compliant"
|
||||
},
|
||||
"fips_140_3": {
|
||||
"security_level": 3,
|
||||
"validation_status": "in_process"
|
||||
}
|
||||
}
|
||||
return compliance
|
||||
|
||||
# Create specialized agents
|
||||
crypto_analyzer = Agent(
|
||||
name="Crypto Analyzer",
|
||||
role="Cryptographic Analysis",
|
||||
goal="Analyze cryptographic schemes",
|
||||
instructions="Evaluate quantum-resistant cryptographic schemes",
|
||||
tools=[analyze_cryptographic_scheme]
|
||||
)
|
||||
|
||||
attack_simulator = Agent(
|
||||
name="Attack Simulator",
|
||||
role="Attack Simulation",
|
||||
goal="Simulate quantum attacks",
|
||||
instructions="Test resistance against quantum attacks",
|
||||
tools=[simulate_quantum_attacks]
|
||||
)
|
||||
|
||||
performance_benchmarker = Agent(
|
||||
name="Performance Benchmarker",
|
||||
role="Performance Testing",
|
||||
goal="Benchmark cryptographic performance",
|
||||
instructions="Measure performance metrics",
|
||||
tools=[benchmark_performance]
|
||||
)
|
||||
|
||||
implementation_assessor = Agent(
|
||||
name="Implementation Assessor",
|
||||
role="Implementation Assessment",
|
||||
goal="Assess implementation security",
|
||||
instructions="Evaluate implementation security",
|
||||
tools=[assess_implementation]
|
||||
)
|
||||
|
||||
compliance_validator = Agent(
|
||||
name="Compliance Validator",
|
||||
role="Compliance Validation",
|
||||
goal="Validate standards compliance",
|
||||
instructions="Verify compliance with standards",
|
||||
tools=[validate_compliance]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_crypto",
|
||||
description="Analyze cryptographic scheme",
|
||||
expected_output="Cryptographic analysis",
|
||||
agent=crypto_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["simulate_attacks", "benchmark_performance"]
|
||||
)
|
||||
|
||||
attack_task = Task(
|
||||
name="simulate_attacks",
|
||||
description="Simulate quantum attacks",
|
||||
expected_output="Attack simulation results",
|
||||
agent=attack_simulator,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
benchmark_task = Task(
|
||||
name="benchmark_performance",
|
||||
description="Benchmark performance",
|
||||
expected_output="Performance benchmarks",
|
||||
agent=performance_benchmarker,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
assessment_task = Task(
|
||||
name="assess_implementation",
|
||||
description="Assess implementation",
|
||||
expected_output="Implementation assessment",
|
||||
agent=implementation_assessor,
|
||||
context=[attack_task, benchmark_task],
|
||||
next_tasks=["validate_compliance"]
|
||||
)
|
||||
|
||||
compliance_task = Task(
|
||||
name="validate_compliance",
|
||||
description="Validate compliance",
|
||||
expected_output="Compliance validation",
|
||||
agent=compliance_validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"compliant": "", # End workflow if compliant
|
||||
"non_compliant": ["assess_implementation"] # Reassess if non-compliant
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[crypto_analyzer, attack_simulator, performance_benchmarker,
|
||||
implementation_assessor, compliance_validator],
|
||||
tasks=[analysis_task, attack_task, benchmark_task,
|
||||
assessment_task, compliance_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Quantum-Resistant Cryptography Validation Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nCryptography Validation Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,219 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_market_conditions():
|
||||
"""Simulates market analysis"""
|
||||
conditions = {
|
||||
"liquidity_pools": {
|
||||
"pool_A": {
|
||||
"token_0": {"balance": 1000000, "price": 1.0},
|
||||
"token_1": {"balance": 500000, "price": 2.0},
|
||||
"total_value_locked": 2000000
|
||||
},
|
||||
"pool_B": {
|
||||
"token_0": {"balance": 800000, "price": 1.0},
|
||||
"token_1": {"balance": 400000, "price": 2.0},
|
||||
"total_value_locked": 1600000
|
||||
}
|
||||
},
|
||||
"market_volatility": 0.15 + (time.time() % 10) / 100,
|
||||
"trading_volume_24h": 5000000 + (time.time() % 1000000),
|
||||
"gas_prices": 50 + (time.time() % 30)
|
||||
}
|
||||
return conditions
|
||||
|
||||
def detect_arbitrage():
|
||||
"""Simulates arbitrage opportunity detection"""
|
||||
opportunities = [
|
||||
{
|
||||
"path": ["pool_A", "pool_B"],
|
||||
"profit_potential": 0.02 + (time.time() % 5) / 100,
|
||||
"required_capital": 10000,
|
||||
"execution_cost": 50,
|
||||
"risk_level": "low"
|
||||
},
|
||||
{
|
||||
"path": ["pool_B", "pool_C"],
|
||||
"profit_potential": 0.03 + (time.time() % 5) / 100,
|
||||
"required_capital": 20000,
|
||||
"execution_cost": 75,
|
||||
"risk_level": "medium"
|
||||
}
|
||||
]
|
||||
return opportunities[int(time.time()) % 2]
|
||||
|
||||
def optimize_liquidity(market_conditions: Dict):
|
||||
"""Optimizes liquidity distribution"""
|
||||
optimizations = {
|
||||
"pool_A": {
|
||||
"target_ratio": 2.0,
|
||||
"suggested_actions": [
|
||||
{
|
||||
"action": "rebalance",
|
||||
"token": "token_1",
|
||||
"amount": 10000,
|
||||
"direction": "add"
|
||||
}
|
||||
],
|
||||
"expected_improvement": 0.05
|
||||
},
|
||||
"pool_B": {
|
||||
"target_ratio": 1.8,
|
||||
"suggested_actions": [
|
||||
{
|
||||
"action": "rebalance",
|
||||
"token": "token_0",
|
||||
"amount": 5000,
|
||||
"direction": "remove"
|
||||
}
|
||||
],
|
||||
"expected_improvement": 0.03
|
||||
}
|
||||
}
|
||||
return optimizations
|
||||
|
||||
def assess_risks(arbitrage: Dict, optimizations: Dict):
|
||||
"""Assesses potential risks"""
|
||||
risk_assessment = {
|
||||
"impermanent_loss_risk": 0.1 + (time.time() % 5) / 100,
|
||||
"smart_contract_risk": "low",
|
||||
"market_manipulation_risk": "medium" if arbitrage["profit_potential"] > 0.025 else "low",
|
||||
"gas_price_risk": "high" if arbitrage["execution_cost"] > 60 else "medium",
|
||||
"mitigation_strategies": [
|
||||
"implement_slippage_protection",
|
||||
"set_maximum_gas_price",
|
||||
"use_multiple_liquidity_sources"
|
||||
]
|
||||
}
|
||||
return risk_assessment
|
||||
|
||||
def execute_trades(arbitrage: Dict, risks: Dict):
|
||||
"""Simulates trade execution"""
|
||||
execution_results = {
|
||||
"status": "success" if time.time() % 2 == 0 else "failed",
|
||||
"executed_volume": arbitrage["required_capital"] * 0.95,
|
||||
"actual_profit": arbitrage["profit_potential"] * 0.9,
|
||||
"gas_used": arbitrage["execution_cost"] * 1.1,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
return execution_results
|
||||
|
||||
# Create specialized agents
|
||||
market_analyzer = Agent(
|
||||
name="Market Analyzer",
|
||||
role="Market Analysis",
|
||||
goal="Analyze market conditions",
|
||||
instructions="Monitor and analyze DeFi market conditions",
|
||||
tools=[analyze_market_conditions]
|
||||
)
|
||||
|
||||
arbitrage_detector = Agent(
|
||||
name="Arbitrage Detector",
|
||||
role="Arbitrage Detection",
|
||||
goal="Detect arbitrage opportunities",
|
||||
instructions="Identify profitable trading opportunities",
|
||||
tools=[detect_arbitrage]
|
||||
)
|
||||
|
||||
liquidity_optimizer = Agent(
|
||||
name="Liquidity Optimizer",
|
||||
role="Liquidity Optimization",
|
||||
goal="Optimize liquidity distribution",
|
||||
instructions="Optimize pool liquidity ratios",
|
||||
tools=[optimize_liquidity]
|
||||
)
|
||||
|
||||
risk_assessor = Agent(
|
||||
name="Risk Assessor",
|
||||
role="Risk Assessment",
|
||||
goal="Assess trading risks",
|
||||
instructions="Evaluate potential risks and mitigation strategies",
|
||||
tools=[assess_risks]
|
||||
)
|
||||
|
||||
trade_executor = Agent(
|
||||
name="Trade Executor",
|
||||
role="Trade Execution",
|
||||
goal="Execute optimized trades",
|
||||
instructions="Execute trades based on analysis",
|
||||
tools=[execute_trades]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
market_task = Task(
|
||||
name="analyze_market",
|
||||
description="Analyze market conditions",
|
||||
expected_output="Market analysis",
|
||||
agent=market_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["detect_arbitrage", "optimize_liquidity"]
|
||||
)
|
||||
|
||||
arbitrage_task = Task(
|
||||
name="detect_arbitrage",
|
||||
description="Detect arbitrage opportunities",
|
||||
expected_output="Arbitrage opportunities",
|
||||
agent=arbitrage_detector,
|
||||
next_tasks=["assess_risks"]
|
||||
)
|
||||
|
||||
liquidity_task = Task(
|
||||
name="optimize_liquidity",
|
||||
description="Optimize liquidity",
|
||||
expected_output="Liquidity optimization",
|
||||
agent=liquidity_optimizer,
|
||||
context=[market_task],
|
||||
next_tasks=["assess_risks"]
|
||||
)
|
||||
|
||||
risk_task = Task(
|
||||
name="assess_risks",
|
||||
description="Assess trading risks",
|
||||
expected_output="Risk assessment",
|
||||
agent=risk_assessor,
|
||||
context=[arbitrage_task, liquidity_task],
|
||||
next_tasks=["execute_trades"]
|
||||
)
|
||||
|
||||
execution_task = Task(
|
||||
name="execute_trades",
|
||||
description="Execute trades",
|
||||
expected_output="Trade execution results",
|
||||
agent=trade_executor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"success": ["analyze_market"], # Continue monitoring if successful
|
||||
"failed": ["optimize_liquidity"] # Reoptimize if failed
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[market_analyzer, arbitrage_detector, liquidity_optimizer,
|
||||
risk_assessor, trade_executor],
|
||||
tasks=[market_task, arbitrage_task, liquidity_task,
|
||||
risk_task, execution_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting DeFi Market Making Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nMarket Making Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,412 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
# Utility Functions
|
||||
def check_network_status():
|
||||
"""Simulates network connectivity check across different channels"""
|
||||
return {
|
||||
"main_network": int(time.time()) % 2 == 0,
|
||||
"backup_network": int(time.time()) % 3 == 0,
|
||||
"mesh_network": True,
|
||||
"satellite_link": int(time.time()) % 4 == 0,
|
||||
"cellular_network": int(time.time()) % 2 == 1
|
||||
}
|
||||
|
||||
def assess_emergency_level():
|
||||
"""Evaluates emergency severity level"""
|
||||
levels = [
|
||||
{
|
||||
"severity": "critical",
|
||||
"affected_areas": ["downtown", "industrial_zone"],
|
||||
"population_impact": 50000,
|
||||
"infrastructure_damage": "severe"
|
||||
},
|
||||
{
|
||||
"severity": "high",
|
||||
"affected_areas": ["residential_zone"],
|
||||
"population_impact": 25000,
|
||||
"infrastructure_damage": "moderate"
|
||||
},
|
||||
{
|
||||
"severity": "medium",
|
||||
"affected_areas": ["suburban_area"],
|
||||
"population_impact": 10000,
|
||||
"infrastructure_damage": "light"
|
||||
}
|
||||
]
|
||||
return levels[int(time.time()) % 3]
|
||||
|
||||
def assess_resources():
|
||||
"""Assesses available emergency resources"""
|
||||
return {
|
||||
"medical": {
|
||||
"ambulances": 20 - (int(time.time()) % 5),
|
||||
"field_hospitals": 3,
|
||||
"medical_teams": 15 - (int(time.time()) % 3),
|
||||
"supplies": {
|
||||
"availability": 75,
|
||||
"distribution_centers": ["central", "north", "south"],
|
||||
"critical_items": ["medications", "blood_supplies", "emergency_kits"]
|
||||
}
|
||||
},
|
||||
"fire_rescue": {
|
||||
"fire_trucks": 15 - (int(time.time()) % 4),
|
||||
"rescue_teams": 10,
|
||||
"equipment": {
|
||||
"availability": 85,
|
||||
"locations": ["main_station", "sub_stations"],
|
||||
"critical_items": ["breathing_apparatus", "rescue_tools"]
|
||||
}
|
||||
},
|
||||
"law_enforcement": {
|
||||
"patrol_units": 30 - (int(time.time()) % 6),
|
||||
"special_units": 5,
|
||||
"equipment": {
|
||||
"availability": 90,
|
||||
"distribution": "citywide",
|
||||
"critical_items": ["communication_devices", "crowd_control"]
|
||||
}
|
||||
},
|
||||
"utilities": {
|
||||
"power_crews": 8,
|
||||
"water_teams": 6,
|
||||
"emergency_generators": 12 - (int(time.time()) % 4),
|
||||
"water_supplies": {
|
||||
"availability": 70,
|
||||
"distribution_points": ["north", "south", "east", "west"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def prioritize_needs(emergency: Dict, resources: Dict):
|
||||
"""Determines priority of resource allocation"""
|
||||
priorities = []
|
||||
|
||||
# Calculate medical priorities
|
||||
if emergency["severity"] == "critical":
|
||||
medical_priority = {
|
||||
"type": "medical",
|
||||
"urgency": "immediate",
|
||||
"required_resources": {
|
||||
"ambulances": min(10, resources["medical"]["ambulances"]),
|
||||
"medical_teams": min(8, resources["medical"]["medical_teams"])
|
||||
}
|
||||
}
|
||||
priorities.append(medical_priority)
|
||||
|
||||
# Calculate rescue priorities
|
||||
if emergency["infrastructure_damage"] in ["severe", "moderate"]:
|
||||
rescue_priority = {
|
||||
"type": "fire_rescue",
|
||||
"urgency": "high",
|
||||
"required_resources": {
|
||||
"fire_trucks": min(5, resources["fire_rescue"]["fire_trucks"]),
|
||||
"rescue_teams": min(4, resources["fire_rescue"]["rescue_teams"])
|
||||
}
|
||||
}
|
||||
priorities.append(rescue_priority)
|
||||
|
||||
# Calculate law enforcement priorities
|
||||
if emergency["population_impact"] > 20000:
|
||||
law_priority = {
|
||||
"type": "law_enforcement",
|
||||
"urgency": "high",
|
||||
"required_resources": {
|
||||
"patrol_units": min(15, resources["law_enforcement"]["patrol_units"]),
|
||||
"special_units": min(2, resources["law_enforcement"]["special_units"])
|
||||
}
|
||||
}
|
||||
priorities.append(law_priority)
|
||||
|
||||
return priorities
|
||||
|
||||
def generate_distribution_plan(priorities: List[Dict]):
|
||||
"""Creates resource distribution and deployment plan"""
|
||||
plan = {
|
||||
"immediate_actions": [],
|
||||
"short_term_actions": [],
|
||||
"coordination_points": []
|
||||
}
|
||||
|
||||
for priority in priorities:
|
||||
if priority["urgency"] == "immediate":
|
||||
plan["immediate_actions"].append({
|
||||
"type": priority["type"],
|
||||
"resources": priority["required_resources"],
|
||||
"deployment_time": "immediate",
|
||||
"coordination": "central_command"
|
||||
})
|
||||
elif priority["urgency"] == "high":
|
||||
plan["short_term_actions"].append({
|
||||
"type": priority["type"],
|
||||
"resources": priority["required_resources"],
|
||||
"deployment_time": "within_1_hour",
|
||||
"coordination": "local_command"
|
||||
})
|
||||
|
||||
# Add coordination points
|
||||
plan["coordination_points"] = [
|
||||
{
|
||||
"location": "central_command",
|
||||
"coordinates": {"lat": 34.0522, "lon": -118.2437},
|
||||
"communication_channels": ["radio", "satellite", "mesh_network"]
|
||||
},
|
||||
{
|
||||
"location": "mobile_command_1",
|
||||
"coordinates": {"lat": 34.0622, "lon": -118.2537},
|
||||
"communication_channels": ["radio", "mesh_network"]
|
||||
}
|
||||
]
|
||||
|
||||
return plan
|
||||
|
||||
def execute_distribution(plan: Dict):
|
||||
"""Simulates the execution of the distribution plan"""
|
||||
execution_results = {
|
||||
"status": "in_progress",
|
||||
"completed_actions": [],
|
||||
"pending_actions": [],
|
||||
"resource_updates": {}
|
||||
}
|
||||
|
||||
# Simulate immediate actions execution
|
||||
for action in plan["immediate_actions"]:
|
||||
success_rate = 0.9 if action["deployment_time"] == "immediate" else 0.95
|
||||
if time.time() % 10 > (1 - success_rate) * 10:
|
||||
execution_results["completed_actions"].append({
|
||||
"action": action,
|
||||
"status": "completed",
|
||||
"completion_time": time.time()
|
||||
})
|
||||
else:
|
||||
execution_results["pending_actions"].append({
|
||||
"action": action,
|
||||
"status": "delayed",
|
||||
"estimated_delay": "30_minutes"
|
||||
})
|
||||
|
||||
# Update resource status
|
||||
execution_results["resource_updates"] = {
|
||||
"medical_units_deployed": len([a for a in execution_results["completed_actions"]
|
||||
if a["action"]["type"] == "medical"]),
|
||||
"rescue_units_deployed": len([a for a in execution_results["completed_actions"]
|
||||
if a["action"]["type"] == "fire_rescue"]),
|
||||
"coordination_status": "operational"
|
||||
}
|
||||
|
||||
return execution_results
|
||||
|
||||
def monitor_effectiveness(execution_results: Dict):
|
||||
"""Monitors the effectiveness of the response"""
|
||||
monitoring = {
|
||||
"response_metrics": {
|
||||
"deployment_speed": calculate_deployment_speed(execution_results),
|
||||
"resource_utilization": calculate_resource_utilization(execution_results),
|
||||
"coordination_efficiency": calculate_coordination_efficiency(execution_results)
|
||||
},
|
||||
"areas_for_improvement": identify_improvements(execution_results),
|
||||
"real_time_updates": generate_updates(execution_results)
|
||||
}
|
||||
return monitoring
|
||||
|
||||
def calculate_deployment_speed(results: Dict) -> float:
|
||||
"""Calculates deployment speed efficiency"""
|
||||
completed = len(results["completed_actions"])
|
||||
total = completed + len(results["pending_actions"])
|
||||
return (completed / total) * 100 if total > 0 else 0
|
||||
|
||||
def calculate_resource_utilization(results: Dict) -> float:
|
||||
"""Calculates resource utilization efficiency"""
|
||||
return 85.0 + (time.time() % 10) # Simulated value
|
||||
|
||||
def calculate_coordination_efficiency(results: Dict) -> float:
|
||||
"""Calculates coordination efficiency"""
|
||||
return 90.0 + (time.time() % 5) # Simulated value
|
||||
|
||||
def identify_improvements(results: Dict) -> List[Dict]:
|
||||
"""Identifies areas for improvement"""
|
||||
return [
|
||||
{
|
||||
"area": "resource_deployment",
|
||||
"suggestion": "optimize_routes",
|
||||
"priority": "high" if len(results["pending_actions"]) > 2 else "medium"
|
||||
},
|
||||
{
|
||||
"area": "coordination",
|
||||
"suggestion": "enhance_communication_protocols",
|
||||
"priority": "medium"
|
||||
}
|
||||
]
|
||||
|
||||
def generate_updates(results: Dict) -> List[Dict]:
|
||||
"""Generates real-time status updates"""
|
||||
return [
|
||||
{
|
||||
"timestamp": time.time(),
|
||||
"type": "status_update",
|
||||
"content": f"Deployed {len(results['completed_actions'])} units"
|
||||
},
|
||||
{
|
||||
"timestamp": time.time(),
|
||||
"type": "resource_update",
|
||||
"content": f"Resource utilization at {calculate_resource_utilization(results)}%"
|
||||
}
|
||||
]
|
||||
|
||||
# Create specialized agents
|
||||
network_monitor = Agent(
|
||||
name="Network Monitor",
|
||||
role="Network Status",
|
||||
goal="Monitor network connectivity",
|
||||
instructions="Track network status across all channels",
|
||||
tools=[check_network_status]
|
||||
)
|
||||
|
||||
emergency_assessor = Agent(
|
||||
name="Emergency Assessor",
|
||||
role="Emergency Assessment",
|
||||
goal="Assess emergency situation",
|
||||
instructions="Evaluate emergency severity and impact",
|
||||
tools=[assess_emergency_level]
|
||||
)
|
||||
|
||||
resource_assessor = Agent(
|
||||
name="Resource Assessor",
|
||||
role="Resource Assessment",
|
||||
goal="Assess available resources",
|
||||
instructions="Monitor and assess resource availability",
|
||||
tools=[assess_resources]
|
||||
)
|
||||
|
||||
priority_analyzer = Agent(
|
||||
name="Priority Analyzer",
|
||||
role="Need Prioritization",
|
||||
goal="Prioritize resource needs",
|
||||
instructions="Analyze and prioritize resource requirements",
|
||||
tools=[prioritize_needs]
|
||||
)
|
||||
|
||||
distribution_planner = Agent(
|
||||
name="Distribution Planner",
|
||||
role="Plan Generation",
|
||||
goal="Generate distribution plans",
|
||||
instructions="Create efficient resource distribution plans",
|
||||
tools=[generate_distribution_plan]
|
||||
)
|
||||
|
||||
execution_manager = Agent(
|
||||
name="Execution Manager",
|
||||
role="Plan Execution",
|
||||
goal="Execute distribution plan",
|
||||
instructions="Manage and execute resource distribution",
|
||||
tools=[execute_distribution]
|
||||
)
|
||||
|
||||
effectiveness_monitor = Agent(
|
||||
name="Effectiveness Monitor",
|
||||
role="Response Monitoring",
|
||||
goal="Monitor response effectiveness",
|
||||
instructions="Track and analyze response effectiveness",
|
||||
tools=[monitor_effectiveness]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
network_task = Task(
|
||||
name="check_network",
|
||||
description="Check network status",
|
||||
expected_output="Network connectivity status",
|
||||
agent=network_monitor,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"True": ["assess_emergency"], # Proceed if any network is available
|
||||
"False": "" # Exit if no network available
|
||||
}
|
||||
)
|
||||
|
||||
emergency_task = Task(
|
||||
name="assess_emergency",
|
||||
description="Assess emergency situation",
|
||||
expected_output="Emergency assessment",
|
||||
agent=emergency_assessor,
|
||||
next_tasks=["assess_resources"]
|
||||
)
|
||||
|
||||
resource_task = Task(
|
||||
name="assess_resources",
|
||||
description="Assess resource availability",
|
||||
expected_output="Resource assessment",
|
||||
agent=resource_assessor,
|
||||
next_tasks=["analyze_priorities"]
|
||||
)
|
||||
|
||||
priority_task = Task(
|
||||
name="analyze_priorities",
|
||||
description="Analyze resource priorities",
|
||||
expected_output="Prioritized needs",
|
||||
agent=priority_analyzer,
|
||||
context=[emergency_task, resource_task],
|
||||
next_tasks=["plan_distribution"]
|
||||
)
|
||||
|
||||
planning_task = Task(
|
||||
name="plan_distribution",
|
||||
description="Plan resource distribution",
|
||||
expected_output="Distribution plan",
|
||||
agent=distribution_planner,
|
||||
next_tasks=["execute_distribution"]
|
||||
)
|
||||
|
||||
execution_task = Task(
|
||||
name="execute_distribution",
|
||||
description="Execute distribution plan",
|
||||
expected_output="Execution results",
|
||||
agent=execution_manager,
|
||||
next_tasks=["monitor_effectiveness"]
|
||||
)
|
||||
|
||||
monitoring_task = Task(
|
||||
name="monitor_effectiveness",
|
||||
description="Monitor response effectiveness",
|
||||
expected_output="Effectiveness analysis",
|
||||
agent=effectiveness_monitor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"success": ["assess_emergency"], # Continue monitoring if successful
|
||||
"needs_improvement": ["plan_distribution"], # Replan if improvements needed
|
||||
"critical_issues": ["assess_resources"] # Reassess resources if critical issues
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[network_monitor, emergency_assessor, resource_assessor,
|
||||
priority_analyzer, distribution_planner, execution_manager,
|
||||
effectiveness_monitor],
|
||||
tasks=[network_task, emergency_task, resource_task,
|
||||
priority_task, planning_task, execution_task,
|
||||
monitoring_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Disaster Recovery Network Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nDisaster Recovery Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,217 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_genetic_markers():
|
||||
"""Simulates genetic marker analysis"""
|
||||
markers = {
|
||||
"metabolism_genes": {
|
||||
"CYP2D6": "rapid_metabolizer",
|
||||
"CYP2C19": "normal_metabolizer",
|
||||
"DPYD": "poor_metabolizer"
|
||||
},
|
||||
"risk_factors": {
|
||||
"cardiovascular": "elevated",
|
||||
"diabetes": "low",
|
||||
"autoimmune": "moderate"
|
||||
},
|
||||
"drug_response_markers": {
|
||||
"TPMT": "high_sensitivity",
|
||||
"HLA-B*5701": "negative",
|
||||
"UGT1A1": "normal"
|
||||
}
|
||||
}
|
||||
return markers
|
||||
|
||||
def evaluate_patient_history():
|
||||
"""Simulates patient history evaluation"""
|
||||
history = {
|
||||
"conditions": [
|
||||
{"name": "hypertension", "duration": "5_years", "severity": "moderate"},
|
||||
{"name": "arthritis", "duration": "2_years", "severity": "mild"}
|
||||
],
|
||||
"medications": [
|
||||
{"name": "lisinopril", "response": "good", "side_effects": "minimal"},
|
||||
{"name": "methotrexate", "response": "moderate", "side_effects": "mild"}
|
||||
],
|
||||
"allergies": ["penicillin", "sulfa"],
|
||||
"family_history": ["diabetes", "heart_disease"]
|
||||
}
|
||||
return history
|
||||
|
||||
def analyze_drug_interactions(genetic_data: Dict, patient_history: Dict):
|
||||
"""Analyzes potential drug interactions"""
|
||||
interactions = []
|
||||
medications = [med["name"] for med in patient_history["medications"]]
|
||||
|
||||
for med in medications:
|
||||
interactions.append({
|
||||
"medication": med,
|
||||
"genetic_impact": "significant" if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer" else "normal",
|
||||
"risk_level": "high" if med in patient_history["allergies"] else "low",
|
||||
"monitoring_needed": True if genetic_data["metabolism_genes"]["DPYD"] == "poor_metabolizer" else False
|
||||
})
|
||||
return interactions
|
||||
|
||||
def generate_protocol(genetic_data: Dict, interactions: List[Dict]):
|
||||
"""Generates treatment protocol"""
|
||||
protocol = {
|
||||
"primary_treatment": {
|
||||
"medication": "custom_formulation_A",
|
||||
"dosage": "adjusted_based_on_metabolism",
|
||||
"frequency": "twice_daily",
|
||||
"monitoring": {
|
||||
"type": "blood_levels",
|
||||
"frequency": "weekly"
|
||||
}
|
||||
},
|
||||
"alternatives": [
|
||||
{
|
||||
"medication": "custom_formulation_B",
|
||||
"conditions": ["genetic_compatibility", "no_interactions"]
|
||||
}
|
||||
],
|
||||
"precautions": []
|
||||
}
|
||||
|
||||
if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer":
|
||||
protocol["precautions"].append("increase_monitoring_frequency")
|
||||
|
||||
if any(i["risk_level"] == "high" for i in interactions):
|
||||
protocol["precautions"].append("alternative_medication_needed")
|
||||
|
||||
return protocol
|
||||
|
||||
def simulate_effectiveness(protocol: Dict):
|
||||
"""Simulates treatment effectiveness"""
|
||||
simulation = {
|
||||
"efficacy_prediction": 0.85 + (time.time() % 2) / 10,
|
||||
"side_effect_risk": 0.15 + (time.time() % 1) / 10,
|
||||
"adherence_probability": 0.9 + (time.time() % 1) / 10,
|
||||
"expected_outcomes": [
|
||||
"symptom_reduction_80_percent",
|
||||
"minimal_side_effects",
|
||||
"good_tolerance"
|
||||
]
|
||||
}
|
||||
return simulation
|
||||
|
||||
# Create specialized agents
|
||||
genetic_analyzer = Agent(
|
||||
name="Genetic Analyzer",
|
||||
role="Genetic Analysis",
|
||||
goal="Analyze genetic markers",
|
||||
instructions="Evaluate genetic markers and variants",
|
||||
tools=[analyze_genetic_markers]
|
||||
)
|
||||
|
||||
history_analyzer = Agent(
|
||||
name="History Analyzer",
|
||||
role="History Analysis",
|
||||
goal="Analyze patient history",
|
||||
instructions="Evaluate medical history and conditions",
|
||||
tools=[evaluate_patient_history]
|
||||
)
|
||||
|
||||
interaction_analyzer = Agent(
|
||||
name="Interaction Analyzer",
|
||||
role="Drug Interaction",
|
||||
goal="Analyze drug interactions",
|
||||
instructions="Evaluate potential drug interactions",
|
||||
tools=[analyze_drug_interactions]
|
||||
)
|
||||
|
||||
protocol_generator = Agent(
|
||||
name="Protocol Generator",
|
||||
role="Protocol Generation",
|
||||
goal="Generate treatment protocol",
|
||||
instructions="Create personalized treatment protocol",
|
||||
tools=[generate_protocol]
|
||||
)
|
||||
|
||||
effectiveness_simulator = Agent(
|
||||
name="Effectiveness Simulator",
|
||||
role="Treatment Simulation",
|
||||
goal="Simulate treatment effectiveness",
|
||||
instructions="Predict treatment outcomes",
|
||||
tools=[simulate_effectiveness]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
genetic_task = Task(
|
||||
name="analyze_genetics",
|
||||
description="Analyze genetic markers",
|
||||
expected_output="Genetic analysis",
|
||||
agent=genetic_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_history"]
|
||||
)
|
||||
|
||||
history_task = Task(
|
||||
name="analyze_history",
|
||||
description="Analyze patient history",
|
||||
expected_output="History analysis",
|
||||
agent=history_analyzer,
|
||||
next_tasks=["analyze_interactions"]
|
||||
)
|
||||
|
||||
interaction_task = Task(
|
||||
name="analyze_interactions",
|
||||
description="Analyze drug interactions",
|
||||
expected_output="Interaction analysis",
|
||||
agent=interaction_analyzer,
|
||||
context=[genetic_task, history_task],
|
||||
next_tasks=["generate_protocol"]
|
||||
)
|
||||
|
||||
protocol_task = Task(
|
||||
name="generate_protocol",
|
||||
description="Generate treatment protocol",
|
||||
expected_output="Treatment protocol",
|
||||
agent=protocol_generator,
|
||||
context=[genetic_task, interaction_task],
|
||||
next_tasks=["simulate_effectiveness"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_effectiveness",
|
||||
description="Simulate treatment effectiveness",
|
||||
expected_output="Effectiveness simulation",
|
||||
agent=effectiveness_simulator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": "", # End workflow if high effectiveness
|
||||
"medium": ["generate_protocol"], # Adjust protocol if medium
|
||||
"low": ["analyze_interactions"] # Reanalyze if low
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[genetic_analyzer, history_analyzer, interaction_analyzer,
|
||||
protocol_generator, effectiveness_simulator],
|
||||
tasks=[genetic_task, history_task, interaction_task,
|
||||
protocol_task, simulation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Personalized Medicine Protocol Generation...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nProtocol Generation Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,202 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_hardware_constraints():
|
||||
"""Simulates hardware analysis"""
|
||||
constraints = {
|
||||
"gpu_memory": 16 * 1024, # MB
|
||||
"compute_capability": "7.5",
|
||||
"memory_bandwidth": 900, # GB/s
|
||||
"tensor_cores": True,
|
||||
"max_power_consumption": 300, # Watts
|
||||
"thermal_limits": 85 # Celsius
|
||||
}
|
||||
return constraints
|
||||
|
||||
def generate_architecture_candidates():
|
||||
"""Generates candidate architectures"""
|
||||
candidates = [
|
||||
{
|
||||
"type": "transformer",
|
||||
"layers": 12 + (int(time.time()) % 6),
|
||||
"attention_heads": 8,
|
||||
"embedding_dim": 512,
|
||||
"estimated_params": 125_000_000
|
||||
},
|
||||
{
|
||||
"type": "cnn",
|
||||
"layers": 50 + (int(time.time()) % 50),
|
||||
"filters": [64, 128, 256, 512],
|
||||
"estimated_params": 25_000_000
|
||||
}
|
||||
]
|
||||
return candidates[int(time.time()) % 2]
|
||||
|
||||
def optimize_hyperparameters(architecture: Dict):
|
||||
"""Optimizes hyperparameters"""
|
||||
optimization = {
|
||||
"learning_rate": 0.001 + (time.time() % 9) / 10000,
|
||||
"batch_size": 32 * (1 + int(time.time()) % 4),
|
||||
"optimizer": "adam",
|
||||
"weight_decay": 0.0001,
|
||||
"dropout_rate": 0.1 + (time.time() % 3) / 10,
|
||||
"activation": "gelu" if architecture["type"] == "transformer" else "relu"
|
||||
}
|
||||
return optimization
|
||||
|
||||
def estimate_performance(architecture: Dict, hyperparams: Dict):
|
||||
"""Estimates model performance"""
|
||||
performance = {
|
||||
"estimated_accuracy": 0.85 + (time.time() % 10) / 100,
|
||||
"estimated_training_time": {
|
||||
"hours": 24 + (int(time.time()) % 24),
|
||||
"gpu_hours": 96
|
||||
},
|
||||
"memory_requirements": {
|
||||
"training": architecture["estimated_params"] * 4 / (1024 * 1024), # GB
|
||||
"inference": architecture["estimated_params"] * 2 / (1024 * 1024) # GB
|
||||
},
|
||||
"flops_count": architecture["estimated_params"] * 2
|
||||
}
|
||||
return performance
|
||||
|
||||
def optimize_deployment(architecture: Dict, performance: Dict):
|
||||
"""Optimizes deployment configuration"""
|
||||
deployment = {
|
||||
"quantization": {
|
||||
"method": "dynamic",
|
||||
"precision": "int8",
|
||||
"estimated_speedup": 2.5
|
||||
},
|
||||
"pruning": {
|
||||
"method": "magnitude",
|
||||
"target_sparsity": 0.3,
|
||||
"estimated_size_reduction": 0.6
|
||||
},
|
||||
"batching": {
|
||||
"max_batch_size": 32,
|
||||
"dynamic_batching": True
|
||||
}
|
||||
}
|
||||
return deployment
|
||||
|
||||
# Create specialized agents
|
||||
hardware_analyzer = Agent(
|
||||
name="Hardware Analyzer",
|
||||
role="Hardware Analysis",
|
||||
goal="Analyze hardware constraints",
|
||||
instructions="Evaluate available hardware resources",
|
||||
tools=[analyze_hardware_constraints]
|
||||
)
|
||||
|
||||
architecture_generator = Agent(
|
||||
name="Architecture Generator",
|
||||
role="Architecture Generation",
|
||||
goal="Generate neural architectures",
|
||||
instructions="Create candidate neural architectures",
|
||||
tools=[generate_architecture_candidates]
|
||||
)
|
||||
|
||||
hyperparameter_optimizer = Agent(
|
||||
name="Hyperparameter Optimizer",
|
||||
role="Hyperparameter Optimization",
|
||||
goal="Optimize hyperparameters",
|
||||
instructions="Find optimal hyperparameter settings",
|
||||
tools=[optimize_hyperparameters]
|
||||
)
|
||||
|
||||
performance_estimator = Agent(
|
||||
name="Performance Estimator",
|
||||
role="Performance Estimation",
|
||||
goal="Estimate model performance",
|
||||
instructions="Predict model performance metrics",
|
||||
tools=[estimate_performance]
|
||||
)
|
||||
|
||||
deployment_optimizer = Agent(
|
||||
name="Deployment Optimizer",
|
||||
role="Deployment Optimization",
|
||||
goal="Optimize deployment settings",
|
||||
instructions="Configure optimal deployment",
|
||||
tools=[optimize_deployment]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
hardware_task = Task(
|
||||
name="analyze_hardware",
|
||||
description="Analyze hardware constraints",
|
||||
expected_output="Hardware analysis",
|
||||
agent=hardware_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["generate_architecture"]
|
||||
)
|
||||
|
||||
architecture_task = Task(
|
||||
name="generate_architecture",
|
||||
description="Generate architecture candidates",
|
||||
expected_output="Architecture candidates",
|
||||
agent=architecture_generator,
|
||||
next_tasks=["optimize_hyperparameters"]
|
||||
)
|
||||
|
||||
hyperparameter_task = Task(
|
||||
name="optimize_hyperparameters",
|
||||
description="Optimize hyperparameters",
|
||||
expected_output="Hyperparameter settings",
|
||||
agent=hyperparameter_optimizer,
|
||||
context=[architecture_task],
|
||||
next_tasks=["estimate_performance"]
|
||||
)
|
||||
|
||||
performance_task = Task(
|
||||
name="estimate_performance",
|
||||
description="Estimate performance",
|
||||
expected_output="Performance estimates",
|
||||
agent=performance_estimator,
|
||||
context=[architecture_task, hyperparameter_task],
|
||||
next_tasks=["optimize_deployment"]
|
||||
)
|
||||
|
||||
deployment_task = Task(
|
||||
name="optimize_deployment",
|
||||
description="Optimize deployment",
|
||||
expected_output="Deployment configuration",
|
||||
agent=deployment_optimizer,
|
||||
context=[architecture_task, performance_task],
|
||||
task_type="decision",
|
||||
condition={
|
||||
"success": ["generate_architecture"], # Try new architecture
|
||||
"failure": ["optimize_hyperparameters"] # Reoptimize hyperparameters
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[hardware_analyzer, architecture_generator, hyperparameter_optimizer,
|
||||
performance_estimator, deployment_optimizer],
|
||||
tasks=[hardware_task, architecture_task, hyperparameter_task,
|
||||
performance_task, deployment_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Neural Architecture Search Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nArchitecture Search Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,197 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_quantum_circuit():
|
||||
"""Simulates quantum circuit analysis"""
|
||||
circuit_metrics = {
|
||||
"depth": 15 + (int(time.time()) % 10),
|
||||
"gates": {
|
||||
"single_qubit": 25 + (int(time.time()) % 15),
|
||||
"two_qubit": 10 + (int(time.time()) % 8),
|
||||
"measurement": 5 + (int(time.time()) % 3)
|
||||
},
|
||||
"qubits": 8 + (int(time.time()) % 4)
|
||||
}
|
||||
return circuit_metrics
|
||||
|
||||
def identify_optimization_opportunities(metrics: Dict):
|
||||
"""Identifies potential optimization areas"""
|
||||
opportunities = []
|
||||
if metrics["depth"] > 20:
|
||||
opportunities.append({
|
||||
"type": "depth_reduction",
|
||||
"potential": "high",
|
||||
"technique": "parallel_gates"
|
||||
})
|
||||
if metrics["gates"]["two_qubit"] > 15:
|
||||
opportunities.append({
|
||||
"type": "gate_reduction",
|
||||
"potential": "medium",
|
||||
"technique": "gate_decomposition"
|
||||
})
|
||||
return opportunities
|
||||
|
||||
def simulate_optimization(opportunities: List[Dict]):
|
||||
"""Simulates optimization results"""
|
||||
results = []
|
||||
for opt in opportunities:
|
||||
improvement = {
|
||||
"high": 0.3 + (time.time() % 2) / 10,
|
||||
"medium": 0.2 + (time.time() % 2) / 10,
|
||||
"low": 0.1 + (time.time() % 2) / 10
|
||||
}
|
||||
results.append({
|
||||
"type": opt["type"],
|
||||
"improvement": improvement[opt["potential"]],
|
||||
"success_probability": 0.8 + (time.time() % 2) / 10
|
||||
})
|
||||
return results
|
||||
|
||||
def benchmark_performance(original: Dict, optimized: List[Dict]):
|
||||
"""Benchmarks optimization performance"""
|
||||
benchmarks = {
|
||||
"execution_time": {
|
||||
"original": 100 + (int(time.time()) % 50),
|
||||
"optimized": 70 + (int(time.time()) % 30)
|
||||
},
|
||||
"fidelity": {
|
||||
"original": 0.9 + (time.time() % 1) / 10,
|
||||
"optimized": 0.85 + (time.time() % 1) / 10
|
||||
},
|
||||
"resource_usage": {
|
||||
"original": original["qubits"],
|
||||
"optimized": original["qubits"] - len(optimized)
|
||||
}
|
||||
}
|
||||
return benchmarks
|
||||
|
||||
def validate_results(benchmarks: Dict):
|
||||
"""Validates optimization results"""
|
||||
validations = {
|
||||
"performance_gain": (benchmarks["execution_time"]["original"] -
|
||||
benchmarks["execution_time"]["optimized"]) /
|
||||
benchmarks["execution_time"]["original"],
|
||||
"fidelity_maintained": benchmarks["fidelity"]["optimized"] > 0.8,
|
||||
"resource_efficient": benchmarks["resource_usage"]["optimized"] <
|
||||
benchmarks["resource_usage"]["original"]
|
||||
}
|
||||
return validations
|
||||
|
||||
# Create specialized agents
|
||||
circuit_analyzer = Agent(
|
||||
name="Circuit Analyzer",
|
||||
role="Circuit Analysis",
|
||||
goal="Analyze quantum circuit structure",
|
||||
instructions="Evaluate quantum circuit metrics",
|
||||
tools=[analyze_quantum_circuit]
|
||||
)
|
||||
|
||||
optimization_finder = Agent(
|
||||
name="Optimization Finder",
|
||||
role="Optimization Discovery",
|
||||
goal="Identify optimization opportunities",
|
||||
instructions="Find potential optimization techniques",
|
||||
tools=[identify_optimization_opportunities]
|
||||
)
|
||||
|
||||
optimizer = Agent(
|
||||
name="Circuit Optimizer",
|
||||
role="Circuit Optimization",
|
||||
goal="Optimize quantum circuit",
|
||||
instructions="Apply optimization techniques",
|
||||
tools=[simulate_optimization]
|
||||
)
|
||||
|
||||
benchmarker = Agent(
|
||||
name="Performance Benchmarker",
|
||||
role="Performance Analysis",
|
||||
goal="Benchmark optimization results",
|
||||
instructions="Measure performance improvements",
|
||||
tools=[benchmark_performance]
|
||||
)
|
||||
|
||||
validator = Agent(
|
||||
name="Results Validator",
|
||||
role="Validation",
|
||||
goal="Validate optimization results",
|
||||
instructions="Ensure optimization quality",
|
||||
tools=[validate_results]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_circuit",
|
||||
description="Analyze quantum circuit",
|
||||
expected_output="Circuit metrics",
|
||||
agent=circuit_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["find_optimizations"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="find_optimizations",
|
||||
description="Find optimization opportunities",
|
||||
expected_output="Optimization opportunities",
|
||||
agent=optimization_finder,
|
||||
next_tasks=["optimize_circuit"]
|
||||
)
|
||||
|
||||
optimization_execution_task = Task(
|
||||
name="optimize_circuit",
|
||||
description="Execute circuit optimization",
|
||||
expected_output="Optimization results",
|
||||
agent=optimizer,
|
||||
next_tasks=["benchmark_performance"]
|
||||
)
|
||||
|
||||
benchmark_task = Task(
|
||||
name="benchmark_performance",
|
||||
description="Benchmark optimization",
|
||||
expected_output="Performance metrics",
|
||||
agent=benchmarker,
|
||||
next_tasks=["validate_results"],
|
||||
context=[analysis_task, optimization_execution_task]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_results",
|
||||
description="Validate optimization results",
|
||||
expected_output="Validation results",
|
||||
agent=validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"True": "", # End workflow if validation passes
|
||||
"False": ["find_optimizations"] # Retry optimization if validation fails
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[circuit_analyzer, optimization_finder, optimizer,
|
||||
benchmarker, validator],
|
||||
tasks=[analysis_task, optimization_task, optimization_execution_task,
|
||||
benchmark_task, validation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Quantum Algorithm Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nOptimization Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,192 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_research_papers():
|
||||
"""Simulates research paper analysis"""
|
||||
papers = [
|
||||
{
|
||||
"topic": "quantum_computing",
|
||||
"gaps": ["error_correction", "scalability"],
|
||||
"methodology": "experimental",
|
||||
"impact_factor": 8.5
|
||||
},
|
||||
{
|
||||
"topic": "machine_learning",
|
||||
"gaps": ["interpretability", "robustness"],
|
||||
"methodology": "theoretical",
|
||||
"impact_factor": 7.8
|
||||
}
|
||||
]
|
||||
return papers[int(time.time()) % 2]
|
||||
|
||||
def identify_knowledge_gaps(papers: Dict):
|
||||
"""Identifies research gaps"""
|
||||
gaps = []
|
||||
for gap in papers["gaps"]:
|
||||
gaps.append({
|
||||
"area": gap,
|
||||
"significance": "high" if papers["impact_factor"] > 8 else "medium",
|
||||
"research_potential": 0.8 + (time.time() % 2) / 10
|
||||
})
|
||||
return gaps
|
||||
|
||||
def design_experiment(gaps: List[Dict]):
|
||||
"""Designs experimental methodology"""
|
||||
experiments = []
|
||||
for gap in gaps:
|
||||
experiments.append({
|
||||
"area": gap["area"],
|
||||
"methodology": {
|
||||
"type": "quantitative",
|
||||
"duration": "3_months",
|
||||
"resources_needed": ["equipment_A", "dataset_B"],
|
||||
"expected_outcome": "validation_metrics"
|
||||
},
|
||||
"priority": gap["significance"]
|
||||
})
|
||||
return experiments
|
||||
|
||||
def validate_methodology(experiments: List[Dict]):
|
||||
"""Validates experimental design"""
|
||||
validations = []
|
||||
for exp in experiments:
|
||||
validations.append({
|
||||
"area": exp["area"],
|
||||
"statistical_power": 0.9 + (time.time() % 1) / 10,
|
||||
"resource_feasibility": 0.8 + (time.time() % 1) / 10,
|
||||
"ethical_compliance": True,
|
||||
"recommendations": []
|
||||
})
|
||||
return validations
|
||||
|
||||
def predict_impact(experiments: List[Dict], validations: List[Dict]):
|
||||
"""Predicts research impact"""
|
||||
predictions = []
|
||||
for exp, val in zip(experiments, validations):
|
||||
predictions.append({
|
||||
"area": exp["area"],
|
||||
"potential_impact": val["statistical_power"] * 10,
|
||||
"novelty_score": 0.7 + (time.time() % 3) / 10,
|
||||
"breakthrough_probability": 0.5 + (time.time() % 4) / 10
|
||||
})
|
||||
return predictions
|
||||
|
||||
# Create specialized agents
|
||||
paper_analyzer = Agent(
|
||||
name="Paper Analyzer",
|
||||
role="Research Analysis",
|
||||
goal="Analyze research papers",
|
||||
instructions="Review and analyze scientific papers",
|
||||
tools=[analyze_research_papers]
|
||||
)
|
||||
|
||||
gap_identifier = Agent(
|
||||
name="Gap Identifier",
|
||||
role="Gap Analysis",
|
||||
goal="Identify knowledge gaps",
|
||||
instructions="Identify research opportunities",
|
||||
tools=[identify_knowledge_gaps]
|
||||
)
|
||||
|
||||
experiment_designer = Agent(
|
||||
name="Experiment Designer",
|
||||
role="Experimental Design",
|
||||
goal="Design research experiments",
|
||||
instructions="Create experimental methodologies",
|
||||
tools=[design_experiment]
|
||||
)
|
||||
|
||||
methodology_validator = Agent(
|
||||
name="Methodology Validator",
|
||||
role="Validation",
|
||||
goal="Validate experimental design",
|
||||
instructions="Ensure methodology validity",
|
||||
tools=[validate_methodology]
|
||||
)
|
||||
|
||||
impact_predictor = Agent(
|
||||
name="Impact Predictor",
|
||||
role="Impact Analysis",
|
||||
goal="Predict research impact",
|
||||
instructions="Assess potential impact",
|
||||
tools=[predict_impact]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_papers",
|
||||
description="Analyze research papers",
|
||||
expected_output="Paper analysis results",
|
||||
agent=paper_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["identify_gaps"]
|
||||
)
|
||||
|
||||
gap_task = Task(
|
||||
name="identify_gaps",
|
||||
description="Identify knowledge gaps",
|
||||
expected_output="Research gaps",
|
||||
agent=gap_identifier,
|
||||
next_tasks=["design_experiments"]
|
||||
)
|
||||
|
||||
design_task = Task(
|
||||
name="design_experiments",
|
||||
description="Design experiments",
|
||||
expected_output="Experimental designs",
|
||||
agent=experiment_designer,
|
||||
next_tasks=["validate_methodology"]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_methodology",
|
||||
description="Validate methodology",
|
||||
expected_output="Validation results",
|
||||
agent=methodology_validator,
|
||||
next_tasks=["predict_impact"]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_impact",
|
||||
description="Predict research impact",
|
||||
expected_output="Impact predictions",
|
||||
agent=impact_predictor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": "", # End workflow if high impact
|
||||
"medium": ["design_experiments"], # Refine if medium impact
|
||||
"low": ["identify_gaps"] # Restart if low impact
|
||||
},
|
||||
context=[design_task, validation_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[paper_analyzer, gap_identifier, experiment_designer,
|
||||
methodology_validator, impact_predictor],
|
||||
tasks=[analysis_task, gap_task, design_task,
|
||||
validation_task, prediction_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Research Assistant Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nResearch Analysis Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,231 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_mission_parameters():
|
||||
"""Simulates mission parameter analysis"""
|
||||
parameters = {
|
||||
"duration": 180, # days
|
||||
"crew_size": 4,
|
||||
"orbital_parameters": {
|
||||
"altitude": 400, # km
|
||||
"inclination": 51.6, # degrees
|
||||
"period": 92.68 # minutes
|
||||
},
|
||||
"mission_objectives": [
|
||||
"scientific_research",
|
||||
"satellite_deployment",
|
||||
"space_station_maintenance"
|
||||
]
|
||||
}
|
||||
return parameters
|
||||
|
||||
def calculate_resource_requirements(params: Dict):
|
||||
"""Calculates required resources"""
|
||||
requirements = {
|
||||
"life_support": {
|
||||
"oxygen": params["duration"] * params["crew_size"] * 0.84, # kg
|
||||
"water": params["duration"] * params["crew_size"] * 2.5, # liters
|
||||
"food": params["duration"] * params["crew_size"] * 1.8 # kg
|
||||
},
|
||||
"power": {
|
||||
"daily_consumption": 30 + (params["crew_size"] * 5), # kWh
|
||||
"peak_demand": 45 + (params["crew_size"] * 8), # kW
|
||||
"backup_capacity": 72 # hours
|
||||
},
|
||||
"propellant": {
|
||||
"main_engine": 2000, # kg
|
||||
"attitude_control": 500, # kg
|
||||
"reserve": 300 # kg
|
||||
}
|
||||
}
|
||||
return requirements
|
||||
|
||||
def plan_contingencies(requirements: Dict):
|
||||
"""Plans contingency scenarios"""
|
||||
contingencies = [
|
||||
{
|
||||
"scenario": "power_failure",
|
||||
"probability": 0.05,
|
||||
"impact": "critical",
|
||||
"resources_needed": {
|
||||
"backup_power": requirements["power"]["daily_consumption"] * 3,
|
||||
"repair_equipment": ["solar_panel_kit", "power_distribution_unit"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "life_support_malfunction",
|
||||
"probability": 0.03,
|
||||
"impact": "severe",
|
||||
"resources_needed": {
|
||||
"oxygen_reserve": requirements["life_support"]["oxygen"] * 0.2,
|
||||
"repair_parts": ["filter_system", "pressure_regulators"]
|
||||
}
|
||||
}
|
||||
]
|
||||
return contingencies[int(time.time()) % 2]
|
||||
|
||||
def optimize_allocation(requirements: Dict, contingencies: Dict):
|
||||
"""Optimizes resource allocation"""
|
||||
allocation = {
|
||||
"primary_resources": {
|
||||
"life_support": {
|
||||
"nominal": requirements["life_support"],
|
||||
"buffer": 0.15 # 15% buffer
|
||||
},
|
||||
"power": {
|
||||
"nominal": requirements["power"],
|
||||
"buffer": 0.2 # 20% buffer
|
||||
}
|
||||
},
|
||||
"contingency_resources": {
|
||||
"type": contingencies["scenario"],
|
||||
"allocation": contingencies["resources_needed"],
|
||||
"priority": "high" if contingencies["impact"] == "critical" else "medium"
|
||||
}
|
||||
}
|
||||
return allocation
|
||||
|
||||
def simulate_mission_scenarios(allocation: Dict):
|
||||
"""Simulates various mission scenarios"""
|
||||
scenarios = {
|
||||
"nominal_operations": {
|
||||
"success_rate": 0.95,
|
||||
"resource_utilization": 0.85,
|
||||
"efficiency_rating": 0.9
|
||||
},
|
||||
"emergency_scenarios": [
|
||||
{
|
||||
"type": "power_reduction",
|
||||
"duration": 48, # hours
|
||||
"impact": "moderate",
|
||||
"resolution_success": 0.88
|
||||
},
|
||||
{
|
||||
"type": "life_support_adjustment",
|
||||
"duration": 24, # hours
|
||||
"impact": "minor",
|
||||
"resolution_success": 0.92
|
||||
}
|
||||
]
|
||||
}
|
||||
return scenarios
|
||||
|
||||
# Create specialized agents
|
||||
mission_analyzer = Agent(
|
||||
name="Mission Analyzer",
|
||||
role="Mission Analysis",
|
||||
goal="Analyze mission parameters",
|
||||
instructions="Evaluate mission requirements and constraints",
|
||||
tools=[analyze_mission_parameters]
|
||||
)
|
||||
|
||||
resource_calculator = Agent(
|
||||
name="Resource Calculator",
|
||||
role="Resource Calculation",
|
||||
goal="Calculate resource requirements",
|
||||
instructions="Determine required resources for mission",
|
||||
tools=[calculate_resource_requirements]
|
||||
)
|
||||
|
||||
contingency_planner = Agent(
|
||||
name="Contingency Planner",
|
||||
role="Contingency Planning",
|
||||
goal="Plan for contingencies",
|
||||
instructions="Develop contingency scenarios and plans",
|
||||
tools=[plan_contingencies]
|
||||
)
|
||||
|
||||
resource_optimizer = Agent(
|
||||
name="Resource Optimizer",
|
||||
role="Resource Optimization",
|
||||
goal="Optimize resource allocation",
|
||||
instructions="Optimize resource distribution",
|
||||
tools=[optimize_allocation]
|
||||
)
|
||||
|
||||
scenario_simulator = Agent(
|
||||
name="Scenario Simulator",
|
||||
role="Scenario Simulation",
|
||||
goal="Simulate mission scenarios",
|
||||
instructions="Simulate various mission scenarios",
|
||||
tools=[simulate_mission_scenarios]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
mission_task = Task(
|
||||
name="analyze_mission",
|
||||
description="Analyze mission parameters",
|
||||
expected_output="Mission parameters",
|
||||
agent=mission_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["calculate_resources"]
|
||||
)
|
||||
|
||||
resource_task = Task(
|
||||
name="calculate_resources",
|
||||
description="Calculate resource requirements",
|
||||
expected_output="Resource requirements",
|
||||
agent=resource_calculator,
|
||||
next_tasks=["plan_contingencies"]
|
||||
)
|
||||
|
||||
contingency_task = Task(
|
||||
name="plan_contingencies",
|
||||
description="Plan contingencies",
|
||||
expected_output="Contingency plans",
|
||||
agent=contingency_planner,
|
||||
context=[resource_task],
|
||||
next_tasks=["optimize_resources"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="optimize_resources",
|
||||
description="Optimize resource allocation",
|
||||
expected_output="Resource allocation",
|
||||
agent=resource_optimizer,
|
||||
context=[resource_task, contingency_task],
|
||||
next_tasks=["simulate_scenarios"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_scenarios",
|
||||
description="Simulate scenarios",
|
||||
expected_output="Simulation results",
|
||||
agent=scenario_simulator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"nominal_operations": "", # End workflow if nominal
|
||||
"emergency_scenarios": ["optimize_resources"] # Reoptimize if emergency
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[mission_analyzer, resource_calculator, contingency_planner,
|
||||
resource_optimizer, scenario_simulator],
|
||||
tasks=[mission_task, resource_task, contingency_task,
|
||||
optimization_task, simulation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Space Mission Resource Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nResource Optimization Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,195 @@
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def scan_code_patterns():
|
||||
"""Simulates code pattern scanning"""
|
||||
patterns = [
|
||||
{
|
||||
"type": "buffer_overflow",
|
||||
"severity": "critical",
|
||||
"location": "memory_management",
|
||||
"frequency": 3
|
||||
},
|
||||
{
|
||||
"type": "sql_injection",
|
||||
"severity": "high",
|
||||
"location": "database_interface",
|
||||
"frequency": 2
|
||||
},
|
||||
{
|
||||
"type": "race_condition",
|
||||
"severity": "medium",
|
||||
"location": "thread_handling",
|
||||
"frequency": 1
|
||||
}
|
||||
]
|
||||
return patterns[int(time.time()) % 3]
|
||||
|
||||
def analyze_attack_vectors(pattern: Dict):
|
||||
"""Analyzes potential attack vectors"""
|
||||
vectors = []
|
||||
severity_scores = {"critical": 9.5, "high": 8.0, "medium": 6.5}
|
||||
base_score = severity_scores[pattern["type"]]
|
||||
|
||||
vectors.append({
|
||||
"type": pattern["type"],
|
||||
"attack_path": f"exploit_{pattern['location']}",
|
||||
"complexity": "high" if pattern["frequency"] < 2 else "medium",
|
||||
"cvss_score": base_score + (time.time() % 1)
|
||||
})
|
||||
return vectors
|
||||
|
||||
def simulate_exploitation(vectors: List[Dict]):
|
||||
"""Simulates exploitation attempts"""
|
||||
results = []
|
||||
for vector in vectors:
|
||||
results.append({
|
||||
"vector": vector["type"],
|
||||
"success_rate": 0.7 + (time.time() % 3) / 10,
|
||||
"detection_time": 100 + (int(time.time()) % 50),
|
||||
"mitigation_possible": vector["complexity"] != "high"
|
||||
})
|
||||
return results
|
||||
|
||||
def generate_signatures(results: List[Dict]):
|
||||
"""Generates vulnerability signatures"""
|
||||
signatures = []
|
||||
for result in results:
|
||||
signatures.append({
|
||||
"pattern": f"signature_{result['vector']}",
|
||||
"reliability": result['success_rate'],
|
||||
"false_positive_rate": 0.1 + (time.time() % 2) / 10,
|
||||
"detection_speed": result['detection_time']
|
||||
})
|
||||
return signatures
|
||||
|
||||
def validate_findings(signatures: List[Dict]):
|
||||
"""Validates vulnerability findings"""
|
||||
validations = []
|
||||
for sig in signatures:
|
||||
validations.append({
|
||||
"signature": sig["pattern"],
|
||||
"confidence": sig["reliability"] * (1 - sig["false_positive_rate"]),
|
||||
"reproducibility": 0.8 + (time.time() % 2) / 10,
|
||||
"severity": "critical" if sig["reliability"] > 0.8 else "high"
|
||||
})
|
||||
return validations
|
||||
|
||||
# Create specialized agents
|
||||
pattern_scanner = Agent(
|
||||
name="Pattern Scanner",
|
||||
role="Code Analysis",
|
||||
goal="Scan for suspicious patterns",
|
||||
instructions="Analyze code for potential vulnerabilities",
|
||||
tools=[scan_code_patterns]
|
||||
)
|
||||
|
||||
vector_analyzer = Agent(
|
||||
name="Vector Analyzer",
|
||||
role="Attack Vector Analysis",
|
||||
goal="Analyze attack vectors",
|
||||
instructions="Identify potential attack paths",
|
||||
tools=[analyze_attack_vectors]
|
||||
)
|
||||
|
||||
exploit_simulator = Agent(
|
||||
name="Exploit Simulator",
|
||||
role="Exploitation Testing",
|
||||
goal="Simulate exploitation attempts",
|
||||
instructions="Test potential vulnerabilities",
|
||||
tools=[simulate_exploitation]
|
||||
)
|
||||
|
||||
signature_generator = Agent(
|
||||
name="Signature Generator",
|
||||
role="Signature Creation",
|
||||
goal="Generate vulnerability signatures",
|
||||
instructions="Create detection signatures",
|
||||
tools=[generate_signatures]
|
||||
)
|
||||
|
||||
finding_validator = Agent(
|
||||
name="Finding Validator",
|
||||
role="Validation",
|
||||
goal="Validate findings",
|
||||
instructions="Verify vulnerability findings",
|
||||
tools=[validate_findings]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
scanning_task = Task(
|
||||
name="scan_patterns",
|
||||
description="Scan code patterns",
|
||||
expected_output="Suspicious patterns",
|
||||
agent=pattern_scanner,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_vectors"]
|
||||
)
|
||||
|
||||
vector_task = Task(
|
||||
name="analyze_vectors",
|
||||
description="Analyze attack vectors",
|
||||
expected_output="Attack vectors",
|
||||
agent=vector_analyzer,
|
||||
next_tasks=["simulate_exploits"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_exploits",
|
||||
description="Simulate exploits",
|
||||
expected_output="Exploitation results",
|
||||
agent=exploit_simulator,
|
||||
next_tasks=["generate_signatures"]
|
||||
)
|
||||
|
||||
signature_task = Task(
|
||||
name="generate_signatures",
|
||||
description="Generate signatures",
|
||||
expected_output="Vulnerability signatures",
|
||||
agent=signature_generator,
|
||||
next_tasks=["validate_findings"]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_findings",
|
||||
description="Validate findings",
|
||||
expected_output="Validation results",
|
||||
agent=finding_validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"critical": ["scan_patterns"], # Continue scanning if critical
|
||||
"high": ["analyze_vectors"], # Reanalyze if high
|
||||
"medium": "" # End workflow if medium
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[pattern_scanner, vector_analyzer, exploit_simulator,
|
||||
signature_generator, finding_validator],
|
||||
tasks=[scanning_task, vector_task, simulation_task,
|
||||
signature_task, validation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Vulnerability Detection Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nVulnerability Detection Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+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.47.tar.gz"
|
||||
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/2.0.50.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.47 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.50 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.47"
|
||||
version = "2.0.50"
|
||||
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.38",
|
||||
"praisonaiagents>=0.0.41",
|
||||
"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.47"
|
||||
version = "2.0.50"
|
||||
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.38"
|
||||
praisonaiagents = ">=0.0.41"
|
||||
python-dotenv = ">=0.19.0"
|
||||
instructor = ">=1.3.3"
|
||||
PyYAML = ">=6.0"
|
||||
|
||||
@@ -3060,7 +3060,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonai"
|
||||
version = "2.0.47"
|
||||
version = "2.0.50"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "instructor" },
|
||||
@@ -3197,7 +3197,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.38" },
|
||||
{ name = "praisonaiagents", specifier = ">=0.0.41" },
|
||||
{ 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" },
|
||||
@@ -3250,16 +3250,16 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.38"
|
||||
version = "0.0.41"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "openai" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "rich" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ac/57/6960631f138850e4076dc0d450b09e91dea7dbc8adc7a92508d191a0e748/praisonaiagents-0.0.38.tar.gz", hash = "sha256:0489221466fdd5dfd8962c74ae0196f0b986f0711be763fbf5e683324210af84", size = 75011 }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d9/39/2e97f6f1ea30948ae93c15cfab67998c999fe859b26481e2dfbddbc5543c/praisonaiagents-0.0.41.tar.gz", hash = "sha256:f8760446ff2bae5957a695616bc23b990bf422054edc2d2d37f2336fd708475b", size = 75859 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/11/e7/5a32bff222ecd1d24ba059f055951cd943ac108e53e1d29e98d7c3d701be/praisonaiagents-0.0.38-py3-none-any.whl", hash = "sha256:26c35aa017935162669f5404286c3202c37065316d903de6c550cfdd57e6cabc", size = 92685 },
|
||||
{ url = "https://files.pythonhosted.org/packages/63/7a/3da6a6076b2501246a0770d662c5d72158eaacfc10eb4b0938ae43b17d19/praisonaiagents-0.0.41-py3-none-any.whl", hash = "sha256:72dc3e1f5c939ab74898e952bba2b106e3f2b5bf4577f9ff96bc725e17d5b212", size = 93589 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in new issue
Block a user