mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-08 01:08:39 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb2b3617fa | ||
|
|
6de67c7d0d | ||
|
|
5699d90894 | ||
|
|
2982e8ea9c | ||
|
|
9dd2146342 | ||
|
|
f79184a6ee | ||
|
|
0985e12ad4 | ||
|
|
0fbb7972e1 | ||
|
|
5744ae853e | ||
|
|
bd6e3da4ff | ||
|
|
f2f51d9e8b | ||
|
|
4a1098603d | ||
|
|
5468e35bc1 | ||
|
|
b468267a87 | ||
|
|
48141bbd9e | ||
|
|
b3cdf53d07 | ||
|
|
aa594ddc32 | ||
|
|
5f330e8fb2 | ||
|
|
ff94e128de | ||
|
|
854a016fc5 | ||
|
|
12e8ed7b77 | ||
|
|
13c5f5537e | ||
|
|
e7c1614ac8 | ||
|
|
7cc6db2a34 | ||
|
|
b869bbc346 | ||
|
|
5492be4412 | ||
|
|
c2e33ef6a6 | ||
|
|
5b2e0a9417 | ||
|
|
2f6d9ebcc9 | ||
|
|
0610a5b3a4 | ||
|
|
7463744e62 | ||
|
|
c7428b8282 | ||
|
|
ff1deb6b97 | ||
|
|
bdbed2667d | ||
|
|
2810ec879c | ||
|
|
04a8c621bb | ||
|
|
17cbadaf64 | ||
|
|
fbcdf84350 | ||
|
|
ab3295caa1 | ||
|
|
95517f5007 | ||
|
|
3800825b38 | ||
|
|
f85e16ab87 | ||
|
|
dbdd3d3d9a | ||
|
|
1cc5dad01f | ||
|
|
3797e4fe25 | ||
|
|
d840e7d0ef | ||
|
|
6f9ca636aa | ||
|
|
f254d9e290 | ||
|
|
2e95279cd5 | ||
|
|
c218ad62ce | ||
|
|
d10849085d | ||
|
|
9594426fc2 | ||
|
|
1c6fc71a06 | ||
|
|
d7289acc1d | ||
|
|
54a748b4c7 | ||
|
|
9f62e9201a | ||
|
|
1b69360d9f | ||
|
|
9bdc6545ad | ||
|
|
06cd909367 | ||
|
|
67aeece7fc | ||
|
|
ef67d0753c | ||
|
|
f374f9f791 | ||
|
|
492fb29af9 | ||
|
|
cd56ebd5cf | ||
|
|
08e99f6ef7 | ||
|
|
670d653ae9 | ||
|
|
faa014b8b0 | ||
|
|
6d454d0c6e | ||
|
|
0ec3fe3510 | ||
|
|
707888cdf9 | ||
|
|
42051630bc | ||
|
|
bfcccb6355 | ||
|
|
e329afc394 | ||
|
|
9417cc6457 | ||
|
|
10a3d279ae | ||
|
|
2a916208e1 | ||
|
|
bcd0bbbd24 | ||
|
|
5701a40f11 | ||
|
|
3ffac395bb | ||
|
|
37119aa3ac | ||
|
|
8b2d324d3b | ||
|
|
6d0b29e60d | ||
|
|
583cbc5efa | ||
|
|
90dd84a152 | ||
|
|
ef7fa66e33 | ||
|
|
1659ed61bc | ||
|
|
b8939ef439 | ||
|
|
4bada9e5fc | ||
|
|
51c4cb00b0 | ||
|
|
ad96549ea3 | ||
|
|
183d10d7cc | ||
|
|
bce1559ab5 | ||
|
|
6f3fb87ba3 | ||
|
|
e7f6b2df67 | ||
|
|
08d72eeb80 | ||
|
|
11aefae90f | ||
|
|
10d5158d27 | ||
|
|
1d8b814fcd | ||
|
|
6e8a5b98a8 | ||
|
|
59d0ff8c95 | ||
|
|
b2109faa06 | ||
|
|
024eaed456 | ||
|
|
4fd3a572cf | ||
|
|
baaf8b6256 | ||
|
|
fe4550d2bc | ||
|
|
db09a94425 | ||
|
|
2db36dc932 | ||
|
|
8c0e4277a4 | ||
|
|
41448617d5 | ||
|
|
49ea23c676 | ||
|
|
bb0dc63680 | ||
|
|
7774f2c565 | ||
|
|
5533fd3476 | ||
|
|
262a90a235 | ||
|
|
60928dcb90 | ||
|
|
c8552e1158 | ||
|
|
c57d7db9bb | ||
|
|
236abc2c83 | ||
|
|
76c5f8fe3f | ||
|
|
82750020d2 | ||
|
|
f49ad9fbc2 | ||
|
|
c086c60fd6 | ||
|
|
4f8f4f2036 | ||
|
|
8e91c20967 | ||
|
|
6f092c1507 | ||
|
|
8f553d3a54 | ||
|
|
2d647e25b5 | ||
|
|
039bb772f5 | ||
|
|
459c2f2b70 | ||
|
|
ee59706357 | ||
|
|
2a51644773 | ||
|
|
cce908fa22 | ||
|
|
acf476f715 | ||
|
|
e5d77de79c | ||
|
|
9ab444b54c | ||
|
|
e13f543c6d | ||
|
|
4f235d358c | ||
|
|
b7847feb1e | ||
|
|
7ac730462c | ||
|
|
9cbc8d082d | ||
|
|
7fb0aed7ac | ||
|
|
206f0d01e7 | ||
|
|
e19a310314 | ||
|
|
1ea572689e | ||
|
|
96df649b05 | ||
|
|
5aed75837a | ||
|
|
9c8f68a05f | ||
|
|
9778a69c4d | ||
|
|
73c7994380 | ||
|
|
82b83ded41 | ||
|
|
fc80db32c2 | ||
|
|
3f115ca7ba | ||
|
|
a32d45e6da | ||
|
|
8823df26ff | ||
|
|
9c2126fbd6 | ||
|
|
741b01bdf0 | ||
|
|
6ed9a69cd8 | ||
|
|
56a42e6d95 | ||
|
|
d2b4affdd1 | ||
|
|
0d5c8b478f | ||
|
|
fdfad70319 | ||
|
|
fba6b2e2a0 | ||
|
|
f9bfb85f44 | ||
|
|
aab4b5b466 | ||
|
|
7ccadde004 | ||
|
|
22a9d5ff23 | ||
|
|
98a11209ea | ||
|
|
df3c97e73a | ||
|
|
27808964be | ||
|
|
b5daf16e0d | ||
|
|
a2cac05d16 |
No files matched your search
+8
-1885
File diff suppressed because it is too large.
Load diff
@@ -20,7 +20,7 @@
|
||||
|
||||
</div>
|
||||
|
||||
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.
|
||||
PraisonAI is a production-ready Multi-AI Agents framework with self-reflection, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. By integrating PraisonAI Agents, AutoGen, and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
|
||||
|
||||
<div align="center">
|
||||
<a href="https://docs.praison.ai">
|
||||
@@ -37,35 +37,24 @@ PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application
|
||||
- 🧠 Reasoning AI Agents
|
||||
- 👁️ Multi Modal AI Agents
|
||||
- 🤝 Multi Agent Collaboration
|
||||
- ⚡ AI Agent Workflow
|
||||
- 🔄 Use CrewAI or AutoGen Framework
|
||||
- 🎭 AI Agent Workflow
|
||||
- 📚 Add Custom Knowledge
|
||||
- 🧠 Agents with Short and Long Term Memory
|
||||
- 📄 Chat with PDF Agents
|
||||
- 💻 Code Interpreter Agents
|
||||
- 📚 RAG Agents
|
||||
- 🤔 Async & Parallel Processing
|
||||
- 🔄 Auto Agents
|
||||
- 🔢 Math Agents
|
||||
- 🎯 Structured Output Agents
|
||||
- 🔗 LangChain Integrated Agents
|
||||
- 📞 Callback Agents
|
||||
- 🤏 Mini AI Agents
|
||||
- 🛠️ 100+ Custom Tools
|
||||
- 📄 YAML Configuration
|
||||
- 💯 100+ LLM Support
|
||||
- 💻 Chat with ENTIRE Codebase
|
||||
- 🎨 Interactive UIs
|
||||
- 📄 YAML-based Configuration
|
||||
- 🛠️ Custom Tool Integration
|
||||
- 🔍 Internet Search Capability (using Crawl4AI and Tavily)
|
||||
- 🖼️ Vision Language Model (VLM) Support
|
||||
- 🎙️ Real-time Voice Interaction
|
||||
|
||||
## Using No Code
|
||||
|
||||
### Auto Mode:
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
praisonai --auto create a movie script about Robots in Mars
|
||||
```
|
||||
|
||||
### Initialise Mode:
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
praisonai --init create a movie script about Robots in Mars
|
||||
praisonai
|
||||
```
|
||||
|
||||
## Using Coding
|
||||
## Using Python Code
|
||||
|
||||
Light weight package dedicated for coding:
|
||||
```bash
|
||||
@@ -76,58 +65,13 @@ pip install praisonaiagents
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
### 1. Single Agent
|
||||
|
||||
Create app.py file and add the code below:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# 1. Create agents
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI and data science",
|
||||
backstory="""You are an expert at a technology research group,
|
||||
skilled in identifying trends and analyzing complex data.""",
|
||||
verbose=True,
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
writer = Agent(
|
||||
name="Writer",
|
||||
role="Tech Content Strategist",
|
||||
goal="Craft compelling content on tech advancements",
|
||||
backstory="""You are a content strategist known for
|
||||
making complex tech topics interesting and easy to understand.""",
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# 2. Define Tasks
|
||||
task1 = Task(
|
||||
name="research_task",
|
||||
description="""Analyze 2024's AI advancements.
|
||||
Find major trends, new technologies, and their effects.""",
|
||||
expected_output="""A detailed report on 2024 AI advancements""",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="writing_task",
|
||||
description="""Create a blog post about major AI advancements using the insights you have.
|
||||
Make it interesting, clear, and suited for tech enthusiasts.
|
||||
It should be at least 4 paragraphs long.""",
|
||||
expected_output="A blog post of at least 4 paragraphs",
|
||||
agent=writer,
|
||||
)
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2],
|
||||
verbose=False,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
from praisonaiagents import Agent
|
||||
agent = Agent(instructions="Your are a helpful AI assistant")
|
||||
agent.start("Write a movie script about a robot in Mars")
|
||||
```
|
||||
|
||||
Run:
|
||||
@@ -135,6 +79,396 @@ Run:
|
||||
python app.py
|
||||
```
|
||||
|
||||
### 2. Multi Agents
|
||||
|
||||
Create app.py file and add the code below:
|
||||
```python
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
research_agent = Agent(instructions="Research about AI")
|
||||
summarise_agent = Agent(instructions="Summarise research agent's findings")
|
||||
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
|
||||
Run:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
## Using No Code
|
||||
|
||||
### Auto Mode:
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
praisonai --auto create a movie script about Robots in Mars
|
||||
```
|
||||
|
||||
## Using JavaScript Code
|
||||
|
||||
```bash
|
||||
npm install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
```javascript
|
||||
const { Agent } = require('praisonai');
|
||||
const agent = new Agent({ instructions: 'You are a helpful AI assistant' });
|
||||
agent.start('Write a movie script about a robot in Mars');
|
||||
```
|
||||
|
||||

