mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-07 17:33:33 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
904e21ca87 | ||
|
|
526665ea11 | ||
|
|
c2e97d2432 | ||
|
|
60be6a1f99 | ||
|
|
0ba7d2e834 | ||
|
|
184b241395 | ||
|
|
4354e76fe5 | ||
|
|
4dd77efb75 | ||
|
|
11db6e18ba | ||
|
|
0d6f698e6c | ||
|
|
b8574f78e2 | ||
|
|
e631774a0f | ||
|
|
df735aa748 | ||
|
|
3bdf5b6c65 | ||
|
|
361fa67108 | ||
|
|
c5abcf362a | ||
|
|
7ed2d99a11 | ||
|
|
81307da7c8 | ||
|
|
fb75153b5c | ||
|
|
cddcfcf170 | ||
|
|
398b0473e0 | ||
|
|
c5d260782a | ||
|
|
116ac5a64d | ||
|
|
abf6e2e8d1 | ||
|
|
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 |
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,769 +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,
|
||||
adisplay_instruction
|
||||
)
|
||||
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()
|
||||
|
||||
def start(self, prompt: str, **kwargs):
|
||||
"""Start the agent with a prompt. This is a convenience method that wraps chat()."""
|
||||
return self.chat(prompt, **kwargs)
|
||||
@@ -1,569 +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, max_iter: int = 10):
|
||||
self.tasks = tasks
|
||||
self.agents = agents
|
||||
self.manager_llm = manager_llm
|
||||
self.verbose = verbose
|
||||
self.max_iter = max_iter
|
||||
|
||||
async def aworkflow(self) -> AsyncGenerator[str, None]:
|
||||
"""Async version of workflow method"""
|
||||
current_iter = 0 # Track how many times we've looped
|
||||
# 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:
|
||||
current_iter += 1
|
||||
if current_iter > self.max_iter:
|
||||
logging.info(f"Max iteration limit {self.max_iter} reached, ending workflow.")
|
||||
break
|
||||
|
||||
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)
|
||||
|
||||
# Reset completed task to "not started" so it can run again
|
||||
if self.tasks[task_id].status == "completed":
|
||||
logging.debug(f"Task {task_id} was completed, resetting to 'not started' for next iteration.")
|
||||
self.tasks[task_id].status = "not started"
|
||||
|
||||
# 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 and 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:
|
||||
# Handle both list and direct string values
|
||||
task_value = tasks[0] if isinstance(tasks, list) else tasks
|
||||
if not task_value or task_value == "exit": # If empty or explicit exit
|
||||
logging.info("Workflow exit condition met, ending workflow")
|
||||
current_task = None
|
||||
break
|
||||
next_task_name = task_value
|
||||
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 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"""
|
||||
current_iter = 0 # Track how many times we've looped
|
||||
# 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:
|
||||
current_iter += 1
|
||||
if current_iter > self.max_iter:
|
||||
logging.info(f"Max iteration limit {self.max_iter} reached, ending workflow.")
|
||||
break
|
||||
|
||||
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)
|
||||
|
||||
# Reset completed task to "not started" so it can run again
|
||||
if self.tasks[task_id].status == "completed":
|
||||
logging.debug(f"Task {task_id} was completed, resetting to 'not started' for next iteration.")
|
||||
self.tasks[task_id].status = "not started"
|
||||
|
||||
# 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 and 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:
|
||||
# Handle both list and direct string values
|
||||
task_value = tasks[0] if isinstance(tasks, list) else tasks
|
||||
if not task_value or task_value == "exit": # If empty or explicit exit
|
||||
logging.info("Workflow exit condition met, ending workflow")
|
||||
current_task = None
|
||||
break
|
||||
next_task_name = task_value
|
||||
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 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.46 gunicorn markdown
|
||||
RUN pip install flask praisonai==2.0.77 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.
|
||||
@@ -2,7 +2,7 @@
|
||||
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: "image-to-text"
|
||||
icon: "text"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: "Shopping Agent"
|
||||
sidebarTitle: "Shopping"
|
||||
description: "Learn how to create AI agents for price comparison and shopping assistance."
|
||||
icon: "shopping-cart"
|
||||
icon: "shop"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -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.46 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.77 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.
|
||||
@@ -1,109 +0,0 @@
|
||||
---
|
||||
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="/usecases/predictive-maintenance"
|
||||
>
|
||||
Learn how to create AI agents for predictive maintenance and equipment monitoring.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Emergency Response"
|
||||
icon="truck-medical"
|
||||
href="/usecases/emergency-response"
|
||||
>
|
||||
Learn how to create AI agents for coordinated emergency response and resource management.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Code Review"
|
||||
icon="code"
|
||||
href="/usecases/code-review"
|
||||
>
|
||||
Learn how to create AI agents for automated code review and issue resolution.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Adaptive Learning"
|
||||
icon="graduation-cap"
|
||||
href="/usecases/adaptive-learning"
|
||||
>
|
||||
Learn how to create AI agents for personalized adaptive learning experiences.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Supply Chain"
|
||||
icon="truck"
|
||||
href="/usecases/supply-chain"
|
||||
>
|
||||
Learn how to create AI agents for supply chain risk management and mitigation.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Customer Service"
|
||||
icon="headset"
|
||||
href="/usecases/customer-service"
|
||||
>
|
||||
Learn how to create AI agents for automated customer service and support.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Fraud Detection"
|
||||
icon="shield-check"
|
||||
href="/usecases/fraud-detection"
|
||||
>
|
||||
Learn how to create AI agents for real-time fraud detection and alert management.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Healthcare Diagnosis"
|
||||
icon="stethoscope"
|
||||
href="/usecases/healthcare-diagnosis"
|
||||
>
|
||||
Learn how to create AI agents for medical diagnosis and treatment recommendations.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Smart City"
|
||||
icon="city"
|
||||
href="/usecases/smart-city"
|
||||
>
|
||||
Learn how to create AI agents for smart city resource optimization and management.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Multilingual Content"
|
||||
icon="language"
|
||||
href="/usecases/multilingual-content"
|
||||
>
|
||||
Learn how to create AI agents for multilingual content generation and cultural adaptation.
|
||||
</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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
File renamed without changes.
@@ -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>
|
||||
@@ -0,0 +1,244 @@
|
||||
---
|
||||
title: "Chat with PDF Agents"
|
||||
sidebarTitle: "Chat with PDF"
|
||||
description: "Learn how to create AI agents that can intelligently chat with PDF documents using vector databases for efficient information retrieval."
|
||||
icon: "file-pdf"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
PDF[PDF Document] --> PDFAgent[("PDF Chat Agent")]
|
||||
VDB[(Vector DB)] --> PDFAgent
|
||||
PDFAgent --> Chat[Chat Interface]
|
||||
Chat --> |Query| VDB
|
||||
Chat --> Out[Response]
|
||||
|
||||
style PDF fill:#8B0000,color:#fff
|
||||
style PDFAgent fill:#2E8B57,color:#fff,shape:circle
|
||||
style VDB fill:#4169E1,color:#fff,shape:cylinder
|
||||
style Chat fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A PDF-centric workflow where Chat agents interact with vector databases to store and retrieve information from PDF documents, enabling natural conversations and intelligent question-answering capabilities.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install PraisonAI Agents with PDF chat 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 `chat_with_pdf.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="PDF Chat Agent",
|
||||
instructions="You answer questions based on the provided PDF document.",
|
||||
knowledge=["document.pdf"], # PDF Indexing
|
||||
)
|
||||
|
||||
agent.start("What is the main topic of this PDF?") # Chat Query
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## PDF Processing and Chat Agents
|
||||
|
||||
<Note>
|
||||
PDF processing involves indexing the document content for efficient retrieval during chat.
|
||||
</Note>
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph In[Input]
|
||||
PDF[PDF Documents]
|
||||
end
|
||||
|
||||
subgraph Router[Vector Store]
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
subgraph Out[Chat Agents]
|
||||
A1[Chat Agent 1]
|
||||
A2[Chat Agent 2]
|
||||
A3[Chat 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
|
||||
```
|
||||
|
||||
The simplest way to create a PDF chat agent is without any configuration:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="PDF Chat Agent",
|
||||
instructions="You answer questions based on the provided PDF document.",
|
||||
knowledge=["document.pdf"] # PDF Indexing
|
||||
)
|
||||
|
||||
agent.start("What are the key points in this document?") # Chat Query
|
||||
```
|
||||
|
||||
### 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": "praison",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
agent = Agent(
|
||||
name="PDF Chat Agent",
|
||||
instructions="You answer questions based on the provided PDF document.",
|
||||
knowledge=["document.pdf"], # PDF Indexing
|
||||
knowledge_config=config # Configuration
|
||||
)
|
||||
|
||||
agent.start("What is the main topic of this PDF?") # Chat Query
|
||||
```
|
||||
|
||||
### 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": "praison",
|
||||
"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"], # Indexing
|
||||
knowledge_config=config, # Configuration
|
||||
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 # Agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[knowledge_agent],
|
||||
tasks=[knowledge_task],
|
||||
process="sequential",
|
||||
user_id="user1" # User ID
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start() # Retrieval
|
||||
```
|
||||
|
||||
## Understanding PDF Chat Agents
|
||||
|
||||
<Card title="What are PDF Chat Agents?" icon="question">
|
||||
PDF Chat agents enable:
|
||||
- Natural conversation with PDF documents
|
||||
- Intelligent information extraction
|
||||
- Context-aware document understanding
|
||||
- Quick answers to document-specific questions
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="PDF Processing" icon="file-pdf">
|
||||
Process and index PDF documents efficiently.
|
||||
</Card>
|
||||
<Card title="Natural Chat" icon="comments">
|
||||
Have natural conversations about PDF content.
|
||||
</Card>
|
||||
<Card title="Smart Retrieval" icon="brain">
|
||||
Intelligently retrieve relevant information from PDFs.
|
||||
</Card>
|
||||
<Card title="Context Awareness" icon="layer-group">
|
||||
Maintain context throughout the conversation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="PDF Issues" icon="triangle-exclamation">
|
||||
If PDF processing isn't working:
|
||||
- Check PDF file format and encoding
|
||||
- Verify document accessibility
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Chat Issues" icon="gauge-high">
|
||||
If chat responses aren't accurate:
|
||||
- Check PDF indexing quality
|
||||
- Verify question clarity
|
||||
- Monitor context retention
|
||||
</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 chat experience, ensure your PDFs are properly formatted and text-searchable.
|
||||
</Note>
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
title: "Command Line Interface"
|
||||
sidebarTitle: "CLI"
|
||||
description: "Use PraisonAI directly from your terminal with simple commands"
|
||||
icon: "terminal"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Start((🚀)) --> CLI[CLI Command]
|
||||
CLI --> Agent[AI Agent]
|
||||
Agent --> Config[Config/YAML]
|
||||
Config --> Out((🏁))
|
||||
|
||||
style Start fill:#8B0000,color:#fff,stroke:#8B0000
|
||||
style CLI fill:#2E8B57,color:#fff
|
||||
style Agent fill:#2E8B57,color:#fff
|
||||
style Config fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff,stroke:#8B0000
|
||||
```
|
||||
|
||||
PraisonAI CLI provides a simple way to interact with AI agents directly from your terminal. You can run quick commands, specify LLM options, or use YAML configuration files for more complex scenarios.
|
||||
|
||||
<Frame>
|
||||
<img src="../demo/praisonai-cli-demo.gif" alt="PraisonAI CLI Demo" />
|
||||
</Frame>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install the PraisonAI package:
|
||||
```bash
|
||||
pip install praisonai
|
||||
```
|
||||
</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>
|
||||
</Steps>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Simple Command" icon="terminal" defaultOpen>
|
||||
Run a simple command directly:
|
||||
```bash
|
||||
praisonai "write a movie script in 3 lines"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="With LLM Option" icon="wand-magic-sparkles" defaultOpen>
|
||||
Specify a different LLM model:
|
||||
```bash
|
||||
praisonai "write a movie script in 3 lines" --llm gpt-4o-mini
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Using YAML Config" icon="file-code" defaultOpen>
|
||||
Run agents defined in a YAML file:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Create Config">
|
||||
Initialize a new agents.yaml file for your project:
|
||||
```bash
|
||||
praisonai --init "Create a movie script about AI"
|
||||
```
|
||||
This will create an `agents.yaml` file with predefined configuration for your task.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Auto Mode">
|
||||
Let PraisonAI automatically create and configure agents:
|
||||
```bash
|
||||
praisonai --auto "Create a movie script about AI"
|
||||
```
|
||||
This mode will analyze your task and set up appropriate agents automatically.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Simple Commands" icon="terminal">
|
||||
Run AI tasks directly from your terminal with simple commands.
|
||||
</Card>
|
||||
<Card title="LLM Options" icon="wand-magic-sparkles">
|
||||
Choose from different LLM models for your specific needs.
|
||||
</Card>
|
||||
<Card title="YAML Support" icon="file-code">
|
||||
Use YAML files for complex agent configurations and workflows.
|
||||
</Card>
|
||||
<Card title="Auto Configuration" icon="robot">
|
||||
Automatic agent setup based on task requirements.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="YAML Configuration" icon="file-code" href="/config">
|
||||
Learn more about YAML configuration options
|
||||
</Card>
|
||||
<Card title="API Reference" icon="code" href="/api-reference">
|
||||
View the complete API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,298 @@
|
||||
---
|
||||
title: "Generate Synthetic Reasoning Data Agents"
|
||||
sidebarTitle: "Generate Reasoning Data"
|
||||
description: "Learn how to generate chain-of-thought reasoning data using PraisonAI Agents."
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start[Start] --> Generator[Question Answer Generator Agent]
|
||||
Generator --> Evaluator[Evaluator Agent]
|
||||
Evaluator --> COT[Reasoning Steps / COT Generator Agent]
|
||||
COT --> COT
|
||||
COT --> Upload[HuggingFace Uploader Agent]
|
||||
Upload --> End[End]
|
||||
|
||||
style Start fill:#8B0000,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Evaluator fill:#2E8B57,color:#fff
|
||||
style COT fill:#2E8B57,color:#fff
|
||||
style Upload fill:#2E8B57,color:#fff
|
||||
style End fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Chain-of-Thought Generation?
|
||||
|
||||
Chain-of-Thought (CoT) Generation is a process where AI agents create detailed, step-by-step reasoning paths for solving problems. This involves generating questions, evaluating them, producing detailed solution steps, and making the data available for training and analysis.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install "praisonaiagents[llm]" datasets huggingface-hub pandas
|
||||
```
|
||||
</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
|
||||
export HF_TOKEN=your_huggingface_token_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import cot_save, cot_upload_to_huggingface
|
||||
from pydantic import BaseModel
|
||||
import os
|
||||
|
||||
# Define Pydantic model for structured output
|
||||
class DecisionModel(BaseModel):
|
||||
response: str
|
||||
decision: str
|
||||
|
||||
def write_csv(file_path, data):
|
||||
"""Write data to CSV file."""
|
||||
if not os.path.exists(file_path):
|
||||
with open(file_path, 'w') as file:
|
||||
file.write(data + '\n')
|
||||
else:
|
||||
with open(file_path, 'a') as file:
|
||||
file.write(data + '\n')
|
||||
return f"Data appended to {file_path}"
|
||||
|
||||
def count_questions(file_path):
|
||||
"""Count lines in file."""
|
||||
with open(file_path, 'r') as file:
|
||||
return sum(1 for _ in file)
|
||||
|
||||
# Create specialized agents
|
||||
qa_generator = Agent(
|
||||
name="Generator",
|
||||
role="Question Creator",
|
||||
goal="Create challenging math and logic questions",
|
||||
backstory="Expert in educational content creation",
|
||||
llm="gpt-4o-mini",
|
||||
tools=[write_csv, count_questions]
|
||||
)
|
||||
|
||||
total_questions_evaluator = Agent(
|
||||
name="TotalQuestionsEvaluator",
|
||||
role="Total Questions Evaluator",
|
||||
goal="Evaluate the total number of questions in qa_pairs.csv file",
|
||||
backstory="Expert in evaluating the total number of questions in a file",
|
||||
llm="gpt-4o-mini",
|
||||
tools=[count_questions],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
cot_generator = Agent(
|
||||
name="COTGenerator",
|
||||
role="Chain of Thought Specialist",
|
||||
goal="Generate and manage chain of thought solutions for Q&A pairs",
|
||||
backstory="Expert in breaking down problems and generating detailed solution steps",
|
||||
tools=[cot_save],
|
||||
llm="gpt-4o-mini",
|
||||
verbose=False
|
||||
)
|
||||
|
||||
upload_to_huggingface = Agent(
|
||||
name="UploadToHuggingface",
|
||||
role="Upload to Huggingface",
|
||||
goal="Upload the generated chain of thought solutions to a Huggingface dataset",
|
||||
backstory="Expert in saving data to Huggingface",
|
||||
tools=[cot_upload_to_huggingface],
|
||||
llm="gpt-4o-mini",
|
||||
verbose=False
|
||||
)
|
||||
|
||||
# Define tasks with workflow
|
||||
generate_task = Task(
|
||||
description="""Generate question and answer in csv format without headers: question, answer and append to qa_pairs.csv file
|
||||
generate 10 unique questions and answers and don't repeat on the same question and answer. Reponse with 'done' when done
|
||||
with append mode as 'a'
|
||||
Example question and answer:
|
||||
question, answer
|
||||
What is the sum of numbers from 1 to 10?, 55
|
||||
Number of r's in the word strawberry, 3
|
||||
""",
|
||||
expected_output="append to qa_pairs.csv file with questions and answers and move to next task",
|
||||
agent=qa_generator,
|
||||
name="generate_task",
|
||||
is_start=True,
|
||||
next_tasks=["evaluate_total_questions"],
|
||||
task_type="decision",
|
||||
condition={
|
||||
"more": "generate_task",
|
||||
"done": "evaluate_total_questions"
|
||||
}
|
||||
)
|
||||
|
||||
evaluate_total_questions_task = Task(
|
||||
description="Evaluate the total number of questions in qa_pairs.csv file is 1",
|
||||
expected_output="Total number of questions in qa_pairs.csv file",
|
||||
agent=total_questions_evaluator,
|
||||
task_type="decision",
|
||||
name="evaluate_total_questions",
|
||||
condition={
|
||||
"more": "generate_task",
|
||||
"done": "generate_cot"
|
||||
}
|
||||
)
|
||||
|
||||
generate_cot_task = Task(
|
||||
name="generate_cot",
|
||||
description="""Generate chain of thought solutions for each question in the input file.
|
||||
Save to cot_solutions.csv file
|
||||
Don't generate chain of thought solutions again after receiving the response from Tool Call
|
||||
After calling the tool, respond with a JSON object:
|
||||
{
|
||||
"response": "done",
|
||||
"decision": "done"
|
||||
}
|
||||
""",
|
||||
expected_output="done",
|
||||
agent=cot_generator,
|
||||
input_file="qa_pairs.csv",
|
||||
task_type="loop",
|
||||
next_tasks=["upload_to_huggingface"],
|
||||
condition={
|
||||
"done": ["upload_to_huggingface"],
|
||||
"exit": [],
|
||||
},
|
||||
output_pydantic=DecisionModel # Use Pydantic model for output validation
|
||||
)
|
||||
|
||||
upload_to_huggingface_task = Task(
|
||||
name="upload_to_huggingface",
|
||||
description="""Upload to Huggingface:
|
||||
1. Save to cot_solutions.csv
|
||||
2. Upload to mervinpraison/cot-dataset""",
|
||||
expected_output="Dataset published successfully",
|
||||
agent=upload_to_huggingface,
|
||||
tools=[cot_upload_to_huggingface]
|
||||
)
|
||||
|
||||
# Initialize workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=[qa_generator, total_questions_evaluator, cot_generator, upload_to_huggingface],
|
||||
tasks=[generate_task, evaluate_total_questions_task, generate_cot_task, upload_to_huggingface_task],
|
||||
process="workflow",
|
||||
max_iter=30,
|
||||
verbose=False
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Run the application">
|
||||
Execute the Python script to start generating chain-of-thought data:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Question Generation" icon="question">
|
||||
Create challenging math and logic questions with answers.
|
||||
</Card>
|
||||
<Card title="Question Evaluation" icon="check-double">
|
||||
Evaluate and validate generated questions for quality.
|
||||
</Card>
|
||||
<Card title="CoT Solutions" icon="diagram-project">
|
||||
Generate detailed chain-of-thought solutions for each question.
|
||||
</Card>
|
||||
<Card title="Data Management" icon="database">
|
||||
Save and manage generated data in structured formats.
|
||||
</Card>
|
||||
<Card title="HuggingFace Integration" icon="cloud-arrow-up">
|
||||
Upload datasets directly to HuggingFace for sharing.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Understanding the Workflow
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Key Components">
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Question Generator" icon="robot">
|
||||
Creates unique math and logic questions with answers. Uses `write_csv` and `count_questions` tools.
|
||||
</Card>
|
||||
<Card title="Questions Evaluator" icon="magnifying-glass-chart">
|
||||
Validates the total number of generated questions. Uses `count_questions` tool.
|
||||
</Card>
|
||||
<Card title="CoT Generator" icon="diagram-project">
|
||||
Produces detailed step-by-step solutions. Uses `cot_save` tool for solution management.
|
||||
</Card>
|
||||
<Card title="HuggingFace Uploader" icon="cloud-arrow-up">
|
||||
Publishes datasets to HuggingFace. Uses `cot_upload_to_huggingface` tool.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task Types and Flow Control">
|
||||
<Tabs>
|
||||
<Tab title="Decision Tasks">
|
||||
Used in question generation and evaluation phases.
|
||||
|
||||
```python Decision Task Example
|
||||
generate_task = Task(
|
||||
task_type="decision",
|
||||
condition={
|
||||
"more": "generate_task",
|
||||
"done": "evaluate_total_questions"
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
<Note>
|
||||
Conditions determine whether to continue generating or move forward. The task can loop back to itself or proceed to the next task.
|
||||
</Note>
|
||||
</Tab>
|
||||
<Tab title="Loop Tasks">
|
||||
Used in Chain-of-Thought generation phase.
|
||||
|
||||
```python Loop Task Example
|
||||
generate_cot_task = Task(
|
||||
task_type="loop",
|
||||
input_file="qa_pairs.csv",
|
||||
output_pydantic=DecisionModel
|
||||
)
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Always use Pydantic models for output validation in loop tasks to ensure data consistency.
|
||||
</Warning>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Info>
|
||||
Each task type serves a specific purpose in the workflow:
|
||||
- **Decision Tasks**: Control flow and branching logic
|
||||
- **Loop Tasks**: Process data iteratively with validation
|
||||
</Info>
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## 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,126 @@
|
||||
---
|
||||
title: "Image Generation AI Agents"
|
||||
sidebarTitle: "Image Generation"
|
||||
description: "Generate high-quality images using PraisonAI Image Agents with both synchronous and asynchronous capabilities."
|
||||
icon: "image"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Start] --> Process[Image Description]
|
||||
Process --> Agent[Image Agent]
|
||||
Agent --> Out[Image URL]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Process fill:#2E8B57,color:#fff
|
||||
style Agent fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Image Generation in PraisonAI allows you to create high-quality images using natural language descriptions. The Image Agent supports both synchronous and asynchronous operations, making it flexible for various use cases.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package with LLM support:
|
||||
```bash
|
||||
pip install "praisonaiagents[llm]"
|
||||
```
|
||||
</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 Agent">
|
||||
Create a new file `image_gen.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents.agent.image_agent import ImageAgent
|
||||
|
||||
# Create an image agent
|
||||
agent = ImageAgent(
|
||||
llm="dall-e-3",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Generate an image
|
||||
result = agent.chat("A cute baby sea otter playing with a laptop")
|
||||
print("Image generation result:", result)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
|
||||
<Tab title="Async">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package with LLM support:
|
||||
```bash
|
||||
pip install "praisonaiagents[llm]"
|
||||
```
|
||||
</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 Async Agent">
|
||||
Create a new file `image_gen_async.py` with the async setup:
|
||||
```python
|
||||
import asyncio
|
||||
from praisonaiagents import ImageAgent
|
||||
|
||||
async def main():
|
||||
agent = ImageAgent(
|
||||
name="ImageCreator",
|
||||
llm="dall-e-3",
|
||||
style="natural"
|
||||
)
|
||||
|
||||
result = await agent.achat("A cute baby sea otter playing with a laptop")
|
||||
print(f"Image generation result: {result}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="DALL-E Integration" icon="image">
|
||||
Seamless integration with DALL-E for high-quality image generation.
|
||||
</Card>
|
||||
<Card title="Async Support" icon="bolt">
|
||||
Asynchronous operations for better performance in concurrent environments.
|
||||
</Card>
|
||||
<Card title="Natural Style" icon="paintbrush">
|
||||
Generate images with natural, realistic styling options.
|
||||
</Card>
|
||||
<Card title="Verbose Mode" icon="message">
|
||||
Detailed output logging for better debugging and monitoring.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Agents Overview" icon="robot" href="/agents">
|
||||
Learn more about PraisonAI Agents and their capabilities
|
||||
</Card>
|
||||
<Card title="API Reference" icon="code" href="/api-reference">
|
||||
View the complete API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -12,7 +12,7 @@ icon: "images"
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
pip install praisonaiagents opencv-python moviepy
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
@@ -71,7 +71,7 @@ icon: "images"
|
||||
<Step title="Install Package">
|
||||
Install the PraisonAI package:
|
||||
```bash
|
||||
pip install praisonai
|
||||
pip install praisonai opencv-python moviepy
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
---
|
||||
title: "RAG Agents"
|
||||
description: "Learn how to create AI agents that can efficiently interact with vector databases for knowledge retrieval and storage."
|
||||
icon: "database"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Input] --> RAGAgent[("RAG Agent")]
|
||||
VDB[(Vector DB)] --> RAGAgent
|
||||
RAGAgent --> Task[Knowledge Task]
|
||||
Task --> |Query| VDB
|
||||
Task --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style RAGAgent fill:#2E8B57,color:#fff,shape:circle
|
||||
style VDB fill:#4169E1,color:#fff,shape:cylinder
|
||||
style Task fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A knowledge-centric workflow where RAG (Retrieval Augmented Generation) agents interact with vector databases to store and retrieve information efficiently, enabling sophisticated question-answering and information retrieval capabilities.
|
||||
|
||||
## 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"], # Indexing
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?") # Retrieval
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Data Indexing and Retrieval Agents
|
||||
|
||||
<Note>
|
||||
Indexing and Ingestion are relatively the same.
|
||||
</Note>
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
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"] # Indexing
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?") # Retrieval
|
||||
```
|
||||
|
||||
### 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": "praison",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"], # Indexing
|
||||
knowledge_config=config # Configuration
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?") # Retrieval
|
||||
```
|
||||
|
||||
### 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": "praison",
|
||||
"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"], # Indexing
|
||||
knowledge_config=config, # Configuration
|
||||
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 # Agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[knowledge_agent],
|
||||
tasks=[knowledge_task],
|
||||
process="sequential",
|
||||
user_id="user1" # User ID
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start() # Retrieval
|
||||
```
|
||||
|
||||
## Retrieval Agents
|
||||
|
||||
<Note>
|
||||
Retrieval is the process of querying the vector database for information.
|
||||
Considering there is data already in the Vector Database.
|
||||
</Note>
|
||||
|
||||
<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 `rag_agent.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Define the configuration for the Knowledge instance
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "praison",
|
||||
"path": ".praison"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create an agent
|
||||
rag_agent = Agent(
|
||||
name="RAG Agent",
|
||||
role="Information Specialist",
|
||||
goal="Retrieve knowledge efficiently",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Define a task for the agent
|
||||
rag_task = Task(
|
||||
name="RAG Task",
|
||||
description="What is KAG?",
|
||||
expected_output="Answer to the question",
|
||||
agent=rag_agent,
|
||||
context=[config] # Retrieval : Vector Database provided as context
|
||||
)
|
||||
|
||||
# Build Agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[rag_agent],
|
||||
tasks=[rag_task],
|
||||
user_id="user1"
|
||||
)
|
||||
|
||||
# Start Agents
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python rag_agent.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).
|
||||
- ChromaDB or other supported vector database
|
||||
</Note>
|
||||
|
||||
### Adding Knowledge to RAG Agents
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "praison",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"], # Indexing
|
||||
knowledge_config=config # Configuration
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?") # Retrieval
|
||||
```
|
||||
|
||||
## Understanding RAG Agents
|
||||
|
||||
<Card title="What are RAG Agents?" icon="question">
|
||||
RAG (Retrieval Augmented Generation) agents enable:
|
||||
- Efficient knowledge retrieval
|
||||
- Semantic search capabilities
|
||||
- Persistent knowledge storage
|
||||
- Context-aware responses
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="RAG Architecture" icon="database">
|
||||
Store and manage vector embeddings efficiently.
|
||||
</Card>
|
||||
<Card title="Semantic Search" icon="magnifying-glass">
|
||||
Find relevant information using semantic similarity.
|
||||
</Card>
|
||||
<Card title="Knowledge Integration" icon="brain">
|
||||
Seamlessly integrate with existing knowledge bases.
|
||||
</Card>
|
||||
<Card title="Context Management" icon="layer-group">
|
||||
Handle complex contextual queries and responses.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="RAG Issues" icon="triangle-exclamation">
|
||||
If RAG system isn't working:
|
||||
- Check database configuration
|
||||
- Verify connection settings
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Query Issues" icon="gauge-high">
|
||||
If queries aren't returning expected results:
|
||||
- Check embedding quality
|
||||
- Verify search parameters
|
||||
- Monitor similarity thresholds
|
||||
</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 vector database is properly configured and indexed for your specific use case.
|
||||
</Note>
|
||||
@@ -0,0 +1,137 @@
|
||||
---
|
||||
title: "Reasoning Extract Agents"
|
||||
description: "Learn how to create AI agents that can perform step-by-step reasoning and extract information"
|
||||
icon: "brain-circuit"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Input] --> RA[("Reasoning Agent")]
|
||||
RA --> Steps[Reasoning Steps]
|
||||
Steps --> SA[("Small Agent")]
|
||||
SA --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style RA fill:#2E8B57,color:#fff,shape:circle
|
||||
style Steps fill:#4169E1,color:#fff
|
||||
style SA fill:#2E8B57,color:#fff,shape:circle
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow where a reasoning agent breaks down complex problems into steps, followed by a smaller agent that processes these steps to provide concise answers.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install required packages:
|
||||
```bash
|
||||
pip install "praisonaiagents[llm]"
|
||||
```
|
||||
|
||||
<Note>
|
||||
praisonaiagents[llm] includes all necessary dependencies for reasoning agents
|
||||
</Note>
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Configure your API key:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create File">
|
||||
Create a new file called `app.py` and add the following code:
|
||||
</Step>
|
||||
|
||||
<Step title="Run Application">
|
||||
Execute the script:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Code
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
reasoning_agent = Agent(
|
||||
role="Helpful Assistant",
|
||||
reasoning_steps=True,
|
||||
llm="deepseek/deepseek-reasoner"
|
||||
)
|
||||
|
||||
small_agent = Agent(
|
||||
role="Helpful Assistant",
|
||||
llm="gpt-3.5-turbo"
|
||||
)
|
||||
|
||||
reasoning_task = Task(
|
||||
description="How many r's in the word 'Strawberry'?",
|
||||
agent=reasoning_agent
|
||||
)
|
||||
|
||||
small_task = Task(
|
||||
description="With the provided reasoning tell me how many r's in the word 'Strawberry'?",
|
||||
agent=small_agent
|
||||
)
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[reasoning_agent, small_agent],
|
||||
tasks=[reasoning_task, small_task]
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Step-by-Step Reasoning" icon="list-check">
|
||||
Break down complex problems into logical steps.
|
||||
</Card>
|
||||
<Card title="Multi-Agent Collaboration" icon="users">
|
||||
Combine reasoning and processing agents.
|
||||
</Card>
|
||||
<Card title="Flexible Models" icon="arrows-split-up-and-left">
|
||||
Use different models for reasoning and processing.
|
||||
</Card>
|
||||
<Card title="Task Chaining" icon="link">
|
||||
Connect reasoning output to processing tasks.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Understanding Reasoning Agents
|
||||
|
||||
<Card title="What are Reasoning Agents?" icon="question">
|
||||
Reasoning agents enable:
|
||||
- Detailed step-by-step analysis
|
||||
- Logical problem decomposition
|
||||
- Clear reasoning paths
|
||||
- Enhanced decision making
|
||||
</Card>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Reasoning Issues" icon="triangle-exclamation">
|
||||
If reasoning steps aren't clear:
|
||||
- Check reasoning_steps parameter
|
||||
- Verify model compatibility
|
||||
- Review task descriptions
|
||||
</Card>
|
||||
|
||||
<Card title="Agent Communication" icon="messages">
|
||||
If agents aren't coordinating:
|
||||
- Ensure task order is correct
|
||||
- Check task dependencies
|
||||
- Verify agent configurations
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
The reasoning agent uses a specialized model (deepseek-reasoner) optimized for step-by-step analysis, while the small agent can use a more general-purpose model for processing the reasoning output.
|
||||
</Note>
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
title: "Repetitive Agents"
|
||||
description: "Learn how to create AI agents that can efficiently handle repetitive tasks through automated loops."
|
||||
icon: "repeat"
|
||||
---
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
A workflow optimization pattern where agents handle repetitive tasks through automated loops, processing multiple instances efficiently while maintaining consistency.
|
||||
|
||||
## 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 `repetitive_agent.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a loop agent that creating a loop of tasks."
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Create the list of tasks to be looped through.",
|
||||
agent=agent,
|
||||
task_type="loop",
|
||||
input_file="tasks.csv"
|
||||
)
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
process="workflow",
|
||||
max_iter=30
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python repetitive_agent.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 Repetitive Agents
|
||||
|
||||
<Card title="What are Repetitive Agents?" icon="question">
|
||||
Repetitive agents enable:
|
||||
- Automated task loops
|
||||
- Batch processing
|
||||
- Consistent task execution
|
||||
- Efficient handling of multiple similar tasks
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Task Looping" icon="repeat">
|
||||
Process multiple tasks through automated loops.
|
||||
</Card>
|
||||
<Card title="Batch Processing" icon="layer-group">
|
||||
Handle multiple similar tasks efficiently.
|
||||
</Card>
|
||||
<Card title="Input Management" icon="file-csv">
|
||||
Process tasks from structured input files.
|
||||
</Card>
|
||||
<Card title="Progress Tracking" icon="chart-line">
|
||||
Monitor task completion and progress.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Loop Issues" icon="triangle-exclamation">
|
||||
If loops aren't working as expected:
|
||||
- Verify input file format
|
||||
- Check task configurations
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Performance Issues" icon="gauge-high">
|
||||
If processing is slow:
|
||||
- Check batch sizes
|
||||
- Verify resource allocation
|
||||
- Monitor memory usage
|
||||
</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 input files are properly formatted and your task configurations are appropriate for your use case.
|
||||
</Note>
|
||||
+442
-98
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "Praison AI"
|
||||
sidebarTitle: "Home"
|
||||
description: "Comprehensive guide to PraisonAI - an AI Agents Framework with Self Reflection, combining PraisonAI Agents, AutoGen, and CrewAI for building multi-agent LLM systems"
|
||||
description: "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."
|
||||
icon: "house"
|
||||
openGraph:
|
||||
url: "/"
|
||||
@@ -66,24 +66,53 @@ seo:
|
||||
Internet search using Crawl4AI and Tavily
|
||||
</Card>
|
||||
</CardGroup>
|
||||
<br />
|
||||
<div className="relative w-full aspect-video overflow-hidden rounded-lg shadow-lg mb-8">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full border-0"
|
||||
src="https://www.youtube.com/embed/Fn1lQjC0GO0"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
style={{
|
||||
maxWidth: '100vw',
|
||||
margin: '0 auto'
|
||||
}}
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Installation Options
|
||||
## Install
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create File">
|
||||
Create `app.py` file
|
||||
|
||||
## Code Example
|
||||
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="Your are a helpful AI assistant")
|
||||
agent.start("Write a movie script about a robot in Mars")
|
||||
```
|
||||
|
||||
```python Multi Agents
|
||||
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()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Run Script">
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Tip>
|
||||
PraisonAI combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customization, and efficient human-agent collaboration.
|
||||
@@ -109,11 +138,11 @@ seo:
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="Code">
|
||||
<Tab title="JavaScript">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
npm install praisonai
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
@@ -122,102 +151,390 @@ seo:
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create File">
|
||||
Create `app.py` file
|
||||
Create `app.js` file
|
||||
|
||||
## Code Example
|
||||
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
```javascript Single Agent
|
||||
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');
|
||||
```
|
||||
|
||||
# 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"
|
||||
)
|
||||
```javascript Multi Agents
|
||||
const { Agent, PraisonAIAgents } = require('praisonai');
|
||||
|
||||
# Define a task
|
||||
task = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
const researchAgent = new Agent({ instructions: 'Research about AI' });
|
||||
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
```python Advanced
|
||||
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()
|
||||
```
|
||||
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
|
||||
agents.start();
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Run Script">
|
||||
```bash
|
||||
python app.py
|
||||
node app.js
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## 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
|
||||
```
|
||||
<br />
|
||||
<div className="relative w-full aspect-video overflow-hidden rounded-lg shadow-lg mb-8">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full border-0"
|
||||
src="https://www.youtube.com/embed/Fn1lQjC0GO0"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
style={{
|
||||
maxWidth: '100vw',
|
||||
margin: '0 auto'
|
||||
}}
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Integration Options
|
||||
|
||||
<AccordionGroup>
|
||||
@@ -338,4 +655,31 @@ seo:
|
||||
<div className="hover:opacity-80 transition-opacity">
|
||||
<img src="https://img.shields.io/github/forks/MervinPraison/PraisonAI?style=social" alt="GitHub Forks" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
## 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) |
|
||||
| Firecrawl Integration | [](https://www.youtube.com/watch?v=UoqUDcLcOYo) |
|
||||
| User Interface | [](https://www.youtube.com/watch?v=tg-ZjNl3OCg) |
|
||||
| Crawl4AI Integration | [](https://www.youtube.com/watch?v=KAvuVUh0XU8) |
|
||||
| Chat Interface | [](https://www.youtube.com/watch?v=sw3uDqn2h1Y) |
|
||||
| Code Interface | [](https://www.youtube.com/watch?v=_5jQayO-MQY) |
|
||||
| Mem0 Integration | [](https://www.youtube.com/watch?v=KIGSgRxf1cY) |
|
||||
| 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) |
|
||||
@@ -11,6 +11,9 @@ pip install praisonaiagents
|
||||
```bash No Code
|
||||
pip install praisonai
|
||||
```
|
||||
```bash JavaScript
|
||||
npm install praisonai
|
||||
```
|
||||
</RequestExample>
|
||||
|
||||
<Note>
|
||||
@@ -90,6 +93,22 @@ Follow these steps to set up PraisonAI in your development environment.
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="JavaScript">
|
||||
<Steps>
|
||||
<Step title="Install PraisonAI">
|
||||
Install the PraisonAI package:
|
||||
```bash
|
||||
npm install praisonai
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
|
||||
+154
-147
@@ -6,9 +6,7 @@ icon: "book-open"
|
||||
|
||||
## What is PraisonAI?
|
||||
|
||||
<Note>
|
||||
PraisonAI is a powerful Multi-Agent Framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
|
||||
</Note>
|
||||
PraisonAI is a powerful Multi-Agent Framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Welcome to PraisonAI" icon="wand-magic-sparkles">
|
||||
Build powerful autonomous agents that understand, decide, and execute with unprecedented capability.
|
||||
@@ -26,45 +24,34 @@ graph LR
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[" "]
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
|
||||
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Agent2[" "]
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
|
||||
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Style for agent containers
|
||||
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Start,Output,Task1,Task2 input
|
||||
class Process,AgentIcon1,AgentIcon2 process
|
||||
class Tools1,Tools2 tools
|
||||
class Agent1,Agent2 transparent
|
||||
```
|
||||
<br />
|
||||
<CardGroup cols={2}>
|
||||
@@ -102,143 +89,163 @@ graph LR
|
||||
## Getting Started is Easy
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys).
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
<Step title="Create Agents">
|
||||
Create `app.py`:
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
<Step title="Create Agent">
|
||||
Create `app.py`:
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
# Create a simple agent
|
||||
summarise_agent = Agent(instructions="Summarise Photosynthesis")
|
||||
|
||||
# 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"
|
||||
)
|
||||
# Run the agent
|
||||
agents = PraisonAIAgents(agents=[summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
|
||||
# Define a task
|
||||
task = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
```python Multiple Agents
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
verbose=False
|
||||
)
|
||||
# Create agents with specific roles
|
||||
diet_agent = Agent(
|
||||
instructions="Give me 5 healthy food recipes",
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
blog_agent = Agent(
|
||||
instructions="Write a blog post about the food recipes",
|
||||
)
|
||||
|
||||
```python Multiple Agents
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
# Run multiple agents
|
||||
agents = PraisonAIAgents(agents=[diet_agent, blog_agent])
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
# 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
|
||||
)
|
||||
<Step title="Run Agents">
|
||||
Execute your script:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
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()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
You'll see:
|
||||
- Agent initialization
|
||||
- Task execution progress
|
||||
- Final results
|
||||
|
||||
<Tip>
|
||||
You have successfully CreatedAI Agents and made them work for you!
|
||||
</Tip>
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install the No Code PraisonAI Package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the PraisonAI package:
|
||||
```bash
|
||||
pip install praisonai
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
<Step title="Create Config">
|
||||
Create `agents.yaml`:
|
||||
|
||||
<Step title="Start AutoAgents">
|
||||
Run your AutoAgents:
|
||||
```bash
|
||||
praisonai --auto "Create a movie script about a robot in Mars"
|
||||
```
|
||||
</Step>
|
||||
<CodeGroup>
|
||||
```yaml Single Agent
|
||||
roles:
|
||||
summarise_agent:
|
||||
instructions: Summarise Photosynthesis
|
||||
```
|
||||
|
||||
```yaml Multiple Agents
|
||||
roles:
|
||||
diet_agent:
|
||||
instructions: Give me 5 healthy food recipes
|
||||
blog_agent:
|
||||
instructions: Write a blog post about the food recipes
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Note>
|
||||
You can automatically create `agents.yaml` using:
|
||||
```bash
|
||||
praisonai --init "your task description"
|
||||
```
|
||||
</Note>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Run Agents">
|
||||
Execute your config:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="JavaScript">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
```bash
|
||||
npm install praisonai
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create File">
|
||||
Create `app.js` file
|
||||
|
||||
## Code Example
|
||||
|
||||
<CodeGroup>
|
||||
```javascript Single Agent
|
||||
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');
|
||||
```
|
||||
|
||||
```javascript Multi Agents
|
||||
const { Agent, PraisonAIAgents } = require('praisonai');
|
||||
|
||||
const researchAgent = new Agent({ instructions: 'Research about AI' });
|
||||
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
|
||||
|
||||
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
|
||||
agents.start();
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Run Script">
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: "Development Setup"
|
||||
sidebarTitle: "Development"
|
||||
description: "Set up your development environment for PraisonAI JavaScript framework"
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
## Development Setup
|
||||
|
||||
<Steps>
|
||||
<Step title="Clone Repository">
|
||||
```bash
|
||||
git clone https://github.com/MervinPraison/PraisonAI.git
|
||||
cd src/praisonai-ts
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Install Dependencies">
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Build Package">
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── agent/ # Agent-related interfaces and implementations
|
||||
├── task/ # Task management and execution
|
||||
├── utils/ # Utility functions and helpers
|
||||
└── types/ # TypeScript type definitions
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
---
|
||||
title: "JavaScript AI Agents Framework"
|
||||
sidebarTitle: "JavaScript Agents"
|
||||
description: "A production-ready Multi AI Agents framework for JavaScript"
|
||||
icon: "js"
|
||||
---
|
||||
|
||||
PraisonAI is a production-ready Multi AI Agents framework for JavaScript, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. It provides a low-code solution to streamline the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
<Tabs>
|
||||
<Tab title="JavaScript">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
<CodeGroup>
|
||||
```bash npm
|
||||
npm install praisonai
|
||||
```
|
||||
```bash yarn
|
||||
yarn add praisonai
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create File">
|
||||
Create `app.js` file
|
||||
|
||||
## Code Example
|
||||
|
||||
<CodeGroup>
|
||||
```javascript Single Agent
|
||||
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');
|
||||
```
|
||||
|
||||
```javascript Multi Agents
|
||||
const { Agent, PraisonAIAgents } = require('praisonai');
|
||||
|
||||
const researchAgent = new Agent({ instructions: 'Research about AI' });
|
||||
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
|
||||
|
||||
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
|
||||
agents.start();
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Run Script">
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
## Usage Examples
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Single Agent Example" icon="user" defaultOpen>
|
||||
Create and run a single agent to perform a specific task:
|
||||
|
||||
```javascript
|
||||
const { Agent } = require('praisonai');
|
||||
|
||||
// Create a simple science explainer agent
|
||||
const agent = new Agent({
|
||||
instructions: "You are a science expert who explains complex phenomena in simple terms.",
|
||||
name: "ScienceExplainer",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Ask a question
|
||||
agent.start("Why is the sky blue?")
|
||||
.then(response => {
|
||||
console.log('\nExplanation:');
|
||||
console.log(response);
|
||||
})
|
||||
.catch(error => console.error('Error:', error));
|
||||
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Multi-Agent Example" icon="users" defaultOpen>
|
||||
Create and run multiple agents working together:
|
||||
|
||||
```javascript
|
||||
const { PraisonAIAgents, Agent } = require('praisonai');
|
||||
|
||||
// Create a story agent and a summary agent
|
||||
const storyAgent = new Agent({
|
||||
instructions: "You are a creative storyteller. Create engaging stories.",
|
||||
name: "Storyteller"
|
||||
});
|
||||
|
||||
const summaryAgent = new Agent({
|
||||
instructions: "You summarize stories into brief, engaging summaries.",
|
||||
name: "Summarizer"
|
||||
});
|
||||
|
||||
// Create multi-agent system
|
||||
const agents = new PraisonAIAgents({
|
||||
agents: [storyAgent, summaryAgent],
|
||||
tasks: [
|
||||
"Create a short story about a magical forest",
|
||||
"Summarize the story in 2 sentences"
|
||||
]
|
||||
});
|
||||
|
||||
// Run the agents
|
||||
agents.start()
|
||||
.then(responses => {
|
||||
console.log('\nStory:');
|
||||
console.log(responses[0]);
|
||||
console.log('\nSummary:');
|
||||
console.log(responses[1]);
|
||||
})
|
||||
.catch(error => console.error('Error:', error));
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task-Based Agent Example" icon="list-check" defaultOpen>
|
||||
Create agents with specific tasks and dependencies:
|
||||
|
||||
```javascript
|
||||
const { Agent, Task } = require('praisonai');
|
||||
|
||||
// Create a task-based agent
|
||||
const agent = new Agent({
|
||||
name: "TaskMaster",
|
||||
role: "Assistant",
|
||||
goal: "Complete tasks efficiently",
|
||||
backstory: "You are an AI assistant that helps complete tasks step by step."
|
||||
});
|
||||
|
||||
// Create a task with dependencies
|
||||
const mainTask = new Task({
|
||||
name: "Write Blog Post",
|
||||
description: "Write a blog post about artificial intelligence",
|
||||
expected_output: "A complete blog post",
|
||||
dependencies: []
|
||||
});
|
||||
|
||||
// Execute the task
|
||||
agent.execute(mainTask)
|
||||
.then(response => {
|
||||
console.log('\nBlog Post:');
|
||||
console.log(response);
|
||||
})
|
||||
.catch(error => console.error('Error:', error));
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Running the Examples
|
||||
|
||||
<Steps>
|
||||
<Step title="Set Environment Variables">
|
||||
```bash
|
||||
export OPENAI_API_KEY='your-api-key'
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Example File">
|
||||
Create a new JavaScript file (e.g., `app.js`) with any of the above examples.
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Example">
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
@@ -0,0 +1,251 @@
|
||||
---
|
||||
title: "Node.js AI Agents Framework"
|
||||
sidebarTitle: "Node.js Agents"
|
||||
description: "A production-ready Multi AI Agents framework for Node.js"
|
||||
icon: "node-js"
|
||||
---
|
||||
|
||||
PraisonAI is a production-ready Multi AI Agents framework for Node.js, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. It provides a low-code solution to streamline the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Node.js">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
<CodeGroup>
|
||||
```bash npm
|
||||
npm install praisonai
|
||||
```
|
||||
```bash yarn
|
||||
yarn add praisonai
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create File">
|
||||
Create `app.js` file
|
||||
|
||||
## Code Example
|
||||
|
||||
<CodeGroup>
|
||||
```javascript Single Agent
|
||||
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');
|
||||
```
|
||||
|
||||
```javascript Multi Agents
|
||||
const { Agent, PraisonAIAgents } = require('praisonai');
|
||||
|
||||
const researchAgent = new Agent({ instructions: 'Research about AI' });
|
||||
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
|
||||
|
||||
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
|
||||
agents.start();
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Run Script">
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Single Agent Example" icon="user" defaultOpen>
|
||||
Create and run a single agent to perform a specific task:
|
||||
|
||||
```typescript
|
||||
import { Agent } from 'praisonai';
|
||||
|
||||
// Single agent example - Science Explainer
|
||||
const agent = new Agent({
|
||||
instructions: `You are a science expert who explains complex phenomena in simple terms.
|
||||
Provide clear, accurate, and easy-to-understand explanations.`,
|
||||
name: "ScienceExplainer",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
agent.start("Why is the sky blue?")
|
||||
.then(response => {
|
||||
console.log('\nExplanation:');
|
||||
console.log(response);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
});
|
||||
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Multi-Agent Example" icon="users" defaultOpen>
|
||||
Create and run multiple agents working together:
|
||||
|
||||
```typescript
|
||||
import { Agent, PraisonAIAgents } from 'praisonai';
|
||||
|
||||
// Create story agent
|
||||
const storyAgent = new Agent({
|
||||
instructions: "You are a storyteller. Write a very short story (2-3 sentences) about a given topic.",
|
||||
name: "StoryAgent",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Create summary agent
|
||||
const summaryAgent = new Agent({
|
||||
instructions: "You are an editor. Create a one-sentence summary of the given story.",
|
||||
name: "SummaryAgent",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Create and start agents
|
||||
const agents = new PraisonAIAgents({
|
||||
agents: [storyAgent, summaryAgent],
|
||||
tasks: [
|
||||
"Write a short story about a cat",
|
||||
"{previous_result}" // This will be replaced with the story
|
||||
],
|
||||
verbose: true
|
||||
});
|
||||
|
||||
agents.start()
|
||||
.then(results => {
|
||||
console.log('\nStory:', results[0]);
|
||||
console.log('\nSummary:', results[1]);
|
||||
})
|
||||
.catch(error => console.error('Error:', error));
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task-Based Agent Example" icon="list-check" defaultOpen>
|
||||
Create agents with specific tasks and dependencies:
|
||||
|
||||
```typescript
|
||||
import { Agent, PraisonAIAgents } from 'praisonai';
|
||||
|
||||
// Create recipe agent
|
||||
const recipeAgent = new Agent({
|
||||
instructions: `You are a professional chef and nutritionist. Create 5 healthy food recipes that are both nutritious and delicious.
|
||||
Each recipe should include:
|
||||
1. Recipe name
|
||||
2. List of ingredients with quantities
|
||||
3. Step-by-step cooking instructions
|
||||
4. Nutritional information
|
||||
5. Health benefits
|
||||
|
||||
Format your response in markdown.`,
|
||||
name: "RecipeAgent",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Create blog agent
|
||||
const blogAgent = new Agent({
|
||||
instructions: `You are a food and health blogger. Write an engaging blog post about the provided recipes.
|
||||
The blog post should:
|
||||
1. Have an engaging title
|
||||
2. Include an introduction about healthy eating
|
||||
3. Discuss each recipe and its unique health benefits
|
||||
4. Include tips for meal planning and preparation
|
||||
5. End with a conclusion encouraging healthy eating habits
|
||||
|
||||
Here are the recipes to write about:
|
||||
{previous_result}
|
||||
|
||||
Format your response in markdown.`,
|
||||
name: "BlogAgent",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Create PraisonAIAgents instance with tasks
|
||||
const agents = new PraisonAIAgents({
|
||||
agents: [recipeAgent, blogAgent],
|
||||
tasks: [
|
||||
"Create 5 healthy and delicious recipes",
|
||||
"Write a blog post about the recipes"
|
||||
],
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Start the agents
|
||||
agents.start()
|
||||
.then(results => {
|
||||
console.log('\nFinal Results:');
|
||||
console.log('\nRecipe Task Results:');
|
||||
console.log(results[0]);
|
||||
console.log('\nBlog Task Results:');
|
||||
console.log(results[1]);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
});
|
||||
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Running the Examples
|
||||
|
||||
<Steps>
|
||||
<Step title="Set Environment Variables">
|
||||
```bash
|
||||
export OPENAI_API_KEY='your-api-key'
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Example File">
|
||||
Create a new TypeScript file (e.g., `app.ts`) with any of the above examples.
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Example">
|
||||
```bash
|
||||
npx ts-node app.ts
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
@@ -0,0 +1,198 @@
|
||||
---
|
||||
title: "TypeScript Async AI Agents"
|
||||
sidebarTitle: "TypeScript Async"
|
||||
description: "A production-ready Multi AI Agents framework for TypeScript Async"
|
||||
icon: "rotate"
|
||||
---
|
||||
|
||||
PraisonAI is a production-ready Multi AI Agents framework for TypeScript Async, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. It provides a low-code solution to streamline the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
|
||||
|
||||
## Installation
|
||||
|
||||
<CodeGroup>
|
||||
```bash npm
|
||||
npm install praisonai
|
||||
```
|
||||
|
||||
```bash yarn
|
||||
yarn add praisonai
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Single Agent Example" icon="user" defaultOpen>
|
||||
Create and run a single agent to perform a specific task:
|
||||
|
||||
```typescript
|
||||
import { Agent, PraisonAIAgents } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create a simple agent (no task specified)
|
||||
const agent = new Agent({
|
||||
name: "BiologyExpert",
|
||||
instructions: "Explain the process of photosynthesis in detail.",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Run the agent
|
||||
const praisonAI = new PraisonAIAgents({
|
||||
agents: [agent],
|
||||
tasks: ["Explain the process of photosynthesis in detail."],
|
||||
verbose: true
|
||||
});
|
||||
|
||||
try {
|
||||
console.log('Starting single agent example...');
|
||||
const results = await praisonAI.start();
|
||||
console.log('\nFinal Results:', results);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Multi-Agent Example" icon="users" defaultOpen>
|
||||
Create and run multiple agents working together:
|
||||
|
||||
```typescript
|
||||
import { Agent, PraisonAIAgents } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create multiple agents with different roles
|
||||
const researchAgent = new Agent({
|
||||
name: "ResearchAgent",
|
||||
instructions: "Research and provide detailed information about renewable energy sources.",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
const summaryAgent = new Agent({
|
||||
name: "SummaryAgent",
|
||||
instructions: "Create a concise summary of the research findings about renewable energy sources. Use {previous_result} as input.",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
const recommendationAgent = new Agent({
|
||||
name: "RecommendationAgent",
|
||||
instructions: "Based on the summary in {previous_result}, provide specific recommendations for implementing renewable energy solutions.",
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Run the agents in sequence
|
||||
const praisonAI = new PraisonAIAgents({
|
||||
agents: [researchAgent, summaryAgent, recommendationAgent],
|
||||
tasks: [
|
||||
"Research and analyze current renewable energy technologies and their implementation.",
|
||||
"Summarize the key findings from the research.",
|
||||
"Provide actionable recommendations based on the summary."
|
||||
],
|
||||
verbose: true
|
||||
});
|
||||
|
||||
try {
|
||||
console.log('Starting multi-agent example...');
|
||||
const results = await praisonAI.start();
|
||||
console.log('\nFinal Results:', results);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task-Based Agent Example" icon="list-check" defaultOpen>
|
||||
Create agents with specific tasks and dependencies:
|
||||
|
||||
```typescript
|
||||
import { Agent, Task, PraisonAIAgents } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create agents first
|
||||
const dietAgent = new Agent({
|
||||
name: "DietAgent",
|
||||
role: "Nutrition Expert",
|
||||
goal: "Create healthy and delicious recipes",
|
||||
backstory: "You are a certified nutritionist with years of experience in creating balanced meal plans.",
|
||||
verbose: true,
|
||||
instructions: `You are a professional chef and nutritionist. Create 5 healthy food recipes that are both nutritious and delicious.
|
||||
Each recipe should include:
|
||||
1. Recipe name
|
||||
2. List of ingredients with quantities
|
||||
3. Step-by-step cooking instructions
|
||||
4. Nutritional information
|
||||
5. Health benefits
|
||||
|
||||
Format your response in markdown.`
|
||||
});
|
||||
|
||||
const blogAgent = new Agent({
|
||||
name: "BlogAgent",
|
||||
role: "Food Blogger",
|
||||
goal: "Write engaging blog posts about food and recipes",
|
||||
backstory: "You are a successful food blogger known for your ability to make recipes sound delicious and approachable.",
|
||||
verbose: true,
|
||||
instructions: `You are a food and health blogger. Write an engaging blog post about the provided recipes.
|
||||
The blog post should:
|
||||
1. Have an engaging title
|
||||
2. Include an introduction about healthy eating`
|
||||
});
|
||||
|
||||
// Create tasks
|
||||
const createRecipesTask = new Task({
|
||||
name: "Create Recipes",
|
||||
description: "Create 5 healthy and delicious recipes",
|
||||
agent: dietAgent
|
||||
});
|
||||
|
||||
const writeBlogTask = new Task({
|
||||
name: "Write Blog",
|
||||
description: "Write a blog post about the recipes",
|
||||
agent: blogAgent,
|
||||
dependencies: [createRecipesTask] // This task depends on the recipes being created first
|
||||
});
|
||||
|
||||
// Run the tasks
|
||||
const praisonAI = new PraisonAIAgents({
|
||||
tasks: [createRecipesTask, writeBlogTask],
|
||||
verbose: true
|
||||
});
|
||||
|
||||
try {
|
||||
console.log('Starting task-based example...');
|
||||
const results = await praisonAI.start();
|
||||
console.log('\nFinal Results:', results);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Running the Examples
|
||||
|
||||
<Steps>
|
||||
<Step title="Set Environment Variables">
|
||||
```bash
|
||||
export OPENAI_API_KEY='your-api-key'
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Example File">
|
||||
Create a new TypeScript file (e.g., `app.ts`) with any of the above examples.
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Example">
|
||||
```bash
|
||||
npx ts-node app.ts
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
Loaded 100 of 407 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user