|
||||
|
||||
## AI Agents Flow
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Define the main flow
|
||||
Start([▶ Start]) --> Agent1
|
||||
Agent1 --> Process[⚙ Process]
|
||||
Process --> Agent2
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
end
|
||||
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
end
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
## AI Agents with Tools
|
||||
|
||||
Create AI agents that can use tools to interact with external systems and perform actions.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
## AI Agents with Memory
|
||||
|
||||
Create AI agents with memory capabilities for maintaining context and information across tasks.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
## AI Agents with Different Processes
|
||||
|
||||
### Sequential Process
|
||||
|
||||
The simplest form of task execution where tasks are performed one after another.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### Hierarchical Process
|
||||
|
||||
Uses a manager agent to coordinate task execution and agent assignments.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### Workflow Process
|
||||
|
||||
Advanced process type supporting complex task relationships and conditional execution.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
#### Agentic Routing Workflow
|
||||
|
||||
Create AI agents that can dynamically route tasks to specialized LLM instances.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Router[LLM Call Router]
|
||||
Router --> LLM1[LLM Call 1]
|
||||
Router --> LLM2[LLM Call 2]
|
||||
Router --> LLM3[LLM Call 3]
|
||||
LLM1 --> Out[Out]
|
||||
LLM2 --> Out
|
||||
LLM3 --> Out
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Router fill:#2E8B57,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Orchestrator Worker
|
||||
|
||||
Create AI agents that orchestrate and distribute tasks among specialized workers.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Router[LLM Call Router]
|
||||
Router --> LLM1[LLM Call 1]
|
||||
Router --> LLM2[LLM Call 2]
|
||||
Router --> LLM3[LLM Call 3]
|
||||
LLM1 --> Synthesizer[Synthesizer]
|
||||
LLM2 --> Synthesizer
|
||||
LLM3 --> Synthesizer
|
||||
Synthesizer --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Router fill:#2E8B57,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Synthesizer fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Autonomous Workflow
|
||||
|
||||
Create AI agents that can autonomously monitor, act, and adapt based on environment feedback.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Human[Human] <--> LLM[LLM Call]
|
||||
LLM -->|ACTION| Environment[Environment]
|
||||
Environment -->|FEEDBACK| LLM
|
||||
LLM --> Stop[Stop]
|
||||
|
||||
style Human fill:#8B0000,color:#fff
|
||||
style LLM fill:#2E8B57,color:#fff
|
||||
style Environment fill:#8B0000,color:#fff
|
||||
style Stop fill:#333,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Parallelization
|
||||
|
||||
Create AI agents that can execute tasks in parallel for improved performance.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> LLM2[LLM Call 2]
|
||||
In --> LLM1[LLM Call 1]
|
||||
In --> LLM3[LLM Call 3]
|
||||
LLM1 --> Aggregator[Aggregator]
|
||||
LLM2 --> Aggregator
|
||||
LLM3 --> Aggregator
|
||||
Aggregator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Aggregator fill:#fff,color:#000
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Prompt Chaining
|
||||
|
||||
Create AI agents with sequential prompt chaining for complex workflows.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> LLM1[LLM Call 1] --> Gate{Gate}
|
||||
Gate -->|Pass| LLM2[LLM Call 2] -->|Output 2| LLM3[LLM Call 3] --> Out[Out]
|
||||
Gate -->|Fail| Exit[Exit]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
style Exit fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Evaluator Optimizer
|
||||
|
||||
Create AI agents that can generate and optimize solutions through iterative feedback.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Generator[LLM Call Generator]
|
||||
Generator -->|SOLUTION| Evaluator[LLM Call Evaluator] -->|ACCEPTED| Out[Out]
|
||||
Evaluator -->|REJECTED + FEEDBACK| Generator
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Evaluator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Repetitive Agents
|
||||
|
||||
Create AI agents that can efficiently handle repetitive tasks through automated loops.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Input] --> LoopAgent[("Looping Agent")]
|
||||
LoopAgent --> Task[Task]
|
||||
Task --> |Next iteration| LoopAgent
|
||||
Task --> |Done| Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style LoopAgent fill:#2E8B57,color:#fff,shape:circle
|
||||
style Task fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## Adding Models
|
||||
|
||||
<div align="center">
|
||||
<a href="https://docs.praison.ai/models">
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/%F0%9F%93%9A_Models-Visit_docs.praison.ai-blue?style=for-the-badge&logo=bookstack&logoColor=white" alt="Models" />
|
||||
</p>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Ollama Integration
|
||||
```bash
|
||||
export OPENAI_BASE_URL=http://localhost:11434/v1
|
||||
@@ -147,267 +481,16 @@ export OPENAI_API_KEY=xxxxxxxxxxx
|
||||
export OPENAI_BASE_URL=https://api.groq.com/openai/v1
|
||||
```
|
||||
|
||||
## Logging
|
||||
```bash
|
||||
export LOGLEVEL=info
|
||||
```
|
||||
|
||||
Advanced logging:
|
||||
```bash
|
||||
export LOGLEVEL=debug
|
||||
```
|
||||
|
||||
<div align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/images/architecture-dark.png" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="docs/images/architecture-light.png" />
|
||||
<img alt="PraisonAI Architecture" src="docs/images/architecture-light.png" />
|
||||
</picture>
|
||||
</div>
|
||||
|
||||
## Different User Interfaces:
|
||||
|
||||
| Interface | Description | URL |
|
||||
|---|---|---|
|
||||
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praison.ai/ui/ui](https://docs.praison.ai/ui/ui) |
|
||||
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praison.ai/ui/chat](https://docs.praison.ai/ui/chat) |
|
||||
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praison.ai/ui/code](https://docs.praison.ai/ui/code) |
|
||||
| **Realtime** | Real-time voice interaction with AI | [https://docs.praison.ai/ui/realtime](https://docs.praison.ai/ui/realtime) |
|
||||
|
||||
| Other Features | Description | Docs |
|
||||
|---|---|---|
|
||||
| **Train** | Fine-tune LLMs using your custom data | [https://docs.praison.ai/train](https://docs.praison.ai/train) |
|
||||
|
||||
|
||||
## Google Colab Multi Agents
|
||||
|
||||
| | Cookbook | Open in Colab |
|
||||
| ------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Basic | PraisonAI | <a target="_blank" href="https://colab.research.google.com/github/MervinPraison/PraisonAI/blob/main/cookbooks/praisonai-googlecolab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" /></a> |
|
||||
| Include Tools | PraisonAI Tools | <a target="_blank" href="https://colab.research.google.com/github/MervinPraison/PraisonAI/blob/main/cookbooks/praisonai-tools-googlecolab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" /></a> |
|
||||
|
||||
## Installation Options
|
||||
|
||||
### Using pip
|
||||
```bash
|
||||
pip install praisonai
|
||||
```
|
||||
|
||||
### Framework-specific Installation
|
||||
```bash
|
||||
# Install with CrewAI support
|
||||
pip install "praisonai[crewai]"
|
||||
|
||||
# Install with AutoGen support
|
||||
pip install "praisonai[autogen]"
|
||||
|
||||
# Install with both frameworks
|
||||
pip install "praisonai[crewai,autogen]"
|
||||
```
|
||||
|
||||
### UI and Additional Features
|
||||
```bash
|
||||
# Install UI support
|
||||
pip install "praisonai[ui]"
|
||||
|
||||
# Install Chat interface
|
||||
pip install "praisonai[chat]"
|
||||
|
||||
# Install Code interface
|
||||
pip install "praisonai[code]"
|
||||
|
||||
# Install Realtime voice interaction
|
||||
pip install "praisonai[realtime]"
|
||||
|
||||
# Install Call feature
|
||||
pip install "praisonai[call]"
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Set your OpenAI API key
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
|
||||
# Initialize with CrewAI (default)
|
||||
praisonai --init "create a movie script about dog in moon"
|
||||
|
||||
# Or initialize with AutoGen
|
||||
praisonai --framework autogen --init "create a movie script about dog in moon"
|
||||
|
||||
# Run the agents
|
||||
praisonai
|
||||
```
|
||||
|
||||
## Full Automatic Mode
|
||||
|
||||
```bash
|
||||
# With CrewAI (default)
|
||||
praisonai --auto "create a movie script about Dog in Moon"
|
||||
|
||||
# With AutoGen
|
||||
praisonai --framework autogen --auto "create a movie script about Dog in Moon"
|
||||
```
|
||||
|
||||
## Framework-specific Features
|
||||
|
||||
### CrewAI
|
||||
When installing with `pip install "praisonai[crewai]"`, you get:
|
||||
- CrewAI framework support
|
||||
- PraisonAI tools integration
|
||||
- Task delegation capabilities
|
||||
- Sequential and parallel task execution
|
||||
|
||||
### AutoGen
|
||||
When installing with `pip install "praisonai[autogen]"`, you get:
|
||||
- AutoGen framework support
|
||||
- PraisonAI tools integration
|
||||
- Multi-agent conversation capabilities
|
||||
- Code execution environment
|
||||
|
||||
|
||||
|
||||
## TL;DR Multi Agents
|
||||
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
praisonai --init create a movie script about dog in moon
|
||||
praisonai
|
||||
```
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Initialise](#initialise)
|
||||
- [Run](#run)
|
||||
- [Full Automatic Mode](#full-automatic-mode)
|
||||
- [User Interface](#user-interface)
|
||||
- [Praison AI Chat](#praison-ai-chat)
|
||||
- [Create Custom Tools](#create-custom-tools)
|
||||
- [Agents Playbook](#agents-playbook)
|
||||
- [Include praisonai package in your project](#include-praisonai-package-in-your-project)
|
||||
- [Commands to Install Dev Dependencies](#commands-to-install-dependencies)
|
||||
- [Other Models](#other-models)
|
||||
- [Contributing](#contributing)
|
||||
- [Star History](#star-history)
|
||||
|
||||
## Installation Multi Agents
|
||||
|
||||
```bash
|
||||
pip install praisonai
|
||||
```
|
||||
|
||||
## Initialise
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
```
|
||||
|
||||
Generate your OPENAI API KEY from here: https://platform.openai.com/api-keys
|
||||
|
||||
Note: You can use other providers such as Ollama, Mistral ... etc. Details are provided at the bottom.
|
||||
|
||||
```bash
|
||||
praisonai --init create a movie script about dog in moon
|
||||
```
|
||||
|
||||
This will automatically create agents.yaml file in the current directory.
|
||||
|
||||
### To initialise with a specific agent framework (Optional):
|
||||
|
||||
```bash
|
||||
praisonai --framework autogen --init create movie script about cat in mars
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
praisonai
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
python -m praisonai
|
||||
```
|
||||
|
||||
### Specify the agent framework (Optional):
|
||||
|
||||
```bash
|
||||
praisonai --framework autogen
|
||||
```
|
||||
|
||||
### Full Automatic Mode
|
||||
|
||||
```bash
|
||||
praisonai --auto create a movie script about Dog in Moon
|
||||
```
|
||||
|
||||
## User Interface
|
||||
|
||||
## PraisonAI User Interfaces:
|
||||
|
||||
| Interface | Description | URL |
|
||||
| --------- | ------------------------------------------ | --------------------------------------------------------------------- |
|
||||
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praisonai.com/ui/ui](https://docs.praison.ai/ui/ui) |
|
||||
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praisonai.com/ui/chat](https://docs.praison.ai/ui/chat) |
|
||||
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praisonai.com/ui/code](https://docs.praison.ai/ui/code) |
|
||||
|
||||
```bash
|
||||
pip install -U "praisonai[ui]"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
chainlit create-secret
|
||||
export CHAINLIT_AUTH_SECRET=xxxxxxxx
|
||||
praisonai ui
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
python -m praisonai ui
|
||||
```
|
||||
|
||||
## Praison AI Chat
|
||||
|
||||
- https://docs.praison.ai/chat/
|
||||
|
||||
```bash
|
||||
pip install "praisonai[chat]"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
praisonai chat
|
||||
```
|
||||
|
||||
### Internet Search
|
||||
|
||||
Praison AI Chat and Praison AI Code now includes internet search capabilities using Crawl4AI and Tavily, allowing you to retrieve up-to-date information during your conversations.
|
||||
|
||||
### Vision Language Model Support
|
||||
|
||||
You can now upload images and ask questions based on them using Vision Language Models. This feature enables visual understanding and analysis within your chat sessions.
|
||||
|
||||
## Praison AI Code
|
||||
|
||||
```bash
|
||||
pip install "praisonai[code]"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
praisonai code
|
||||
```
|
||||
|
||||
### Internet Search
|
||||
|
||||
Praison AI Code also includes internet search functionality, enabling you to find relevant code snippets and programming information online.
|
||||
|
||||
## Create Custom Tools
|
||||
|
||||
- https://docs.praison.ai/tools/custom/
|
||||
## No Code Options
|
||||
|
||||
## Agents Playbook
|
||||
|
||||
### Simple Playbook Example
|
||||
|
||||
Create `agents.yaml` file and add the code below:
|
||||
|
||||
```yaml
|
||||
framework: crewai
|
||||
framework: praisonai
|
||||
topic: Artificial Intelligence
|
||||
roles:
|
||||
screenwriter:
|
||||
@@ -420,62 +503,25 @@ roles:
|
||||
expected_output: "Complete script ready for production."
|
||||
```
|
||||
|
||||
*To run the playbook:*
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
|
||||
## Use 100+ Models
|
||||
|
||||
- https://docs.praison.ai/models/
|
||||
<div align="center">
|
||||
<a href="https://docs.praison.ai">
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/📚_Documentation-Visit_docs.praison.ai-blue?style=for-the-badge&logo=bookstack&logoColor=white" alt="Documentation" />
|
||||
</p>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Include praisonai package in your project
|
||||
## Development:
|
||||
|
||||
- https://docs.praison.ai/developers/wrapper
|
||||
- https://docs.praison.ai/developers/wrapper-tools/
|
||||
|
||||
## Option 1: Using RAW YAML
|
||||
|
||||
```python
|
||||
from praisonai import PraisonAI
|
||||
|
||||
# Example agent_yaml content
|
||||
agent_yaml = """
|
||||
framework: "crewai"
|
||||
topic: "Space Exploration"
|
||||
|
||||
roles:
|
||||
astronomer:
|
||||
role: "Space Researcher"
|
||||
goal: "Discover new insights about {topic}"
|
||||
backstory: "You are a curious and dedicated astronomer with a passion for unraveling the mysteries of the cosmos."
|
||||
tasks:
|
||||
investigate_exoplanets:
|
||||
description: "Research and compile information about exoplanets discovered in the last decade."
|
||||
expected_output: "A summarized report on exoplanet discoveries, including their size, potential habitability, and distance from Earth."
|
||||
"""
|
||||
|
||||
# Create a PraisonAI instance with the agent_yaml content
|
||||
praisonai = PraisonAI(agent_yaml=agent_yaml)
|
||||
|
||||
# Run PraisonAI
|
||||
result = praisonai.run()
|
||||
|
||||
# Print the result
|
||||
print(result)
|
||||
```
|
||||
|
||||
## Option 2: Using separate agents.yaml file
|
||||
|
||||
Note: Please create agents.yaml file before hand.
|
||||
|
||||
```python
|
||||
from praisonai import PraisonAI
|
||||
|
||||
def basic(): # Basic Mode
|
||||
praisonai = PraisonAI(agent_file="agents.yaml")
|
||||
praisonai.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
basic()
|
||||
```
|
||||
|
||||
## Commands to Install Dependencies:
|
||||
Below is used for development only.
|
||||
|
||||
### Using uv
|
||||
```bash
|
||||
@@ -500,18 +546,34 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
|
||||
- Submit a pull request via GitHub's web interface.
|
||||
- Await feedback from project maintainers.
|
||||
|
||||
## Other Features
|
||||
|
||||
- 🔄 Use CrewAI or AutoGen Framework
|
||||
- 💻 Chat with ENTIRE Codebase
|
||||
- 🎨 Interactive UIs
|
||||
- 📄 YAML-based Configuration
|
||||
- 🛠️ Custom Tool Integration
|
||||
- 🔍 Internet Search Capability (using Crawl4AI and Tavily)
|
||||
- 🖼️ Vision Language Model (VLM) Support
|
||||
- 🎙️ Real-time Voice Interaction
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://docs.praison.ai)
|
||||
|
||||
## License
|
||||
|
||||
Praison AI is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
|
||||
|
||||
## Video Tutorials
|
||||
|
||||
| Topic | Video |
|
||||
|-------|--------|
|
||||
| AI Agents with Self Reflection | [](https://www.youtube.com/watch?v=vLXobEN2Vc8) |
|
||||
| Reasoning Data Generating Agent | [](https://www.youtube.com/watch?v=fUT332Y2zA8) |
|
||||
| AI Agents with Reasoning | [](https://www.youtube.com/watch?v=KNDVWGN3TpM) |
|
||||
| Multimodal AI Agents | [](https://www.youtube.com/watch?v=hjAWmUT1qqY) |
|
||||
| AI Agents Workflow | [](https://www.youtube.com/watch?v=yWTH44QPl2A) |
|
||||
| Async AI Agents | [](https://www.youtube.com/watch?v=VhVQfgo00LE) |
|
||||
| Mini AI Agents | [](https://www.youtube.com/watch?v=OkvYp5aAGSg) |
|
||||
| AI Agents with Memory | [](https://www.youtube.com/watch?v=1hVfVxvPnnQ) |
|
||||
| Repetitive Agents | [](https://www.youtube.com/watch?v=dAYGxsjDOPg) |
|
||||
| Introduction | [](https://www.youtube.com/watch?v=Fn1lQjC0GO0) |
|
||||
| Tools Overview | [](https://www.youtube.com/watch?v=XaQRgRpV7jo) |
|
||||
| Custom Tools | [](https://www.youtube.com/watch?v=JSU2Rndh06c) |
|
||||
@@ -524,59 +586,5 @@ Praison AI is an open-sourced software licensed under the **[MIT license](https:
|
||||
| Training | [](https://www.youtube.com/watch?v=aLawE8kwCrI) |
|
||||
| Realtime Voice Interface | [](https://www.youtube.com/watch?v=frRHfevTCSw) |
|
||||
| Call Interface | [](https://www.youtube.com/watch?v=m1cwrUG2iAk) |
|
||||
| Reasoning Extract Agents | [](https://www.youtube.com/watch?v=2PPamsADjJA) |
|
||||
|
||||
## License
|
||||
|
||||
Praison AI is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
|
||||
|
||||
## Local Docker Development with Live Reload
|
||||
|
||||
To facilitate local development with live reload, you can use Docker. Follow the steps below:
|
||||
|
||||
1. **Create a `Dockerfile.dev`**:
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN pip install flask praisonai==2.0.18 watchdog
|
||||
|
||||
EXPOSE 5555
|
||||
|
||||
ENV FLASK_ENV=development
|
||||
|
||||
CMD ["flask", "run", "--host=0.0.0.0"]
|
||||
```
|
||||
|
||||
2. **Create a `docker-compose.yml`**:
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.dev
|
||||
volumes:
|
||||
- .:/app
|
||||
ports:
|
||||
- "5555:5555"
|
||||
environment:
|
||||
FLASK_ENV: development
|
||||
command: flask run --host=0.0.0.0
|
||||
|
||||
watch:
|
||||
image: alpine:latest
|
||||
volumes:
|
||||
- .:/app
|
||||
command: sh -c "apk add --no-cache inotify-tools && while inotifywait -r -e modify,create,delete /app; do kill -HUP 1; done"
|
||||
```
|
||||
|
||||
3. **Run Docker Compose**:
|
||||
```bash
|
||||
docker-compose up
|
||||
```
|
||||
|
||||
This setup will allow you to develop locally with live reload, making it easier to test and iterate on your code.
|
||||
@@ -1,8 +0,0 @@
|
||||
1. Make minimal code changes as possible
|
||||
2. if you are creating function, make sure to name it in more easy, user friendly , optimised manner.
|
||||
3. Never copy the exact code if presented with a code from other location or file or codebase, just make it optimised
|
||||
4. Always Follow the principle LESS IS MORE
|
||||
5. Make it minimal change as possible
|
||||
6. Firstly try not to make any modification to the existing code as possible
|
||||
7. Only modify the existing code if its highly required, without that if it cant be done, then add new code section.
|
||||
8. If you are adding new code, make sure to add it in a way that it can be easily integrated with the existing codebase.
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Agent module for AI agents"""
|
||||
from .agent import Agent
|
||||
|
||||
__all__ = ['Agent']
|
||||
@@ -1,764 +0,0 @@
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import List, Optional, Any, Dict, Union, Literal, TYPE_CHECKING
|
||||
from rich.console import Console
|
||||
from rich.live import Live
|
||||
from openai import AsyncOpenAI
|
||||
from ..main import (
|
||||
display_error,
|
||||
display_tool_call,
|
||||
display_instruction,
|
||||
display_interaction,
|
||||
display_generating,
|
||||
display_self_reflection,
|
||||
ReflectionOutput,
|
||||
client,
|
||||
error_logs
|
||||
)
|
||||
import inspect
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..task.task import Task
|
||||
|
||||
class Agent:
|
||||
def _generate_tool_definition(self, function_name):
|
||||
"""
|
||||
Generate a tool definition from a function name by inspecting the function.
|
||||
"""
|
||||
logging.debug(f"Attempting to generate tool definition for: {function_name}")
|
||||
|
||||
# First try to get the tool definition if it exists
|
||||
tool_def_name = f"{function_name}_definition"
|
||||
tool_def = globals().get(tool_def_name)
|
||||
logging.debug(f"Looking for {tool_def_name} in globals: {tool_def is not None}")
|
||||
|
||||
if not tool_def:
|
||||
import __main__
|
||||
tool_def = getattr(__main__, tool_def_name, None)
|
||||
logging.debug(f"Looking for {tool_def_name} in __main__: {tool_def is not None}")
|
||||
|
||||
if tool_def:
|
||||
logging.debug(f"Found tool definition: {tool_def}")
|
||||
return tool_def
|
||||
|
||||
# Try to find the function in the agent's tools list first
|
||||
func = None
|
||||
for tool in self.tools:
|
||||
if callable(tool) and getattr(tool, '__name__', '') == function_name:
|
||||
func = tool
|
||||
break
|
||||
|
||||
logging.debug(f"Looking for {function_name} in agent tools: {func is not None}")
|
||||
|
||||
# If not found in tools, try globals and main
|
||||
if not func:
|
||||
func = globals().get(function_name)
|
||||
logging.debug(f"Looking for {function_name} in globals: {func is not None}")
|
||||
|
||||
if not func:
|
||||
import __main__
|
||||
func = getattr(__main__, function_name, None)
|
||||
logging.debug(f"Looking for {function_name} in __main__: {func is not None}")
|
||||
|
||||
if not func or not callable(func):
|
||||
logging.debug(f"Function {function_name} not found or not callable")
|
||||
return None
|
||||
|
||||
import inspect
|
||||
# Langchain tools
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
original_func = func
|
||||
func = func.run
|
||||
function_name = original_func.__name__
|
||||
|
||||
sig = inspect.signature(func)
|
||||
logging.debug(f"Function signature: {sig}")
|
||||
|
||||
# Skip self, *args, **kwargs, so they don't get passed in arguments
|
||||
parameters_list = []
|
||||
for name, param in sig.parameters.items():
|
||||
if name == "self":
|
||||
continue
|
||||
if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
|
||||
continue
|
||||
parameters_list.append((name, param))
|
||||
|
||||
parameters = {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": []
|
||||
}
|
||||
|
||||
# Parse docstring for parameter descriptions
|
||||
docstring = inspect.getdoc(func)
|
||||
logging.debug(f"Function docstring: {docstring}")
|
||||
|
||||
param_descriptions = {}
|
||||
if docstring:
|
||||
import re
|
||||
param_section = re.split(r'\s*Args:\s*', docstring)
|
||||
logging.debug(f"Param section split: {param_section}")
|
||||
if len(param_section) > 1:
|
||||
param_lines = param_section[1].split('\n')
|
||||
for line in param_lines:
|
||||
line = line.strip()
|
||||
if line and ':' in line:
|
||||
param_name, param_desc = line.split(':', 1)
|
||||
param_descriptions[param_name.strip()] = param_desc.strip()
|
||||
|
||||
logging.debug(f"Parameter descriptions: {param_descriptions}")
|
||||
|
||||
for name, param in parameters_list:
|
||||
param_type = "string" # Default type
|
||||
if param.annotation != inspect.Parameter.empty:
|
||||
if param.annotation == int:
|
||||
param_type = "integer"
|
||||
elif param.annotation == float:
|
||||
param_type = "number"
|
||||
elif param.annotation == bool:
|
||||
param_type = "boolean"
|
||||
elif param.annotation == list:
|
||||
param_type = "array"
|
||||
elif param.annotation == dict:
|
||||
param_type = "object"
|
||||
|
||||
param_info = {"type": param_type}
|
||||
if name in param_descriptions:
|
||||
param_info["description"] = param_descriptions[name]
|
||||
|
||||
parameters["properties"][name] = param_info
|
||||
if param.default == inspect.Parameter.empty:
|
||||
parameters["required"].append(name)
|
||||
|
||||
logging.debug(f"Generated parameters: {parameters}")
|
||||
|
||||
# Extract description from docstring
|
||||
description = docstring.split('\n')[0] if docstring else f"Function {function_name}"
|
||||
|
||||
tool_def = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": function_name,
|
||||
"description": description,
|
||||
"parameters": parameters
|
||||
}
|
||||
}
|
||||
logging.debug(f"Generated tool definition: {tool_def}")
|
||||
return tool_def
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
role: Optional[str] = None,
|
||||
goal: Optional[str] = None,
|
||||
backstory: Optional[str] = None,
|
||||
instructions: Optional[str] = None,
|
||||
llm: Optional[Union[str, Any]] = None,
|
||||
tools: Optional[List[Any]] = None,
|
||||
function_calling_llm: Optional[Any] = None,
|
||||
max_iter: int = 20,
|
||||
max_rpm: Optional[int] = None,
|
||||
max_execution_time: Optional[int] = None,
|
||||
memory: Optional[Any] = None,
|
||||
verbose: bool = True,
|
||||
allow_delegation: bool = False,
|
||||
step_callback: Optional[Any] = None,
|
||||
cache: bool = True,
|
||||
system_template: Optional[str] = None,
|
||||
prompt_template: Optional[str] = None,
|
||||
response_template: Optional[str] = None,
|
||||
allow_code_execution: Optional[bool] = False,
|
||||
max_retry_limit: int = 2,
|
||||
respect_context_window: bool = True,
|
||||
code_execution_mode: Literal["safe", "unsafe"] = "safe",
|
||||
embedder_config: Optional[Dict[str, Any]] = None,
|
||||
knowledge_sources: Optional[List[Any]] = None,
|
||||
use_system_prompt: Optional[bool] = True,
|
||||
markdown: bool = True,
|
||||
self_reflect: bool = False,
|
||||
max_reflect: int = 3,
|
||||
min_reflect: int = 1,
|
||||
reflect_llm: Optional[str] = None
|
||||
):
|
||||
# Handle backward compatibility for required fields
|
||||
if all(x is None for x in [name, role, goal, backstory, instructions]):
|
||||
raise ValueError("At least one of name, role, goal, backstory, or instructions must be provided")
|
||||
|
||||
# If instructions are provided, use them to set role, goal, and backstory
|
||||
if instructions:
|
||||
self.name = name or "Agent"
|
||||
self.role = role or "Assistant"
|
||||
self.goal = goal or instructions
|
||||
self.backstory = backstory or instructions
|
||||
# Set self_reflect to False by default for instruction-based agents
|
||||
self.self_reflect = False if self_reflect is None else self_reflect
|
||||
else:
|
||||
# Use provided values or defaults
|
||||
self.name = name or "Agent"
|
||||
self.role = role or "Assistant"
|
||||
self.goal = goal or "Help the user with their tasks"
|
||||
self.backstory = backstory or "I am an AI assistant"
|
||||
# Default to True for traditional agents if not specified
|
||||
self.self_reflect = True if self_reflect is None else self_reflect
|
||||
|
||||
self.instructions = instructions
|
||||
# Check for model name in environment variable if not provided
|
||||
self.llm = llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
self.tools = tools if tools else [] # Store original tools
|
||||
self.function_calling_llm = function_calling_llm
|
||||
self.max_iter = max_iter
|
||||
self.max_rpm = max_rpm
|
||||
self.max_execution_time = max_execution_time
|
||||
self.memory = memory
|
||||
self.verbose = verbose
|
||||
self.allow_delegation = allow_delegation
|
||||
self.step_callback = step_callback
|
||||
self.cache = cache
|
||||
self.system_template = system_template
|
||||
self.prompt_template = prompt_template
|
||||
self.response_template = response_template
|
||||
self.allow_code_execution = allow_code_execution
|
||||
self.max_retry_limit = max_retry_limit
|
||||
self.respect_context_window = respect_context_window
|
||||
self.code_execution_mode = code_execution_mode
|
||||
self.embedder_config = embedder_config
|
||||
self.knowledge_sources = knowledge_sources
|
||||
self.use_system_prompt = use_system_prompt
|
||||
self.chat_history = []
|
||||
self.markdown = markdown
|
||||
self.max_reflect = max_reflect
|
||||
self.min_reflect = min_reflect
|
||||
# Use the same model selection logic for reflect_llm
|
||||
self.reflect_llm = reflect_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
self.console = Console() # Create a single console instance for the agent
|
||||
|
||||
# Initialize system prompt
|
||||
self.system_prompt = f"""{self.backstory}\n
|
||||
Your Role: {self.role}\n
|
||||
Your Goal: {self.goal}
|
||||
"""
|
||||
|
||||
def generate_task(self) -> 'Task':
|
||||
"""Generate a Task object from the agent's instructions"""
|
||||
from ..task.task import Task
|
||||
|
||||
description = self.instructions if self.instructions else f"Execute task as {self.role} with goal: {self.goal}"
|
||||
expected_output = "Complete the assigned task successfully"
|
||||
|
||||
return Task(
|
||||
name=self.name,
|
||||
description=description,
|
||||
expected_output=expected_output,
|
||||
agent=self,
|
||||
tools=self.tools
|
||||
)
|
||||
|
||||
def execute_tool(self, function_name, arguments):
|
||||
"""
|
||||
Execute a tool dynamically based on the function name and arguments.
|
||||
"""
|
||||
logging.debug(f"{self.name} executing tool {function_name} with arguments: {arguments}")
|
||||
|
||||
# Try to find the function in the agent's tools list first
|
||||
func = None
|
||||
for tool in self.tools:
|
||||
if (callable(tool) and getattr(tool, '__name__', '') == function_name) or \
|
||||
(inspect.isclass(tool) and tool.__name__ == function_name):
|
||||
func = tool
|
||||
break
|
||||
|
||||
if func is None:
|
||||
# If not found in tools, try globals and main
|
||||
func = globals().get(function_name)
|
||||
if not func:
|
||||
import __main__
|
||||
func = getattr(__main__, function_name, None)
|
||||
|
||||
if func:
|
||||
try:
|
||||
# If it's a class with run method, instantiate and call run
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
instance = func()
|
||||
# Extract only the parameters that run() expects
|
||||
run_params = {k: v for k, v in arguments.items()
|
||||
if k in inspect.signature(instance.run).parameters
|
||||
and k != 'self'}
|
||||
return instance.run(**run_params)
|
||||
# Otherwise treat as regular function
|
||||
elif callable(func):
|
||||
return func(**arguments)
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
logging.error(f"Error executing tool {function_name}: {error_msg}")
|
||||
return {"error": error_msg}
|
||||
|
||||
error_msg = f"Tool '{function_name}' is not callable"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
def clear_history(self):
|
||||
self.chat_history = []
|
||||
|
||||
def __str__(self):
|
||||
return f"Agent(name='{self.name}', role='{self.role}', goal='{self.goal}')"
|
||||
|
||||
def _chat_completion(self, messages, temperature=0.2, tools=None, stream=True):
|
||||
start_time = time.time()
|
||||
logging.debug(f"{self.name} sending messages to LLM: {messages}")
|
||||
|
||||
formatted_tools = []
|
||||
if tools is None:
|
||||
tools = self.tools
|
||||
if tools:
|
||||
for tool in tools:
|
||||
if isinstance(tool, str):
|
||||
# Generate tool definition for string tool names
|
||||
tool_def = self._generate_tool_definition(tool)
|
||||
if tool_def:
|
||||
formatted_tools.append(tool_def)
|
||||
else:
|
||||
logging.warning(f"Could not generate definition for tool: {tool}")
|
||||
elif isinstance(tool, dict):
|
||||
formatted_tools.append(tool)
|
||||
elif hasattr(tool, "to_openai_tool"):
|
||||
formatted_tools.append(tool.to_openai_tool())
|
||||
elif callable(tool):
|
||||
formatted_tools.append(self._generate_tool_definition(tool.__name__))
|
||||
else:
|
||||
logging.warning(f"Tool {tool} not recognized")
|
||||
|
||||
try:
|
||||
initial_response = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
tools=formatted_tools if formatted_tools else None,
|
||||
stream=False
|
||||
)
|
||||
|
||||
tool_calls = getattr(initial_response.choices[0].message, 'tool_calls', None)
|
||||
|
||||
if tool_calls:
|
||||
messages.append({
|
||||
"role": "assistant",
|
||||
"content": initial_response.choices[0].message.content,
|
||||
"tool_calls": tool_calls
|
||||
})
|
||||
|
||||
for tool_call in tool_calls:
|
||||
function_name = tool_call.function.name
|
||||
arguments = json.loads(tool_call.function.arguments)
|
||||
|
||||
if self.verbose:
|
||||
display_tool_call(f"Agent {self.name} is calling function '{function_name}' with arguments: {arguments}")
|
||||
|
||||
tool_result = self.execute_tool(function_name, arguments)
|
||||
results_str = json.dumps(tool_result) if tool_result else "Function returned an empty output"
|
||||
|
||||
if self.verbose:
|
||||
display_tool_call(f"Function '{function_name}' returned: {results_str}")
|
||||
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.id,
|
||||
"content": results_str
|
||||
})
|
||||
|
||||
if stream:
|
||||
response_stream = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
stream=True
|
||||
)
|
||||
full_response_text = ""
|
||||
|
||||
# Create Live display with proper configuration
|
||||
with Live(
|
||||
display_generating("", start_time),
|
||||
console=self.console,
|
||||
refresh_per_second=4,
|
||||
transient=True, # Changed to False to preserve output
|
||||
vertical_overflow="ellipsis",
|
||||
auto_refresh=True
|
||||
) as live:
|
||||
for chunk in response_stream:
|
||||
if chunk.choices[0].delta.content:
|
||||
full_response_text += chunk.choices[0].delta.content
|
||||
live.update(display_generating(full_response_text, start_time))
|
||||
|
||||
# Clear the last generating display with a blank line
|
||||
self.console.print()
|
||||
|
||||
final_response = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
stream=False
|
||||
)
|
||||
return final_response
|
||||
else:
|
||||
if tool_calls:
|
||||
final_response = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
stream=False
|
||||
)
|
||||
return final_response
|
||||
else:
|
||||
return initial_response
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat completion: {e}")
|
||||
return None
|
||||
|
||||
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None):
|
||||
if self.use_system_prompt:
|
||||
system_prompt = f"""{self.backstory}\n
|
||||
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()}"
|
||||
elif output_pydantic:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
|
||||
else:
|
||||
system_prompt = None
|
||||
|
||||
messages = []
|
||||
if system_prompt:
|
||||
messages.append({"role": "system", "content": system_prompt})
|
||||
messages.extend(self.chat_history)
|
||||
|
||||
# Modify prompt if output_json or output_pydantic is specified
|
||||
original_prompt = prompt
|
||||
if output_json or output_pydantic:
|
||||
if isinstance(prompt, str):
|
||||
prompt += "\nReturn ONLY a valid JSON object. No other text or explanation."
|
||||
elif isinstance(prompt, list):
|
||||
# For multimodal prompts, append to the text content
|
||||
for item in prompt:
|
||||
if item["type"] == "text":
|
||||
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
|
||||
break
|
||||
|
||||
if isinstance(prompt, list):
|
||||
# If we receive a multimodal prompt list, place it directly in the user message
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
else:
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
|
||||
final_response_text = None
|
||||
reflection_count = 0
|
||||
start_time = time.time()
|
||||
|
||||
while True:
|
||||
try:
|
||||
if self.verbose:
|
||||
# Handle both string and list prompts for instruction display
|
||||
display_text = prompt
|
||||
if isinstance(prompt, list):
|
||||
# Extract text content from multimodal prompt
|
||||
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
|
||||
|
||||
if display_text and str(display_text).strip():
|
||||
# Pass agent information to display_instruction
|
||||
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
|
||||
display_instruction(
|
||||
f"Agent {self.name} is processing prompt: {display_text}",
|
||||
console=self.console,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=agent_tools
|
||||
)
|
||||
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=tools if tools else None)
|
||||
if not response:
|
||||
return None
|
||||
|
||||
tool_calls = getattr(response.choices[0].message, 'tool_calls', None)
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
|
||||
if tool_calls:
|
||||
messages.append({
|
||||
"role": "assistant",
|
||||
"content": response_text,
|
||||
"tool_calls": tool_calls
|
||||
})
|
||||
|
||||
for tool_call in tool_calls:
|
||||
function_name = tool_call.function.name
|
||||
arguments = json.loads(tool_call.function.arguments)
|
||||
|
||||
if self.verbose:
|
||||
display_tool_call(f"Agent {self.name} is calling function '{function_name}' with arguments: {arguments}", console=self.console)
|
||||
|
||||
tool_result = self.execute_tool(function_name, arguments)
|
||||
|
||||
if tool_result:
|
||||
if self.verbose:
|
||||
display_tool_call(f"Function '{function_name}' returned: {tool_result}", console=self.console)
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.id,
|
||||
"content": json.dumps(tool_result)
|
||||
})
|
||||
else:
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.id,
|
||||
"content": "Function returned an empty output"
|
||||
})
|
||||
|
||||
response = self._chat_completion(messages, temperature=temperature)
|
||||
if not response:
|
||||
return None
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
|
||||
# Handle output_json or output_pydantic if specified
|
||||
if output_json or output_pydantic:
|
||||
# Add to chat history and return raw response
|
||||
self.chat_history.append({"role": "user", "content": original_prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
if self.verbose:
|
||||
display_interaction(original_prompt, response_text, markdown=self.markdown,
|
||||
generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
if not self.self_reflect:
|
||||
self.chat_history.append({"role": "user", "content": original_prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
if self.verbose:
|
||||
logging.debug(f"Agent {self.name} final response: {response_text}")
|
||||
display_interaction(original_prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
reflection_prompt = f"""
|
||||
Reflect on your previous response: '{response_text}'.
|
||||
Identify any flaws, improvements, or actions.
|
||||
Provide a "satisfactory" status ('yes' or 'no').
|
||||
Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
"""
|
||||
logging.debug(f"{self.name} reflection attempt {reflection_count+1}, sending prompt: {reflection_prompt}")
|
||||
messages.append({"role": "user", "content": reflection_prompt})
|
||||
|
||||
try:
|
||||
reflection_response = client.beta.chat.completions.parse(
|
||||
model=self.reflect_llm if self.reflect_llm else self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
response_format=ReflectionOutput
|
||||
)
|
||||
|
||||
reflection_output = reflection_response.choices[0].message.parsed
|
||||
|
||||
if self.verbose:
|
||||
display_self_reflection(f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
|
||||
|
||||
messages.append({"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"})
|
||||
|
||||
# Only consider satisfactory after minimum reflections
|
||||
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
# Check if we've hit max reflections
|
||||
if reflection_count >= self.max_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Maximum reflection count reached, returning current response", console=self.console)
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
logging.debug(f"{self.name} reflection count {reflection_count + 1}, continuing reflection process")
|
||||
messages.append({"role": "user", "content": "Now regenerate your response using the reflection you made"})
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=None, stream=True)
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
reflection_count += 1
|
||||
continue # Continue the loop for more reflections
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
|
||||
logging.error("Reflection parsing failed.", exc_info=True)
|
||||
messages.append({"role": "assistant", "content": f"Self Reflection failed."})
|
||||
reflection_count += 1
|
||||
continue # Continue even after error to try again
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat: {e}", console=self.console)
|
||||
return None
|
||||
|
||||
def clean_json_output(self, output: str) -> str:
|
||||
"""Clean and extract JSON from response text."""
|
||||
cleaned = output.strip()
|
||||
# Remove markdown code blocks if present
|
||||
if cleaned.startswith("```json"):
|
||||
cleaned = cleaned[len("```json"):].strip()
|
||||
if cleaned.startswith("```"):
|
||||
cleaned = cleaned[len("```"):].strip()
|
||||
if cleaned.endswith("```"):
|
||||
cleaned = cleaned[:-3].strip()
|
||||
return cleaned
|
||||
|
||||
async def achat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None):
|
||||
"""Async version of chat method"""
|
||||
try:
|
||||
# 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()}"
|
||||
elif output_pydantic:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
|
||||
|
||||
# Build messages
|
||||
if isinstance(prompt, str):
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt + ("\nReturn ONLY a valid JSON object. No other text or explanation." if (output_json or output_pydantic) else "")}
|
||||
]
|
||||
else:
|
||||
# For multimodal prompts
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
]
|
||||
if output_json or output_pydantic:
|
||||
# Add JSON instruction to text content
|
||||
for item in messages[-1]["content"]:
|
||||
if item["type"] == "text":
|
||||
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
|
||||
break
|
||||
|
||||
# Display instruction with agent info if verbose
|
||||
if self.verbose:
|
||||
display_text = prompt
|
||||
if isinstance(prompt, list):
|
||||
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
|
||||
|
||||
if display_text and str(display_text).strip():
|
||||
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
|
||||
await adisplay_instruction(
|
||||
f"Agent {self.name} is processing prompt: {display_text}",
|
||||
console=self.console,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=agent_tools
|
||||
)
|
||||
|
||||
# Format tools if provided
|
||||
formatted_tools = []
|
||||
if tools:
|
||||
for tool in tools:
|
||||
if isinstance(tool, str):
|
||||
tool_def = self._generate_tool_definition(tool)
|
||||
if tool_def:
|
||||
formatted_tools.append(tool_def)
|
||||
elif isinstance(tool, dict):
|
||||
formatted_tools.append(tool)
|
||||
elif hasattr(tool, "to_openai_tool"):
|
||||
formatted_tools.append(tool.to_openai_tool())
|
||||
elif callable(tool):
|
||||
formatted_tools.append(self._generate_tool_definition(tool.__name__))
|
||||
|
||||
# Create async OpenAI client
|
||||
async_client = AsyncOpenAI()
|
||||
|
||||
# Make the API call based on the type of request
|
||||
if tools:
|
||||
response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
tools=formatted_tools
|
||||
)
|
||||
return await self._achat_completion(response, tools)
|
||||
elif output_json or output_pydantic:
|
||||
response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
# Return the raw response
|
||||
return response.choices[0].message.content
|
||||
else:
|
||||
response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature
|
||||
)
|
||||
return response.choices[0].message.content
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat completion: {e}")
|
||||
return None
|
||||
|
||||
async def _achat_completion(self, response, tools):
|
||||
"""Async version of _chat_completion method"""
|
||||
try:
|
||||
message = response.choices[0].message
|
||||
if not hasattr(message, 'tool_calls') or not message.tool_calls:
|
||||
return message.content
|
||||
|
||||
results = []
|
||||
for tool_call in message.tool_calls:
|
||||
try:
|
||||
function_name = tool_call.function.name
|
||||
arguments = json.loads(tool_call.function.arguments)
|
||||
|
||||
# Find the matching tool
|
||||
tool = next((t for t in tools if t.__name__ == function_name), None)
|
||||
if not tool:
|
||||
display_error(f"Tool {function_name} not found")
|
||||
continue
|
||||
|
||||
# Check if the tool is async
|
||||
if asyncio.iscoroutinefunction(tool):
|
||||
result = await tool(**arguments)
|
||||
else:
|
||||
# Run sync function in executor to avoid blocking
|
||||
loop = asyncio.get_event_loop()
|
||||
result = await loop.run_in_executor(None, lambda: tool(**arguments))
|
||||
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
display_error(f"Error executing tool {function_name}: {e}")
|
||||
results.append(None)
|
||||
|
||||
# If we have results, format them into a response
|
||||
if results:
|
||||
formatted_results = "\n".join([str(r) for r in results if r is not None])
|
||||
if formatted_results:
|
||||
messages = [
|
||||
{"role": "system", "content": self.system_prompt},
|
||||
{"role": "assistant", "content": "Here are the tool results:"},
|
||||
{"role": "user", "content": formatted_results + "\nPlease process these results and provide a final response."}
|
||||
]
|
||||
try:
|
||||
async_client = AsyncOpenAI()
|
||||
final_response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=0.2
|
||||
)
|
||||
return final_response.choices[0].message.content
|
||||
except Exception as e:
|
||||
display_error(f"Error in final chat completion: {e}")
|
||||
return formatted_results
|
||||
return formatted_results
|
||||
return None
|
||||
except Exception as e:
|
||||
display_error(f"Error in _achat_completion: {e}")
|
||||
return None
|
||||
|
||||
def run(self):
|
||||
"""Alias for start() method"""
|
||||
return self.start()
|
||||
@@ -1,534 +0,0 @@
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import Dict, Optional, List, Any, AsyncGenerator
|
||||
from pydantic import BaseModel
|
||||
from ..agent.agent import Agent
|
||||
from ..task.task import Task
|
||||
from ..main import display_error, client
|
||||
|
||||
class LoopItems(BaseModel):
|
||||
items: List[Any]
|
||||
|
||||
class Process:
|
||||
def __init__(self, tasks: Dict[str, Task], agents: List[Agent], manager_llm: Optional[str] = None, verbose: bool = False):
|
||||
self.tasks = tasks
|
||||
self.agents = agents
|
||||
self.manager_llm = manager_llm
|
||||
self.verbose = verbose
|
||||
|
||||
async def aworkflow(self) -> AsyncGenerator[str, None]:
|
||||
"""Async version of workflow method"""
|
||||
# Build workflow relationships first
|
||||
for task in self.tasks.values():
|
||||
if task.next_tasks:
|
||||
for next_task_name in task.next_tasks:
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
if next_task:
|
||||
next_task.previous_tasks.append(task.name)
|
||||
|
||||
# Find start task
|
||||
start_task = None
|
||||
for task_id, task in self.tasks.items():
|
||||
if task.is_start:
|
||||
start_task = task
|
||||
break
|
||||
|
||||
if not start_task:
|
||||
start_task = list(self.tasks.values())[0]
|
||||
logging.info("No start task marked, using first task")
|
||||
|
||||
current_task = start_task
|
||||
visited_tasks = set()
|
||||
loop_data = {} # Store loop-specific data
|
||||
|
||||
while current_task and current_task.id not in visited_tasks:
|
||||
task_id = current_task.id
|
||||
logging.info(f"Executing workflow task: {current_task.name if current_task.name else task_id}")
|
||||
|
||||
# Add context from previous tasks to description
|
||||
if current_task.previous_tasks or current_task.context:
|
||||
context = "\nInput data from previous tasks:"
|
||||
|
||||
# Add data from previous tasks in workflow
|
||||
for prev_name in current_task.previous_tasks:
|
||||
prev_task = next((t for t in self.tasks.values() if t.name == prev_name), None)
|
||||
if prev_task and prev_task.result:
|
||||
# Handle loop data
|
||||
if current_task.task_type == "loop":
|
||||
# create a loop manager Agent
|
||||
loop_manager = Agent(
|
||||
name="Loop Manager",
|
||||
role="Loop data processor",
|
||||
goal="Process loop data and convert it to list format",
|
||||
backstory="Expert at handling loop data and converting it to proper format",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# get the loop data convert it to list using calling Agent class chat
|
||||
loop_prompt = f"""
|
||||
Process this data into a list format:
|
||||
{prev_task.result.raw}
|
||||
|
||||
Return a JSON object with an 'items' array containing the items to process.
|
||||
"""
|
||||
if current_task.async_execution:
|
||||
loop_data_str = await loop_manager.achat(
|
||||
prompt=loop_prompt,
|
||||
output_json=LoopItems
|
||||
)
|
||||
else:
|
||||
loop_data_str = loop_manager.chat(
|
||||
prompt=loop_prompt,
|
||||
output_json=LoopItems
|
||||
)
|
||||
|
||||
try:
|
||||
# The response will already be parsed into LoopItems model
|
||||
loop_data[f"loop_{current_task.name}"] = {
|
||||
"items": loop_data_str.items,
|
||||
"index": 0,
|
||||
"remaining": len(loop_data_str.items)
|
||||
}
|
||||
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
|
||||
except Exception as e:
|
||||
display_error(f"Failed to process loop data: {e}")
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
else:
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
|
||||
# Add data from context tasks
|
||||
if current_task.context:
|
||||
for ctx_task in current_task.context:
|
||||
if ctx_task.result and ctx_task.name != current_task.name:
|
||||
context += f"\n{ctx_task.name}: {ctx_task.result.raw}"
|
||||
|
||||
# Update task description with context
|
||||
current_task.description = current_task.description + context
|
||||
|
||||
# Execute task using existing run_task method
|
||||
yield task_id
|
||||
visited_tasks.add(task_id)
|
||||
|
||||
# Handle loop progression
|
||||
if current_task.task_type == "loop":
|
||||
loop_key = f"loop_{current_task.name}"
|
||||
if loop_key in loop_data:
|
||||
loop_info = loop_data[loop_key]
|
||||
loop_info["index"] += 1
|
||||
has_more = loop_info["remaining"] > 0
|
||||
|
||||
# Update result to trigger correct condition
|
||||
if current_task.result:
|
||||
result = current_task.result.raw
|
||||
if has_more:
|
||||
result += "\nmore"
|
||||
else:
|
||||
result += "\ndone"
|
||||
current_task.result.raw = result
|
||||
|
||||
# Determine next task based on result
|
||||
next_task = None
|
||||
if current_task.result:
|
||||
if current_task.task_type in ["decision", "loop"]:
|
||||
result = current_task.result.raw.lower()
|
||||
# Check conditions
|
||||
for condition, tasks in current_task.condition.items():
|
||||
if condition.lower() in result and tasks:
|
||||
next_task_name = tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
# For loops, allow revisiting the same task
|
||||
if next_task and next_task.id == current_task.id:
|
||||
visited_tasks.discard(current_task.id)
|
||||
break
|
||||
|
||||
if not next_task and current_task.next_tasks:
|
||||
next_task_name = current_task.next_tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
|
||||
current_task = next_task
|
||||
if not current_task:
|
||||
logging.info("Workflow execution completed")
|
||||
break
|
||||
|
||||
async def asequential(self) -> AsyncGenerator[str, None]:
|
||||
"""Async version of sequential method"""
|
||||
for task_id in self.tasks:
|
||||
if self.tasks[task_id].status != "completed":
|
||||
yield task_id
|
||||
|
||||
async def ahierarchical(self) -> AsyncGenerator[str, None]:
|
||||
"""Async version of hierarchical method"""
|
||||
logging.debug(f"Starting hierarchical task execution with {len(self.tasks)} tasks")
|
||||
manager_agent = Agent(
|
||||
name="Manager",
|
||||
role="Project manager",
|
||||
goal="Manage the entire flow of tasks and delegate them to the right agent",
|
||||
backstory="Expert project manager to coordinate tasks among agents",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True,
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
class ManagerInstructions(BaseModel):
|
||||
task_id: int
|
||||
agent_name: str
|
||||
action: str
|
||||
|
||||
manager_task = Task(
|
||||
name="manager_task",
|
||||
description="Decide the order of tasks and which agent executes them",
|
||||
expected_output="All tasks completed successfully",
|
||||
agent=manager_agent
|
||||
)
|
||||
manager_task_id = yield manager_task
|
||||
logging.info(f"Created manager task with ID {manager_task_id}")
|
||||
|
||||
completed_count = 0
|
||||
total_tasks = len(self.tasks) - 1
|
||||
logging.info(f"Need to complete {total_tasks} tasks (excluding manager task)")
|
||||
|
||||
while completed_count < total_tasks:
|
||||
tasks_summary = []
|
||||
for tid, tk in self.tasks.items():
|
||||
if tk.name == "manager_task":
|
||||
continue
|
||||
task_info = {
|
||||
"task_id": tid,
|
||||
"name": tk.name,
|
||||
"description": tk.description,
|
||||
"status": tk.status if tk.status else "not started",
|
||||
"agent": tk.agent.name if tk.agent else "No agent"
|
||||
}
|
||||
tasks_summary.append(task_info)
|
||||
logging.info(f"Task {tid} status: {task_info}")
|
||||
|
||||
manager_prompt = f"""
|
||||
Here is the current status of all tasks except yours (manager_task):
|
||||
{tasks_summary}
|
||||
|
||||
Provide a JSON with the structure:
|
||||
{{
|
||||
"task_id": <int>,
|
||||
"agent_name": "<string>",
|
||||
"action": "<execute or stop>"
|
||||
}}
|
||||
"""
|
||||
|
||||
try:
|
||||
logging.info("Requesting manager instructions...")
|
||||
if manager_task.async_execution:
|
||||
manager_response = await client.beta.chat.completions.parse(
|
||||
model=self.manager_llm,
|
||||
messages=[
|
||||
{"role": "system", "content": manager_task.description},
|
||||
{"role": "user", "content": manager_prompt}
|
||||
],
|
||||
temperature=0.7,
|
||||
response_format=ManagerInstructions
|
||||
)
|
||||
else:
|
||||
manager_response = client.beta.chat.completions.parse(
|
||||
model=self.manager_llm,
|
||||
messages=[
|
||||
{"role": "system", "content": manager_task.description},
|
||||
{"role": "user", "content": manager_prompt}
|
||||
],
|
||||
temperature=0.7,
|
||||
response_format=ManagerInstructions
|
||||
)
|
||||
parsed_instructions = manager_response.choices[0].message.parsed
|
||||
logging.info(f"Manager instructions: {parsed_instructions}")
|
||||
except Exception as e:
|
||||
display_error(f"Manager parse error: {e}")
|
||||
logging.error(f"Manager parse error: {str(e)}", exc_info=True)
|
||||
break
|
||||
|
||||
selected_task_id = parsed_instructions.task_id
|
||||
selected_agent_name = parsed_instructions.agent_name
|
||||
action = parsed_instructions.action
|
||||
|
||||
logging.info(f"Manager selected task_id={selected_task_id}, agent={selected_agent_name}, action={action}")
|
||||
|
||||
if action.lower() == "stop":
|
||||
logging.info("Manager decided to stop task execution")
|
||||
break
|
||||
|
||||
if selected_task_id not in self.tasks:
|
||||
error_msg = f"Manager selected invalid task id {selected_task_id}"
|
||||
display_error(error_msg)
|
||||
logging.error(error_msg)
|
||||
break
|
||||
|
||||
original_agent = self.tasks[selected_task_id].agent.name if self.tasks[selected_task_id].agent else "None"
|
||||
for a in self.agents:
|
||||
if a.name == selected_agent_name:
|
||||
self.tasks[selected_task_id].agent = a
|
||||
logging.info(f"Changed agent for task {selected_task_id} from {original_agent} to {selected_agent_name}")
|
||||
break
|
||||
|
||||
if self.tasks[selected_task_id].status != "completed":
|
||||
logging.info(f"Starting execution of task {selected_task_id}")
|
||||
yield selected_task_id
|
||||
logging.info(f"Finished execution of task {selected_task_id}, status: {self.tasks[selected_task_id].status}")
|
||||
|
||||
if self.tasks[selected_task_id].status == "completed":
|
||||
completed_count += 1
|
||||
logging.info(f"Task {selected_task_id} completed. Total completed: {completed_count}/{total_tasks}")
|
||||
|
||||
self.tasks[manager_task.id].status = "completed"
|
||||
if self.verbose >= 1:
|
||||
logging.info("All tasks completed under manager supervision.")
|
||||
logging.info("Hierarchical task execution finished")
|
||||
|
||||
def workflow(self):
|
||||
"""Synchronous version of workflow method"""
|
||||
# Build workflow relationships first
|
||||
for task in self.tasks.values():
|
||||
if task.next_tasks:
|
||||
for next_task_name in task.next_tasks:
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
if next_task:
|
||||
next_task.previous_tasks.append(task.name)
|
||||
|
||||
# Find start task
|
||||
start_task = None
|
||||
for task_id, task in self.tasks.items():
|
||||
if task.is_start:
|
||||
start_task = task
|
||||
break
|
||||
|
||||
if not start_task:
|
||||
start_task = list(self.tasks.values())[0]
|
||||
logging.info("No start task marked, using first task")
|
||||
|
||||
current_task = start_task
|
||||
visited_tasks = set()
|
||||
loop_data = {} # Store loop-specific data
|
||||
|
||||
while current_task and current_task.id not in visited_tasks:
|
||||
task_id = current_task.id
|
||||
logging.info(f"Executing workflow task: {current_task.name if current_task.name else task_id}")
|
||||
|
||||
# Add context from previous tasks to description
|
||||
if current_task.previous_tasks or current_task.context:
|
||||
context = "\nInput data from previous tasks:"
|
||||
|
||||
# Add data from previous tasks in workflow
|
||||
for prev_name in current_task.previous_tasks:
|
||||
prev_task = next((t for t in self.tasks.values() if t.name == prev_name), None)
|
||||
if prev_task and prev_task.result:
|
||||
# Handle loop data
|
||||
if current_task.task_type == "loop":
|
||||
# create a loop manager Agent
|
||||
loop_manager = Agent(
|
||||
name="Loop Manager",
|
||||
role="Loop data processor",
|
||||
goal="Process loop data and convert it to list format",
|
||||
backstory="Expert at handling loop data and converting it to proper format",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# get the loop data convert it to list using calling Agent class chat
|
||||
loop_prompt = f"""
|
||||
Process this data into a list format:
|
||||
{prev_task.result.raw}
|
||||
|
||||
Return a JSON object with an 'items' array containing the items to process.
|
||||
"""
|
||||
loop_data_str = loop_manager.chat(
|
||||
prompt=loop_prompt,
|
||||
output_json=LoopItems
|
||||
)
|
||||
|
||||
try:
|
||||
# The response will already be parsed into LoopItems model
|
||||
loop_data[f"loop_{current_task.name}"] = {
|
||||
"items": loop_data_str.items,
|
||||
"index": 0,
|
||||
"remaining": len(loop_data_str.items)
|
||||
}
|
||||
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
|
||||
except Exception as e:
|
||||
display_error(f"Failed to process loop data: {e}")
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
else:
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
|
||||
# Add data from context tasks
|
||||
if current_task.context:
|
||||
for ctx_task in current_task.context:
|
||||
if ctx_task.result and ctx_task.name != current_task.name:
|
||||
context += f"\n{ctx_task.name}: {ctx_task.result.raw}"
|
||||
|
||||
# Update task description with context
|
||||
current_task.description = current_task.description + context
|
||||
|
||||
# Execute task using existing run_task method
|
||||
yield task_id
|
||||
visited_tasks.add(task_id)
|
||||
|
||||
# Handle loop progression
|
||||
if current_task.task_type == "loop":
|
||||
loop_key = f"loop_{current_task.name}"
|
||||
if loop_key in loop_data:
|
||||
loop_info = loop_data[loop_key]
|
||||
loop_info["index"] += 1
|
||||
has_more = loop_info["remaining"] > 0
|
||||
|
||||
# Update result to trigger correct condition
|
||||
if current_task.result:
|
||||
result = current_task.result.raw
|
||||
if has_more:
|
||||
result += "\nmore"
|
||||
else:
|
||||
result += "\ndone"
|
||||
current_task.result.raw = result
|
||||
|
||||
# Determine next task based on result
|
||||
next_task = None
|
||||
if current_task.result:
|
||||
if current_task.task_type in ["decision", "loop"]:
|
||||
result = current_task.result.raw.lower()
|
||||
# Check conditions
|
||||
for condition, tasks in current_task.condition.items():
|
||||
if condition.lower() in result and tasks:
|
||||
next_task_name = tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
# For loops, allow revisiting the same task
|
||||
if next_task and next_task.id == current_task.id:
|
||||
visited_tasks.discard(current_task.id)
|
||||
break
|
||||
|
||||
if not next_task and current_task.next_tasks:
|
||||
next_task_name = current_task.next_tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
|
||||
current_task = next_task
|
||||
if not current_task:
|
||||
logging.info("Workflow execution completed")
|
||||
break
|
||||
|
||||
def sequential(self):
|
||||
"""Synchronous version of sequential method"""
|
||||
for task_id in self.tasks:
|
||||
if self.tasks[task_id].status != "completed":
|
||||
yield task_id
|
||||
|
||||
def hierarchical(self):
|
||||
"""Synchronous version of hierarchical method"""
|
||||
logging.debug(f"Starting hierarchical task execution with {len(self.tasks)} tasks")
|
||||
manager_agent = Agent(
|
||||
name="Manager",
|
||||
role="Project manager",
|
||||
goal="Manage the entire flow of tasks and delegate them to the right agent",
|
||||
backstory="Expert project manager to coordinate tasks among agents",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True,
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
class ManagerInstructions(BaseModel):
|
||||
task_id: int
|
||||
agent_name: str
|
||||
action: str
|
||||
|
||||
manager_task = Task(
|
||||
name="manager_task",
|
||||
description="Decide the order of tasks and which agent executes them",
|
||||
expected_output="All tasks completed successfully",
|
||||
agent=manager_agent
|
||||
)
|
||||
manager_task_id = yield manager_task
|
||||
logging.info(f"Created manager task with ID {manager_task_id}")
|
||||
|
||||
completed_count = 0
|
||||
total_tasks = len(self.tasks) - 1
|
||||
logging.info(f"Need to complete {total_tasks} tasks (excluding manager task)")
|
||||
|
||||
while completed_count < total_tasks:
|
||||
tasks_summary = []
|
||||
for tid, tk in self.tasks.items():
|
||||
if tk.name == "manager_task":
|
||||
continue
|
||||
task_info = {
|
||||
"task_id": tid,
|
||||
"name": tk.name,
|
||||
"description": tk.description,
|
||||
"status": tk.status if tk.status else "not started",
|
||||
"agent": tk.agent.name if tk.agent else "No agent"
|
||||
}
|
||||
tasks_summary.append(task_info)
|
||||
logging.info(f"Task {tid} status: {task_info}")
|
||||
|
||||
manager_prompt = f"""
|
||||
Here is the current status of all tasks except yours (manager_task):
|
||||
{tasks_summary}
|
||||
|
||||
Provide a JSON with the structure:
|
||||
{{
|
||||
"task_id": <int>,
|
||||
"agent_name": "<string>",
|
||||
"action": "<execute or stop>"
|
||||
}}
|
||||
"""
|
||||
|
||||
try:
|
||||
logging.info("Requesting manager instructions...")
|
||||
manager_response = client.beta.chat.completions.parse(
|
||||
model=self.manager_llm,
|
||||
messages=[
|
||||
{"role": "system", "content": manager_task.description},
|
||||
{"role": "user", "content": manager_prompt}
|
||||
],
|
||||
temperature=0.7,
|
||||
response_format=ManagerInstructions
|
||||
)
|
||||
parsed_instructions = manager_response.choices[0].message.parsed
|
||||
logging.info(f"Manager instructions: {parsed_instructions}")
|
||||
except Exception as e:
|
||||
display_error(f"Manager parse error: {e}")
|
||||
logging.error(f"Manager parse error: {str(e)}", exc_info=True)
|
||||
break
|
||||
|
||||
selected_task_id = parsed_instructions.task_id
|
||||
selected_agent_name = parsed_instructions.agent_name
|
||||
action = parsed_instructions.action
|
||||
|
||||
logging.info(f"Manager selected task_id={selected_task_id}, agent={selected_agent_name}, action={action}")
|
||||
|
||||
if action.lower() == "stop":
|
||||
logging.info("Manager decided to stop task execution")
|
||||
break
|
||||
|
||||
if selected_task_id not in self.tasks:
|
||||
error_msg = f"Manager selected invalid task id {selected_task_id}"
|
||||
display_error(error_msg)
|
||||
logging.error(error_msg)
|
||||
break
|
||||
|
||||
original_agent = self.tasks[selected_task_id].agent.name if self.tasks[selected_task_id].agent else "None"
|
||||
for a in self.agents:
|
||||
if a.name == selected_agent_name:
|
||||
self.tasks[selected_task_id].agent = a
|
||||
logging.info(f"Changed agent for task {selected_task_id} from {original_agent} to {selected_agent_name}")
|
||||
break
|
||||
|
||||
if self.tasks[selected_task_id].status != "completed":
|
||||
logging.info(f"Starting execution of task {selected_task_id}")
|
||||
yield selected_task_id
|
||||
logging.info(f"Finished execution of task {selected_task_id}, status: {self.tasks[selected_task_id].status}")
|
||||
|
||||
if self.tasks[selected_task_id].status == "completed":
|
||||
completed_count += 1
|
||||
logging.info(f"Task {selected_task_id} completed. Total completed: {completed_count}/{total_tasks}")
|
||||
|
||||
self.tasks[manager_task.id].status = "completed"
|
||||
if self.verbose >= 1:
|
||||
logging.info("All tasks completed under manager supervision.")
|
||||
logging.info("Hierarchical task execution finished")
|
||||
Generated
-1590
File diff suppressed because it is too large.
Load diff
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,6 +1,6 @@
|
||||
FROM python:3.11-slim
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN pip install flask praisonai==2.0.41 gunicorn markdown
|
||||
RUN pip install flask praisonai==2.0.68 gunicorn markdown
|
||||
EXPOSE 8080
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: "AI Agents"
|
||||
description: "Overview of all available PraisonAI agents and their capabilities"
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
PraisonAI provides a diverse set of specialized agents for various tasks. Each agent is designed with specific capabilities and tools to handle different types of tasks effectively.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Define the main flow
|
||||
Start([▶ Start]) --> Agent1
|
||||
Agent1 --> Process[⚙ Process]
|
||||
Process --> Agent2
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
end
|
||||
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
end
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
## Data & Analysis
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Data Analyst" icon="chart-line" href="/agents/data-analyst">
|
||||
Analyze data from various sources, create visualizations, and generate insights.
|
||||
</Card>
|
||||
<Card title="Finance" icon="money-bill-trend-up" href="/agents/finance">
|
||||
Track stocks, analyze financial data, and provide investment recommendations.
|
||||
</Card>
|
||||
<Card title="Research" icon="magnifying-glass-chart" href="/agents/research">
|
||||
Conduct comprehensive research and analysis across various topics.
|
||||
</Card>
|
||||
<Card title="Wikipedia" icon="book" href="/agents/wikipedia">
|
||||
Search and extract information from Wikipedia articles.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Media & Content
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Image Analysis" icon="image" href="/agents/image">
|
||||
Analyze and understand visual content from images.
|
||||
</Card>
|
||||
<Card title="Image to Text" icon="text" href="/agents/image-to-text">
|
||||
Convert images to textual descriptions and extract text content.
|
||||
</Card>
|
||||
<Card title="Video" icon="video" href="/agents/video">
|
||||
Analyze video content and extract meaningful information.
|
||||
</Card>
|
||||
<Card title="Markdown" icon="markdown" href="/agents/markdown">
|
||||
Generate and format content in Markdown syntax.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Search & Recommendations
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Web Search" icon="globe" href="/agents/websearch">
|
||||
Perform intelligent web searches and gather information.
|
||||
</Card>
|
||||
<Card title="Recommendation" icon="thumbs-up" href="/agents/recommendation">
|
||||
Generate personalized recommendations based on preferences.
|
||||
</Card>
|
||||
<Card title="Shopping" icon="shop" href="/agents/shopping">
|
||||
Compare prices and find the best deals across stores.
|
||||
</Card>
|
||||
<Card title="Planning" icon="calendar" href="/agents/planning">
|
||||
Create travel plans and detailed itineraries.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Development
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Programming" icon="code" href="/agents/programming">
|
||||
Write, analyze, and debug code across multiple languages.
|
||||
</Card>
|
||||
<Card title="Single Agent" icon="circle-1" href="/agents/single">
|
||||
Simple, focused agent for basic tasks without external tools.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Getting Started
|
||||
|
||||
Each agent can be easily initialized and customized for your specific needs. Here's a basic example:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create an agent with specific instructions
|
||||
agent = Agent(instructions="Your task-specific instructions")
|
||||
|
||||
# Start the agent with a task
|
||||
response = agent.start("Your task description")
|
||||
```
|
||||
|
||||
For more detailed information about each agent, click on the respective cards above.
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: "Data Analyst Agent"
|
||||
sidebarTitle: "Data Analyst"
|
||||
description: "Learn how to create AI agents for data analysis and insights generation."
|
||||
icon: "chart-line"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Data Source] --> Reader[Data Reader]
|
||||
Reader --> Analyzer[Data Analyzer]
|
||||
Analyzer --> Generator[Insights Generator]
|
||||
Generator --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Reader fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Data Analyst Agent can read data from various sources, analyze it, and generate insights.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `data_analysis.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import (
|
||||
read_csv, read_excel, write_csv, write_excel,
|
||||
filter_data, get_summary, group_by, pivot_table
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Data Analyst Agent",
|
||||
tools=[
|
||||
read_csv, read_excel, write_csv, write_excel,
|
||||
filter_data, get_summary, group_by, pivot_table
|
||||
]
|
||||
)
|
||||
|
||||
# Start analysis with a specific task
|
||||
agent.start(f"""
|
||||
Read the data from the csv file {os.path.join(os.path.dirname(__file__), "tesla-stock-price.csv")}
|
||||
Analyse the data and give me the insights
|
||||
read_csv to read the file
|
||||
""")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Data Analysis Workflow
|
||||
|
||||
The Data Analyst Agent is designed to perform comprehensive data analysis tasks using a suite of specialized tools. Here's how it works:
|
||||
|
||||
1. **Data Reading**: The agent can read data from various sources:
|
||||
- CSV files using `read_csv`
|
||||
- Excel files using `read_excel`
|
||||
|
||||
2. **Data Analysis**: Multiple analysis tools are available:
|
||||
- `filter_data`: Filter datasets based on conditions
|
||||
- `get_summary`: Generate statistical summaries
|
||||
- `group_by`: Group data by specific columns
|
||||
- `pivot_table`: Create pivot tables for analysis
|
||||
|
||||
3. **Data Export**: Results can be exported to:
|
||||
- CSV format using `write_csv`
|
||||
- Excel format using `write_excel`
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Multiple Data Sources" icon="table">
|
||||
Support for both CSV and Excel file formats.
|
||||
</Card>
|
||||
<Card title="Analysis Tools" icon="calculator">
|
||||
Comprehensive suite of analysis tools including filtering, summarization, and pivoting.
|
||||
</Card>
|
||||
<Card title="Data Export" icon="file-export">
|
||||
Export capabilities to various formats.
|
||||
</Card>
|
||||
<Card title="Automated Insights" icon="lightbulb">
|
||||
Automatic generation of data insights and patterns.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyzing stock data
|
||||
agent.start("""
|
||||
1. Read 'stock_data.csv'
|
||||
2. Filter data for the last 30 days
|
||||
3. Calculate daily returns
|
||||
4. Generate summary statistics
|
||||
5. Export results to 'analysis_results.xlsx'
|
||||
""")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex analysis workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
|
||||
- Check out other specialized agents like the [Finance Agent](/agents/finance) for specific use cases
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
title: "Finance Agent"
|
||||
sidebarTitle: "Finance"
|
||||
description: "Learn how to create AI agents for financial analysis and investment recommendations."
|
||||
icon: "money-bill-trend-up"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Request] --> Price[Stock Price]
|
||||
Price --> Info[Stock Info]
|
||||
Info --> History[Historical Data]
|
||||
History --> Out[Investment Advice]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Price fill:#2E8B57,color:#fff
|
||||
style Info fill:#2E8B57,color:#fff
|
||||
style History fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Finance Agent can analyze stock market data and provide investment recommendations.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `finance_analysis.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import get_stock_price, get_stock_info, get_historical_data
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Research Agent",
|
||||
tools=[get_stock_price, get_stock_info, get_historical_data]
|
||||
)
|
||||
agent.start("Understand current stock price and historical data of Apple and Google. Tell me if I can invest in them")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Financial Analysis
|
||||
|
||||
The Finance Agent specializes in stock market analysis and investment recommendations using three key components:
|
||||
|
||||
1. **Real-time Price Data**: Uses `get_stock_price` to fetch current market prices
|
||||
2. **Company Information**: Retrieves company details using `get_stock_info`
|
||||
3. **Historical Analysis**: Analyzes trends with `get_historical_data`
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Real-time Data" icon="clock">
|
||||
Access to current stock market prices and information.
|
||||
</Card>
|
||||
<Card title="Company Analysis" icon="building">
|
||||
Detailed company information and fundamentals.
|
||||
</Card>
|
||||
<Card title="Historical Trends" icon="chart-line">
|
||||
Analysis of historical price movements and patterns.
|
||||
</Card>
|
||||
<Card title="Investment Advice" icon="money-bill">
|
||||
AI-powered investment recommendations.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyzing specific stocks
|
||||
agent.start("""
|
||||
1. Get current prices for AAPL and GOOGL
|
||||
2. Retrieve company information
|
||||
3. Analyze 6-month historical data
|
||||
4. Provide investment recommendations
|
||||
""")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex financial analysis
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
|
||||
- Check out the [Data Analyst Agent](/agents/data-analyst) for detailed data analysis capabilities
|
||||
@@ -0,0 +1,140 @@
|
||||
---
|
||||
title: "Image to Text Agent"
|
||||
sidebarTitle: "Image to Text"
|
||||
description: "Learn how to create AI agents for converting images to textual descriptions and extracting text from images."
|
||||
icon: "text"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Image Input] --> OCR[Text Extractor]
|
||||
OCR --> Analyzer[Content Analyzer]
|
||||
Analyzer --> Generator[Description Generator]
|
||||
Generator --> Out[Text Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style OCR fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Image-to-Text Agent can extract text from images and generate comprehensive descriptions.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `image_to_text.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create Image-to-Text Agent
|
||||
image_text_agent = Agent(
|
||||
name="ImageTextConverter",
|
||||
role="Image Text Extraction Specialist",
|
||||
goal="Convert image content to textual descriptions and extract text",
|
||||
backstory="""You are an expert in OCR and image understanding.
|
||||
You excel at extracting text from images and generating detailed descriptions.""",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create text extraction task
|
||||
extraction_task = Task(
|
||||
name="extract_text",
|
||||
description="Extract all text from this image and describe its layout.",
|
||||
expected_output="Extracted text and layout description",
|
||||
agent=image_text_agent,
|
||||
images=["document.jpg"]
|
||||
)
|
||||
|
||||
# Create description task
|
||||
description_task = Task(
|
||||
name="generate_description",
|
||||
description="Generate a detailed description of the image content.",
|
||||
expected_output="Comprehensive description of visual elements",
|
||||
agent=image_text_agent,
|
||||
images=["scene.jpg"]
|
||||
)
|
||||
|
||||
# Create PraisonAIAgents instance
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_text_agent],
|
||||
tasks=[extraction_task, description_task],
|
||||
process="sequential",
|
||||
verbose=1
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Image-to-Text Conversion
|
||||
|
||||
The Image-to-Text Agent combines multiple capabilities to convert visual content into textual form:
|
||||
|
||||
1. **OCR Processing**: Extracts text from images using optical character recognition
|
||||
2. **Layout Analysis**: Understands the spatial arrangement of text and visual elements
|
||||
3. **Content Description**: Generates natural language descriptions of image content
|
||||
4. **Text Formatting**: Preserves text formatting and structure where possible
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Text Extraction" icon="text">
|
||||
Advanced OCR capabilities for text extraction.
|
||||
</Card>
|
||||
<Card title="Layout Understanding" icon="table-layout">
|
||||
Analysis of text and content layout.
|
||||
</Card>
|
||||
<Card title="Content Description" icon="pen-to-square">
|
||||
Detailed descriptions of visual content.
|
||||
</Card>
|
||||
<Card title="Format Preservation" icon="paragraph">
|
||||
Maintains text formatting and structure.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Processing a document image
|
||||
document_task = Task(
|
||||
name="process_document",
|
||||
description="Extract text and analyze document layout",
|
||||
expected_output="Extracted text with layout information",
|
||||
agent=image_text_agent,
|
||||
images=["business_document.jpg"]
|
||||
)
|
||||
|
||||
# Run single task
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_text_agent],
|
||||
tasks=[document_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex document processing
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving text extraction accuracy
|
||||
- Check out the [Image Agent](/agents/image) for pure image analysis capabilities
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
title: "Image Analysis Agent"
|
||||
sidebarTitle: "Image Analysis"
|
||||
description: "Learn how to create AI agents for image analysis and visual content understanding."
|
||||
icon: "image"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Image Input] --> Analyzer[Image Analyzer]
|
||||
Analyzer --> Detector[Object Detector]
|
||||
Detector --> Generator[Description Generator]
|
||||
Generator --> Out[Analysis Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Detector fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Image Analysis Agent can process and analyze visual content, detect objects, and generate detailed descriptions.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `image_analysis.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create Image Analysis Agent
|
||||
image_agent = Agent(
|
||||
name="ImageAnalyst",
|
||||
role="Image Analysis Specialist",
|
||||
goal="Analyze images and videos to extract meaningful information",
|
||||
backstory="""You are an expert in computer vision and image analysis.
|
||||
You excel at describing images, detecting objects, and understanding visual content.""",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create tasks for different types of analysis
|
||||
task1 = Task(
|
||||
name="analyze_landmark",
|
||||
description="Describe this famous landmark and its architectural features.",
|
||||
expected_output="Detailed description of the landmark's architecture and significance",
|
||||
agent=image_agent,
|
||||
images=["https://example.com/landmark.jpg"]
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="analyze_local_image",
|
||||
description="What objects can you see in this image? Describe their arrangement.",
|
||||
expected_output="Detailed description of objects and their spatial relationships",
|
||||
agent=image_agent,
|
||||
images=["local_image.jpg"]
|
||||
)
|
||||
|
||||
# Create PraisonAIAgents instance
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_agent],
|
||||
tasks=[task1, task2],
|
||||
process="sequential",
|
||||
verbose=1
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Image Analysis
|
||||
|
||||
The Image Analysis Agent is designed to process and understand visual content through several key capabilities:
|
||||
|
||||
1. **Image Input**: Supports both URL and local file inputs
|
||||
2. **Object Detection**: Identifies and locates objects within images
|
||||
3. **Architectural Analysis**: Specialized in analyzing architectural features
|
||||
4. **Spatial Understanding**: Describes spatial relationships between objects
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Multiple Input Sources" icon="images">
|
||||
Support for both URL and local image files.
|
||||
</Card>
|
||||
<Card title="Object Detection" icon="magnifying-glass">
|
||||
Advanced object detection and recognition.
|
||||
</Card>
|
||||
<Card title="Architectural Analysis" icon="building">
|
||||
Specialized analysis of architectural features.
|
||||
</Card>
|
||||
<Card title="Detailed Descriptions" icon="pen">
|
||||
Generation of comprehensive visual descriptions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyzing a landmark image
|
||||
landmark_task = Task(
|
||||
name="analyze_famous_landmark",
|
||||
description="Analyze this historical landmark",
|
||||
expected_output="Architectural details and historical significance",
|
||||
agent=image_agent,
|
||||
images=["https://example.com/landmark.jpg"]
|
||||
)
|
||||
|
||||
# Run single task
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_agent],
|
||||
tasks=[landmark_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex image analysis workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
|
||||
- Check out the [Video Agent](/agents/video) for video content analysis
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: "Markdown Agent"
|
||||
sidebarTitle: "Markdown"
|
||||
description: "Learn how to create AI agents for generating and formatting content in Markdown."
|
||||
icon: "markdown"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Content Request] --> Generator[Content Generator]
|
||||
Generator --> Formatter[Markdown Formatter]
|
||||
Formatter --> Validator[Format Validator]
|
||||
Validator --> Out[Markdown Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Formatter fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Markdown Agent can generate and format content in Markdown syntax.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `markdown_generator.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create Markdown Agent
|
||||
markdown_agent = Agent(
|
||||
name="MarkdownWriter",
|
||||
role="Markdown Content Specialist",
|
||||
goal="Generate well-formatted content in Markdown syntax",
|
||||
instructions="You are a Markdown Agent, output in markdown format",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Generate content
|
||||
response = markdown_agent.start(
|
||||
"Write a blog post about artificial intelligence"
|
||||
)
|
||||
|
||||
# Save to file
|
||||
with open('blog_post.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Markdown Generation
|
||||
|
||||
The Markdown Agent specializes in creating properly formatted Markdown content:
|
||||
|
||||
1. **Content Generation**: Creates original content based on prompts
|
||||
2. **Markdown Formatting**: Applies proper Markdown syntax
|
||||
3. **Structure Validation**: Ensures correct formatting
|
||||
4. **Document Organization**: Creates well-structured documents
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Content Creation" icon="pen-to-square">
|
||||
Generates original, well-structured content.
|
||||
</Card>
|
||||
<Card title="Markdown Syntax" icon="code">
|
||||
Proper implementation of Markdown formatting.
|
||||
</Card>
|
||||
<Card title="Document Structure" icon="sitemap">
|
||||
Organized document hierarchy and sections.
|
||||
</Card>
|
||||
<Card title="Format Validation" icon="check">
|
||||
Ensures correct Markdown syntax usage.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Generate a technical documentation
|
||||
agent = Agent(
|
||||
instructions="You are a Markdown Agent, output in markdown format"
|
||||
)
|
||||
|
||||
# Generate API documentation
|
||||
response = agent.start("""
|
||||
Create technical documentation for a REST API with:
|
||||
- Introduction
|
||||
- Authentication
|
||||
- Endpoints
|
||||
- Examples
|
||||
""")
|
||||
|
||||
# Save documentation
|
||||
with open('api_docs.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex document generation
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving content quality
|
||||
- Check out the [Documentation Agent](/agents/documentation) for specialized documentation generation
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
title: "Planning Agent"
|
||||
sidebarTitle: "Planning"
|
||||
description: "Learn how to create AI agents for trip planning and itinerary generation."
|
||||
icon: "calendar"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Request] --> Search[Web Search]
|
||||
Search --> Analyzer[Options Analyzer]
|
||||
Analyzer --> Generator[Plan Generator]
|
||||
Generator --> Out[Itinerary]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Planning Agent can search for travel options and create detailed itineraries.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `travel_planner.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Planning Agent
|
||||
planning_agent = Agent(
|
||||
name="TravelPlanner",
|
||||
role="Travel Planning Specialist",
|
||||
goal="Create comprehensive travel plans and itineraries",
|
||||
instructions="You are a Planning Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Generate travel plan
|
||||
response = planning_agent.start(
|
||||
"I want to go to London next week, find me a good hotel and flight"
|
||||
)
|
||||
|
||||
# Save plan
|
||||
with open('travel_plan.txt', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Travel Planning
|
||||
|
||||
The Planning Agent combines multiple capabilities to create comprehensive travel plans:
|
||||
|
||||
1. **Web Search**: Uses DuckDuckGo to find current travel options
|
||||
2. **Options Analysis**: Evaluates and compares different choices
|
||||
3. **Plan Generation**: Creates detailed itineraries
|
||||
4. **Recommendations**: Provides personalized suggestions
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Flight Search" icon="plane">
|
||||
Finds and compares flight options.
|
||||
</Card>
|
||||
<Card title="Hotel Booking" icon="hotel">
|
||||
Recommends suitable accommodations.
|
||||
</Card>
|
||||
<Card title="Itinerary Creation" icon="calendar-days">
|
||||
Generates detailed travel schedules.
|
||||
</Card>
|
||||
<Card title="Real-time Data" icon="clock">
|
||||
Uses current pricing and availability.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Create a weekend trip plan
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Planning Agent", tools=[duckduckgo])
|
||||
agent.start("I want to go London next week, find me a good hotel and flight")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex travel planning
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendations
|
||||
- Check out the [Research Agent](/agents/research) for detailed destination research
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
title: "Programming Agent"
|
||||
sidebarTitle: "Programming"
|
||||
description: "Learn how to create AI agents for code development, analysis, and execution."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Code Request] --> Analyzer[Code Analyzer]
|
||||
Analyzer --> Generator[Code Generator]
|
||||
Generator --> Executor[Code Executor]
|
||||
Executor --> Debugger[Code Debugger]
|
||||
Debugger --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Executor fill:#2E8B57,color:#fff
|
||||
style Debugger fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Programming Agent can analyze, generate, execute, and debug code.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `code_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import execute_code, analyze_code, format_code, lint_code, disassemble_code # Code Tools
|
||||
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info # Shell Tools
|
||||
from praisonaiagents.tools import duckduckgo # Web Search Tool
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Programming Agent", self_reflect=True, min_reflect=5, max_reflect=10,
|
||||
tools=[execute_code, analyze_code, format_code, lint_code, disassemble_code, execute_command, list_processes, kill_process, get_system_info, duckduckgo]
|
||||
)
|
||||
agent.start(
|
||||
"Write a python script using yfinance to find the stock price of Tesla"
|
||||
"First check if required packages are installed"
|
||||
"Run it using execute_code"
|
||||
"execute_command if you want to run any terminal command"
|
||||
"search internet using duckduckgo if you want to know update python package information"
|
||||
"Analyse the output using analyze_code and fix error if required"
|
||||
"if no package is installed, install it"
|
||||
"then run the code"
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Code Development
|
||||
|
||||
The Programming Agent combines multiple tools for comprehensive code development:
|
||||
|
||||
1. **Code Tools**:
|
||||
- `execute_code`: Run Python code
|
||||
- `analyze_code`: Analyze code structure
|
||||
- `format_code`: Format code to standards
|
||||
- `lint_code`: Check code quality
|
||||
- `disassemble_code`: View bytecode
|
||||
|
||||
2. **Shell Tools**:
|
||||
- `execute_command`: Run terminal commands
|
||||
- `list_processes`: View running processes
|
||||
- `kill_process`: Terminate processes
|
||||
- `get_system_info`: System information
|
||||
|
||||
3. **Web Tools**:
|
||||
- `duckduckgo`: Search for programming resources
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Code Execution" icon="play">
|
||||
Run and test code directly.
|
||||
</Card>
|
||||
<Card title="Code Analysis" icon="magnifying-glass-code">
|
||||
Analyze and improve code quality.
|
||||
</Card>
|
||||
<Card title="System Integration" icon="terminal">
|
||||
Execute system commands and manage processes.
|
||||
</Card>
|
||||
<Card title="Package Management" icon="box">
|
||||
Handle dependencies and installations.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Create and run a data analysis script
|
||||
response = agent.start("""
|
||||
1. Create a script that:
|
||||
- Uses pandas for data analysis
|
||||
- Reads a CSV file
|
||||
- Performs basic statistics
|
||||
- Creates a visualization
|
||||
2. Check and install required packages
|
||||
3. Execute and analyze the results
|
||||
""")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex development workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving code quality
|
||||
- Check out the [Data Analyst Agent](/agents/data-analyst) for specialized data analysis
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
title: "Recommendation Agent"
|
||||
sidebarTitle: "Recommendation"
|
||||
description: "Learn how to create AI agents for personalized recommendations across various domains."
|
||||
icon: "thumbs-up"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[User Preferences] --> Search[Content Search]
|
||||
Search --> Analyzer[Preference Analyzer]
|
||||
Analyzer --> Generator[Recommendation Generator]
|
||||
Generator --> Out[Recommendations]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Recommendation Agent can analyze preferences and generate personalized recommendations.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `recommendation_system.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Recommendation Agent
|
||||
recommendation_agent = Agent(
|
||||
name="RecommendationEngine",
|
||||
role="Recommendation Specialist",
|
||||
goal="Generate personalized recommendations based on preferences",
|
||||
instructions="You are a Recommendation Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Get recommendations
|
||||
response = recommendation_agent.start(
|
||||
"Recommend me a good movie to watch in 2025"
|
||||
)
|
||||
|
||||
# Save recommendations
|
||||
with open('recommendations.txt', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Recommendation System
|
||||
|
||||
The Recommendation Agent uses multiple approaches to generate personalized suggestions:
|
||||
|
||||
1. **Content Search**: Uses DuckDuckGo to find current options
|
||||
2. **Preference Analysis**: Understands user preferences
|
||||
3. **Recommendation Generation**: Creates personalized suggestions
|
||||
4. **Content Filtering**: Filters based on relevance and quality
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Personalization" icon="user">
|
||||
Tailored recommendations based on preferences.
|
||||
</Card>
|
||||
<Card title="Real-time Data" icon="clock">
|
||||
Up-to-date content and information.
|
||||
</Card>
|
||||
<Card title="Multi-domain" icon="layer-group">
|
||||
Recommendations across various categories.
|
||||
</Card>
|
||||
<Card title="Content Filtering" icon="filter">
|
||||
Quality-based content selection.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Get personalized recommendations
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Recommendation Agent", tools=[duckduckgo])
|
||||
agent.start("Recommend me a good movie to watch in 2025")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex recommendation systems
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
|
||||
- Check out the [Research Agent](/agents/research) for detailed content research
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
title: "Research Agent"
|
||||
sidebarTitle: "Research"
|
||||
description: "Learn how to create AI agents for conducting comprehensive research and analysis."
|
||||
icon: "magnifying-glass-chart"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Research Query] --> Search[Web Search]
|
||||
Search --> Analyzer[Content Analyzer]
|
||||
Analyzer --> Synthesizer[Information Synthesizer]
|
||||
Synthesizer --> Out[Research Report]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Synthesizer fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Research Agent can gather, analyze, and synthesize information from various sources.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `research_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Research Agent
|
||||
research_agent = Agent(
|
||||
name="ResearchAssistant",
|
||||
role="Research Specialist",
|
||||
goal="Conduct comprehensive research and analysis",
|
||||
instructions="You are a Research Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Conduct research
|
||||
response = research_agent.start(
|
||||
"Research about AI developments in 2024"
|
||||
)
|
||||
|
||||
# Save research findings
|
||||
with open('research_report.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Research Process
|
||||
|
||||
The Research Agent employs a systematic approach to information gathering and analysis:
|
||||
|
||||
1. **Web Search**: Uses DuckDuckGo to find relevant sources
|
||||
2. **Content Analysis**: Evaluates source credibility and relevance
|
||||
3. **Information Synthesis**: Combines findings into coherent insights
|
||||
4. **Report Generation**: Creates structured research reports
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Web Research" icon="globe">
|
||||
Comprehensive online information gathering.
|
||||
</Card>
|
||||
<Card title="Content Analysis" icon="microscope">
|
||||
In-depth evaluation of sources.
|
||||
</Card>
|
||||
<Card title="Information Synthesis" icon="layer-group">
|
||||
Integration of multiple sources.
|
||||
</Card>
|
||||
<Card title="Report Generation" icon="file-lines">
|
||||
Structured research documentation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
|
||||
agent.start("Research about AI 2024")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex research projects
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
|
||||
- Check out the [Data Analyst Agent](/agents/data-analyst) for data-driven research
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
title: "Shopping Agent"
|
||||
sidebarTitle: "Shopping"
|
||||
description: "Learn how to create AI agents for price comparison and shopping assistance."
|
||||
icon: "shop"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Product Query] --> Search[Store Search]
|
||||
Search --> Analyzer[Price Analyzer]
|
||||
Analyzer --> Comparator[Price Comparator]
|
||||
Comparator --> Out[Price Report]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Comparator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Shopping Agent can search for products, compare prices, and provide shopping recommendations.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `shopping_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Shopping Agent
|
||||
shopping_agent = Agent(
|
||||
name="ShoppingAssistant",
|
||||
role="Shopping Specialist",
|
||||
goal="Find the best prices and deals across stores",
|
||||
instructions="You are a Shopping Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Search for product prices
|
||||
response = shopping_agent.start(
|
||||
"I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table"
|
||||
)
|
||||
|
||||
# Save price comparison
|
||||
with open('price_comparison.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Shopping Assistant
|
||||
|
||||
The Shopping Agent combines multiple capabilities for effective price comparison:
|
||||
|
||||
1. **Store Search**: Uses DuckDuckGo to find retailers
|
||||
2. **Price Analysis**: Gathers pricing information
|
||||
3. **Price Comparison**: Compares prices across stores
|
||||
4. **Deal Finding**: Identifies special offers and discounts
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Price Comparison" icon="scale-balanced">
|
||||
Compare prices across multiple stores.
|
||||
</Card>
|
||||
<Card title="Deal Detection" icon="tag">
|
||||
Find special offers and discounts.
|
||||
</Card>
|
||||
<Card title="Store Analysis" icon="store">
|
||||
Evaluate retailer reliability.
|
||||
</Card>
|
||||
<Card title="Price Tracking" icon="chart-line">
|
||||
Monitor price changes over time.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Compare product prices
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Shopping Agent", tools=[duckduckgo])
|
||||
agent.start("I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex shopping research
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving price accuracy
|
||||
- Check out the [Research Agent](/agents/research) for detailed product research
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
title: "Single Agent"
|
||||
sidebarTitle: "Single"
|
||||
description: "Learn how to create a basic single-purpose AI agent for simple tasks."
|
||||
icon: "circle-1"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Input] --> Agent[Single Agent]
|
||||
Agent --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Agent fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how to create and use a simple single-purpose agent.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `simple_agent.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="You are a Markdown Agent, output in markdown format")
|
||||
agent.start("Write a blog post about AI")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Single Agent
|
||||
|
||||
The Single Agent is the simplest form of PraisonAI agent:
|
||||
|
||||
1. **Simple Setup**: Minimal configuration required
|
||||
2. **Single Purpose**: Focused on one specific task
|
||||
3. **Direct Execution**: Straightforward input-output flow
|
||||
4. **No Dependencies**: No external tools required
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Simple Setup" icon="square-1">
|
||||
Minimal configuration needed.
|
||||
</Card>
|
||||
<Card title="Focused Task" icon="bullseye">
|
||||
Single-purpose execution.
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt">
|
||||
Rapid implementation.
|
||||
</Card>
|
||||
<Card title="No Tools" icon="toolbox">
|
||||
No external dependencies.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Create a content generation agent
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create content agent
|
||||
agent = Agent(
|
||||
instructions="You are a Content Generation Agent, create engaging content"
|
||||
)
|
||||
|
||||
# Generate content
|
||||
response = agent.start("""
|
||||
Write a short story about:
|
||||
- A future world
|
||||
- With advanced AI
|
||||
- And human collaboration
|
||||
""")
|
||||
|
||||
# Save the story
|
||||
with open('ai_story.txt', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for more complex workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving output quality
|
||||
- Check out other specialized agents like the [Markdown Agent](/agents/markdown) for specific use cases
|
||||
@@ -0,0 +1,149 @@
|
||||
---
|
||||
title: "Video Agent"
|
||||
sidebarTitle: "Video"
|
||||
description: "Learn how to create AI agents for video analysis and content understanding."
|
||||
icon: "video"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Video Input] --> Analyzer[Content Analyzer]
|
||||
Analyzer --> Detector[Object Detector]
|
||||
Detector --> Transcriber[Text Transcriber]
|
||||
Transcriber --> Out[Analysis Report]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Detector fill:#2E8B57,color:#fff
|
||||
style Transcriber fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Video Agent can analyze video content, detect objects, and extract meaningful information.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `video_analyzer.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create Video Analysis Agent
|
||||
video_agent = Agent(
|
||||
name="VideoAnalyst",
|
||||
role="Video Analysis Specialist",
|
||||
goal="Analyze videos to extract meaningful information",
|
||||
backstory="""You are an expert in computer vision and video analysis.
|
||||
You excel at describing content, detecting objects, and understanding context.""",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create video analysis task
|
||||
analysis_task = Task(
|
||||
name="analyze_video",
|
||||
description="""Analyze this video and provide:
|
||||
1. Summary of main events
|
||||
2. Key objects and people
|
||||
3. Text and important information
|
||||
4. Context and setting""",
|
||||
expected_output="Comprehensive video analysis",
|
||||
agent=video_agent,
|
||||
images=["video.mp4"]
|
||||
)
|
||||
|
||||
# Create PraisonAIAgents instance
|
||||
agents = PraisonAIAgents(
|
||||
agents=[video_agent],
|
||||
tasks=[analysis_task],
|
||||
process="sequential",
|
||||
verbose=1
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Video Analysis
|
||||
|
||||
The Video Agent combines multiple capabilities for comprehensive video understanding:
|
||||
|
||||
1. **Content Analysis**: Analyzes video scenes and events
|
||||
2. **Object Detection**: Identifies objects and people
|
||||
3. **Text Extraction**: Captures text shown in videos
|
||||
4. **Context Understanding**: Interprets settings and situations
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Scene Analysis" icon="film">
|
||||
Detailed analysis of video scenes.
|
||||
</Card>
|
||||
<Card title="Object Detection" icon="cube">
|
||||
Identification of objects and people.
|
||||
</Card>
|
||||
<Card title="Text Extraction" icon="closed-captioning">
|
||||
Capture of text and captions.
|
||||
</Card>
|
||||
<Card title="Context Analysis" icon="sitemap">
|
||||
Understanding of video context.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyze a presentation video
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
video_agent = Agent(
|
||||
name="VideoAnalyst",
|
||||
role="Video Analysis Specialist",
|
||||
goal="Extract information from presentation videos",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create presentation analysis task
|
||||
presentation_task = Task(
|
||||
name="analyze_presentation",
|
||||
description="""Analyze this presentation video:
|
||||
1. Extract key points
|
||||
2. Capture slide content
|
||||
3. Note speaker's main arguments
|
||||
4. Summarize Q&A session""",
|
||||
expected_output="Detailed presentation summary",
|
||||
agent=video_agent,
|
||||
images=["presentation.mp4"]
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents = PraisonAIAgents(
|
||||
agents=[video_agent],
|
||||
tasks=[presentation_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex video analysis
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
|
||||
- Check out the [Image Agent](/agents/image) for still image analysis
|
||||
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: "Web Search Agent"
|
||||
sidebarTitle: "Web Search"
|
||||
description: "Learn how to create AI agents for intelligent web searching and information gathering."
|
||||
icon: "globe"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Search Query] --> Search[Web Search]
|
||||
Search --> Filter[Content Filter]
|
||||
Filter --> Summarizer[Content Summarizer]
|
||||
Summarizer --> Out[Search Results]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Filter fill:#2E8B57,color:#fff
|
||||
style Summarizer fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Web Search Agent can perform intelligent searches and process web content.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `web_search.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Web Search Agent
|
||||
search_agent = Agent(
|
||||
name="WebSearcher",
|
||||
role="Web Search Specialist",
|
||||
goal="Perform intelligent web searches and gather information",
|
||||
instructions="You are a Web Search Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Perform search
|
||||
response = search_agent.start(
|
||||
"Search about AI developments in 2024"
|
||||
)
|
||||
|
||||
# Save search results
|
||||
with open('search_results.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Web Search
|
||||
|
||||
The Web Search Agent employs sophisticated search strategies:
|
||||
|
||||
1. **Query Processing**: Optimizes search queries
|
||||
2. **Content Filtering**: Filters relevant results
|
||||
3. **Information Extraction**: Extracts key information
|
||||
4. **Result Summarization**: Summarizes findings
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Smart Search" icon="magnifying-glass">
|
||||
Intelligent query processing.
|
||||
</Card>
|
||||
<Card title="Content Filtering" icon="filter">
|
||||
Relevance-based filtering.
|
||||
</Card>
|
||||
<Card title="Information Extraction" icon="scissors">
|
||||
Key information extraction.
|
||||
</Card>
|
||||
<Card title="Result Summary" icon="list">
|
||||
Concise result summaries.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Perform topic research
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Web Search Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Research specific topic
|
||||
response = agent.start("""
|
||||
Search for information about quantum computing:
|
||||
- Recent breakthroughs
|
||||
- Leading companies
|
||||
- Current applications
|
||||
- Future predictions
|
||||
""")
|
||||
|
||||
# Save research results
|
||||
with open('quantum_computing_research.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex search workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving search relevance
|
||||
- Check out the [Research Agent](/agents/research) for comprehensive research capabilities
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
title: "Wikipedia Agent"
|
||||
sidebarTitle: "Wikipedia"
|
||||
description: "Learn how to create AI agents for searching and extracting information from Wikipedia."
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Query] --> Search[Wiki Search]
|
||||
Search --> Page[Page Retrieval]
|
||||
Page --> Summary[Content Summary]
|
||||
Summary --> Out[Knowledge Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Page fill:#2E8B57,color:#fff
|
||||
style Summary fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Wikipedia Agent can search, retrieve, and summarize Wikipedia content.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `wikipedia_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import (
|
||||
wiki_search,
|
||||
wiki_summary,
|
||||
wiki_page,
|
||||
wiki_random,
|
||||
wiki_language
|
||||
)
|
||||
|
||||
# Create Wikipedia Agent
|
||||
wiki_agent = Agent(
|
||||
name="WikipediaAssistant",
|
||||
role="Wikipedia Research Specialist",
|
||||
goal="Extract and summarize Wikipedia content",
|
||||
instructions="You are a Wikipedia Agent",
|
||||
tools=[
|
||||
wiki_search,
|
||||
wiki_summary,
|
||||
wiki_page,
|
||||
wiki_random,
|
||||
wiki_language
|
||||
],
|
||||
self_reflect=True,
|
||||
min_reflect=3,
|
||||
max_reflect=5
|
||||
)
|
||||
|
||||
# Research a topic
|
||||
response = wiki_agent.start("""
|
||||
What is the history of AI?
|
||||
First search the history of AI
|
||||
Read the page of the history of AI
|
||||
Get the summary of the page
|
||||
""")
|
||||
|
||||
# Save research results
|
||||
with open('ai_history.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Wikipedia Research
|
||||
|
||||
The Wikipedia Agent provides comprehensive Wikipedia access through multiple tools:
|
||||
|
||||
1. **Wiki Search**: `wiki_search` for finding relevant articles
|
||||
2. **Page Access**: `wiki_page` for retrieving full articles
|
||||
3. **Summarization**: `wiki_summary` for concise overviews
|
||||
4. **Random Articles**: `wiki_random` for discovering content
|
||||
5. **Language Support**: `wiki_language` for multilingual access
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Article Search" icon="magnifying-glass">
|
||||
Find relevant Wikipedia articles.
|
||||
</Card>
|
||||
<Card title="Content Retrieval" icon="book-open">
|
||||
Access complete article content.
|
||||
</Card>
|
||||
<Card title="Summarization" icon="compress">
|
||||
Generate concise article summaries.
|
||||
</Card>
|
||||
<Card title="Multilingual" icon="language">
|
||||
Access content in multiple languages.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Research a scientific topic
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Wikipedia Agent",
|
||||
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
|
||||
self_reflect=True,
|
||||
min_reflect=3,
|
||||
max_reflect=5,
|
||||
)
|
||||
agent.start(
|
||||
"What is the history of AI?"
|
||||
"First search the history of AI"
|
||||
"Read the page of the history of AI"
|
||||
"Get the summary of the page"
|
||||
)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex Wikipedia research
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
|
||||
- Check out the [Research Agent](/agents/research) for broader research capabilities
|
||||
@@ -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.41 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.68 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
+25
-103
@@ -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
|
||||
@@ -126,86 +112,22 @@ graph LR
|
||||
<Step title="Create Agent">
|
||||
Create `app.py`:
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create an agent
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o"
|
||||
)
|
||||
agent = Agent(instructions="Your are a helpful AI assistant")
|
||||
agent.start("Write a movie script about a robot in Mars")
|
||||
```
|
||||
|
||||
# Define a task
|
||||
task = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
```python Multi Agents
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
verbose=False
|
||||
)
|
||||
research_agent = Agent(instructions="Research about AI")
|
||||
summarise_agent = Agent(instructions="Summarise research agent's findings")
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
```python Multiple Agents
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create multiple agents
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
name="Writer",
|
||||
role="Tech Content Strategist",
|
||||
goal="Craft compelling content on tech advancements",
|
||||
backstory="You are a content strategist",
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# Define multiple tasks
|
||||
task1 = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="writing_task",
|
||||
description="Create a blog post about AI advancements",
|
||||
expected_output="A blog post",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
# Run with hierarchical process
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2],
|
||||
verbose=False,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
---
|
||||
title: "AI Agents with Knowledge"
|
||||
sidebarTitle: "Knowledge"
|
||||
description: "Learn how to create AI agents with custom knowledge bases"
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph In[Input]
|
||||
PDF[PDF]
|
||||
TXT[TXT]
|
||||
MD[MD]
|
||||
end
|
||||
|
||||
subgraph Router[Vector Store]
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
subgraph Out[Agents]
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
|
||||
In --> Router
|
||||
Router --> A1
|
||||
Router --> A2
|
||||
Router --> A3
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Router fill:#2E8B57,color:#fff
|
||||
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>
|
||||
<Step title="Install Package">
|
||||
Install PraisonAI Agents with knowledge support:
|
||||
```bash
|
||||
pip install "praisonaiagents[knowledge]"
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key:
|
||||
```bash
|
||||
export OPENAI_API_KEY=xxxxx
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `app.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"]
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Basic Usage
|
||||
|
||||
The simplest way to create a knowledge-based agent is without any configuration:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"]
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
For more control over the knowledge base, you can specify a configuration:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "custom_knowledge",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"],
|
||||
knowledge_config=config
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
|
||||
## Multi-Agent Knowledge System
|
||||
|
||||
For more complex scenarios, you can create a knowledge-based system with multiple agents:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import logging
|
||||
import os
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Define the configuration for the Knowledge instance
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "knowledge_test",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create an agent with knowledge capabilities
|
||||
knowledge_agent = Agent(
|
||||
name="KnowledgeAgent",
|
||||
role="Information Specialist",
|
||||
goal="Store and retrieve knowledge efficiently",
|
||||
backstory="Expert in managing and utilizing stored knowledge",
|
||||
knowledge=["sample.pdf"],
|
||||
knowledge_config=config,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Define a task for the agent
|
||||
knowledge_task = Task(
|
||||
name="knowledge_task",
|
||||
description="Who is Mervin Praison?",
|
||||
expected_output="Answer to the question",
|
||||
agent=knowledge_agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[knowledge_agent],
|
||||
tasks=[knowledge_task],
|
||||
process="sequential",
|
||||
user_id="user1"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
## Understanding Knowledge Configuration
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Vector Store Options">
|
||||
- **Provider**: Choose between different vector store backends (e.g., "chroma")
|
||||
- **Collection Name**: Name for your knowledge collection
|
||||
- **Path**: Location to store the vector database
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Supported File Types">
|
||||
- PDF documents (*.pdf)
|
||||
- Text files (*.txt)
|
||||
- Markdown files (*.md, *.mdx)
|
||||
- And more...
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Multi-Agent Setup">
|
||||
- **Role**: Define specialized roles for knowledge agents
|
||||
- **Goal**: Set specific knowledge management objectives
|
||||
- **Process**: Choose between sequential or parallel execution
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Custom Knowledge" icon="book">
|
||||
Import your own documents and data as knowledge sources
|
||||
</Card>
|
||||
<Card title="Vector Storage" icon="database">
|
||||
Efficient storage and retrieval of knowledge embeddings
|
||||
</Card>
|
||||
<Card title="Multiple Sources" icon="layer-group">
|
||||
Combine multiple documents and file types
|
||||
</Card>
|
||||
<Card title="Persistent Storage" icon="hard-drive">
|
||||
Save and reuse knowledge bases across sessions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Document Preparation**
|
||||
- Clean and well-formatted documents work best
|
||||
- Break large documents into smaller chunks
|
||||
- Use consistent formatting
|
||||
|
||||
2. **Knowledge Organization**
|
||||
- Group related documents together
|
||||
- Use meaningful file names
|
||||
- Keep knowledge bases focused and relevant
|
||||
|
||||
3. **Performance Optimization**
|
||||
- Monitor vector store size
|
||||
- Clean up unused collections
|
||||
- Use appropriate chunk sizes
|
||||
|
||||
4. **Multi-Agent Coordination**
|
||||
- Define clear roles and responsibilities
|
||||
- Set appropriate logging levels for debugging
|
||||
- Use unique collection names for different agent groups
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Memory Management](/concepts/memory) for long-term recall
|
||||
- Explore [Tool Integration](/concepts/tools) for enhanced capabilities
|
||||
- Check out [Examples](/examples) for implementation ideas
|
||||
+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>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 134 KiB |
@@ -0,0 +1,75 @@
|
||||
---
|
||||
title: 'Local Development'
|
||||
description: 'Set up local development environment with Docker and live reload'
|
||||
---
|
||||
|
||||
## Logging
|
||||
```bash
|
||||
export LOGLEVEL=info
|
||||
```
|
||||
|
||||
Advanced logging:
|
||||
```bash
|
||||
export LOGLEVEL=debug
|
||||
```
|
||||
|
||||
## Local Docker Development with Live Reload
|
||||
|
||||
To facilitate local development with live reload, you can use Docker. Follow the steps below:
|
||||
|
||||
### 1. Create Dockerfile.dev
|
||||
|
||||
<CodeGroup>
|
||||
```dockerfile Dockerfile.dev
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN pip install flask praisonai==2.0.18 watchdog
|
||||
|
||||
EXPOSE 5555
|
||||
|
||||
ENV FLASK_ENV=development
|
||||
|
||||
CMD ["flask", "run", "--host=0.0.0.0"]
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 2. Create docker-compose.yml
|
||||
|
||||
<CodeGroup>
|
||||
```yaml docker-compose.yml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.dev
|
||||
volumes:
|
||||
- .:/app
|
||||
ports:
|
||||
- "5555:5555"
|
||||
environment:
|
||||
FLASK_ENV: development
|
||||
command: flask run --host=0.0.0.0
|
||||
|
||||
watch:
|
||||
image: alpine:latest
|
||||
volumes:
|
||||
- .:/app
|
||||
command: sh -c "apk add --no-cache inotify-tools && while inotifywait -r -e modify,create,delete /app; do kill -HUP 1; done"
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 3. Run Docker Compose
|
||||
|
||||
<CodeGroup>
|
||||
```bash Terminal
|
||||
docker-compose up
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
This setup will allow you to develop locally with live reload, making it easier to test and iterate on your code.
|
||||
@@ -0,0 +1,244 @@
|
||||
---
|
||||
title: "Adaptive Learning"
|
||||
description: "Learn how to create AI agents for personalized adaptive learning experiences."
|
||||
icon: "graduation-cap"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Assessor[Student Assessor]
|
||||
Assessor --> Generator[Content Generator]
|
||||
Generator --> Evaluator[Performance Evaluator]
|
||||
Evaluator --> Adapter[Difficulty Adapter]
|
||||
Adapter --> |decrease/increase| Generator
|
||||
Adapter --> |maintain| Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Assessor fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Evaluator fill:#2E8B57,color:#fff
|
||||
style Adapter fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Learn how to implement an adaptive learning system using AI agents for personalized education and dynamic content adjustment.
|
||||
|
||||
## 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
|
||||
|
||||
def assess_student_level():
|
||||
"""Simulates student assessment"""
|
||||
levels = ["beginner", "intermediate", "advanced"]
|
||||
current_time = int(time.time())
|
||||
return levels[current_time % 3]
|
||||
|
||||
def generate_content(level: str):
|
||||
"""Simulates content generation"""
|
||||
content_types = {
|
||||
"beginner": "basic concepts and examples",
|
||||
"intermediate": "practice problems and applications",
|
||||
"advanced": "complex scenarios and projects"
|
||||
}
|
||||
return content_types.get(level, "basic concepts")
|
||||
|
||||
def evaluate_performance():
|
||||
"""Simulates performance evaluation"""
|
||||
scores = ["low", "medium", "high"]
|
||||
current_time = int(time.time())
|
||||
return scores[current_time % 3]
|
||||
|
||||
def adapt_difficulty(performance: str):
|
||||
"""Simulates difficulty adaptation"""
|
||||
adaptations = {
|
||||
"low": "decrease",
|
||||
"medium": "maintain",
|
||||
"high": "increase"
|
||||
}
|
||||
return adaptations.get(performance, "maintain")
|
||||
|
||||
# Create specialized agents
|
||||
assessor = Agent(
|
||||
name="Student Assessor",
|
||||
role="Level Assessment",
|
||||
goal="Assess student's current level",
|
||||
instructions="Evaluate student's knowledge and skills",
|
||||
tools=[assess_student_level]
|
||||
)
|
||||
|
||||
generator = Agent(
|
||||
name="Content Generator",
|
||||
role="Content Creation",
|
||||
goal="Generate appropriate learning content",
|
||||
instructions="Create content based on student's level",
|
||||
tools=[generate_content]
|
||||
)
|
||||
|
||||
evaluator = Agent(
|
||||
name="Performance Evaluator",
|
||||
role="Performance Assessment",
|
||||
goal="Evaluate student's performance",
|
||||
instructions="Assess learning outcomes",
|
||||
tools=[evaluate_performance]
|
||||
)
|
||||
|
||||
adapter = Agent(
|
||||
name="Difficulty Adapter",
|
||||
role="Content Adaptation",
|
||||
goal="Adapt content difficulty",
|
||||
instructions="Adjust difficulty based on performance",
|
||||
tools=[adapt_difficulty]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
assessment_task = Task(
|
||||
name="assess_level",
|
||||
description="Assess student's current level",
|
||||
expected_output="Student's proficiency level",
|
||||
agent=assessor,
|
||||
is_start=True,
|
||||
next_tasks=["generate_content"]
|
||||
)
|
||||
|
||||
generation_task = Task(
|
||||
name="generate_content",
|
||||
description="Generate appropriate content",
|
||||
expected_output="Learning content",
|
||||
agent=generator,
|
||||
next_tasks=["evaluate_performance"]
|
||||
)
|
||||
|
||||
evaluation_task = Task(
|
||||
name="evaluate_performance",
|
||||
description="Evaluate student's performance",
|
||||
expected_output="Performance assessment",
|
||||
agent=evaluator,
|
||||
next_tasks=["adapt_difficulty"]
|
||||
)
|
||||
|
||||
adaptation_task = Task(
|
||||
name="adapt_difficulty",
|
||||
description="Adapt content difficulty",
|
||||
expected_output="Difficulty adjustment",
|
||||
agent=adapter,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"decrease": ["generate_content"],
|
||||
"maintain": "",
|
||||
"increase": ["generate_content"]
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[assessor, generator, evaluator, adapter],
|
||||
tasks=[assessment_task, generation_task, evaluation_task, adaptation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Adaptive Learning Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nAdaptive Learning 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__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Run your adaptive learning system:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
</Note>
|
||||
|
||||
## Understanding Adaptive Learning
|
||||
|
||||
<Card title="What is Adaptive Learning?" icon="question">
|
||||
Adaptive learning enables:
|
||||
- Personalized learning experiences
|
||||
- Dynamic content adjustment
|
||||
- Performance-based progression
|
||||
- Continuous skill assessment
|
||||
- Intelligent difficulty scaling
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Student Assessment" icon="user-graduate">
|
||||
Evaluate student proficiency:
|
||||
- Knowledge level assessment
|
||||
- Skill gap identification
|
||||
- Learning style analysis
|
||||
</Card>
|
||||
<Card title="Content Generation" icon="book">
|
||||
Create personalized content:
|
||||
- Level-appropriate materials
|
||||
- Custom learning paths
|
||||
- Interactive exercises
|
||||
</Card>
|
||||
<Card title="Performance Tracking" icon="chart-line">
|
||||
Monitor learning progress:
|
||||
- Real-time evaluation
|
||||
- Progress tracking
|
||||
- Achievement metrics
|
||||
</Card>
|
||||
<Card title="Dynamic Adaptation" icon="sliders">
|
||||
Adjust learning experience:
|
||||
- Difficulty scaling
|
||||
- Content optimization
|
||||
- Pace adjustment
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about chaining prompts for complex workflows
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
|
||||
Explore how to optimize and evaluate solutions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -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,203 @@
|
||||
---
|
||||
title: "Code Analysis Agent"
|
||||
description: "Learn how to create AI agents for comprehensive code analysis and quality assessment."
|
||||
icon: "code-merge"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Code Analyzer]
|
||||
Analyzer --> Quality[Quality Assessment]
|
||||
Quality --> Metrics[Core Metrics]
|
||||
Metrics --> Technical[Technical Review]
|
||||
Technical --> Recommendations[Recommendations]
|
||||
Recommendations --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Quality fill:#2E8B57,color:#fff
|
||||
style Metrics fill:#2E8B57,color:#fff
|
||||
style Technical fill:#2E8B57,color:#fff
|
||||
style Recommendations fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Code Analysis?
|
||||
|
||||
Code Analysis is a systematic process of evaluating source code to assess its quality, maintainability, performance, and security. This helps developers and organizations maintain high code standards and identify areas for improvement.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quality Assessment" icon="chart-simple">
|
||||
Comprehensive evaluation of code quality with numerical scoring.
|
||||
</Card>
|
||||
<Card title="Core Metrics Analysis" icon="gauge">
|
||||
Analysis of architecture, maintainability, performance, and security.
|
||||
</Card>
|
||||
<Card title="Technical Assessment" icon="code">
|
||||
Review of tech stack, complexity, and best practices adherence.
|
||||
</Card>
|
||||
<Card title="Risk Assessment" icon="shield">
|
||||
Identification of potential risks and security vulnerabilities.
|
||||
</Card>
|
||||
<Card title="Recommendations" icon="lightbulb">
|
||||
Actionable suggestions for improvements and enhancements.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents gitingest
|
||||
```
|
||||
</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 `code_analysis.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
from gitingest import ingest
|
||||
|
||||
class CodeMetrics(BaseModel):
|
||||
category: str
|
||||
score: int
|
||||
findings: List[str]
|
||||
|
||||
class CodeAnalysisReport(BaseModel):
|
||||
overall_quality: int
|
||||
code_metrics: List[CodeMetrics]
|
||||
architecture_score: int
|
||||
maintainability_score: int
|
||||
performance_score: int
|
||||
security_score: int
|
||||
test_coverage: int
|
||||
key_strengths: List[str]
|
||||
improvement_areas: List[str]
|
||||
tech_stack: List[str]
|
||||
recommendations: List[str]
|
||||
complexity_metrics: Dict[str, int]
|
||||
best_practices: List[Dict[str, str]]
|
||||
potential_risks: List[str]
|
||||
documentation_quality: int
|
||||
|
||||
code_analyzer = Agent(
|
||||
role="Code Analysis Expert",
|
||||
goal="Provide comprehensive code evaluation and recommendations",
|
||||
backstory="""Expert code analyst specializing in architecture review,
|
||||
best practices, and technical debt assessment.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
code_analysis_task = Task(
|
||||
description="""Analyze code repository and provide structured evaluation:
|
||||
|
||||
1. Overall Quality (0-100)
|
||||
2. Core Metrics Analysis:
|
||||
- Architecture and Design
|
||||
- Code Maintainability
|
||||
- Performance Optimization
|
||||
- Security Practices
|
||||
- Test Coverage
|
||||
3. Technical Assessment:
|
||||
- Technology Stack Review
|
||||
- Code Complexity Analysis
|
||||
- Best Practices Adherence
|
||||
- Risk Assessment
|
||||
4. Recommendations:
|
||||
- Key Improvements
|
||||
- Architecture Suggestions
|
||||
- Security Enhancements""",
|
||||
expected_output="Detailed code analysis report with metrics and recommendations",
|
||||
agent=code_analyzer,
|
||||
output_pydantic=CodeAnalysisReport
|
||||
)
|
||||
|
||||
def analyze_code(code_source: str) -> CodeAnalysisReport:
|
||||
"""
|
||||
Analyze code from directory path or GitHub URL
|
||||
"""
|
||||
# Ingest code content
|
||||
summary, tree, content = ingest(code_source)
|
||||
|
||||
# Concatenate context into structured format
|
||||
context_text = f"""
|
||||
CODE REPOSITORY ANALYSIS
|
||||
=======================
|
||||
|
||||
SUMMARY
|
||||
-------
|
||||
{summary}
|
||||
|
||||
REPOSITORY STRUCTURE
|
||||
-------------------
|
||||
{tree}
|
||||
|
||||
SOURCE CODE
|
||||
-----------
|
||||
{content}
|
||||
"""
|
||||
|
||||
# Initialize and run analysis
|
||||
agents = PraisonAIAgents(
|
||||
agents=[code_analyzer],
|
||||
tasks=[code_analysis_task]
|
||||
)
|
||||
|
||||
return agents.start(context_text)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
code_source = "https://github.com/openai/openai-python/tree/main/src/openai/cli/_api/chat" # GitHub URL or local directory
|
||||
result = analyze_code(code_source)
|
||||
print(result)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding the Output
|
||||
|
||||
The code analysis generates a comprehensive report with the following components:
|
||||
|
||||
- Overall Quality Score (0-100)
|
||||
- Core Metrics Analysis
|
||||
- Architecture and Design Score
|
||||
- Code Maintainability Score
|
||||
- Performance Score
|
||||
- Security Score
|
||||
- Test Coverage Percentage
|
||||
- Technical Assessment
|
||||
- Technology Stack
|
||||
- Complexity Metrics
|
||||
- Best Practices Review
|
||||
- Risk Assessment
|
||||
- Recommendations
|
||||
- Key Improvements
|
||||
- Architecture Suggestions
|
||||
- Security Enhancements
|
||||
|
||||
## 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>
|
||||
<Card title="API Reference" icon="code" href="/api-reference">
|
||||
Explore the complete API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,207 @@
|
||||
---
|
||||
title: "Code Review"
|
||||
sidebarTitle: "Code Review"
|
||||
description: "Learn how to create AI agents for automated code review and issue resolution."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Code Analyzer]
|
||||
Analyzer --> Suggester[Fix Suggester]
|
||||
Suggester --> Applier[Fix Applier]
|
||||
Applier -->|fixed| Out[Out]
|
||||
Applier -->|manual_review| Suggester
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Suggester fill:#2E8B57,color:#fff
|
||||
style Applier fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how AI agents can automate code review, from analysis through fix suggestion and application.
|
||||
|
||||
## 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 List, Dict
|
||||
|
||||
def analyze_code_changes():
|
||||
"""Simulates code analysis"""
|
||||
issues = [
|
||||
{"type": "style", "severity": "low", "file": "main.py"},
|
||||
{"type": "security", "severity": "high", "file": "auth.py"},
|
||||
{"type": "performance", "severity": "medium", "file": "data.py"}
|
||||
]
|
||||
return issues[int(time.time()) % 3]
|
||||
|
||||
def suggest_fixes(issue: Dict):
|
||||
"""Simulates fix suggestions"""
|
||||
fixes = {
|
||||
"style": "Apply PEP 8 formatting",
|
||||
"security": "Implement input validation",
|
||||
"performance": "Use list comprehension"
|
||||
}
|
||||
return fixes.get(issue["type"], "Review manually")
|
||||
|
||||
def apply_automated_fix(fix: str):
|
||||
"""Simulates applying automated fixes"""
|
||||
success = int(time.time()) % 2 == 0
|
||||
return "fixed" if success else "manual_review"
|
||||
|
||||
# Create specialized agents
|
||||
analyzer = Agent(
|
||||
name="Code Analyzer",
|
||||
role="Code analysis",
|
||||
goal="Analyze code changes and identify issues",
|
||||
instructions="Review code changes and report issues",
|
||||
tools=[analyze_code_changes]
|
||||
)
|
||||
|
||||
fix_suggester = Agent(
|
||||
name="Fix Suggester",
|
||||
role="Solution provider",
|
||||
goal="Suggest fixes for identified issues",
|
||||
instructions="Provide appropriate fix suggestions",
|
||||
tools=[suggest_fixes]
|
||||
)
|
||||
|
||||
fix_applier = Agent(
|
||||
name="Fix Applier",
|
||||
role="Fix implementation",
|
||||
goal="Apply suggested fixes automatically when possible",
|
||||
instructions="Implement suggested fixes and report results",
|
||||
tools=[apply_automated_fix]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_code",
|
||||
description="Analyze code changes for issues",
|
||||
expected_output="Identified code issues",
|
||||
agent=analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["suggest_fixes"]
|
||||
)
|
||||
|
||||
suggestion_task = Task(
|
||||
name="suggest_fixes",
|
||||
description="Suggest fixes for identified issues",
|
||||
expected_output="Fix suggestions",
|
||||
agent=fix_suggester,
|
||||
next_tasks=["apply_fixes"]
|
||||
)
|
||||
|
||||
fix_task = Task(
|
||||
name="apply_fixes",
|
||||
description="Apply suggested fixes",
|
||||
expected_output="Fix application status",
|
||||
agent=fix_applier,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"fixed": "",
|
||||
"manual_review": ["suggest_fixes"] # Loop back for manual review
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[analyzer, fix_suggester, fix_applier],
|
||||
tasks=[analysis_task, suggestion_task, fix_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Code Review Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nCode Review 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__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
- Basic understanding of Python
|
||||
</Note>
|
||||
|
||||
## Understanding Code Review
|
||||
|
||||
<Card title="What is Code Review?" icon="question">
|
||||
Automated code review workflow enables:
|
||||
- Automated issue detection
|
||||
- Intelligent fix suggestions
|
||||
- Automated fix application
|
||||
- Manual review routing when needed
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Issue Detection" icon="magnifying-glass">
|
||||
Automatically identify code issues and their severity.
|
||||
</Card>
|
||||
<Card title="Fix Suggestions" icon="lightbulb">
|
||||
Generate appropriate fix suggestions based on issue type.
|
||||
</Card>
|
||||
<Card title="Automated Fixes" icon="wand-magic-sparkles">
|
||||
Apply fixes automatically when possible.
|
||||
</Card>
|
||||
<Card title="Manual Review" icon="user-check">
|
||||
Route complex issues for manual review.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about sequential prompt execution
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
|
||||
Explore optimization techniques
|
||||
</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,206 @@
|
||||
---
|
||||
title: Customer Service
|
||||
sidebar_title: Customer Service
|
||||
icon: "user-group"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Classifier[Query Classifier]
|
||||
Classifier --> Handler[Query Handler]
|
||||
Handler --> Evaluator[Satisfaction Evaluator]
|
||||
Evaluator --> Optimizer[Response Optimizer]
|
||||
Optimizer --> Out[Out]
|
||||
Optimizer --> Classifier
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
style Classifier fill:#2E8B57,color:#fff
|
||||
style Handler fill:#2E8B57,color:#fff
|
||||
style Evaluator fill:#2E8B57,color:#fff
|
||||
style Optimizer fill:#2E8B57,color:#fff
|
||||
```
|
||||
|
||||
Learn how to create AI agents for automated customer service and response optimization.
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
|
||||
2. Set your OpenAI API key:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
3. Create a file named `app.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
|
||||
def classify_query():
|
||||
"""Simulates query classification"""
|
||||
query_types = [
|
||||
{"type": "technical", "priority": "high", "complexity": "complex"},
|
||||
{"type": "billing", "priority": "medium", "complexity": "simple"},
|
||||
{"type": "general", "priority": "low", "complexity": "simple"}
|
||||
]
|
||||
return query_types[int(time.time()) % 3]
|
||||
|
||||
def handle_query(query: Dict):
|
||||
"""Simulates query handling"""
|
||||
responses = {
|
||||
"technical": "Technical support solution provided",
|
||||
"billing": "Billing inquiry resolved",
|
||||
"general": "General information provided"
|
||||
}
|
||||
return responses.get(query["type"], "Query forwarded to specialist")
|
||||
|
||||
def evaluate_satisfaction():
|
||||
"""Simulates satisfaction evaluation"""
|
||||
scores = ["satisfied", "neutral", "unsatisfied"]
|
||||
return scores[int(time.time()) % 3]
|
||||
|
||||
def optimize_response(satisfaction: str):
|
||||
"""Simulates response optimization"""
|
||||
optimizations = {
|
||||
"satisfied": "maintain_approach",
|
||||
"neutral": "minor_adjustments",
|
||||
"unsatisfied": "major_revision"
|
||||
}
|
||||
return optimizations.get(satisfaction, "review_process")
|
||||
|
||||
# Create specialized agents
|
||||
classifier = Agent(
|
||||
name="Query Classifier",
|
||||
role="Query Classification",
|
||||
goal="Classify incoming customer queries",
|
||||
instructions="Analyze and categorize customer queries",
|
||||
tools=[classify_query]
|
||||
)
|
||||
|
||||
handler = Agent(
|
||||
name="Query Handler",
|
||||
role="Query Resolution",
|
||||
goal="Handle customer queries appropriately",
|
||||
instructions="Provide appropriate responses to queries",
|
||||
tools=[handle_query]
|
||||
)
|
||||
|
||||
evaluator = Agent(
|
||||
name="Satisfaction Evaluator",
|
||||
role="Satisfaction Assessment",
|
||||
goal="Evaluate customer satisfaction",
|
||||
instructions="Assess response effectiveness",
|
||||
tools=[evaluate_satisfaction]
|
||||
)
|
||||
|
||||
optimizer = Agent(
|
||||
name="Response Optimizer",
|
||||
role="Service Optimization",
|
||||
goal="Optimize service based on feedback",
|
||||
instructions="Improve response strategies",
|
||||
tools=[optimize_response]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
classification_task = Task(
|
||||
name="classify_query",
|
||||
description="Classify customer query",
|
||||
expected_output="Query classification",
|
||||
agent=classifier,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": ["handle_query", "evaluate_satisfaction"],
|
||||
"medium": ["handle_query", "evaluate_satisfaction"],
|
||||
"low": ["handle_query"]
|
||||
}
|
||||
)
|
||||
|
||||
handling_task = Task(
|
||||
name="handle_query",
|
||||
description="Handle customer query",
|
||||
expected_output="Query response",
|
||||
agent=handler,
|
||||
next_tasks=["evaluate_satisfaction"]
|
||||
)
|
||||
|
||||
evaluation_task = Task(
|
||||
name="evaluate_satisfaction",
|
||||
description="Evaluate customer satisfaction",
|
||||
expected_output="Satisfaction level",
|
||||
agent=evaluator,
|
||||
next_tasks=["optimize_response"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="optimize_response",
|
||||
description="Optimize response strategy",
|
||||
expected_output="Optimization recommendations",
|
||||
agent=optimizer,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"major_revision": ["classify_query"],
|
||||
"minor_adjustments": "",
|
||||
"maintain_approach": ""
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[classifier, handler, evaluator, optimizer],
|
||||
tasks=[classification_task, handling_task, evaluation_task, optimization_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Customer Service Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nCustomer Service 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__":
|
||||
main()
|
||||
```
|
||||
|
||||
4. Run the system:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key
|
||||
</Note>
|
||||
|
||||
## Understanding Customer Service
|
||||
|
||||
The customer service workflow demonstrates how AI agents can automate and optimize customer support operations. The system uses specialized agents to classify queries, handle responses, evaluate satisfaction, and continuously improve service quality through feedback-driven optimization.
|
||||
|
||||
## Features
|
||||
|
||||
- **Query Classification**: Automatically categorizes customer inquiries based on type, priority, and complexity
|
||||
- **Intelligent Response Handling**: Provides appropriate responses based on query classification
|
||||
- **Satisfaction Evaluation**: Assesses customer satisfaction with provided solutions
|
||||
- **Response Optimization**: Continuously improves service quality through feedback analysis
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining)
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser)
|
||||
@@ -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>
|
||||
@@ -0,0 +1,241 @@
|
||||
---
|
||||
title: "Emergency Response"
|
||||
sidebarTitle: "Emergency Response"
|
||||
description: "Learn how to create AI agents for coordinated emergency response and resource management."
|
||||
icon: "truck-medical"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Router[Emergency Router]
|
||||
Router -->|critical/high| Dispatcher[Resource Dispatcher]
|
||||
Router -->|medium/low| Dispatcher
|
||||
Dispatcher --> Monitor[Response Monitor]
|
||||
Monitor -->|ongoing| Coordinator[Response Coordinator]
|
||||
Monitor -->|completed| Out[Out]
|
||||
Coordinator --> Out
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Router fill:#2E8B57,color:#fff
|
||||
style Dispatcher fill:#2E8B57,color:#fff
|
||||
style Monitor fill:#2E8B57,color:#fff
|
||||
style Coordinator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how AI agents can coordinate emergency response, from initial assessment through resource dispatch and response monitoring.
|
||||
|
||||
## 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
|
||||
|
||||
def assess_emergency(incident: Dict):
|
||||
"""Simulates emergency assessment"""
|
||||
severity_levels = ["low", "medium", "high", "critical"]
|
||||
current_time = int(time.time())
|
||||
severity = severity_levels[current_time % 4]
|
||||
print(f"Incident assessed with {severity} severity")
|
||||
return severity
|
||||
|
||||
def dispatch_resources(severity: str):
|
||||
"""Simulates resource dispatch"""
|
||||
resources = {
|
||||
"low": ["local_police"],
|
||||
"medium": ["local_police", "ambulance"],
|
||||
"high": ["local_police", "ambulance", "fire"],
|
||||
"critical": ["local_police", "ambulance", "fire", "special_units"]
|
||||
}
|
||||
dispatched = resources.get(severity, ["local_police"])
|
||||
print(f"Dispatching resources: {dispatched}")
|
||||
return dispatched
|
||||
|
||||
def monitor_response():
|
||||
"""Simulates response monitoring"""
|
||||
current_time = int(time.time())
|
||||
status = "completed" if current_time % 3 == 0 else "ongoing"
|
||||
return status
|
||||
|
||||
# Create specialized agents
|
||||
router = Agent(
|
||||
name="Emergency Router",
|
||||
role="Emergency Assessment",
|
||||
goal="Evaluate emergency severity and type",
|
||||
instructions="Assess incident and determine required response",
|
||||
tools=[assess_emergency]
|
||||
)
|
||||
|
||||
dispatcher = Agent(
|
||||
name="Resource Dispatcher",
|
||||
role="Resource Management",
|
||||
goal="Coordinate and dispatch appropriate resources",
|
||||
instructions="Deploy resources based on emergency assessment",
|
||||
tools=[dispatch_resources]
|
||||
)
|
||||
|
||||
monitor = Agent(
|
||||
name="Response Monitor",
|
||||
role="Response Tracking",
|
||||
goal="Track response progress and effectiveness",
|
||||
instructions="Monitor ongoing response and provide status updates",
|
||||
tools=[monitor_response]
|
||||
)
|
||||
|
||||
synthesizer = Agent(
|
||||
name="Response Coordinator",
|
||||
role="Response Synthesis",
|
||||
goal="Coordinate multi-agency response",
|
||||
instructions="Synthesize information and coordinate overall response"
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
assessment_task = Task(
|
||||
name="assess_emergency",
|
||||
description="Evaluate emergency severity and type",
|
||||
expected_output="Emergency severity level",
|
||||
agent=router,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"critical": ["dispatch_resources", "monitor_response"],
|
||||
"high": ["dispatch_resources", "monitor_response"],
|
||||
"medium": ["dispatch_resources"],
|
||||
"low": ["dispatch_resources"]
|
||||
}
|
||||
)
|
||||
|
||||
dispatch_task = Task(
|
||||
name="dispatch_resources",
|
||||
description="Deploy appropriate emergency resources",
|
||||
expected_output="List of dispatched resources",
|
||||
agent=dispatcher,
|
||||
next_tasks=["monitor_response"]
|
||||
)
|
||||
|
||||
monitor_task = Task(
|
||||
name="monitor_response",
|
||||
description="Track response progress",
|
||||
expected_output="Response status",
|
||||
agent=monitor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"ongoing": ["coordinate_response"],
|
||||
"completed": ""
|
||||
}
|
||||
)
|
||||
|
||||
coordinate_task = Task(
|
||||
name="coordinate_response",
|
||||
description="Coordinate overall emergency response",
|
||||
expected_output="Coordinated response plan",
|
||||
agent=synthesizer,
|
||||
context=[assessment_task, dispatch_task, monitor_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[router, dispatcher, monitor, synthesizer],
|
||||
tasks=[assessment_task, dispatch_task, monitor_task, coordinate_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
# Simulate emergency incident
|
||||
incident = {
|
||||
"type": "fire",
|
||||
"location": "123 Main St",
|
||||
"reported_time": time.time()
|
||||
}
|
||||
|
||||
print("\nStarting Emergency Response Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start(initial_input=incident)
|
||||
|
||||
# Print results
|
||||
print("\nEmergency Response 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__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
- Basic understanding of Python
|
||||
</Note>
|
||||
|
||||
## Understanding Emergency Response
|
||||
|
||||
<Card title="What is Emergency Response?" icon="question">
|
||||
Emergency response workflow enables:
|
||||
- Dynamic severity assessment
|
||||
- Automated resource dispatch
|
||||
- Real-time response monitoring
|
||||
- Multi-agency coordination
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Severity Assessment" icon="gauge-high">
|
||||
Automatically evaluate incident severity and type.
|
||||
</Card>
|
||||
<Card title="Resource Management" icon="truck">
|
||||
Dispatch appropriate resources based on severity.
|
||||
</Card>
|
||||
<Card title="Response Monitoring" icon="eye">
|
||||
Track response progress and effectiveness.
|
||||
</Card>
|
||||
<Card title="Response Coordination" icon="people-group">
|
||||
Coordinate multi-agency response efforts.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about sequential prompt execution
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
|
||||
Explore optimization techniques
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,189 @@
|
||||
---
|
||||
title: "Examples"
|
||||
sidebarTitle: "Examples"
|
||||
description: "Explore real-world examples and use cases built with PraisonAI Agents."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Predictive Maintenance"
|
||||
icon="wrench"
|
||||
href="/examples/predictive-maintenance"
|
||||
>
|
||||
Learn how to create AI agents for predictive maintenance and equipment monitoring.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Emergency Response"
|
||||
icon="truck-medical"
|
||||
href="/examples/emergency-response"
|
||||
>
|
||||
Learn how to create AI agents for coordinated emergency response and resource management.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Code Review"
|
||||
icon="code"
|
||||
href="/examples/code-review"
|
||||
>
|
||||
Learn how to create AI agents for automated code review and issue resolution.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Adaptive Learning"
|
||||
icon="graduation-cap"
|
||||
href="/examples/adaptive-learning"
|
||||
>
|
||||
Learn how to create AI agents for personalized adaptive learning experiences.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Supply Chain"
|
||||
icon="truck"
|
||||
href="/examples/supply-chain"
|
||||
>
|
||||
Learn how to create AI agents for supply chain risk management and mitigation.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Customer Service"
|
||||
icon="headset"
|
||||
href="/examples/customer-service"
|
||||
>
|
||||
Learn how to create AI agents for automated customer service and support.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Fraud Detection"
|
||||
icon="shield-check"
|
||||
href="/examples/fraud-detection"
|
||||
>
|
||||
Learn how to create AI agents for real-time fraud detection and alert management.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Healthcare Diagnosis"
|
||||
icon="stethoscope"
|
||||
href="/examples/healthcare-diagnosis"
|
||||
>
|
||||
Learn how to create AI agents for medical diagnosis and treatment recommendations.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Smart City"
|
||||
icon="city"
|
||||
href="/examples/smart-city"
|
||||
>
|
||||
Learn how to create AI agents for smart city resource optimization and management.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Multilingual Content"
|
||||
icon="language"
|
||||
href="/examples/multilingual-content"
|
||||
>
|
||||
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?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Features"
|
||||
icon="stars"
|
||||
href="/features/promptchaining"
|
||||
>
|
||||
Explore advanced features like prompt chaining and parallel execution
|
||||
</Card>
|
||||
<Card
|
||||
title="API Reference"
|
||||
icon="code"
|
||||
href="/api-reference"
|
||||
>
|
||||
View the complete API reference documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,237 @@
|
||||
---
|
||||
title: "Fraud Detection"
|
||||
sidebarTitle: "Fraud Detection"
|
||||
description: "Learn how to create AI agents for real-time fraud detection and alert management."
|
||||
icon: "shield-check"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Transaction Analyzer]
|
||||
Analyzer -->|high risk| Verifier[Identity Verifier]
|
||||
Analyzer -->|all risks| Checker[Pattern Checker]
|
||||
Checker --> Generator[Alert Generator]
|
||||
Verifier --> Generator
|
||||
Generator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Verifier fill:#2E8B57,color:#fff
|
||||
style Checker fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how AI agents can detect fraud in real-time, from transaction analysis through alert generation.
|
||||
|
||||
## 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_transaction():
|
||||
"""Simulates transaction analysis"""
|
||||
transactions = [
|
||||
{"type": "credit_card", "amount": 5000, "location": "foreign", "risk": "high"},
|
||||
{"type": "wire", "amount": 2000, "location": "domestic", "risk": "medium"},
|
||||
{"type": "online", "amount": 500, "location": "domestic", "risk": "low"}
|
||||
]
|
||||
return transactions[int(time.time()) % 3]
|
||||
|
||||
def check_patterns(transaction: Dict):
|
||||
"""Simulates pattern checking"""
|
||||
patterns = {
|
||||
"high": ["unusual_location", "large_amount"],
|
||||
"medium": ["frequency_anomaly"],
|
||||
"low": ["within_normal_limits"]
|
||||
}
|
||||
return patterns.get(transaction["risk"], ["unknown"])
|
||||
|
||||
def verify_identity():
|
||||
"""Simulates identity verification"""
|
||||
results = ["verified", "suspicious", "failed"]
|
||||
return results[int(time.time()) % 3]
|
||||
|
||||
def generate_alert(verification: str, patterns: List[str]):
|
||||
"""Simulates alert generation"""
|
||||
if verification == "failed" or "unusual_location" in patterns:
|
||||
return "high_priority_alert"
|
||||
elif verification == "suspicious":
|
||||
return "medium_priority_alert"
|
||||
return "low_priority_alert"
|
||||
|
||||
# Create specialized agents
|
||||
transaction_analyzer = Agent(
|
||||
name="Transaction Analyzer",
|
||||
role="Transaction Analysis",
|
||||
goal="Analyze transactions for suspicious patterns",
|
||||
instructions="Monitor and analyze financial transactions",
|
||||
tools=[analyze_transaction]
|
||||
)
|
||||
|
||||
pattern_checker = Agent(
|
||||
name="Pattern Checker",
|
||||
role="Pattern Detection",
|
||||
goal="Identify suspicious patterns",
|
||||
instructions="Check for known fraud patterns",
|
||||
tools=[check_patterns]
|
||||
)
|
||||
|
||||
identity_verifier = Agent(
|
||||
name="Identity Verifier",
|
||||
role="Identity Verification",
|
||||
goal="Verify transaction identities",
|
||||
instructions="Perform identity verification checks",
|
||||
tools=[verify_identity]
|
||||
)
|
||||
|
||||
alert_generator = Agent(
|
||||
name="Alert Generator",
|
||||
role="Alert Management",
|
||||
goal="Generate appropriate alerts",
|
||||
instructions="Create and prioritize alerts",
|
||||
tools=[generate_alert]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_transaction",
|
||||
description="Analyze transaction details",
|
||||
expected_output="Transaction analysis",
|
||||
agent=transaction_analyzer,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": ["check_patterns", "verify_identity"],
|
||||
"medium": ["check_patterns"],
|
||||
"low": ["check_patterns"]
|
||||
}
|
||||
)
|
||||
|
||||
pattern_task = Task(
|
||||
name="check_patterns",
|
||||
description="Check for suspicious patterns",
|
||||
expected_output="Identified patterns",
|
||||
agent=pattern_checker,
|
||||
next_tasks=["generate_alert"],
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
verification_task = Task(
|
||||
name="verify_identity",
|
||||
description="Verify transaction identity",
|
||||
expected_output="Verification result",
|
||||
agent=identity_verifier,
|
||||
next_tasks=["generate_alert"],
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
alert_task = Task(
|
||||
name="generate_alert",
|
||||
description="Generate fraud alert",
|
||||
expected_output="Alert priority",
|
||||
agent=alert_generator,
|
||||
context=[pattern_task, verification_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[transaction_analyzer, pattern_checker, identity_verifier, alert_generator],
|
||||
tasks=[analysis_task, pattern_task, verification_task, alert_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Fraud Detection Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nFraud 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>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
- Basic understanding of Python
|
||||
</Note>
|
||||
|
||||
## Understanding Fraud Detection
|
||||
|
||||
<Card title="What is Fraud Detection?" icon="question">
|
||||
Automated fraud detection workflow enables:
|
||||
- Real-time transaction monitoring
|
||||
- Pattern-based detection
|
||||
- Identity verification
|
||||
- Prioritized alert generation
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Transaction Analysis" icon="magnifying-glass">
|
||||
Analyze transactions for risk levels and suspicious patterns.
|
||||
</Card>
|
||||
<Card title="Pattern Detection" icon="chart-line">
|
||||
Identify known fraud patterns and anomalies.
|
||||
</Card>
|
||||
<Card title="Identity Verification" icon="user-check">
|
||||
Verify transaction identities for high-risk cases.
|
||||
</Card>
|
||||
<Card title="Alert Management" icon="bell">
|
||||
Generate and prioritize fraud alerts.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about sequential prompt execution
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
|
||||
Explore optimization techniques
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,265 @@
|
||||
---
|
||||
title: "Hackathon Judge Agent"
|
||||
description: "Learn how to create AI agents for evaluating hackathon projects through video demonstrations."
|
||||
icon: "trophy"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Judge[Hackathon Judge]
|
||||
Judge --> Scores[Project Scores]
|
||||
Scores --> Analysis[Detailed Analysis]
|
||||
Analysis --> Feedback[Feedback]
|
||||
Feedback --> Recommendations[Recommendations]
|
||||
Recommendations --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Judge fill:#2E8B57,color:#fff
|
||||
style Scores fill:#2E8B57,color:#fff
|
||||
style Analysis fill:#2E8B57,color:#fff
|
||||
style Feedback fill:#2E8B57,color:#fff
|
||||
style Recommendations fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Hackathon Project Evaluation?
|
||||
|
||||
Hackathon Project Evaluation is an automated process for assessing hackathon projects through video demonstrations. It provides comprehensive scoring across multiple dimensions including innovation, technical complexity, and presentation quality, helping organizers make informed decisions and providing valuable feedback to participants.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Project Scoring" icon="star">
|
||||
Comprehensive scoring system across multiple dimensions (0-100).
|
||||
</Card>
|
||||
<Card title="Technical Analysis" icon="microchip">
|
||||
Evaluation of technical complexity and implementation quality.
|
||||
</Card>
|
||||
<Card title="Innovation Assessment" icon="lightbulb">
|
||||
Analysis of creativity and unique project features.
|
||||
</Card>
|
||||
<Card title="Market Analysis" icon="chart-line">
|
||||
Assessment of market potential and scalability.
|
||||
</Card>
|
||||
<Card title="Detailed Feedback" icon="comments">
|
||||
Constructive feedback and specific recommendations for improvement.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents opencv-python moviepy
|
||||
```
|
||||
</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 `hackathon_judge.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
import os
|
||||
import json
|
||||
|
||||
class ProjectEvaluation(BaseModel):
|
||||
innovation_score: int # 0-100
|
||||
technical_complexity: int # 0-100
|
||||
presentation_quality: int # 0-100
|
||||
user_experience: int # 0-100
|
||||
completeness: int # 0-100
|
||||
overall_score: int # 0-100
|
||||
key_strengths: List[str]
|
||||
areas_for_improvement: List[str]
|
||||
notable_features: List[str]
|
||||
technical_highlights: List[str]
|
||||
recommendations: List[str]
|
||||
market_potential: str
|
||||
scalability_assessment: str
|
||||
|
||||
# Create Vision Analysis Agent
|
||||
hackathon_judge = Agent(
|
||||
name="HackathonJudge",
|
||||
role="Technical Project Evaluator",
|
||||
goal="Evaluate hackathon projects through video demonstrations",
|
||||
backstory="""You are an experienced hackathon judge and technical expert.
|
||||
You excel at evaluating innovation, technical implementation, and presentation quality.
|
||||
You provide constructive feedback and identify both strengths and areas for improvement.""",
|
||||
llm="gpt-4o-mini", # Using vision-capable model
|
||||
self_reflect=False,
|
||||
knowledge=""
|
||||
)
|
||||
|
||||
def evaluate_project(video_path: str) -> ProjectEvaluation:
|
||||
"""
|
||||
Evaluate a hackathon project based on its video demonstration
|
||||
"""
|
||||
evaluation_task = Task(
|
||||
name="project_evaluation",
|
||||
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
|
||||
|
||||
1. Score the following aspects (0-100):
|
||||
- Innovation and Creativity
|
||||
- Technical Complexity
|
||||
- Presentation Quality
|
||||
- User Experience
|
||||
- Project Completeness
|
||||
|
||||
2. Identify:
|
||||
- Key strengths and standout features
|
||||
- Areas that could be improved
|
||||
- Notable technical implementations
|
||||
- Market potential and scalability
|
||||
|
||||
3. Provide:
|
||||
- Specific recommendations for improvement
|
||||
- Technical suggestions
|
||||
- Potential future enhancements""",
|
||||
expected_output="Detailed project evaluation with scores and feedback",
|
||||
agent=hackathon_judge,
|
||||
output_pydantic=ProjectEvaluation,
|
||||
images=[video_path] # Video input for multimodal analysis
|
||||
)
|
||||
|
||||
# Initialize and run evaluation
|
||||
agents = PraisonAIAgents(
|
||||
agents=[hackathon_judge],
|
||||
tasks=[evaluation_task],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
response = agents.start()
|
||||
|
||||
try:
|
||||
# If response contains task_results, extract the Pydantic model directly
|
||||
if isinstance(response, dict) and 'task_results' in response:
|
||||
task_output = response['task_results'][0]
|
||||
if hasattr(task_output, 'pydantic'):
|
||||
return task_output.pydantic
|
||||
elif hasattr(task_output, 'raw'):
|
||||
# Extract JSON from raw string if it's wrapped in ```json
|
||||
raw_text = task_output.raw
|
||||
if raw_text.startswith('```json'):
|
||||
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
|
||||
evaluation_data = json.loads(raw_text)
|
||||
else:
|
||||
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
|
||||
# If response is a string, try to parse it as JSON
|
||||
elif isinstance(response, str):
|
||||
evaluation_data = json.loads(response)
|
||||
# If response is a dict with task_status
|
||||
elif isinstance(response, dict) and 'task_status' in response:
|
||||
content = response['task_status']
|
||||
if isinstance(content, dict):
|
||||
evaluation_data = content
|
||||
else:
|
||||
evaluation_data = json.loads(content) if isinstance(content, str) else content
|
||||
else:
|
||||
evaluation_data = response
|
||||
|
||||
print(f"Debug - Parsed evaluation_data: {evaluation_data}")
|
||||
|
||||
# Create and return ProjectEvaluation instance
|
||||
return ProjectEvaluation(
|
||||
innovation_score=int(evaluation_data.get('innovation_score', 0)),
|
||||
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
|
||||
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
|
||||
user_experience=int(evaluation_data.get('user_experience', 0)),
|
||||
completeness=int(evaluation_data.get('completeness', 0)),
|
||||
overall_score=int(evaluation_data.get('overall_score', 0)),
|
||||
key_strengths=evaluation_data.get('key_strengths', []),
|
||||
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
|
||||
notable_features=evaluation_data.get('notable_features', []),
|
||||
technical_highlights=evaluation_data.get('technical_highlights', []),
|
||||
recommendations=evaluation_data.get('recommendations', []),
|
||||
market_potential=str(evaluation_data.get('market_potential', '')),
|
||||
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Debug - Raw response: {response}")
|
||||
print(f"Error processing response: {e}")
|
||||
raise
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
video_path = os.path.join(current_dir, "presentation.mp4")
|
||||
result = evaluate_project(video_path) # Now returns ProjectEvaluation directly
|
||||
|
||||
print("\nHackathon Project Evaluation")
|
||||
print("===========================")
|
||||
print(f"\nOverall Score: {result.overall_score}/100")
|
||||
print("\nDetailed Scores:")
|
||||
print(f"Innovation: {result.innovation_score}/100")
|
||||
print(f"Technical Complexity: {result.technical_complexity}/100")
|
||||
print(f"Presentation: {result.presentation_quality}/100")
|
||||
print(f"User Experience: {result.user_experience}/100")
|
||||
print(f"Completeness: {result.completeness}/100")
|
||||
|
||||
print("\nKey Strengths:")
|
||||
for strength in result.key_strengths:
|
||||
print(f"- {strength}")
|
||||
|
||||
print("\nAreas for Improvement:")
|
||||
for area in result.areas_for_improvement:
|
||||
print(f"- {area}")
|
||||
|
||||
print("\nTechnical Highlights:")
|
||||
for highlight in result.technical_highlights:
|
||||
print(f"- {highlight}")
|
||||
|
||||
print("\nRecommendations:")
|
||||
for rec in result.recommendations:
|
||||
print(f"- {rec}")
|
||||
|
||||
print(f"\nMarket Potential: {result.market_potential}")
|
||||
print(f"\nScalability Assessment: {result.scalability_assessment}")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding the Output
|
||||
|
||||
The hackathon project evaluation generates a comprehensive report with the following components:
|
||||
|
||||
- Scoring Metrics (0-100)
|
||||
- Innovation Score
|
||||
- Technical Complexity
|
||||
- Presentation Quality
|
||||
- User Experience
|
||||
- Project Completeness
|
||||
- Overall Score
|
||||
- Qualitative Analysis
|
||||
- Key Strengths
|
||||
- Areas for Improvement
|
||||
- Notable Features
|
||||
- Technical Highlights
|
||||
- Strategic Assessment
|
||||
- Recommendations
|
||||
- Market Potential
|
||||
- Scalability Assessment
|
||||
|
||||
## 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>
|
||||
<Card title="API Reference" icon="code" href="/api-reference">
|
||||
Explore the complete API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,278 @@
|
||||
---
|
||||
title: "Healthcare Diagnosis"
|
||||
description: "Learn how to create AI agents for automated medical diagnosis and treatment recommendations."
|
||||
icon: "stethoscope"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Symptoms[Symptom Analyzer]
|
||||
Symptoms --> Labs[Lab Processor]
|
||||
Symptoms --> History[History Analyzer]
|
||||
Labs --> Diagnosis[Diagnosis Generator]
|
||||
History --> Diagnosis
|
||||
Diagnosis --> Treatment[Treatment Recommender]
|
||||
Treatment --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Symptoms fill:#2E8B57,color:#fff
|
||||
style Labs fill:#2E8B57,color:#fff
|
||||
style History fill:#2E8B57,color:#fff
|
||||
style Diagnosis fill:#2E8B57,color:#fff
|
||||
style Treatment fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Learn how to implement an automated healthcare diagnosis system using AI agents for symptom analysis, lab processing, and treatment recommendations.
|
||||
|
||||
## 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
|
||||
|
||||
def analyze_symptoms():
|
||||
"""Simulates symptom analysis"""
|
||||
cases = [
|
||||
{"symptoms": ["fever", "cough", "fatigue"], "severity": "high", "duration": "5_days"},
|
||||
{"symptoms": ["headache", "nausea"], "severity": "medium", "duration": "2_days"},
|
||||
{"symptoms": ["rash", "itching"], "severity": "low", "duration": "1_week"}
|
||||
]
|
||||
return cases[int(time.time()) % 3]
|
||||
|
||||
def process_lab_results():
|
||||
"""Simulates lab result processing"""
|
||||
results = [
|
||||
{"blood_count": "abnormal", "inflammation": "high", "markers": "elevated"},
|
||||
{"blood_count": "normal", "inflammation": "low", "markers": "normal"},
|
||||
{"blood_count": "normal", "inflammation": "medium", "markers": "elevated"}
|
||||
]
|
||||
return results[int(time.time()) % 3]
|
||||
|
||||
def analyze_medical_history():
|
||||
"""Simulates medical history analysis"""
|
||||
histories = [
|
||||
{"chronic_conditions": True, "allergies": True, "risk_factors": "high"},
|
||||
{"chronic_conditions": False, "allergies": True, "risk_factors": "medium"},
|
||||
{"chronic_conditions": False, "allergies": False, "risk_factors": "low"}
|
||||
]
|
||||
return histories[int(time.time()) % 3]
|
||||
|
||||
def generate_diagnosis(symptoms: Dict, lab_results: Dict, history: Dict):
|
||||
"""Simulates diagnosis generation"""
|
||||
if symptoms["severity"] == "high" and lab_results["markers"] == "elevated":
|
||||
return {"diagnosis": "serious_condition", "confidence": "high"}
|
||||
elif symptoms["severity"] == "medium" or lab_results["inflammation"] == "medium":
|
||||
return {"diagnosis": "moderate_condition", "confidence": "medium"}
|
||||
return {"diagnosis": "mild_condition", "confidence": "high"}
|
||||
|
||||
def recommend_treatment(diagnosis: Dict):
|
||||
"""Simulates treatment recommendation"""
|
||||
treatments = {
|
||||
"serious_condition": ["immediate_intervention", "specialist_referral"],
|
||||
"moderate_condition": ["medication", "follow_up"],
|
||||
"mild_condition": ["rest", "observation"]
|
||||
}
|
||||
return treatments.get(diagnosis["diagnosis"], ["general_care"])
|
||||
|
||||
# Create specialized agents
|
||||
symptom_analyzer = Agent(
|
||||
name="Symptom Analyzer",
|
||||
role="Symptom Analysis",
|
||||
goal="Analyze patient symptoms",
|
||||
instructions="Evaluate reported symptoms and their severity",
|
||||
tools=[analyze_symptoms]
|
||||
)
|
||||
|
||||
lab_processor = Agent(
|
||||
name="Lab Processor",
|
||||
role="Lab Analysis",
|
||||
goal="Process laboratory results",
|
||||
instructions="Analyze and interpret lab test results",
|
||||
tools=[process_lab_results]
|
||||
)
|
||||
|
||||
history_analyzer = Agent(
|
||||
name="History Analyzer",
|
||||
role="Medical History Analysis",
|
||||
goal="Analyze patient medical history",
|
||||
instructions="Review and assess patient medical history",
|
||||
tools=[analyze_medical_history]
|
||||
)
|
||||
|
||||
diagnosis_generator = Agent(
|
||||
name="Diagnosis Generator",
|
||||
role="Diagnosis Generation",
|
||||
goal="Generate comprehensive diagnosis",
|
||||
instructions="Combine all inputs to generate diagnosis",
|
||||
tools=[generate_diagnosis]
|
||||
)
|
||||
|
||||
treatment_recommender = Agent(
|
||||
name="Treatment Recommender",
|
||||
role="Treatment Planning",
|
||||
goal="Recommend appropriate treatment",
|
||||
instructions="Suggest treatment based on diagnosis",
|
||||
tools=[recommend_treatment]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
symptom_task = Task(
|
||||
name="analyze_symptoms",
|
||||
description="Analyze patient symptoms",
|
||||
expected_output="Symptom analysis",
|
||||
agent=symptom_analyzer,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": ["process_labs", "analyze_history"],
|
||||
"medium": ["process_labs", "analyze_history"],
|
||||
"low": ["process_labs"]
|
||||
}
|
||||
)
|
||||
|
||||
lab_task = Task(
|
||||
name="process_labs",
|
||||
description="Process lab results",
|
||||
expected_output="Lab analysis",
|
||||
agent=lab_processor,
|
||||
next_tasks=["generate_diagnosis"]
|
||||
)
|
||||
|
||||
history_task = Task(
|
||||
name="analyze_history",
|
||||
description="Analyze medical history",
|
||||
expected_output="History analysis",
|
||||
agent=history_analyzer,
|
||||
next_tasks=["generate_diagnosis"]
|
||||
)
|
||||
|
||||
diagnosis_task = Task(
|
||||
name="generate_diagnosis",
|
||||
description="Generate diagnosis",
|
||||
expected_output="Diagnosis and confidence level",
|
||||
agent=diagnosis_generator,
|
||||
next_tasks=["recommend_treatment"],
|
||||
context=[symptom_task, lab_task, history_task]
|
||||
)
|
||||
|
||||
treatment_task = Task(
|
||||
name="recommend_treatment",
|
||||
description="Recommend treatment",
|
||||
expected_output="Treatment recommendations",
|
||||
agent=treatment_recommender,
|
||||
context=[diagnosis_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[symptom_analyzer, lab_processor, history_analyzer,
|
||||
diagnosis_generator, treatment_recommender],
|
||||
tasks=[symptom_task, lab_task, history_task, diagnosis_task, treatment_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Healthcare Diagnosis Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nDiagnosis 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__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Run your healthcare diagnosis system:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
</Note>
|
||||
|
||||
## Understanding Healthcare Diagnosis
|
||||
|
||||
<Card title="What is Healthcare Diagnosis?" icon="question">
|
||||
Healthcare diagnosis enables:
|
||||
- Automated symptom analysis
|
||||
- Lab result processing
|
||||
- Medical history review
|
||||
- Diagnosis generation
|
||||
- Treatment recommendations
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Symptom Analysis" icon="stethoscope">
|
||||
Analyze patient symptoms:
|
||||
- Severity assessment
|
||||
- Duration tracking
|
||||
- Pattern recognition
|
||||
</Card>
|
||||
<Card title="Lab Processing" icon="flask">
|
||||
Process medical tests:
|
||||
- Blood count analysis
|
||||
- Inflammation markers
|
||||
- Test result interpretation
|
||||
</Card>
|
||||
<Card title="History Analysis" icon="book-medical">
|
||||
Review medical history:
|
||||
- Chronic conditions
|
||||
- Allergies
|
||||
- Risk factors
|
||||
</Card>
|
||||
<Card title="Treatment Planning" icon="prescription">
|
||||
Generate treatment plans:
|
||||
- Immediate interventions
|
||||
- Medication recommendations
|
||||
- Follow-up scheduling
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about chaining prompts for complex workflows
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
|
||||
Explore how to optimize and evaluate solutions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -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,276 @@
|
||||
---
|
||||
title: "Multilingual Content"
|
||||
description: "Learn how to create AI agents for multilingual content generation and cultural adaptation."
|
||||
icon: "language"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Generator[Content Generator]
|
||||
Generator --> Translator[Content Translator]
|
||||
Translator --> Cultural[Cultural Checker]
|
||||
Cultural --> Adapter[Content Adapter]
|
||||
Adapter --> Quality[Quality Assessor]
|
||||
Quality --> Out[Out]
|
||||
Quality --> Adapter
|
||||
Quality --> Translator
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Translator fill:#2E8B57,color:#fff
|
||||
style Cultural fill:#2E8B57,color:#fff
|
||||
style Adapter fill:#2E8B57,color:#fff
|
||||
style Quality fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Learn how to implement a multilingual content generation system using AI agents for content creation, translation, cultural adaptation, and quality assurance.
|
||||
|
||||
## 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
|
||||
|
||||
def generate_base_content():
|
||||
"""Simulates base content generation"""
|
||||
content_types = [
|
||||
{"type": "marketing", "tone": "professional", "length": "medium"},
|
||||
{"type": "technical", "tone": "formal", "length": "long"},
|
||||
{"type": "social", "tone": "casual", "length": "short"}
|
||||
]
|
||||
return content_types[int(time.time()) % 3]
|
||||
|
||||
def translate_content(content: Dict):
|
||||
"""Simulates content translation"""
|
||||
languages = ["spanish", "french", "german", "japanese", "chinese"]
|
||||
translations = {lang: f"Translated content in {lang}" for lang in languages}
|
||||
return translations
|
||||
|
||||
def check_cultural_context(translations: Dict):
|
||||
"""Simulates cultural context verification"""
|
||||
cultural_issues = {
|
||||
"spanish": [],
|
||||
"french": ["idiom_mismatch"],
|
||||
"german": [],
|
||||
"japanese": ["formality_level"],
|
||||
"chinese": ["cultural_reference"]
|
||||
}
|
||||
return cultural_issues
|
||||
|
||||
def adapt_content(issues: Dict):
|
||||
"""Simulates content adaptation"""
|
||||
adaptations = {
|
||||
"idiom_mismatch": "localized_expression",
|
||||
"formality_level": "adjusted_tone",
|
||||
"cultural_reference": "localized_reference"
|
||||
}
|
||||
return {lang: [adaptations[issue] for issue in issues]
|
||||
for lang, issues in issues.items() if issues}
|
||||
|
||||
def quality_check():
|
||||
"""Simulates quality assessment"""
|
||||
quality_levels = ["high", "medium", "needs_revision"]
|
||||
return quality_levels[int(time.time()) % 3]
|
||||
|
||||
# Create specialized agents
|
||||
content_generator = Agent(
|
||||
name="Content Generator",
|
||||
role="Base Content Creation",
|
||||
goal="Generate high-quality base content",
|
||||
instructions="Create engaging base content",
|
||||
tools=[generate_base_content]
|
||||
)
|
||||
|
||||
translator = Agent(
|
||||
name="Content Translator",
|
||||
role="Translation",
|
||||
goal="Translate content accurately",
|
||||
instructions="Translate content while maintaining meaning",
|
||||
tools=[translate_content]
|
||||
)
|
||||
|
||||
cultural_checker = Agent(
|
||||
name="Cultural Checker",
|
||||
role="Cultural Verification",
|
||||
goal="Verify cultural appropriateness",
|
||||
instructions="Check for cultural sensitivities",
|
||||
tools=[check_cultural_context]
|
||||
)
|
||||
|
||||
content_adapter = Agent(
|
||||
name="Content Adapter",
|
||||
role="Content Adaptation",
|
||||
goal="Adapt content for cultural fit",
|
||||
instructions="Modify content based on cultural context",
|
||||
tools=[adapt_content]
|
||||
)
|
||||
|
||||
quality_assessor = Agent(
|
||||
name="Quality Assessor",
|
||||
role="Quality Assessment",
|
||||
goal="Ensure content quality",
|
||||
instructions="Assess overall content quality",
|
||||
tools=[quality_check]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
generation_task = Task(
|
||||
name="generate_content",
|
||||
description="Generate base content",
|
||||
expected_output="Base content for translation",
|
||||
agent=content_generator,
|
||||
is_start=True,
|
||||
next_tasks=["translate_content"]
|
||||
)
|
||||
|
||||
translation_task = Task(
|
||||
name="translate_content",
|
||||
description="Translate content to target languages",
|
||||
expected_output="Translated content",
|
||||
agent=translator,
|
||||
next_tasks=["check_cultural"]
|
||||
)
|
||||
|
||||
cultural_task = Task(
|
||||
name="check_cultural",
|
||||
description="Check cultural appropriateness",
|
||||
expected_output="Cultural context issues",
|
||||
agent=cultural_checker,
|
||||
next_tasks=["adapt_content"]
|
||||
)
|
||||
|
||||
adaptation_task = Task(
|
||||
name="adapt_content",
|
||||
description="Adapt content for cultural fit",
|
||||
expected_output="Culturally adapted content",
|
||||
agent=content_adapter,
|
||||
next_tasks=["assess_quality"]
|
||||
)
|
||||
|
||||
quality_task = Task(
|
||||
name="assess_quality",
|
||||
description="Assess content quality",
|
||||
expected_output="Quality assessment",
|
||||
agent=quality_assessor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": "", # Complete workflow
|
||||
"medium": ["adapt_content"], # Minor revisions needed
|
||||
"needs_revision": ["translate_content"] # Major revisions needed
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[content_generator, translator, cultural_checker,
|
||||
content_adapter, quality_assessor],
|
||||
tasks=[generation_task, translation_task, cultural_task,
|
||||
adaptation_task, quality_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Multilingual Content Generation Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nContent 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__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Run your multilingual content generation system:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
</Note>
|
||||
|
||||
## Understanding Multilingual Content Generation
|
||||
|
||||
<Card title="What is Multilingual Content Generation?" icon="question">
|
||||
Multilingual content generation enables:
|
||||
- Base content creation
|
||||
- Accurate translation
|
||||
- Cultural context verification
|
||||
- Content adaptation
|
||||
- Quality assurance
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Content Generation" icon="pen">
|
||||
Generate base content:
|
||||
- Marketing content
|
||||
- Technical documentation
|
||||
- Social media posts
|
||||
</Card>
|
||||
<Card title="Translation" icon="language">
|
||||
Translate content:
|
||||
- Multiple languages
|
||||
- Meaning preservation
|
||||
- Context awareness
|
||||
</Card>
|
||||
<Card title="Cultural Adaptation" icon="globe">
|
||||
Ensure cultural fit:
|
||||
- Cultural sensitivity
|
||||
- Idiom localization
|
||||
- Reference adaptation
|
||||
</Card>
|
||||
<Card title="Quality Control" icon="check">
|
||||
Quality assurance:
|
||||
- Content assessment
|
||||
- Revision workflow
|
||||
- Continuous improvement
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about chaining prompts for complex workflows
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
|
||||
Explore how to optimize and evaluate solutions
|
||||
</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,287 @@
|
||||
---
|
||||
title: "Predictive Maintenance"
|
||||
description: "Learn how to create AI agents for predictive maintenance and equipment monitoring."
|
||||
icon: "gear"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Monitor[Sensor Monitor]
|
||||
Monitor --> Analyzer[Performance Analyzer]
|
||||
Analyzer --> Detector[Anomaly Detector]
|
||||
Detector --> Predictor[Failure Predictor]
|
||||
Predictor -->|critical| Scheduler[Maintenance Scheduler]
|
||||
Predictor -->|warning| Scheduler
|
||||
Predictor -->|normal| Out[Out]
|
||||
Scheduler --> Out
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
style Monitor fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Detector fill:#2E8B57,color:#fff
|
||||
style Predictor fill:#2E8B57,color:#fff
|
||||
style Scheduler fill:#2E8B57,color:#fff
|
||||
```
|
||||
|
||||
Learn how to implement a predictive maintenance system using AI agents for real-time equipment monitoring and maintenance scheduling.
|
||||
|
||||
## 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 `predictive_maintenance.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def collect_sensor_data():
|
||||
"""Simulates sensor data collection"""
|
||||
sensor_readings = {
|
||||
"temperature": 75 + (int(time.time()) % 20),
|
||||
"vibration": 0.5 + (int(time.time()) % 10) / 10,
|
||||
"pressure": 100 + (int(time.time()) % 50),
|
||||
"noise_level": 60 + (int(time.time()) % 30)
|
||||
}
|
||||
return sensor_readings
|
||||
|
||||
def analyze_performance():
|
||||
"""Simulates performance analysis"""
|
||||
metrics = {
|
||||
"efficiency": 0.8 + (int(time.time()) % 20) / 100,
|
||||
"uptime": 0.95 + (int(time.time()) % 5) / 100,
|
||||
"output_quality": 0.9 + (int(time.time()) % 10) / 100
|
||||
}
|
||||
return metrics
|
||||
|
||||
def detect_anomalies(sensor_data: Dict, performance: Dict):
|
||||
"""Simulates anomaly detection"""
|
||||
anomalies = []
|
||||
if sensor_data["temperature"] > 90:
|
||||
anomalies.append({"type": "temperature_high", "severity": "critical"})
|
||||
if sensor_data["vibration"] > 1.2:
|
||||
anomalies.append({"type": "vibration_excess", "severity": "warning"})
|
||||
if performance["efficiency"] < 0.85:
|
||||
anomalies.append({"type": "efficiency_low", "severity": "warning"})
|
||||
return anomalies
|
||||
|
||||
def predict_failures(anomalies: List[Dict]):
|
||||
"""Simulates failure prediction"""
|
||||
predictions = []
|
||||
severity_scores = {"critical": 0.9, "warning": 0.6}
|
||||
|
||||
for anomaly in anomalies:
|
||||
predictions.append({
|
||||
"component": anomaly["type"].split("_")[0],
|
||||
"probability": severity_scores[anomaly["severity"]],
|
||||
"timeframe": "24_hours" if anomaly["severity"] == "critical" else "7_days"
|
||||
})
|
||||
return predictions
|
||||
|
||||
def schedule_maintenance(predictions: List[Dict]):
|
||||
"""Simulates maintenance scheduling"""
|
||||
schedule = []
|
||||
for pred in predictions:
|
||||
schedule.append({
|
||||
"component": pred["component"],
|
||||
"priority": "immediate" if pred["timeframe"] == "24_hours" else "planned",
|
||||
"estimated_duration": "2_hours",
|
||||
"required_parts": ["replacement_" + pred["component"]]
|
||||
})
|
||||
return schedule
|
||||
|
||||
# Create specialized agents
|
||||
sensor_monitor = Agent(
|
||||
name="Sensor Monitor",
|
||||
role="Data Collection",
|
||||
goal="Collect sensor data",
|
||||
instructions="Monitor and collect sensor readings",
|
||||
tools=[collect_sensor_data]
|
||||
)
|
||||
|
||||
performance_analyzer = Agent(
|
||||
name="Performance Analyzer",
|
||||
role="Performance Analysis",
|
||||
goal="Analyze equipment performance",
|
||||
instructions="Analyze operational metrics",
|
||||
tools=[analyze_performance]
|
||||
)
|
||||
|
||||
anomaly_detector = Agent(
|
||||
name="Anomaly Detector",
|
||||
role="Anomaly Detection",
|
||||
goal="Detect operational anomalies",
|
||||
instructions="Identify abnormal patterns",
|
||||
tools=[detect_anomalies]
|
||||
)
|
||||
|
||||
failure_predictor = Agent(
|
||||
name="Failure Predictor",
|
||||
role="Failure Prediction",
|
||||
goal="Predict potential failures",
|
||||
instructions="Predict equipment failures",
|
||||
tools=[predict_failures]
|
||||
)
|
||||
|
||||
maintenance_scheduler = Agent(
|
||||
name="Maintenance Scheduler",
|
||||
role="Maintenance Planning",
|
||||
goal="Schedule maintenance activities",
|
||||
instructions="Plan and schedule maintenance",
|
||||
tools=[schedule_maintenance]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
sensor_task = Task(
|
||||
name="collect_data",
|
||||
description="Collect sensor data",
|
||||
expected_output="Sensor readings",
|
||||
agent=sensor_monitor,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_performance"],
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
performance_task = Task(
|
||||
name="analyze_performance",
|
||||
description="Analyze performance metrics",
|
||||
expected_output="Performance analysis",
|
||||
agent=performance_analyzer,
|
||||
next_tasks=["detect_anomalies"],
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
anomaly_task = Task(
|
||||
name="detect_anomalies",
|
||||
description="Detect operational anomalies",
|
||||
expected_output="Detected anomalies",
|
||||
agent=anomaly_detector,
|
||||
next_tasks=["predict_failures"],
|
||||
context=[sensor_task, performance_task]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_failures",
|
||||
description="Predict potential failures",
|
||||
expected_output="Failure predictions",
|
||||
agent=failure_predictor,
|
||||
next_tasks=["schedule_maintenance"],
|
||||
task_type="decision",
|
||||
condition={
|
||||
"critical": ["schedule_maintenance"],
|
||||
"warning": ["schedule_maintenance"],
|
||||
"normal": ""
|
||||
}
|
||||
)
|
||||
|
||||
scheduling_task = Task(
|
||||
name="schedule_maintenance",
|
||||
description="Schedule maintenance activities",
|
||||
expected_output="Maintenance schedule",
|
||||
agent=maintenance_scheduler,
|
||||
context=[prediction_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[sensor_monitor, performance_analyzer, anomaly_detector,
|
||||
failure_predictor, maintenance_scheduler],
|
||||
tasks=[sensor_task, performance_task, anomaly_task,
|
||||
prediction_task, scheduling_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Predictive Maintenance Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nMaintenance Planning 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>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Run your predictive maintenance system:
|
||||
```bash
|
||||
python predictive_maintenance.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
</Note>
|
||||
|
||||
## Understanding Predictive Maintenance
|
||||
|
||||
<Card title="What is Predictive Maintenance?" icon="question">
|
||||
Predictive maintenance using AI agents enables:
|
||||
- Real-time equipment monitoring
|
||||
- Performance analysis and anomaly detection
|
||||
- Failure prediction and prevention
|
||||
- Automated maintenance scheduling
|
||||
- Optimized resource allocation
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Real-time Monitoring" icon="gauge-high">
|
||||
Continuous monitoring of equipment sensors and performance metrics.
|
||||
</Card>
|
||||
<Card title="Anomaly Detection" icon="triangle-exclamation">
|
||||
Automated detection of abnormal patterns and potential issues.
|
||||
</Card>
|
||||
<Card title="Failure Prediction" icon="chart-line">
|
||||
Advanced analytics to predict potential equipment failures.
|
||||
</Card>
|
||||
<Card title="Maintenance Planning" icon="calendar">
|
||||
Automated scheduling of maintenance activities based on predictions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about sequential prompt chaining for complex workflows
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="magnifying-glass" href="/features/evaluator-optimiser">
|
||||
Explore how to optimize agent outputs through evaluation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure your sensor data collection and analysis parameters are properly configured for your specific equipment.
|
||||
</Note>
|
||||
@@ -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,301 @@
|
||||
---
|
||||
title: "Smart City"
|
||||
description: "Learn how to create AI agents for smart city resource management and optimization."
|
||||
icon: "city"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Monitor[Utility Monitor]
|
||||
Monitor --> Analyzer[Pattern Analyzer]
|
||||
Analyzer --> Optimizer[Resource Optimizer]
|
||||
Optimizer --> Implementation[Implementation Agent]
|
||||
Implementation --> Feedback[Feedback Monitor]
|
||||
Feedback --> Monitor
|
||||
Feedback --> Optimizer
|
||||
Feedback --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Monitor fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Optimizer fill:#2E8B57,color:#fff
|
||||
style Implementation fill:#2E8B57,color:#fff
|
||||
style Feedback fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Learn how to implement a smart city resource management system using AI agents for monitoring, analysis, and optimization of city utilities.
|
||||
|
||||
## 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
|
||||
|
||||
def monitor_utilities():
|
||||
"""Simulates utility usage monitoring"""
|
||||
readings = {
|
||||
"power": {
|
||||
"consumption": int(time.time()) % 1000,
|
||||
"peak_hours": ["morning", "evening"],
|
||||
"grid_load": "medium"
|
||||
},
|
||||
"water": {
|
||||
"consumption": int(time.time()) % 500,
|
||||
"pressure": "normal",
|
||||
"quality": "good"
|
||||
},
|
||||
"traffic": {
|
||||
"congestion": "high",
|
||||
"peak_zones": ["downtown", "industrial"],
|
||||
"incidents": 2
|
||||
}
|
||||
}
|
||||
return readings
|
||||
|
||||
def analyze_patterns():
|
||||
"""Simulates usage pattern analysis"""
|
||||
patterns = [
|
||||
{"type": "daily_cycle", "confidence": 0.85, "trend": "increasing"},
|
||||
{"type": "weekly_cycle", "confidence": 0.92, "trend": "stable"},
|
||||
{"type": "seasonal", "confidence": 0.78, "trend": "decreasing"}
|
||||
]
|
||||
return patterns[int(time.time()) % 3]
|
||||
|
||||
def optimize_resources(readings: Dict, patterns: Dict):
|
||||
"""Simulates resource optimization"""
|
||||
optimizations = {
|
||||
"power": {
|
||||
"action": "load_balancing",
|
||||
"target_zones": ["residential", "commercial"],
|
||||
"expected_savings": "15%"
|
||||
},
|
||||
"water": {
|
||||
"action": "pressure_adjustment",
|
||||
"target_zones": ["industrial"],
|
||||
"expected_savings": "8%"
|
||||
},
|
||||
"traffic": {
|
||||
"action": "signal_timing",
|
||||
"target_zones": ["downtown"],
|
||||
"expected_impact": "20% reduction"
|
||||
}
|
||||
}
|
||||
return optimizations
|
||||
|
||||
def implement_changes(optimizations: Dict):
|
||||
"""Simulates implementation of optimization changes"""
|
||||
success_rates = {
|
||||
"load_balancing": 0.95,
|
||||
"pressure_adjustment": 0.88,
|
||||
"signal_timing": 0.85
|
||||
}
|
||||
return {"status": "implemented", "success_rate": success_rates[optimizations["power"]["action"]]}
|
||||
|
||||
def monitor_feedback():
|
||||
"""Simulates monitoring of optimization feedback"""
|
||||
feedbacks = ["positive", "neutral", "negative"]
|
||||
return feedbacks[int(time.time()) % 3]
|
||||
|
||||
# Create specialized agents
|
||||
utility_monitor = Agent(
|
||||
name="Utility Monitor",
|
||||
role="Resource Monitoring",
|
||||
goal="Monitor city utility usage",
|
||||
instructions="Track and report utility consumption patterns",
|
||||
tools=[monitor_utilities]
|
||||
)
|
||||
|
||||
pattern_analyzer = Agent(
|
||||
name="Pattern Analyzer",
|
||||
role="Pattern Analysis",
|
||||
goal="Analyze usage patterns",
|
||||
instructions="Identify and analyze resource usage patterns",
|
||||
tools=[analyze_patterns]
|
||||
)
|
||||
|
||||
resource_optimizer = Agent(
|
||||
name="Resource Optimizer",
|
||||
role="Resource Optimization",
|
||||
goal="Optimize resource allocation",
|
||||
instructions="Generate resource optimization strategies",
|
||||
tools=[optimize_resources]
|
||||
)
|
||||
|
||||
implementation_agent = Agent(
|
||||
name="Implementation Agent",
|
||||
role="Change Implementation",
|
||||
goal="Implement optimization changes",
|
||||
instructions="Execute optimization strategies",
|
||||
tools=[implement_changes]
|
||||
)
|
||||
|
||||
feedback_monitor = Agent(
|
||||
name="Feedback Monitor",
|
||||
role="Feedback Monitoring",
|
||||
goal="Monitor optimization results",
|
||||
instructions="Track and analyze optimization feedback",
|
||||
tools=[monitor_feedback]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
monitoring_task = Task(
|
||||
name="monitor_utilities",
|
||||
description="Monitor utility usage",
|
||||
expected_output="Current utility readings",
|
||||
agent=utility_monitor,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_patterns"]
|
||||
)
|
||||
|
||||
pattern_task = Task(
|
||||
name="analyze_patterns",
|
||||
description="Analyze usage patterns",
|
||||
expected_output="Usage patterns analysis",
|
||||
agent=pattern_analyzer,
|
||||
next_tasks=["optimize_resources"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="optimize_resources",
|
||||
description="Generate optimization strategies",
|
||||
expected_output="Resource optimization plans",
|
||||
agent=resource_optimizer,
|
||||
next_tasks=["implement_changes"],
|
||||
context=[monitoring_task, pattern_task]
|
||||
)
|
||||
|
||||
implementation_task = Task(
|
||||
name="implement_changes",
|
||||
description="Implement optimization changes",
|
||||
expected_output="Implementation status",
|
||||
agent=implementation_agent,
|
||||
next_tasks=["monitor_feedback"]
|
||||
)
|
||||
|
||||
feedback_task = Task(
|
||||
name="monitor_feedback",
|
||||
description="Monitor optimization feedback",
|
||||
expected_output="Optimization feedback",
|
||||
agent=feedback_monitor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"negative": ["monitor_utilities"], # Start over if negative feedback
|
||||
"neutral": ["optimize_resources"], # Adjust optimization if neutral
|
||||
"positive": "" # End workflow if positive
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[utility_monitor, pattern_analyzer, resource_optimizer,
|
||||
implementation_agent, feedback_monitor],
|
||||
tasks=[monitoring_task, pattern_task, optimization_task,
|
||||
implementation_task, feedback_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Smart City Resource Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# 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__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Run your smart city management system:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
</Note>
|
||||
|
||||
## Understanding Smart City Management
|
||||
|
||||
<Card title="What is Smart City Management?" icon="question">
|
||||
Smart city management enables:
|
||||
- Real-time utility monitoring
|
||||
- Pattern analysis and prediction
|
||||
- Resource optimization
|
||||
- Automated implementation
|
||||
- Continuous feedback monitoring
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Utility Monitoring" icon="gauge">
|
||||
Monitor city utilities:
|
||||
- Power consumption
|
||||
- Water usage
|
||||
- Traffic patterns
|
||||
</Card>
|
||||
<Card title="Pattern Analysis" icon="chart-line">
|
||||
Analyze usage patterns:
|
||||
- Daily cycles
|
||||
- Weekly trends
|
||||
- Seasonal variations
|
||||
</Card>
|
||||
<Card title="Resource Optimization" icon="sliders">
|
||||
Optimize resource allocation:
|
||||
- Load balancing
|
||||
- Pressure adjustment
|
||||
- Traffic signal timing
|
||||
</Card>
|
||||
<Card title="Feedback Loop" icon="rotate">
|
||||
Continuous improvement:
|
||||
- Implementation tracking
|
||||
- Success rate monitoring
|
||||
- Adaptive optimization
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about chaining prompts for complex workflows
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
|
||||
Explore how to optimize and evaluate solutions
|
||||
</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,211 @@
|
||||
---
|
||||
title: "Supply Chain"
|
||||
sidebarTitle: "Supply Chain"
|
||||
description: "Learn how to create AI agents for supply chain risk management and mitigation."
|
||||
icon: "truck"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Monitor[Global Monitor]
|
||||
Monitor -->|high/medium/critical| Analyzer[Impact Analyzer]
|
||||
Analyzer --> Generator[Strategy Generator]
|
||||
Generator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Monitor fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how AI agents can monitor global events, analyze supply chain impacts, and generate mitigation strategies.
|
||||
|
||||
## 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
|
||||
|
||||
def monitor_global_events():
|
||||
"""Simulates monitoring of global events"""
|
||||
events = [
|
||||
{"type": "natural_disaster", "severity": "high", "region": "Asia"},
|
||||
{"type": "political_unrest", "severity": "medium", "region": "Europe"},
|
||||
{"type": "economic_crisis", "severity": "critical", "region": "Americas"}
|
||||
]
|
||||
return events[int(time.time()) % 3]
|
||||
|
||||
def analyze_supply_impact(event: Dict):
|
||||
"""Simulates impact analysis on supply chain"""
|
||||
impact_matrix = {
|
||||
"natural_disaster": {"delay": "severe", "cost": "high", "risk_level": 9},
|
||||
"political_unrest": {"delay": "moderate", "cost": "medium", "risk_level": 6},
|
||||
"economic_crisis": {"delay": "significant", "cost": "extreme", "risk_level": 8}
|
||||
}
|
||||
return impact_matrix.get(event["type"])
|
||||
|
||||
def generate_mitigation_strategies(impact: Dict):
|
||||
"""Simulates generation of mitigation strategies"""
|
||||
strategies = {
|
||||
"severe": ["activate_backup_suppliers", "emergency_logistics_routing"],
|
||||
"moderate": ["increase_buffer_stock", "alternative_transport"],
|
||||
"significant": ["diversify_suppliers", "hedge_currency_risks"]
|
||||
}
|
||||
return strategies.get(impact["delay"], ["review_supply_chain"])
|
||||
|
||||
# Create specialized agents
|
||||
monitor_agent = Agent(
|
||||
name="Global Monitor",
|
||||
role="Event Monitoring",
|
||||
goal="Monitor and identify global events affecting supply chain",
|
||||
instructions="Track and report significant global events",
|
||||
tools=[monitor_global_events]
|
||||
)
|
||||
|
||||
impact_analyzer = Agent(
|
||||
name="Impact Analyzer",
|
||||
role="Impact Assessment",
|
||||
goal="Analyze event impact on supply chain",
|
||||
instructions="Assess potential disruptions and risks",
|
||||
tools=[analyze_supply_impact]
|
||||
)
|
||||
|
||||
strategy_generator = Agent(
|
||||
name="Strategy Generator",
|
||||
role="Strategy Development",
|
||||
goal="Generate mitigation strategies",
|
||||
instructions="Develop strategies to address identified risks",
|
||||
tools=[generate_mitigation_strategies]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
monitoring_task = Task(
|
||||
name="monitor_events",
|
||||
description="Monitor global events affecting supply chain",
|
||||
expected_output="Identified global events",
|
||||
agent=monitor_agent,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": ["analyze_impact"],
|
||||
"medium": ["analyze_impact"],
|
||||
"critical": ["analyze_impact"]
|
||||
}
|
||||
)
|
||||
|
||||
impact_task = Task(
|
||||
name="analyze_impact",
|
||||
description="Analyze impact on supply chain",
|
||||
expected_output="Impact assessment",
|
||||
agent=impact_analyzer,
|
||||
next_tasks=["generate_strategies"]
|
||||
)
|
||||
|
||||
strategy_task = Task(
|
||||
name="generate_strategies",
|
||||
description="Generate mitigation strategies",
|
||||
expected_output="List of mitigation strategies",
|
||||
agent=strategy_generator,
|
||||
context=[monitoring_task, impact_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[monitor_agent, impact_analyzer, strategy_generator],
|
||||
tasks=[monitoring_task, impact_task, strategy_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Supply Chain Risk Management Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nRisk Management 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__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
- Basic understanding of Python
|
||||
</Note>
|
||||
|
||||
## Understanding Supply Chain Risk Management
|
||||
|
||||
<Card title="What is Supply Chain Risk Management?" icon="question">
|
||||
Automated supply chain risk management workflow enables:
|
||||
- Real-time global event monitoring
|
||||
- Impact assessment and risk analysis
|
||||
- Strategy generation for risk mitigation
|
||||
- Proactive supply chain optimization
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Event Monitoring" icon="globe">
|
||||
Monitor global events that could affect supply chain operations.
|
||||
</Card>
|
||||
<Card title="Impact Analysis" icon="chart-line">
|
||||
Assess potential disruptions and quantify risks to the supply chain.
|
||||
</Card>
|
||||
<Card title="Strategy Generation" icon="lightbulb">
|
||||
Generate mitigation strategies based on event impact.
|
||||
</Card>
|
||||
<Card title="Risk Management" icon="shield-check">
|
||||
Proactively manage and mitigate supply chain risks.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about sequential prompt execution
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
|
||||
Explore optimization techniques
|
||||
</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>
|
||||
@@ -4,6 +4,26 @@ description: "Async AI Agents allow you to run AI tasks asynchronously, improvin
|
||||
icon: "clock"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Agent1[AI Agent]
|
||||
Agent1 --> Agent2[AI Agent]
|
||||
Agent1 --> Agent3[AI Agent]
|
||||
Agent1 --> Agent4[AI Agent]
|
||||
Agent2 --> Out[Out]
|
||||
Agent3 --> Out
|
||||
Agent4 --> Out
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Agent1 fill:#2E8B57,color:#fff
|
||||
style Agent2 fill:#2E8B57,color:#fff
|
||||
style Agent3 fill:#2E8B57,color:#fff
|
||||
style Agent4 fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Async AI Agents allow you to run AI tasks asynchronously, improving performance and efficiency in your applications.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
|
||||
@@ -4,6 +4,47 @@ description: "AutoAgents automatically creates and manages AI agents and tasks b
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Plan[Plan Tasks]
|
||||
|
||||
subgraph Creation[Automatic Agent Creation]
|
||||
Plan --> Agent1[AI Agent 1]
|
||||
Plan --> Agent2[AI Agent 2]
|
||||
Plan --> Agent3[AI Agent 3]
|
||||
end
|
||||
|
||||
subgraph Tools[Automatic Tool Assignment]
|
||||
Agent1 --> Tool1[Tools 1]
|
||||
Agent2 --> Tool2[Tools 2]
|
||||
Agent3 --> Tool3[Tools 3]
|
||||
end
|
||||
|
||||
Tools --> Execution
|
||||
|
||||
subgraph Execution[Execution]
|
||||
Exec1[AI Agent 1] --> Exec2[AI Agent 2]
|
||||
Exec2 --> Exec3[AI Agent 3]
|
||||
end
|
||||
|
||||
Exec3 --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Plan fill:#2E8B57,color:#fff
|
||||
style Agent1 fill:#2E8B57,color:#fff
|
||||
style Agent2 fill:#2E8B57,color:#fff
|
||||
style Agent3 fill:#2E8B57,color:#fff
|
||||
style Tool1 fill:#2E8B57,color:#fff
|
||||
style Tool2 fill:#2E8B57,color:#fff
|
||||
style Tool3 fill:#2E8B57,color:#fff
|
||||
style Exec1 fill:#2E8B57,color:#fff
|
||||
style Exec2 fill:#2E8B57,color:#fff
|
||||
style Exec3 fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
AutoAgents automatically creates and manages AI agents and tasks based on high-level instructions.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
---
|
||||
title: "Agentic Autonomous Workflow"
|
||||
sidebarTitle: "Autonomous Workflow"
|
||||
description: "Learn how to create AI agents that can autonomously monitor, act, and adapt based on environment feedback."
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Human[Human] <--> LLM[LLM Call]
|
||||
LLM -->|ACTION| Environment[Environment]
|
||||
Environment -->|FEEDBACK| LLM
|
||||
LLM --> Stop[Stop]
|
||||
|
||||
style Human fill:#8B0000,color:#fff
|
||||
style LLM fill:#2E8B57,color:#fff
|
||||
style Environment fill:#8B0000,color:#fff
|
||||
style Stop fill:#333,color:#fff
|
||||
```
|
||||
|
||||
An agent-based workflow where LLMs act autonomously within a loop, interacting with their environment and receiving feedback to refine their actions and decisions.
|
||||
|
||||
## 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
|
||||
|
||||
def get_environment_state():
|
||||
"""Simulates getting current environment state"""
|
||||
current_time = int(time.time())
|
||||
states = ["normal", "critical", "optimal"]
|
||||
state = states[current_time % 3]
|
||||
print(f"Environment state: {state}")
|
||||
return state
|
||||
|
||||
def perform_action(state: str):
|
||||
"""Simulates performing an action based on state"""
|
||||
actions = {
|
||||
"normal": "maintain",
|
||||
"critical": "fix",
|
||||
"optimal": "enhance"
|
||||
}
|
||||
action = actions.get(state, "observe")
|
||||
print(f"Performing action: {action} for state: {state}")
|
||||
return action
|
||||
|
||||
def get_feedback():
|
||||
"""Simulates environment feedback"""
|
||||
current_time = int(time.time())
|
||||
feedback = "positive" if current_time % 2 == 0 else "negative"
|
||||
print(f"Feedback received: {feedback}")
|
||||
return feedback
|
||||
|
||||
# Create specialized agents
|
||||
llm_caller = Agent(
|
||||
name="Environment Monitor",
|
||||
role="State analyzer",
|
||||
goal="Monitor environment and analyze state",
|
||||
instructions="Check environment state and provide analysis",
|
||||
tools=[get_environment_state]
|
||||
)
|
||||
|
||||
action_agent = Agent(
|
||||
name="Action Executor",
|
||||
role="Action performer",
|
||||
goal="Execute appropriate actions based on state",
|
||||
instructions="Determine and perform actions based on environment state",
|
||||
tools=[perform_action]
|
||||
)
|
||||
|
||||
feedback_agent = Agent(
|
||||
name="Feedback Processor",
|
||||
role="Feedback analyzer",
|
||||
goal="Process environment feedback and adapt strategy",
|
||||
instructions="Analyze feedback and provide adaptation recommendations",
|
||||
tools=[get_feedback]
|
||||
)
|
||||
|
||||
# Create tasks for autonomous workflow
|
||||
monitor_task = Task(
|
||||
name="monitor_environment",
|
||||
description="Monitor and analyze environment state",
|
||||
expected_output="Current environment state analysis",
|
||||
agent=llm_caller,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
next_tasks=["execute_action"],
|
||||
condition={
|
||||
"normal": ["execute_action"],
|
||||
"critical": ["execute_action"],
|
||||
"optimal": "exit"
|
||||
}
|
||||
)
|
||||
|
||||
action_task = Task(
|
||||
name="execute_action",
|
||||
description="Execute appropriate action based on state",
|
||||
expected_output="Action execution result",
|
||||
agent=action_agent,
|
||||
next_tasks=["process_feedback"]
|
||||
)
|
||||
|
||||
feedback_task = Task(
|
||||
name="process_feedback",
|
||||
description="Process feedback and adapt strategy",
|
||||
expected_output="Strategy adaptation based on feedback",
|
||||
agent=feedback_agent,
|
||||
next_tasks=["monitor_environment"], # Create feedback loop
|
||||
context=[monitor_task, action_task] # Access to previous states and actions
|
||||
)
|
||||
|
||||
# Create workflow manager
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[llm_caller, action_agent, feedback_agent],
|
||||
tasks=[monitor_task, action_task, feedback_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Autonomous Agent Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run autonomous workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nAutonomous Agent Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
task_name = result.description
|
||||
print(f"\nTask: {task_name}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
- Basic understanding of Python
|
||||
</Note>
|
||||
|
||||
## Understanding Autonomous Workflow
|
||||
|
||||
<Card title="What is Autonomous Workflow?" icon="question">
|
||||
Autonomous Workflow enables:
|
||||
- Continuous environment monitoring
|
||||
- Automated decision-making and action execution
|
||||
- Real-time feedback processing
|
||||
- Self-adapting behavior based on outcomes
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Environment Monitoring" icon="eye">
|
||||
Continuously monitor and analyze environment state.
|
||||
</Card>
|
||||
<Card title="Adaptive Actions" icon="gears">
|
||||
Execute context-aware actions based on state analysis.
|
||||
</Card>
|
||||
<Card title="Feedback Processing" icon="rotate">
|
||||
Process and learn from action outcomes.
|
||||
</Card>
|
||||
<Card title="Self-Optimization" icon="arrow-trend-up">
|
||||
Improve performance through continuous learning.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Configuration Options
|
||||
|
||||
```python
|
||||
# Create a monitor agent
|
||||
monitor = Agent(
|
||||
name="Environment Monitor",
|
||||
role="State analyzer",
|
||||
goal="Monitor and analyze state",
|
||||
tools=[get_environment_state], # Environment monitoring tools
|
||||
verbose=True # Enable detailed logging
|
||||
)
|
||||
|
||||
# Create an action agent
|
||||
action = Agent(
|
||||
name="Action Executor",
|
||||
role="Action performer",
|
||||
goal="Execute appropriate actions",
|
||||
tools=[perform_action] # Action execution tools
|
||||
)
|
||||
|
||||
# Create monitoring task
|
||||
monitor_task = Task(
|
||||
name="monitor_environment",
|
||||
description="Monitor environment state",
|
||||
agent=monitor,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"normal": ["execute_action"],
|
||||
"critical": ["execute_action"],
|
||||
"optimal": "exit"
|
||||
}
|
||||
)
|
||||
|
||||
# Create feedback loop task
|
||||
feedback_task = Task(
|
||||
name="process_feedback",
|
||||
description="Process and adapt",
|
||||
agent=feedback_agent,
|
||||
next_tasks=["monitor_environment"], # Create feedback loop
|
||||
context=[monitor_task, action_task] # Access history
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Monitoring Issues" icon="triangle-exclamation">
|
||||
If monitoring fails:
|
||||
- Check environment access
|
||||
- Verify state detection
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Adaptation Flow" icon="diagram-project">
|
||||
If adaptation is incorrect:
|
||||
- Review feedback processing
|
||||
- Check action outcomes
|
||||
- Verify learning loop
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure your environment monitoring is reliable and your feedback processing logic is properly configured for effective adaptation.
|
||||
</Note>
|
||||
@@ -5,6 +5,20 @@ description: "Learn how to implement callbacks to monitor and log AI agent inter
|
||||
icon: "bell"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Agent[AI Agent]
|
||||
Agent --> Out[Out]
|
||||
Agent --> Callback[Callback]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Agent fill:#2E8B57,color:#fff
|
||||
style Callback fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Learn how to implement callbacks to monitor and log AI agent interactions, errors, and task completions.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
|
||||
Loaded 100 of 481 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user