mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-08 01:08:39 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
633d724eb2 | ||
|
|
5cfda3fa54 | ||
|
|
370cb108f2 | ||
|
|
83cb80e907 | ||
|
|
f385de04e0 | ||
|
|
18695543e5 | ||
|
|
267f223a3e | ||
|
|
02bd52a06d | ||
|
|
076576af85 | ||
|
|
17547073ec | ||
|
|
124a95d7d0 | ||
|
|
8ca4e3285d | ||
|
|
5eac60dab3 | ||
|
|
59ee7cbbe5 | ||
|
|
81517b58e5 | ||
|
|
c1a8338a24 | ||
|
|
dba5a49569 | ||
|
|
6dab69e9d7 | ||
|
|
90563207f7 | ||
|
|
46330b0487 | ||
|
|
a133f0d5e2 | ||
|
|
fb22e6e1c7 | ||
|
|
e938fe63ea | ||
|
|
ef96e53843 | ||
|
|
036c463a43 | ||
|
|
0e6b4aefc3 | ||
|
|
bbb9f677ae | ||
|
|
0da201b3b6 | ||
|
|
a7b85043e1 | ||
|
|
dc393e1211 | ||
|
|
fdff17faf9 | ||
|
|
b3d893fae1 | ||
|
|
d92dede515 | ||
|
|
a1882233dc | ||
|
|
aa6b6ac62e | ||
|
|
c540ba34fb | ||
|
|
0abb1b659a | ||
|
|
81adb28688 | ||
|
|
5fbe6e948c | ||
|
|
6128e4c885 | ||
|
|
0e563989ed | ||
|
|
510a853e05 | ||
|
|
d6084cb7ce | ||
|
|
8d4b1c411b | ||
|
|
3be05c855b | ||
|
|
3e5a2f76f4 | ||
|
|
8eee881d2e | ||
|
|
d75f4be41a | ||
|
|
9ea89448ef | ||
|
|
0a5e2df278 | ||
|
|
cc3b64f89b | ||
|
|
546dc5a441 | ||
|
|
bd7422c7ca | ||
|
|
0c2c6da8dd | ||
|
|
b43688086f | ||
|
|
820619e8d9 | ||
|
|
94202adddd | ||
|
|
c7911629b1 | ||
|
|
5a4e3ba707 | ||
|
|
641057b622 | ||
|
|
db1dbf142e | ||
|
|
d9a19ae277 | ||
|
|
3c9d889b4f | ||
|
|
2f324e74db | ||
|
|
c22fef3e6d | ||
|
|
53bee19948 | ||
|
|
798fe68908 | ||
|
|
95796cd4c7 | ||
|
|
b447b7e6eb | ||
|
|
29dfe4b192 | ||
|
|
aca95b1713 | ||
|
|
b4cc3d7a8e | ||
|
|
c6c27e58a6 | ||
|
|
ae21881522 | ||
|
|
68efb982af | ||
|
|
c539306b96 | ||
|
|
c2f2d43d0d | ||
|
|
7847515b4b | ||
|
|
1f2c412521 | ||
|
|
355fe1e59c | ||
|
|
2ed64adc48 | ||
|
|
b8bc8583b1 | ||
|
|
51a3a065c4 | ||
|
|
4ba8745544 | ||
|
|
efc347f507 | ||
|
|
72a162c722 | ||
|
|
734a632dd4 | ||
|
|
dfaa3ed671 | ||
|
|
175b55704d | ||
|
|
084d1a2820 | ||
|
|
8518c3ae9d | ||
|
|
ac95c0000b | ||
|
|
8447e02f5d | ||
|
|
3e612f61dc | ||
|
|
b39c04dfb5 | ||
|
|
8fc367ee6d | ||
|
|
f7f157d3e7 | ||
|
|
05ede2a366 | ||
|
|
f8a2a93400 | ||
|
|
1a77826a21 | ||
|
|
adfd982547 | ||
|
|
facd52103e | ||
|
|
06d3d3decb | ||
|
|
7f35ac6113 | ||
|
|
e68fbb46f6 | ||
|
|
50a7bf6c91 | ||
|
|
eaf337b301 | ||
|
|
bce6e424d8 | ||
|
|
5cad05dc0d | ||
|
|
3ecc722866 | ||
|
|
2f73cf1882 | ||
|
|
c881fb3280 | ||
|
|
15f9cbbe47 | ||
|
|
f431347793 | ||
|
|
e0725c1296 | ||
|
|
b40295efb9 | ||
|
|
2f7769d334 | ||
|
|
c326aaf015 | ||
|
|
03874553eb | ||
|
|
97ae6647c9 | ||
|
|
046fb7cbe7 | ||
|
|
afdd6ab6f8 | ||
|
|
4581486a81 | ||
|
|
e10b991fab | ||
|
|
2d790f79a9 | ||
|
|
ec04dd7a91 | ||
|
|
bd49416f2b | ||
|
|
da2e11921c | ||
|
|
8287c3a3d4 | ||
|
|
6904f86557 | ||
|
|
cbebb3a900 | ||
|
|
413484ea9f | ||
|
|
785317c4fa | ||
|
|
c70f9ebf1f | ||
|
|
d278f2d2b2 | ||
|
|
df4596a699 | ||
|
|
dd0f47ec81 | ||
|
|
e53017a2fe | ||
|
|
fe034ba8f4 | ||
|
|
063e5780d6 | ||
|
|
904e21ca87 | ||
|
|
526665ea11 | ||
|
|
c2e97d2432 | ||
|
|
60be6a1f99 | ||
|
|
680949742e | ||
|
|
560219dcd7 | ||
|
|
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 |
No files matched your search
+8
-1885
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
|
||||
+4
-1
@@ -1,3 +1,4 @@
|
||||
workspace.code-workspace
|
||||
.vscode
|
||||
crewai
|
||||
.cache
|
||||
@@ -66,4 +67,6 @@ agents/praisonaiagents/build
|
||||
agents/praisonaiagents/dist
|
||||
agents/praisonaiagents/praisonaiagents.egg-info
|
||||
.codegpt
|
||||
.praison
|
||||
.praison
|
||||
# Local Netlify folder
|
||||
.netlify
|
||||
@@ -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, AG2 (Formerly 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 AG2 (Formerly 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,817 +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
|
||||
import uuid
|
||||
|
||||
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: Optional[List[str]] = None,
|
||||
knowledge_config: Optional[Dict[str, 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,
|
||||
user_id: 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 = knowledge
|
||||
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}
|
||||
"""
|
||||
|
||||
# Generate unique IDs
|
||||
self.agent_id = str(uuid.uuid4())
|
||||
|
||||
# Store user_id
|
||||
self.user_id = user_id
|
||||
|
||||
# Initialize Knowledge with provided or default config
|
||||
from praisonaiagents.knowledge import Knowledge
|
||||
self.knowledge = Knowledge(knowledge_config or None)
|
||||
|
||||
# Handle knowledge
|
||||
if knowledge:
|
||||
for source in knowledge:
|
||||
self._process_knowledge(source)
|
||||
|
||||
def _process_knowledge(self, knowledge_item):
|
||||
"""Process and store knowledge from a file path, URL, or string."""
|
||||
try:
|
||||
if os.path.exists(knowledge_item):
|
||||
# It's a file path
|
||||
self.knowledge.add(knowledge_item, user_id=self.user_id, agent_id=self.agent_id)
|
||||
elif knowledge_item.startswith("http://") or knowledge_item.startswith("https://"):
|
||||
# It's a URL
|
||||
pass
|
||||
else:
|
||||
# It's a string content
|
||||
self.knowledge.store(knowledge_item, user_id=self.user_id, agent_id=self.agent_id)
|
||||
except Exception as e:
|
||||
logging.error(f"Error processing knowledge item: {knowledge_item}, error: {e}")
|
||||
|
||||
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):
|
||||
# Search for existing knowledge if any knowledge is provided
|
||||
if self.knowledge:
|
||||
search_results = self.knowledge.search(prompt, agent_id=self.agent_id)
|
||||
if search_results:
|
||||
# Check if search_results is a list of dictionaries or strings
|
||||
if isinstance(search_results, dict) and 'results' in search_results:
|
||||
# Extract memory content from the results
|
||||
knowledge_content = "\n".join([result['memory'] for result in search_results['results']])
|
||||
else:
|
||||
# If search_results is a list of strings, join them directly
|
||||
knowledge_content = "\n".join(search_results)
|
||||
|
||||
# Append found knowledge to the prompt
|
||||
prompt = f"{prompt}\n\nKnowledge: {knowledge_content}"
|
||||
|
||||
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,738 +0,0 @@
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, Optional, List
|
||||
from pydantic import BaseModel
|
||||
from rich.text import Text
|
||||
from rich.panel import Panel
|
||||
from rich.console import Console
|
||||
from ..main import display_error, TaskOutput, error_logs, client
|
||||
from ..agent.agent import Agent
|
||||
from ..task.task import Task
|
||||
from ..process.process import Process, LoopItems
|
||||
import asyncio
|
||||
import uuid
|
||||
|
||||
# Set up logger
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def encode_file_to_base64(file_path: str) -> str:
|
||||
"""Base64-encode a file."""
|
||||
import base64
|
||||
with open(file_path, "rb") as f:
|
||||
return base64.b64encode(f.read()).decode("utf-8")
|
||||
|
||||
def process_video(video_path: str, seconds_per_frame=2):
|
||||
"""Split video into frames (base64-encoded)."""
|
||||
import cv2
|
||||
import base64
|
||||
base64_frames = []
|
||||
video = cv2.VideoCapture(video_path)
|
||||
total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
fps = video.get(cv2.CAP_PROP_FPS)
|
||||
frames_to_skip = int(fps * seconds_per_frame)
|
||||
curr_frame = 0
|
||||
while curr_frame < total_frames:
|
||||
video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
|
||||
success, frame = video.read()
|
||||
if not success:
|
||||
break
|
||||
_, buffer = cv2.imencode(".jpg", frame)
|
||||
base64_frames.append(base64.b64encode(buffer).decode("utf-8"))
|
||||
curr_frame += frames_to_skip
|
||||
video.release()
|
||||
return base64_frames
|
||||
|
||||
class PraisonAIAgents:
|
||||
def __init__(self, agents, tasks=None, verbose=0, completion_checker=None, max_retries=5, process="sequential", manager_llm=None, memory=False, memory_config=None, embedder=None, user_id=None):
|
||||
if not agents:
|
||||
raise ValueError("At least one agent must be provided")
|
||||
|
||||
self.run_id = str(uuid.uuid4()) # Auto-generate run_id
|
||||
self.user_id = user_id # Optional user_id
|
||||
|
||||
# Pass user_id to each agent
|
||||
for agent in agents:
|
||||
agent.user_id = self.user_id
|
||||
|
||||
self.agents = agents
|
||||
self.tasks = {}
|
||||
if max_retries < 3:
|
||||
max_retries = 3
|
||||
self.completion_checker = completion_checker if completion_checker else self.default_completion_checker
|
||||
self.task_id_counter = 0
|
||||
self.verbose = verbose
|
||||
self.max_retries = max_retries
|
||||
self.process = process
|
||||
|
||||
# Check for manager_llm in environment variable if not provided
|
||||
self.manager_llm = manager_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
|
||||
# Set logger level based on verbose
|
||||
if verbose >= 5:
|
||||
logger.setLevel(logging.INFO)
|
||||
else:
|
||||
logger.setLevel(logging.WARNING)
|
||||
|
||||
# Also set third-party loggers to WARNING
|
||||
logging.getLogger('chromadb').setLevel(logging.WARNING)
|
||||
logging.getLogger('openai').setLevel(logging.WARNING)
|
||||
logging.getLogger('httpx').setLevel(logging.WARNING)
|
||||
logging.getLogger('httpcore').setLevel(logging.WARNING)
|
||||
|
||||
if self.verbose:
|
||||
logger.info(f"Using model {self.manager_llm} for manager")
|
||||
|
||||
# If no tasks provided, generate them from agents
|
||||
if tasks is None:
|
||||
tasks = []
|
||||
for agent in self.agents:
|
||||
task = agent.generate_task()
|
||||
tasks.append(task)
|
||||
logger.info(f"Auto-generated {len(tasks)} tasks from agents")
|
||||
else:
|
||||
# Validate tasks for backward compatibility
|
||||
if not tasks:
|
||||
raise ValueError("If tasks are provided, at least one task must be present")
|
||||
logger.info(f"Using {len(tasks)} provided tasks")
|
||||
|
||||
# Add tasks and set their status
|
||||
for task in tasks:
|
||||
self.add_task(task)
|
||||
task.status = "not started"
|
||||
|
||||
# If tasks were auto-generated from agents or process is sequential, set up sequential flow
|
||||
if len(tasks) > 1 and (process == "sequential" or all(task.next_tasks == [] for task in tasks)):
|
||||
for i in range(len(tasks) - 1):
|
||||
# Set up next task relationship
|
||||
tasks[i].next_tasks = [tasks[i + 1].name]
|
||||
# Set up context for the next task to include the current task
|
||||
if tasks[i + 1].context is None:
|
||||
tasks[i + 1].context = []
|
||||
tasks[i + 1].context.append(tasks[i])
|
||||
logger.info("Set up sequential flow with automatic context passing")
|
||||
|
||||
self._state = {} # Add state storage at PraisonAIAgents level
|
||||
|
||||
# Initialize memory system
|
||||
self.shared_memory = None
|
||||
if memory:
|
||||
try:
|
||||
from ..memory.memory import Memory
|
||||
|
||||
# Get memory config from parameter or first task
|
||||
mem_cfg = memory_config
|
||||
if not mem_cfg:
|
||||
mem_cfg = next((t.config.get('memory_config') for t in tasks if hasattr(t, 'config') and t.config), None)
|
||||
|
||||
# Set default memory config if none provided
|
||||
if not mem_cfg:
|
||||
mem_cfg = {
|
||||
"provider": "rag",
|
||||
"use_embedding": True,
|
||||
"storage": {
|
||||
"type": "sqlite",
|
||||
"path": "./.praison/memory.db"
|
||||
},
|
||||
"rag_db_path": "./.praison/chroma_db"
|
||||
}
|
||||
|
||||
# Add embedder config if provided
|
||||
if embedder:
|
||||
if isinstance(embedder, dict):
|
||||
mem_cfg = mem_cfg or {}
|
||||
mem_cfg["embedder"] = embedder
|
||||
else:
|
||||
# Handle direct embedder function
|
||||
mem_cfg = mem_cfg or {}
|
||||
mem_cfg["embedder_function"] = embedder
|
||||
|
||||
if mem_cfg:
|
||||
# Pass verbose level to Memory
|
||||
self.shared_memory = Memory(config=mem_cfg, verbose=verbose)
|
||||
if verbose >= 5:
|
||||
logger.info("Initialized shared memory for PraisonAIAgents")
|
||||
|
||||
# Distribute memory to tasks
|
||||
for task in tasks:
|
||||
if not task.memory:
|
||||
task.memory = self.shared_memory
|
||||
if verbose >= 5:
|
||||
logger.info(f"Assigned shared memory to task {task.id}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize shared memory: {e}")
|
||||
|
||||
# Update tasks with shared memory
|
||||
if self.shared_memory:
|
||||
for task in tasks:
|
||||
if not task.memory:
|
||||
task.memory = self.shared_memory
|
||||
logger.info(f"Assigned shared memory to task {task.id}")
|
||||
|
||||
def add_task(self, task):
|
||||
task_id = self.task_id_counter
|
||||
task.id = task_id
|
||||
self.tasks[task_id] = task
|
||||
self.task_id_counter += 1
|
||||
return task_id
|
||||
|
||||
def clean_json_output(self, output: str) -> str:
|
||||
cleaned = output.strip()
|
||||
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
|
||||
|
||||
def default_completion_checker(self, task, agent_output):
|
||||
if task.output_json and task.result and task.result.json_dict:
|
||||
return True
|
||||
if task.output_pydantic and task.result and task.result.pydantic:
|
||||
return True
|
||||
return len(agent_output.strip()) > 0
|
||||
|
||||
async def aexecute_task(self, task_id):
|
||||
"""Async version of execute_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
|
||||
# Only import multimodal dependencies if task has images
|
||||
if task.images and task.status == "not started":
|
||||
try:
|
||||
import cv2
|
||||
import base64
|
||||
from moviepy import VideoFileClip
|
||||
except ImportError as e:
|
||||
display_error(f"Error: Missing required dependencies for image/video processing: {e}")
|
||||
display_error("Please install with: pip install opencv-python moviepy")
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
if task.status == "not started":
|
||||
task.status = "in progress"
|
||||
|
||||
executor_agent = task.agent
|
||||
|
||||
# Ensure tools are available from both task and agent
|
||||
tools = task.tools or []
|
||||
if executor_agent and executor_agent.tools:
|
||||
tools.extend(executor_agent.tools)
|
||||
|
||||
task_prompt = f"""
|
||||
You need to do the following task: {task.description}.
|
||||
Expected Output: {task.expected_output}.
|
||||
"""
|
||||
if task.context:
|
||||
context_results = ""
|
||||
for context_task in task.context:
|
||||
if context_task.result:
|
||||
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
|
||||
else:
|
||||
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
|
||||
task_prompt += f"""
|
||||
Here are the results of previous tasks that might be useful:\n
|
||||
{context_results}
|
||||
"""
|
||||
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
|
||||
|
||||
if self.verbose >= 2:
|
||||
logger.info(f"Executing task {task_id}: {task.description} using {executor_agent.name}")
|
||||
logger.debug(f"Starting execution of task {task_id} with prompt:\n{task_prompt}")
|
||||
|
||||
if task.images:
|
||||
def _get_multimodal_message(text_prompt, images):
|
||||
content = [{"type": "text", "text": text_prompt}]
|
||||
|
||||
for img in images:
|
||||
# If local file path for a valid image
|
||||
if os.path.exists(img):
|
||||
ext = os.path.splitext(img)[1].lower()
|
||||
# If it's a .mp4, convert to frames
|
||||
if ext == ".mp4":
|
||||
frames = process_video(img, seconds_per_frame=1)
|
||||
content.append({"type": "text", "text": "These are frames from the video."})
|
||||
for f in frames:
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:image/jpg;base64,{f}"}
|
||||
})
|
||||
else:
|
||||
encoded = encode_file_to_base64(img)
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/{ext.lstrip('.')};base64,{encoded}"
|
||||
}
|
||||
})
|
||||
else:
|
||||
# Treat as a remote URL
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": img}
|
||||
})
|
||||
return content
|
||||
|
||||
agent_output = await executor_agent.achat(
|
||||
_get_multimodal_message(task_prompt, task.images),
|
||||
tools=tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
else:
|
||||
agent_output = await executor_agent.achat(
|
||||
task_prompt,
|
||||
tools=tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
|
||||
if agent_output:
|
||||
task_output = TaskOutput(
|
||||
description=task.description,
|
||||
summary=task.description[:10],
|
||||
raw=agent_output,
|
||||
agent=executor_agent.name,
|
||||
output_format="RAW"
|
||||
)
|
||||
|
||||
if task.output_json:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
task_output.json_dict = parsed
|
||||
task_output.output_format = "JSON"
|
||||
except:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as JSON")
|
||||
logger.debug(f"Output that failed JSON parsing: {agent_output}")
|
||||
|
||||
if task.output_pydantic:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
pyd_obj = task.output_pydantic(**parsed)
|
||||
task_output.pydantic = pyd_obj
|
||||
task_output.output_format = "Pydantic"
|
||||
except:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as Pydantic Model")
|
||||
logger.debug(f"Output that failed Pydantic parsing: {agent_output}")
|
||||
|
||||
task.result = task_output
|
||||
return task_output
|
||||
else:
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
async def arun_task(self, task_id):
|
||||
"""Async version of run_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
if task.status == "completed":
|
||||
logger.info(f"Task with ID {task_id} is already completed")
|
||||
return
|
||||
|
||||
retries = 0
|
||||
while task.status != "completed" and retries < self.max_retries:
|
||||
logger.debug(f"Attempt {retries+1} for task {task_id}")
|
||||
if task.status in ["not started", "in progress"]:
|
||||
task_output = await self.aexecute_task(task_id)
|
||||
if task_output and self.completion_checker(task, task_output.raw):
|
||||
task.status = "completed"
|
||||
# Run execute_callback for memory operations
|
||||
try:
|
||||
await task.execute_callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing memory callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
# Run task callback if exists
|
||||
if task.callback:
|
||||
try:
|
||||
if asyncio.iscoroutinefunction(task.callback):
|
||||
await task.callback(task_output)
|
||||
else:
|
||||
task.callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing task callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
self.save_output_to_file(task, task_output)
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} completed successfully.")
|
||||
else:
|
||||
task.status = "in progress"
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} not completed, retrying")
|
||||
await asyncio.sleep(1)
|
||||
retries += 1
|
||||
else:
|
||||
if task.status == "failed":
|
||||
logger.info("Task is failed, resetting to in-progress for another try...")
|
||||
task.status = "in progress"
|
||||
else:
|
||||
logger.info("Invalid Task status")
|
||||
break
|
||||
|
||||
if retries == self.max_retries and task.status != "completed":
|
||||
logger.info(f"Task {task_id} failed after {self.max_retries} retries.")
|
||||
|
||||
async def arun_all_tasks(self):
|
||||
"""Async version of run_all_tasks method"""
|
||||
process = Process(
|
||||
tasks=self.tasks,
|
||||
agents=self.agents,
|
||||
manager_llm=self.manager_llm,
|
||||
verbose=self.verbose
|
||||
)
|
||||
|
||||
if self.process == "workflow":
|
||||
# Collect all tasks that should run in parallel
|
||||
parallel_tasks = []
|
||||
async for task_id in process.aworkflow():
|
||||
if self.tasks[task_id].async_execution and self.tasks[task_id].is_start:
|
||||
parallel_tasks.append(task_id)
|
||||
elif parallel_tasks:
|
||||
# Execute collected parallel tasks
|
||||
await asyncio.gather(*[self.arun_task(t) for t in parallel_tasks])
|
||||
parallel_tasks = []
|
||||
# Run the current non-parallel task
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
|
||||
# Execute any remaining parallel tasks
|
||||
if parallel_tasks:
|
||||
await asyncio.gather(*[self.arun_task(t) for t in parallel_tasks])
|
||||
|
||||
elif self.process == "sequential":
|
||||
async for task_id in process.asequential():
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
elif self.process == "hierarchical":
|
||||
async for task_id in process.ahierarchical():
|
||||
if isinstance(task_id, Task):
|
||||
task_id = self.add_task(task_id)
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
|
||||
async def astart(self):
|
||||
"""Async version of start method"""
|
||||
await self.arun_all_tasks()
|
||||
return {
|
||||
"task_status": self.get_all_tasks_status(),
|
||||
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
|
||||
}
|
||||
|
||||
def save_output_to_file(self, task, task_output):
|
||||
if task.output_file:
|
||||
try:
|
||||
if task.create_directory:
|
||||
os.makedirs(os.path.dirname(task.output_file), exist_ok=True)
|
||||
with open(task.output_file, "w") as f:
|
||||
f.write(str(task_output))
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task output saved to {task.output_file}")
|
||||
except Exception as e:
|
||||
display_error(f"Error saving task output to file: {e}")
|
||||
|
||||
def execute_task(self, task_id):
|
||||
"""Synchronous version of execute_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
|
||||
logger.info(f"Starting execution of task {task_id}")
|
||||
logger.info(f"Task config: {task.config}")
|
||||
|
||||
# Initialize memory before task execution
|
||||
if not task.memory:
|
||||
task.memory = task.initialize_memory()
|
||||
|
||||
logger.info(f"Task memory status: {'Initialized' if task.memory else 'Not initialized'}")
|
||||
|
||||
# Only import multimodal dependencies if task has images
|
||||
if task.images and task.status == "not started":
|
||||
try:
|
||||
import cv2
|
||||
import base64
|
||||
from moviepy import VideoFileClip
|
||||
except ImportError as e:
|
||||
display_error(f"Error: Missing required dependencies for image/video processing: {e}")
|
||||
display_error("Please install with: pip install opencv-python moviepy")
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
if task.status == "not started":
|
||||
task.status = "in progress"
|
||||
|
||||
executor_agent = task.agent
|
||||
|
||||
task_prompt = f"""
|
||||
You need to do the following task: {task.description}.
|
||||
Expected Output: {task.expected_output}.
|
||||
"""
|
||||
if task.context:
|
||||
context_results = ""
|
||||
for context_task in task.context:
|
||||
if context_task.result:
|
||||
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
|
||||
else:
|
||||
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
|
||||
task_prompt += f"""
|
||||
Here are the results of previous tasks that might be useful:\n
|
||||
{context_results}
|
||||
"""
|
||||
# Add memory context if available
|
||||
if task.memory:
|
||||
try:
|
||||
memory_context = task.memory.build_context_for_task(task.description)
|
||||
if memory_context:
|
||||
task_prompt += f"\n\nRelevant memory context:\n{memory_context}"
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting memory context: {e}")
|
||||
|
||||
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
|
||||
|
||||
if self.verbose >= 2:
|
||||
logger.info(f"Executing task {task_id}: {task.description} using {executor_agent.name}")
|
||||
logger.debug(f"Starting execution of task {task_id} with prompt:\n{task_prompt}")
|
||||
|
||||
if task.images:
|
||||
def _get_multimodal_message(text_prompt, images):
|
||||
content = [{"type": "text", "text": text_prompt}]
|
||||
|
||||
for img in images:
|
||||
# If local file path for a valid image
|
||||
if os.path.exists(img):
|
||||
ext = os.path.splitext(img)[1].lower()
|
||||
# If it's a .mp4, convert to frames
|
||||
if ext == ".mp4":
|
||||
frames = process_video(img, seconds_per_frame=1)
|
||||
content.append({"type": "text", "text": "These are frames from the video."})
|
||||
for f in frames:
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:image/jpg;base64,{f}"}
|
||||
})
|
||||
else:
|
||||
encoded = encode_file_to_base64(img)
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/{ext.lstrip('.')};base64,{encoded}"
|
||||
}
|
||||
})
|
||||
else:
|
||||
# Treat as a remote URL
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": img}
|
||||
})
|
||||
return content
|
||||
|
||||
agent_output = executor_agent.chat(
|
||||
_get_multimodal_message(task_prompt, task.images),
|
||||
tools=task.tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
else:
|
||||
agent_output = executor_agent.chat(
|
||||
task_prompt,
|
||||
tools=task.tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
|
||||
if agent_output:
|
||||
# Store the response in memory
|
||||
if task.memory:
|
||||
try:
|
||||
task.store_in_memory(
|
||||
content=agent_output,
|
||||
agent_name=executor_agent.name,
|
||||
task_id=task_id
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to store agent output in memory: {e}")
|
||||
|
||||
task_output = TaskOutput(
|
||||
description=task.description,
|
||||
summary=task.description[:10],
|
||||
raw=agent_output,
|
||||
agent=executor_agent.name,
|
||||
output_format="RAW"
|
||||
)
|
||||
|
||||
if task.output_json:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
task_output.json_dict = parsed
|
||||
task_output.output_format = "JSON"
|
||||
except:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as JSON")
|
||||
logger.debug(f"Output that failed JSON parsing: {agent_output}")
|
||||
|
||||
if task.output_pydantic:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
pyd_obj = task.output_pydantic(**parsed)
|
||||
task_output.pydantic = pyd_obj
|
||||
task_output.output_format = "Pydantic"
|
||||
except:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as Pydantic Model")
|
||||
logger.debug(f"Output that failed Pydantic parsing: {agent_output}")
|
||||
|
||||
task.result = task_output
|
||||
return task_output
|
||||
else:
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
def run_task(self, task_id):
|
||||
"""Synchronous version of run_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
if task.status == "completed":
|
||||
logger.info(f"Task with ID {task_id} is already completed")
|
||||
return
|
||||
|
||||
retries = 0
|
||||
while task.status != "completed" and retries < self.max_retries:
|
||||
logger.debug(f"Attempt {retries+1} for task {task_id}")
|
||||
if task.status in ["not started", "in progress"]:
|
||||
task_output = self.execute_task(task_id)
|
||||
if task_output and self.completion_checker(task, task_output.raw):
|
||||
task.status = "completed"
|
||||
# Run execute_callback for memory operations
|
||||
try:
|
||||
if asyncio.get_event_loop().is_running():
|
||||
asyncio.create_task(task.execute_callback(task_output))
|
||||
else:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
loop.run_until_complete(task.execute_callback(task_output))
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing memory callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
# Run task callback if exists
|
||||
if task.callback:
|
||||
try:
|
||||
if asyncio.iscoroutinefunction(task.callback):
|
||||
if asyncio.get_event_loop().is_running():
|
||||
asyncio.create_task(task.callback(task_output))
|
||||
else:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
loop.run_until_complete(task.callback(task_output))
|
||||
else:
|
||||
task.callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing task callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
self.save_output_to_file(task, task_output)
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} completed successfully.")
|
||||
else:
|
||||
task.status = "in progress"
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} not completed, retrying")
|
||||
time.sleep(1)
|
||||
retries += 1
|
||||
else:
|
||||
if task.status == "failed":
|
||||
logger.info("Task is failed, resetting to in-progress for another try...")
|
||||
task.status = "in progress"
|
||||
else:
|
||||
logger.info("Invalid Task status")
|
||||
break
|
||||
|
||||
if retries == self.max_retries and task.status != "completed":
|
||||
logger.info(f"Task {task_id} failed after {self.max_retries} retries.")
|
||||
|
||||
def run_all_tasks(self):
|
||||
"""Synchronous version of run_all_tasks method"""
|
||||
process = Process(
|
||||
tasks=self.tasks,
|
||||
agents=self.agents,
|
||||
manager_llm=self.manager_llm,
|
||||
verbose=self.verbose
|
||||
)
|
||||
|
||||
if self.process == "workflow":
|
||||
for task_id in process.workflow():
|
||||
self.run_task(task_id)
|
||||
elif self.process == "sequential":
|
||||
for task_id in process.sequential():
|
||||
self.run_task(task_id)
|
||||
elif self.process == "hierarchical":
|
||||
for task_id in process.hierarchical():
|
||||
if isinstance(task_id, Task):
|
||||
task_id = self.add_task(task_id)
|
||||
self.run_task(task_id)
|
||||
|
||||
def get_task_status(self, task_id):
|
||||
if task_id in self.tasks:
|
||||
return self.tasks[task_id].status
|
||||
return None
|
||||
|
||||
def get_all_tasks_status(self):
|
||||
return {task_id: self.tasks[task_id].status for task_id in self.tasks}
|
||||
|
||||
def get_task_result(self, task_id):
|
||||
if task_id in self.tasks:
|
||||
return self.tasks[task_id].result
|
||||
return None
|
||||
|
||||
def get_task_details(self, task_id):
|
||||
if task_id in self.tasks:
|
||||
return str(self.tasks[task_id])
|
||||
return None
|
||||
|
||||
def get_agent_details(self, agent_name):
|
||||
agent = [task.agent for task in self.tasks.values() if task.agent and task.agent.name == agent_name]
|
||||
if agent:
|
||||
return str(agent[0])
|
||||
return None
|
||||
|
||||
def start(self):
|
||||
self.run_all_tasks()
|
||||
return {
|
||||
"task_status": self.get_all_tasks_status(),
|
||||
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
|
||||
}
|
||||
|
||||
def set_state(self, key: str, value: Any) -> None:
|
||||
"""Set a state value"""
|
||||
self._state[key] = value
|
||||
|
||||
def get_state(self, key: str, default: Any = None) -> Any:
|
||||
"""Get a state value"""
|
||||
return self._state.get(key, default)
|
||||
|
||||
def update_state(self, updates: Dict) -> None:
|
||||
"""Update multiple state values"""
|
||||
self._state.update(updates)
|
||||
|
||||
def clear_state(self) -> None:
|
||||
"""Clear all state values"""
|
||||
self._state.clear()
|
||||
@@ -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")
|
||||
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.48 gunicorn markdown
|
||||
RUN pip install flask praisonai==2.2.1 gunicorn markdown
|
||||
EXPOSE 8080
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
|
||||
@@ -13,7 +13,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonaiagents>=0.0.4 \
|
||||
praisonai_tools \
|
||||
"praisonai==2.0.18" \
|
||||
"praisonai==2.2.1" \
|
||||
"praisonai[chat]" \
|
||||
"embedchain[github,youtube]"
|
||||
|
||||
@@ -15,7 +15,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonaiagents>=0.0.4 \
|
||||
praisonai_tools \
|
||||
"praisonai==2.0.18" \
|
||||
"praisonai==2.2.1" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[chat]" \
|
||||
"praisonai[realtime]" \
|
||||
@@ -13,7 +13,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonaiagents>=0.0.4 \
|
||||
praisonai_tools \
|
||||
"praisonai==2.0.18" \
|
||||
"praisonai==2.2.1" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[crewai]"
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -6,6 +6,45 @@ 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}>
|
||||
|
||||
@@ -30,7 +30,7 @@ Features:
|
||||
- Built-in tools
|
||||
- Structured workflows
|
||||
|
||||
### AutoGen Integration
|
||||
### AG2 (Formerly AutoGen) Integration
|
||||
Requires installation with:
|
||||
```bash
|
||||
pip install "praisonai[autogen]"
|
||||
|
||||
+4
-4
@@ -23,7 +23,7 @@ from praisonai.auto import AutoGenerator
|
||||
### praisonai.agents_generator
|
||||
Framework-specific agent generation and orchestration:
|
||||
- CrewAI support (requires `praisonai[crewai]`)
|
||||
- AutoGen support (requires `praisonai[autogen]`)
|
||||
- AG2 (Formerly AutoGen) support (requires `praisonai[autogen]`)
|
||||
|
||||
```python
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
@@ -51,7 +51,7 @@ pip install praisonai
|
||||
|
||||
# Framework-specific installations
|
||||
pip install "praisonai[crewai]" # Install with CrewAI support
|
||||
pip install "praisonai[autogen]" # Install with AutoGen support
|
||||
pip install "praisonai[autogen]" # Install with AG2 support
|
||||
pip install "praisonai[crewai,autogen]" # Install both frameworks
|
||||
|
||||
# Additional features
|
||||
@@ -71,9 +71,9 @@ When installing with `pip install "praisonai[crewai]"`, you get:
|
||||
- Task delegation capabilities
|
||||
- Sequential and parallel task execution
|
||||
|
||||
### AutoGen
|
||||
### AG2 (Formerly AutoGen)
|
||||
When installing with `pip install "praisonai[autogen]"`, you get:
|
||||
- AutoGen framework support
|
||||
- AG2 framework support
|
||||
- PraisonAI tools integration
|
||||
- Multi-agent conversation capabilities
|
||||
- Code execution environment
|
||||
@@ -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.48 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.2.1 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
+12
-76
@@ -112,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>
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ flowchart LR
|
||||
end
|
||||
|
||||
subgraph Router[Vector Store]
|
||||
DB[(Chroma)]
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
subgraph Out[Agents]
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
title: "Introduction to AI Agents"
|
||||
description: "Welcome to the beginner's course on AI Agents"
|
||||
icon: "book-open"
|
||||
---
|
||||
|
||||
# Introduction to AI Agents
|
||||
|
||||
Welcome to the beginners' course on AI Agents! This course is designed to help you understand and build your own AI agents, even if you have little to no programming experience.
|
||||
|
||||
## What Are AI Agents?
|
||||
|
||||
An AI agent is a software program that can:
|
||||
- Understand information from its environment
|
||||
- Make decisions based on that information
|
||||
- Take actions to achieve specific goals
|
||||
|
||||
Think of an AI agent like a helpful assistant that can perform tasks for you automatically.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Perceive Information] --> B[Make Decisions]
|
||||
B --> C[Take Actions]
|
||||
C --> A
|
||||
```
|
||||
|
||||
## Examples in Daily Life
|
||||
|
||||
You might already be using AI agents without realizing it:
|
||||
|
||||
- **Virtual Assistants**: Siri, Alexa, and Google Assistant are AI agents that respond to your voice commands
|
||||
- **Recommendation Systems**: Netflix, YouTube, and Amazon use AI agents to suggest content you might like
|
||||
- **Smart Home Devices**: Devices that adjust temperature or lighting based on your preferences
|
||||
|
||||
## What You'll Learn in This Course
|
||||
|
||||
Throughout this course, you will:
|
||||
|
||||
1. Understand the basic concepts of AI agents
|
||||
2. Learn about different types of AI agents
|
||||
3. Explore how AI agents make decisions
|
||||
4. Discover how to build simple AI agents without complex programming
|
||||
5. Create your own functional AI agents
|
||||
|
||||
## Who This Course Is For
|
||||
|
||||
This course is perfect for:
|
||||
- Complete beginners with no prior knowledge of AI
|
||||
- Non-technical professionals interested in how AI can solve problems
|
||||
- Students curious about artificial intelligence
|
||||
- Anyone who wants to understand and use AI agents in practical ways
|
||||
|
||||
Let's begin our journey into the fascinating world of AI agents!
|
||||
<iframe
|
||||
id="codeExecutionFrame"
|
||||
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
|
||||
width="100%"
|
||||
height="600px"
|
||||
frameborder="0"
|
||||
allow="clipboard-read; clipboard-write"
|
||||
scrolling="yes"
|
||||
onload="resizeIframe(this)"
|
||||
></iframe>
|
||||
|
||||
<IframeWithAutoHeight />
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Ready to Start?" icon="rocket">
|
||||
Continue to the next lesson to learn about the different types of AI agents.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,113 @@
|
||||
---
|
||||
title: "Types of AI Agents"
|
||||
description: "Understanding the different categories of AI agents"
|
||||
icon: "sitemap"
|
||||
---
|
||||
|
||||
# Types of AI Agents
|
||||
|
||||
AI agents come in different forms, each designed for specific purposes and with varying levels of complexity. Understanding these types will help you choose the right approach for your needs.
|
||||
|
||||
## Simple Reflex Agents
|
||||
|
||||
These are the most basic type of AI agents that operate using simple if-then rules.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="lightbulb">
|
||||
- React directly to current input only
|
||||
- No memory of past events
|
||||
- No prediction of future states
|
||||
- Use predefined rules to determine actions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: A basic thermostat that turns heating on when temperature drops below a set point.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Sensor Input] --> B{If-Then Rules}
|
||||
B --> C[Action]
|
||||
```
|
||||
|
||||
## Model-Based Agents
|
||||
|
||||
These agents maintain an internal model of their environment to make better decisions.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="brain">
|
||||
- Build and maintain an internal representation of the world
|
||||
- Can work with partial information
|
||||
- Can consider "what if" scenarios
|
||||
- Make decisions based on their understanding of how the world works
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: A GPS navigation system that models roads and traffic conditions.
|
||||
|
||||
## Goal-Based Agents
|
||||
|
||||
These agents make decisions based on how their actions will help achieve specific goals.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="bullseye">
|
||||
- Consider future consequences of actions
|
||||
- Evaluate which actions will lead toward goals
|
||||
- Can plan sequences of actions
|
||||
- Choose actions that maximize goal attainment
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: A chess-playing AI that plans moves to achieve checkmate.
|
||||
|
||||
## Utility-Based Agents
|
||||
|
||||
These agents choose actions that maximize a specific utility (or happiness) function.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="chart-line">
|
||||
- Assign a utility value to different possible outcomes
|
||||
- Consider probability and risk
|
||||
- Choose actions that maximize expected utility
|
||||
- Can balance competing objectives
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: An investment robo-advisor that balances risk and return.
|
||||
|
||||
## Learning Agents
|
||||
|
||||
These agents improve their performance over time through experience.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="graduation-cap">
|
||||
- Learn from past experiences
|
||||
- Adapt to changing environments
|
||||
- Improve decision-making over time
|
||||
- Can discover new strategies
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: Recommendation systems that learn your preferences over time.
|
||||
|
||||
## Understanding Agent Complexity
|
||||
|
||||
<Tip>
|
||||
As you move from Simple Reflex Agents toward Learning Agents, both capability and complexity increase. For beginners, starting with simpler agent types is often best.
|
||||
</Tip>
|
||||
|
||||
## Which Agent Type Should You Build?
|
||||
|
||||
The best type of agent for your project depends on:
|
||||
|
||||
1. **The problem complexity**: Simple problems may only need reflex agents
|
||||
2. **Available data**: Learning agents need training data
|
||||
3. **Required adaptability**: Will your agent need to adapt to new situations?
|
||||
4. **Available resources**: More complex agents require more computational power
|
||||
|
||||
In this course, we'll focus primarily on goal-based and simple learning agents as they provide a good balance of capability and complexity for beginners.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Next Steps" icon="arrow-right">
|
||||
In the next lesson, we'll explore how agents process information and make decisions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,157 @@
|
||||
---
|
||||
title: "Agent Architecture"
|
||||
description: "Understanding how AI agents are structured"
|
||||
icon: "layer-group"
|
||||
---
|
||||
|
||||
# Agent Architecture
|
||||
|
||||
Understanding how AI agents are structured will help you build more effective agents. This lesson covers the fundamental components of an agent's architecture.
|
||||
|
||||
## Basic Components of an AI Agent
|
||||
|
||||
Every AI agent, regardless of complexity, has these basic components:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Sensors/Input] --> B[Processing Unit]
|
||||
B --> C[Decision-Making]
|
||||
C --> D[Actions/Output]
|
||||
```
|
||||
|
||||
### 1. Input (Sensors)
|
||||
|
||||
This is how agents receive information from their environment.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Examples of Input" icon="eye">
|
||||
- Text input from users
|
||||
- Data from databases
|
||||
- Image or audio input
|
||||
- API responses
|
||||
- Sensor readings (in physical agents)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 2. Processing Unit
|
||||
|
||||
This component processes information and converts it into a format the agent can understand.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Processing Functions" icon="gears">
|
||||
- Data cleaning and transformation
|
||||
- Feature extraction
|
||||
- Context building
|
||||
- Information retrieval
|
||||
- Pattern recognition
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 3. Decision-Making Core
|
||||
|
||||
The "brain" of the agent that determines what actions to take.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Decision Components" icon="brain">
|
||||
- Language models (like GPT-4)
|
||||
- Rule systems
|
||||
- Planning algorithms
|
||||
- Knowledge base
|
||||
- Memory systems
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 4. Output (Actions)
|
||||
|
||||
The actions the agent can perform to achieve its goals.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Action Examples" icon="hand">
|
||||
- Generating text responses
|
||||
- Creating visual content
|
||||
- Making API calls
|
||||
- Controlling other systems
|
||||
- Updating databases
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## The Agent Loop
|
||||
|
||||
Agents operate in a continuous loop:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Perceive] --> B[Process]
|
||||
B --> C[Decide]
|
||||
C --> D[Act]
|
||||
D --> A
|
||||
```
|
||||
|
||||
This cycle allows agents to continuously:
|
||||
1. Gather information
|
||||
2. Update their understanding
|
||||
3. Make new decisions
|
||||
4. Take appropriate actions
|
||||
|
||||
## PraisonAI Agent Architecture
|
||||
|
||||
In the PraisonAI framework, agents follow a specific architecture:
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="PraisonAI Agent Components" icon="puzzle-piece">
|
||||
- **Instructions**: Defines the agent's purpose and behavior
|
||||
- **Language Model**: Powers the agent's intelligence (e.g., GPT-4)
|
||||
- **Memory**: Stores context and previous interactions
|
||||
- **Tools**: Specialized capabilities an agent can use
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### Simple Agent Structure
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a simple agent
|
||||
research_agent = Agent(
|
||||
instructions="Research the latest developments in renewable energy",
|
||||
name="ResearchAgent"
|
||||
)
|
||||
|
||||
# Start the agent
|
||||
research_agent.start()
|
||||
```
|
||||
|
||||
## Understanding Agent Communication
|
||||
|
||||
Multi-agent systems allow agents to communicate with each other:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Agent 1] --> B[Agent 2]
|
||||
B --> C[Agent 3]
|
||||
C --> A
|
||||
```
|
||||
|
||||
Each agent can:
|
||||
- Pass information to other agents
|
||||
- Request assistance from specialized agents
|
||||
- Collaborate on complex tasks
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Component Importance" icon="check">
|
||||
Each component plays a vital role in the agent's functionality
|
||||
</Card>
|
||||
<Card title="Agent Customization" icon="gear">
|
||||
You can customize each component based on your specific needs
|
||||
</Card>
|
||||
<Card title="Component Balance" icon="scale-balanced">
|
||||
A well-designed agent balances all components effectively
|
||||
</Card>
|
||||
<Card title="Continuous Improvement" icon="arrow-trend-up">
|
||||
Agents can be improved by enhancing individual components
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to define effective instructions for your AI agents.
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: "Creating Effective Agent Instructions"
|
||||
description: "How to write clear instructions for your AI agents"
|
||||
icon: "file-lines"
|
||||
---
|
||||
|
||||
# Creating Effective Agent Instructions
|
||||
|
||||
The instructions you give to your AI agent are crucial to its performance. Well-crafted instructions lead to agents that understand their purpose and execute tasks effectively.
|
||||
|
||||
## Why Instructions Matter
|
||||
|
||||
Instructions serve as the agent's "job description" and guide its behavior:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clarity" icon="glasses">
|
||||
Clear instructions reduce confusion and misinterpretation
|
||||
</Card>
|
||||
<Card title="Focus" icon="bullseye">
|
||||
Specific instructions keep the agent on task
|
||||
</Card>
|
||||
<Card title="Boundaries" icon="border-all">
|
||||
Good instructions define what an agent should and shouldn't do
|
||||
</Card>
|
||||
<Card title="Personality" icon="face-smile">
|
||||
Instructions can shape how an agent communicates
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Elements of Effective Instructions
|
||||
|
||||
### 1. Role Definition
|
||||
|
||||
Tell the agent who it is and what its expertise should be.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
You are a financial analyst with expertise in market trends and investment strategies.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
You are a helper.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 2. Purpose and Goals
|
||||
|
||||
Clearly state what the agent should accomplish.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
Your goal is to analyze company quarterly reports and provide actionable investment insights.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
Help with finance stuff.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 3. Process Guidelines
|
||||
|
||||
Explain how the agent should approach tasks.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
First analyze the data trends, then identify key risk factors, and finally make recommendations based on the client's risk tolerance.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
Just do a good analysis.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 4. Response Format
|
||||
|
||||
Specify how you want information presented.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
Present your analysis in a structured format with: Summary, Key Findings, Risk Assessment, and Recommendations.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
Tell me what you find.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Instructions Template
|
||||
|
||||
Here's a template you can use to create effective agent instructions:
|
||||
|
||||
```
|
||||
You are a [ROLE] specializing in [EXPERTISE AREAS].
|
||||
|
||||
Your goal is to [MAIN OBJECTIVE].
|
||||
|
||||
When approaching tasks:
|
||||
1. [FIRST STEP/APPROACH]
|
||||
2. [SECOND STEP/APPROACH]
|
||||
3. [THIRD STEP/APPROACH]
|
||||
|
||||
Present your results in [FORMAT PREFERENCES].
|
||||
|
||||
Additional guidelines:
|
||||
- [SPECIFIC BEHAVIOR 1]
|
||||
- [SPECIFIC BEHAVIOR 2]
|
||||
- [SPECIFIC BEHAVIOR 3]
|
||||
```
|
||||
|
||||
## Examples in PraisonAI
|
||||
|
||||
Let's look at how instructions are implemented in PraisonAI:
|
||||
|
||||
<CodeGroup>
|
||||
```python Simple Example
|
||||
from praisonaiagents import Agent
|
||||
|
||||
research_agent = Agent(
|
||||
instructions="You are a research assistant specializing in climate science. Your goal is to find the latest research on rising sea levels and summarize key findings in bullet points."
|
||||
)
|
||||
|
||||
research_agent.start()
|
||||
```
|
||||
|
||||
```python Detailed Example
|
||||
from praisonaiagents import Agent
|
||||
|
||||
content_agent = Agent(
|
||||
name="ContentCreator",
|
||||
instructions="""
|
||||
You are a content creation specialist with expertise in digital marketing.
|
||||
|
||||
Your goal is to create engaging blog content that drives traffic and conversions.
|
||||
|
||||
When creating content:
|
||||
1. Research the target keyword thoroughly
|
||||
2. Create an attention-grabbing headline
|
||||
3. Develop well-structured content with clear sections
|
||||
4. Include actionable takeaways for readers
|
||||
|
||||
Present content in markdown format with proper headings, bullet points, and emphasis where appropriate.
|
||||
|
||||
Additional guidelines:
|
||||
- Maintain a conversational but professional tone
|
||||
- Include 2-3 relevant statistics to support key points
|
||||
- Add a call-to-action at the end of each piece
|
||||
"""
|
||||
)
|
||||
|
||||
content_agent.start("Create a blog post about sustainable living tips")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Common Instruction Mistakes
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Being Too Vague" icon="cloud">
|
||||
Vague instructions lead to unpredictable outputs
|
||||
</Card>
|
||||
<Card title="Information Overload" icon="bomb">
|
||||
Too many details can confuse the agent's priorities
|
||||
</Card>
|
||||
<Card title="Contradictory Guidelines" icon="arrows-split-up-and-left">
|
||||
Conflicting instructions create confusion
|
||||
</Card>
|
||||
<Card title="Missing Context" icon="puzzle-piece-missing">
|
||||
Insufficient background information leads to generic outputs
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Refining Your Instructions
|
||||
|
||||
<Tip>
|
||||
Good instructions often require iteration. Start with basic instructions, review the agent's performance, and refine as needed.
|
||||
</Tip>
|
||||
|
||||
Effective instruction improvement follows this cycle:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Write Initial Instructions] --> B[Test Agent Performance]
|
||||
B --> C[Identify Issues/Gaps]
|
||||
C --> D[Refine Instructions]
|
||||
D --> B
|
||||
```
|
||||
|
||||
In the next lesson, we'll explore how agents use tools to extend their capabilities.
|
||||
@@ -0,0 +1,183 @@
|
||||
---
|
||||
title: "Agent Tools"
|
||||
description: "Understanding how tools extend agent capabilities"
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
# Agent Tools
|
||||
|
||||
Tools allow AI agents to interact with the world and perform specific actions. Think of tools as the "hands" of your agent that let it accomplish tasks beyond just generating text.
|
||||
|
||||
## What Are Agent Tools?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="toolbox">
|
||||
Tools are functions or capabilities that agents can access to perform specific actions, retrieve information, or interact with external systems.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
Just as humans use tools to extend their physical abilities, AI agents use digital tools to extend their capabilities.
|
||||
|
||||
## Why Tools Matter
|
||||
|
||||
Tools transform agents from simple chat interfaces into powerful assistants that can:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Access Information" icon="database">
|
||||
Retrieve data from various sources
|
||||
</Card>
|
||||
<Card title="Perform Calculations" icon="calculator">
|
||||
Analyze numbers and data accurately
|
||||
</Card>
|
||||
<Card title="Create Content" icon="pen-to-square">
|
||||
Generate images, code, or other media
|
||||
</Card>
|
||||
<Card title="Control Systems" icon="gears">
|
||||
Interact with other software or hardware
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Common Types of Tools
|
||||
|
||||
### 1. Information Retrieval Tools
|
||||
|
||||
These tools help agents access information beyond their training data.
|
||||
|
||||
**Examples:**
|
||||
- Web search tools
|
||||
- Database query tools
|
||||
- Document retrieval tools
|
||||
|
||||
```python
|
||||
# Example of a simple web search tool
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def web_search(query):
|
||||
# Simplified example
|
||||
return f"Results for: {query}"
|
||||
|
||||
agent = Agent(
|
||||
instructions="Research assistant",
|
||||
tools=[web_search]
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Computation Tools
|
||||
|
||||
These tools perform calculations or data processing.
|
||||
|
||||
**Examples:**
|
||||
- Calculator tools
|
||||
- Data analysis tools
|
||||
- Conversion tools
|
||||
|
||||
### 3. Content Creation Tools
|
||||
|
||||
These tools help generate or modify various types of content.
|
||||
|
||||
**Examples:**
|
||||
- Image generation tools
|
||||
- Code writing tools
|
||||
- Document formatting tools
|
||||
|
||||
### 4. External API Tools
|
||||
|
||||
These tools connect to third-party services.
|
||||
|
||||
**Examples:**
|
||||
- Weather API tools
|
||||
- Translation API tools
|
||||
- E-commerce API tools
|
||||
|
||||
## How Tools Work in PraisonAI
|
||||
|
||||
In the PraisonAI framework, tools follow a simple pattern:
|
||||
|
||||
1. Tools are defined as functions
|
||||
2. Tools are registered with an agent
|
||||
3. The agent decides when to use appropriate tools
|
||||
4. Tool results are incorporated into the agent's reasoning
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Agent Receives Task] --> B{Needs a Tool?}
|
||||
B -->|Yes| C[Select Appropriate Tool]
|
||||
C --> D[Execute Tool]
|
||||
D --> E[Process Tool Results]
|
||||
E --> F[Continue Task]
|
||||
B -->|No| F
|
||||
```
|
||||
|
||||
## Creating Basic Tools
|
||||
|
||||
Here's a simple example of creating and using tools in PraisonAI:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Define a simple calculator tool
|
||||
def calculator(expression):
|
||||
try:
|
||||
return str(eval(expression))
|
||||
except:
|
||||
return "Error: Could not calculate"
|
||||
|
||||
# Create an agent with the tool
|
||||
math_agent = Agent(
|
||||
instructions="You are a math tutor helping students solve problems",
|
||||
tools=[calculator]
|
||||
)
|
||||
|
||||
# Use the agent
|
||||
math_agent.start("Calculate 24 * 17 and explain the steps")
|
||||
```
|
||||
|
||||
## Tool Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Descriptions" icon="comment">
|
||||
Provide detailed descriptions so the agent knows when to use each tool
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="shield">
|
||||
Make tools robust with proper error handling
|
||||
</Card>
|
||||
<Card title="Focused Purpose" icon="bullseye">
|
||||
Each tool should do one thing well
|
||||
</Card>
|
||||
<Card title="Input Validation" icon="check-double">
|
||||
Validate inputs to prevent misuse
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Building a Toolbox
|
||||
|
||||
As you advance, you'll want to create a collection of tools your agent can use:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tool
|
||||
|
||||
# Define multiple tools
|
||||
def weather(location):
|
||||
return f"Weather in {location}: Sunny, 75°F"
|
||||
|
||||
def translator(text, target_language):
|
||||
return f"Translated to {target_language}: {text} (placeholder)"
|
||||
|
||||
def reminder(message, time):
|
||||
return f"Reminder set for {time}: {message}"
|
||||
|
||||
# Create tool collection
|
||||
tools = [
|
||||
Tool(name="weather", function=weather, description="Get weather for a location"),
|
||||
Tool(name="translator", function=translator, description="Translate text"),
|
||||
Tool(name="reminder", function=reminder, description="Set a reminder")
|
||||
]
|
||||
|
||||
# Create agent with multiple tools
|
||||
assistant = Agent(
|
||||
instructions="You are a helpful personal assistant",
|
||||
tools=tools
|
||||
)
|
||||
```
|
||||
|
||||
In the next lesson, we'll explore how agents use memory to maintain context across interactions.
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
title: "Agent Memory"
|
||||
description: "Understanding how agents maintain context and learn"
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
# Agent Memory
|
||||
|
||||
Memory enables AI agents to remember past interactions, maintain context, and provide more coherent responses over time. Without memory, agents would treat each interaction as if it was their first.
|
||||
|
||||
## Why Memory Matters
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Context Awareness" icon="comments">
|
||||
Remembers previous parts of a conversation
|
||||
</Card>
|
||||
<Card title="Personalization" icon="user-gear">
|
||||
Recalls user preferences and history
|
||||
</Card>
|
||||
<Card title="Continuous Learning" icon="graduation-cap">
|
||||
Builds on past experiences
|
||||
</Card>
|
||||
<Card title="Task Persistence" icon="list-check">
|
||||
Maintains progress on long-running tasks
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Types of Agent Memory
|
||||
|
||||
### 1. Short-Term Memory (Conversation Memory)
|
||||
|
||||
This type of memory stores recent interactions within a session.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[User Input 1] --> B[Agent Response 1]
|
||||
B --> C[User Input 2]
|
||||
C --> D[Agent Response 2]
|
||||
D --> E[User Input 3]
|
||||
```
|
||||
|
||||
The agent can refer back to earlier messages in the same conversation.
|
||||
|
||||
### 2. Long-Term Memory
|
||||
|
||||
This allows agents to remember information across different sessions.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Use Cases" icon="clock">
|
||||
- Remembering user preferences
|
||||
- Recalling previous tasks completed
|
||||
- Storing learned information
|
||||
- Maintaining relationship history
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 3. Working Memory
|
||||
|
||||
This is where agents process current information and combine it with retrieved memories.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Current Input] --> D[Working Memory]
|
||||
B[Short-Term Memory] --> D
|
||||
C[Long-Term Memory] --> D
|
||||
D --> E[Agent Response]
|
||||
```
|
||||
|
||||
## How Memory Works in PraisonAI
|
||||
|
||||
In the PraisonAI framework, memory is handled automatically for basic cases and can be customized for more advanced needs:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Basic agent with default memory handling
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant that remembers our conversations"
|
||||
)
|
||||
|
||||
# The conversation history is maintained automatically
|
||||
agent.start("My name is Alex")
|
||||
agent.continue("What's my name?")# Note: TODO: This Feature yet to be developed # Agent will remember "Alex"
|
||||
```
|
||||
|
||||
## Memory Limitations
|
||||
|
||||
<Tip>
|
||||
All AI memories have limitations. They aren't perfect and may occasionally forget or misremember information.
|
||||
</Tip>
|
||||
|
||||
Common limitations include:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Memory Capacity" icon="database">
|
||||
Limit to how much information can be stored
|
||||
</Card>
|
||||
<Card title="Context Window" icon="window">
|
||||
Only a portion of memory fits in the active context
|
||||
</Card>
|
||||
<Card title="Memory Decay" icon="hourglass-half">
|
||||
Older memories may become less accessible
|
||||
</Card>
|
||||
<Card title="Memory Retrieval" icon="magnifying-glass">
|
||||
Finding the right memory at the right time
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Implementing Persistent Memory
|
||||
|
||||
For more advanced applications, you can implement custom memory systems:
|
||||
|
||||
```python
|
||||
# Note: TODO: This Feature yet to be tested
|
||||
from praisonaiagents import Agent, Memory
|
||||
|
||||
# Create a simple memory store
|
||||
memory = Memory()
|
||||
|
||||
# Add information to memory
|
||||
memory.add("user_name", "Alex")
|
||||
memory.add("favorite_color", "blue")
|
||||
|
||||
# Create agent with this memory
|
||||
agent = Agent(
|
||||
instructions="You are a personal assistant",
|
||||
memory=memory
|
||||
)
|
||||
|
||||
# The agent can now access these memories
|
||||
agent.start("What's my favorite color?") # Agent should respond "blue"
|
||||
```
|
||||
|
||||
## Memory Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prioritize Important Info" icon="star">
|
||||
Not everything needs to be remembered
|
||||
</Card>
|
||||
<Card title="Verify When Uncertain" icon="question">
|
||||
Have agents confirm uncertain memories
|
||||
</Card>
|
||||
<Card title="Structured Storage" icon="folder-tree">
|
||||
Organize memories by categories
|
||||
</Card>
|
||||
<Card title="Regular Updates" icon="arrows-rotate">
|
||||
Update memories when information changes
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Memory in Multi-Agent Systems
|
||||
|
||||
In systems with multiple agents, memory can be:
|
||||
|
||||
1. **Private**: Each agent has its own memories
|
||||
2. **Shared**: Agents have access to a common memory store
|
||||
3. **Hybrid**: Some memories are private, others are shared
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Agent 1] --> B[Private Memory 1]
|
||||
C[Agent 2] --> D[Private Memory 2]
|
||||
A -.-> E[Shared Memory]
|
||||
C -.-> E
|
||||
```
|
||||
|
||||
In the next lesson, we'll learn about how to set up multiple agents to work together effectively.
|
||||
@@ -0,0 +1,171 @@
|
||||
---
|
||||
title: "Multi-Agent Systems"
|
||||
description: "How multiple agents can work together"
|
||||
icon: "users"
|
||||
---
|
||||
|
||||
# Multi-Agent Systems
|
||||
|
||||
Multi-agent systems allow multiple AI agents to work together, each handling different parts of a complex task. This approach mirrors how human teams collaborate, with each member contributing their specialized skills.
|
||||
|
||||
## Why Use Multiple Agents?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Specialization" icon="star">
|
||||
Each agent can focus on its area of expertise
|
||||
</Card>
|
||||
<Card title="Complex Tasks" icon="puzzle-piece">
|
||||
Break down difficult problems into manageable pieces
|
||||
</Card>
|
||||
<Card title="Scalability" icon="arrows-up-down">
|
||||
Add more agents as tasks become more complex
|
||||
</Card>
|
||||
<Card title="Diverse Perspectives" icon="lightbulb">
|
||||
Different agents can approach problems differently
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Basic Multi-Agent Architecture
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Research Agent] --> B[Analysis Agent]
|
||||
B --> C[Writing Agent]
|
||||
C --> D[Final Output]
|
||||
```
|
||||
|
||||
In this example:
|
||||
1. The Research Agent gathers information
|
||||
2. The Analysis Agent processes and interprets the data
|
||||
3. The Writing Agent creates the final content
|
||||
|
||||
## Multi-Agent Patterns
|
||||
|
||||
### 1. Pipeline Pattern
|
||||
|
||||
Agents work in sequence, with each agent handling a specific stage of the process.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Agent 1] --> B[Agent 2]
|
||||
B --> C[Agent 3]
|
||||
```
|
||||
|
||||
**Example Use Case**: Content creation where one agent researches, another drafts, and a third edits.
|
||||
|
||||
### 2. Expert Panel Pattern
|
||||
|
||||
Multiple specialist agents work in parallel on the same problem, then their outputs are combined.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Task --> A[Expert Agent 1]
|
||||
Task --> B[Expert Agent 2]
|
||||
Task --> C[Expert Agent 3]
|
||||
A --> D[Coordination Agent]
|
||||
B --> D
|
||||
C --> D
|
||||
D --> Result
|
||||
```
|
||||
|
||||
**Example Use Case**: Financial analysis where different experts analyze market trends, economic indicators, and company performance.
|
||||
|
||||
### 3. Hierarchical Pattern
|
||||
|
||||
A manager agent delegates tasks to worker agents and coordinates their efforts.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Manager Agent] --> B[Worker Agent 1]
|
||||
A --> C[Worker Agent 2]
|
||||
A --> D[Worker Agent 3]
|
||||
B --> A
|
||||
C --> A
|
||||
D --> A
|
||||
```
|
||||
|
||||
**Example Use Case**: Project management where a coordinator assigns tasks and integrates results.
|
||||
|
||||
## Implementing Multi-Agent Systems in PraisonAI
|
||||
|
||||
Here's a simple example of creating a multi-agent system:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Create individual agents
|
||||
research_agent = Agent(
|
||||
name="Researcher",
|
||||
instructions="Research the latest trends in renewable energy"
|
||||
)
|
||||
|
||||
analysis_agent = Agent(
|
||||
name="Analyst",
|
||||
instructions="Analyze the research findings and identify key insights"
|
||||
)
|
||||
|
||||
writing_agent = Agent(
|
||||
name="Writer",
|
||||
instructions="Create a clear, engaging report based on the analysis"
|
||||
)
|
||||
|
||||
# Create a multi-agent system
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, analysis_agent, writing_agent]
|
||||
)
|
||||
|
||||
# Start the agents
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Agent Communication
|
||||
|
||||
For agents to work together effectively, they need to communicate. This happens through:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Output Passing" icon="arrow-right">
|
||||
One agent's output becomes another's input
|
||||
</Card>
|
||||
<Card title="Shared Memory" icon="database">
|
||||
Agents can access common information
|
||||
</Card>
|
||||
<Card title="Message Exchange" icon="comments">
|
||||
Agents can send specific messages to each other
|
||||
</Card>
|
||||
<Card title="Coordination Protocols" icon="traffic-light">
|
||||
Rules that determine how agents interact
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Challenges in Multi-Agent Systems
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Coordination" icon="shuffle">
|
||||
Ensuring agents work together smoothly
|
||||
</Card>
|
||||
<Card title="Conflicting Goals" icon="arrows-split-up-and-left">
|
||||
Managing agents with different objectives
|
||||
</Card>
|
||||
<Card title="Information Transfer" icon="exchange">
|
||||
Passing information effectively between agents
|
||||
</Card>
|
||||
<Card title="Resource Management" icon="microchip">
|
||||
Allocating computational resources efficiently
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Designing Effective Multi-Agent Systems
|
||||
|
||||
<Tip>
|
||||
Start simple with just 2-3 agents and a clear workflow before scaling to more complex systems.
|
||||
</Tip>
|
||||
|
||||
Key principles for effective design:
|
||||
|
||||
1. **Clear Role Definition**: Each agent should have a specific and well-defined role
|
||||
2. **Minimized Dependencies**: Reduce complex interdependencies between agents
|
||||
3. **Standardized Communication**: Use consistent formats for information exchange
|
||||
4. **Failure Handling**: Plan for cases where an agent fails to complete its task
|
||||
5. **Performance Monitoring**: Track how well each agent and the overall system performs
|
||||
|
||||
In the next lesson, we'll explore how to create effective agent workflows using the Process component.
|
||||
@@ -0,0 +1,152 @@
|
||||
---
|
||||
title: "Agent Process"
|
||||
description: "Understanding agent workflows and processes"
|
||||
icon: "diagram-project"
|
||||
---
|
||||
|
||||
# Agent Process
|
||||
|
||||
The Process component in AI agent systems defines how agents work together and the flow of information between them. Think of it as the "playbook" that coordinates how agents complete tasks.
|
||||
|
||||
## What is an Agent Process?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="route">
|
||||
A process is a structured workflow that defines the sequence of steps, decision points, and information flow between agents to complete a task.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Process Flow Basics
|
||||
|
||||
A simple process flow might look like this:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Start] --> B[Gather Information]
|
||||
B --> C[Process Information]
|
||||
C --> D[Make Decision]
|
||||
D --> E[Take Action]
|
||||
E --> F[Report Results]
|
||||
```
|
||||
|
||||
Each step could be handled by a different agent or by the same agent in different stages.
|
||||
|
||||
## Types of Process Flows
|
||||
|
||||
### 1. Sequential Process
|
||||
|
||||
Agents work in a straight line, one after another.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Agent 1] --> B[Agent 2]
|
||||
B --> C[Agent 3]
|
||||
C --> D[Complete]
|
||||
```
|
||||
|
||||
**Best for**: Tasks with clear, linear stages
|
||||
|
||||
### 2. Parallel Process
|
||||
|
||||
Multiple agents work simultaneously on different parts of a task.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Start] --> B[Agent 1]
|
||||
A --> C[Agent 2]
|
||||
A --> D[Agent 3]
|
||||
B --> E[Combine Results]
|
||||
C --> E
|
||||
D --> E
|
||||
E --> F[Complete]
|
||||
```
|
||||
|
||||
**Best for**: Tasks that can be broken into independent pieces
|
||||
|
||||
### 3. Conditional Process
|
||||
|
||||
The workflow changes based on decisions or conditions.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Start] --> B{Decision Point}
|
||||
B -->|Condition A| C[Agent 1]
|
||||
B -->|Condition B| D[Agent 2]
|
||||
C --> E[Complete]
|
||||
D --> E
|
||||
```
|
||||
|
||||
**Best for**: Tasks requiring different approaches based on circumstances
|
||||
|
||||
## Implementing Process in PraisonAI
|
||||
|
||||
Here's a simple example of creating a process in PraisonAI:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Process, PraisonAIAgents
|
||||
|
||||
# Create agents
|
||||
research_agent = Agent(
|
||||
name="Researcher",
|
||||
instructions="Research the topic and gather key information about AI"
|
||||
)
|
||||
|
||||
writing_agent = Agent(
|
||||
name="Writer",
|
||||
instructions="Create content based on the research"
|
||||
)
|
||||
|
||||
editing_agent = Agent(
|
||||
name="Editor",
|
||||
instructions="Review and improve the content"
|
||||
)
|
||||
|
||||
# Create the multi-agent system with the process
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, writing_agent, editing_agent],
|
||||
process="hierarchical"
|
||||
)
|
||||
|
||||
# Start the process
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Process Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Step Definitions" icon="list-check">
|
||||
Define exactly what each step should accomplish
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="bug">
|
||||
Include steps for handling unexpected situations
|
||||
</Card>
|
||||
<Card title="Feedback Loops" icon="repeat">
|
||||
Allow agents to request clarification when needed
|
||||
</Card>
|
||||
<Card title="Modular Design" icon="cubes">
|
||||
Create reusable process components
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Tip>
|
||||
Start with simple processes and gradually add complexity as you become more comfortable with the system.
|
||||
</Tip>
|
||||
|
||||
## Monitoring Process Execution
|
||||
|
||||
It's important to track how your processes are running:
|
||||
|
||||
```python
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, writing_agent, editing_agent],
|
||||
process=content_process,
|
||||
verbose=True # Enables detailed logging
|
||||
)
|
||||
```
|
||||
|
||||
This will provide information about:
|
||||
- Which step is currently running
|
||||
- The inputs and outputs of each step
|
||||
- Any errors or issues encountered
|
||||
|
||||
In the next lesson, we'll explore how to use knowledge bases to enhance agent capabilities.
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
title: "Knowledge Bases"
|
||||
description: "Enhancing agents with specialized knowledge"
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
# Knowledge Bases
|
||||
|
||||
Knowledge bases provide agents with specialized information beyond their training data. They help agents answer specific questions, follow guidelines, or work within defined domains.
|
||||
|
||||
## What is a Knowledge Base?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="database">
|
||||
A knowledge base is a structured collection of information that an agent can access to answer questions or make decisions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
Think of a knowledge base as a specialized reference library for your agent.
|
||||
|
||||
## Why Use Knowledge Bases?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Domain Expertise" icon="user-graduate">
|
||||
Provide specialized information for specific fields
|
||||
</Card>
|
||||
<Card title="Current Information" icon="clock">
|
||||
Include data beyond the agent's training cutoff
|
||||
</Card>
|
||||
<Card title="Custom Guidelines" icon="list">
|
||||
Define rules and policies for the agent to follow
|
||||
</Card>
|
||||
<Card title="Consistent Responses" icon="equals">
|
||||
Ensure agents provide standardized answers
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Types of Knowledge Bases
|
||||
|
||||
### 1. Document Collections
|
||||
|
||||
Text documents, articles, guides, or manuals that agents can reference.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Query] --> B[Search Documents]
|
||||
B --> C[Find Relevant Content]
|
||||
C --> D[Generate Response]
|
||||
```
|
||||
|
||||
### 2. Structured Data
|
||||
|
||||
Databases, tables, or other structured formats that organize information systematically.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Examples" icon="table">
|
||||
- Product catalogs with specifications
|
||||
- Customer information databases
|
||||
- Statistical data collections
|
||||
- Reference tables for compliance information
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 3. Vector Databases
|
||||
|
||||
Special databases that store information as numerical representations (vectors) for semantic search.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[User Question] --> B[Convert to Vector]
|
||||
B --> C[Find Similar Vectors]
|
||||
C --> D[Retrieve Related Information]
|
||||
D --> E[Generate Answer]
|
||||
```
|
||||
|
||||
## Implementing Knowledge Bases in PraisonAI
|
||||
|
||||
Here's an example of how to use a knowledge base with an agent:
|
||||
|
||||
```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?")
|
||||
```
|
||||
|
||||
## Knowledge Retrieval Process
|
||||
|
||||
When an agent uses a knowledge base, this typical process occurs:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[User Question] --> B[Query Processing]
|
||||
B --> C[Search Knowledge Base]
|
||||
C --> D[Rank Results]
|
||||
D --> E[Synthesize Answer]
|
||||
```
|
||||
|
||||
1. **Query Processing**: The user's question is analyzed
|
||||
2. **Search**: The system searches the knowledge base for relevant information
|
||||
3. **Ranking**: Results are ranked by relevance
|
||||
4. **Synthesis**: The agent creates an answer using the retrieved information
|
||||
|
||||
## Best Practices for Knowledge Bases
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Keep Information Current" icon="arrows-rotate">
|
||||
Regularly update your knowledge base
|
||||
</Card>
|
||||
<Card title="Organize Logically" icon="folder-tree">
|
||||
Structure information in intuitive categories
|
||||
</Card>
|
||||
<Card title="Prioritize Quality" icon="star">
|
||||
Focus on accurate, high-quality information
|
||||
</Card>
|
||||
<Card title="Include Examples" icon="list">
|
||||
Add examples to illustrate complex concepts
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## When to Use Knowledge Bases
|
||||
|
||||
Knowledge bases are particularly valuable when:
|
||||
|
||||
1. Your agent needs to reference specific information that may change over time
|
||||
2. You need to ensure consistent answers to common questions
|
||||
3. Your agent needs to follow specific guidelines or protocols
|
||||
4. You want to provide expertise in specialized domains
|
||||
|
||||
<Tip>
|
||||
Start with a small knowledge base focusing on the most important information, then expand as needed.
|
||||
</Tip>
|
||||
|
||||
## Creating a Simple Knowledge Base
|
||||
|
||||
For beginners, you can start with a simple text-based knowledge base:
|
||||
|
||||
```
|
||||
# Company FAQ Knowledge Base
|
||||
|
||||
## Return Policy
|
||||
Our return policy allows customers to return products within 30 days of purchase for a full refund.
|
||||
|
||||
## Shipping Information
|
||||
Standard shipping takes 3-5 business days. Express shipping takes 1-2 business days.
|
||||
|
||||
## Product Warranty
|
||||
All products come with a 1-year limited warranty covering manufacturing defects.
|
||||
```
|
||||
|
||||
Save this as a text file and add it to your knowledge base:
|
||||
|
||||
```python
|
||||
kb = KnowledgeBase()
|
||||
kb.add_document("company_faq.txt")
|
||||
```
|
||||
|
||||
In the next lesson, we'll explore how agents handle tasks and the task management process.
|
||||
@@ -0,0 +1,274 @@
|
||||
---
|
||||
title: "Agent Tasks"
|
||||
description: "Understanding how agents handle and manage tasks"
|
||||
icon: "clipboard-list"
|
||||
---
|
||||
|
||||
# Agent Tasks
|
||||
|
||||
Tasks are the specific units of work that AI agents perform. Understanding how to define and manage tasks is essential for creating effective agent systems.
|
||||
|
||||
## What is an Agent Task?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="list-check">
|
||||
A task is a specific, well-defined piece of work assigned to an agent with clear inputs, expected outputs, and success criteria.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
Just as human jobs are broken into specific responsibilities, agent systems work best when complex goals are divided into manageable tasks.
|
||||
|
||||
## Anatomy of a Task
|
||||
|
||||
A well-defined task includes:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Objective" icon="bullseye">
|
||||
What the task should accomplish
|
||||
</Card>
|
||||
<Card title="Inputs" icon="arrow-right-to-bracket">
|
||||
Information provided to complete the task
|
||||
</Card>
|
||||
<Card title="Process" icon="gears">
|
||||
Steps to follow or approach to take
|
||||
</Card>
|
||||
<Card title="Outputs" icon="arrow-right-from-bracket">
|
||||
Expected results or deliverables
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Task Types
|
||||
|
||||
### 1. Information Tasks
|
||||
|
||||
These tasks involve finding, analyzing, or summarizing information.
|
||||
|
||||
**Examples:**
|
||||
- Research a topic
|
||||
- Summarize a document
|
||||
- Extract data from text
|
||||
- Answer questions
|
||||
|
||||
### 2. Creation Tasks
|
||||
|
||||
These tasks involve generating new content.
|
||||
|
||||
**Examples:**
|
||||
- Write an article
|
||||
- Create a marketing plan
|
||||
- Generate images (with appropriate tools)
|
||||
- Design a workflow
|
||||
|
||||
### 3. Analysis Tasks
|
||||
|
||||
These tasks involve evaluating information and drawing conclusions.
|
||||
|
||||
**Examples:**
|
||||
- Analyze data trends
|
||||
- Review content for quality
|
||||
- Evaluate options
|
||||
- Identify patterns
|
||||
|
||||
### 4. Interaction Tasks
|
||||
|
||||
These tasks involve communicating or working with users or other systems.
|
||||
|
||||
**Examples:**
|
||||
- Answer customer questions
|
||||
- Guide users through processes
|
||||
- Collect information from users
|
||||
- Notify about events
|
||||
|
||||
## Creating Tasks in PraisonAI
|
||||
|
||||
### Task Flow
|
||||
|
||||
The typical lifecycle of a task follows this pattern:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Define Task] --> B[Assign to Agent]
|
||||
B --> C[Execute Task]
|
||||
C --> D[Return Results]
|
||||
D --> E[Evaluate Success]
|
||||
```
|
||||
|
||||
### Task Configuration
|
||||
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
task = Task(
|
||||
description="Research AI trends",
|
||||
expected_output="Summary report",
|
||||
agent=research_agent
|
||||
)
|
||||
```
|
||||
```python Advanced
|
||||
task = Task(
|
||||
description="Analyze market data",
|
||||
expected_output="Detailed analysis",
|
||||
agent=analyst_agent,
|
||||
tools=[AnalysisTool()],
|
||||
output_file="analysis.md",
|
||||
async_execution=True
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
# Understanding Tasks
|
||||
<br />
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Task Flow Steps
|
||||
Start([▶ Start]) --> TaskDef
|
||||
TaskDef --> AgentAssign
|
||||
AgentAssign --> Exec
|
||||
Exec --> Output([✓ Output])
|
||||
|
||||
%% Define subgraphs for each step
|
||||
subgraph TaskDef[" "]
|
||||
TD_Icon[📋 Task Definition]
|
||||
TD_Desc[Description & Requirements]
|
||||
|
||||
TD_Icon --- TD_Desc
|
||||
|
||||
style TD_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style TD_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph AgentAssign[" "]
|
||||
AA_Icon[🤖 Agent Assignment]
|
||||
AA_Desc[Matching & Delegation]
|
||||
|
||||
AA_Icon --- AA_Desc
|
||||
|
||||
style AA_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AA_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Exec[" "]
|
||||
E_Icon[⚙️ Execution]
|
||||
E_Desc[Processing & Tools]
|
||||
|
||||
E_Icon --- E_Desc
|
||||
|
||||
style E_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style E_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Style for containers
|
||||
style TaskDef fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style AgentAssign fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Exec fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
```
|
||||
<br /><br />
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Task States
|
||||
Pending([📥 Pending]) --> InProgress([⚡ In Progress])
|
||||
InProgress --> Completed([✅ Completed])
|
||||
InProgress --> Failed([❌ Failed])
|
||||
|
||||
%% Styling
|
||||
style Pending fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style InProgress fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Completed fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Failed fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
```
|
||||
|
||||
## Task Types
|
||||
|
||||
<Steps>
|
||||
<Step title="Basic Task">
|
||||
Simple, single-operation tasks with clear inputs and outputs
|
||||
</Step>
|
||||
<Step title="Decision Task">
|
||||
Tasks involving choices and conditional paths
|
||||
```python
|
||||
decision_task = Task(
|
||||
type="decision",
|
||||
conditions={
|
||||
"success": ["next_task"],
|
||||
"failure": ["error_task"]
|
||||
}
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
<Step title="Loop Task">
|
||||
Repetitive operations over collections
|
||||
```python
|
||||
loop_task = Task(
|
||||
type="loop",
|
||||
items=data_list,
|
||||
operation="process_item"
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Task Relationships
|
||||
|
||||
<Warning>
|
||||
Properly managing task dependencies is crucial for complex workflows. Always ensure proper context sharing and error handling.
|
||||
</Warning>
|
||||
|
||||
### Context Sharing
|
||||
```python
|
||||
task_a = Task(name="research")
|
||||
task_b = Task(
|
||||
name="analyze",
|
||||
context=[task_a] # Uses task_a's output
|
||||
)
|
||||
```
|
||||
|
||||
## Task Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Be Specific" icon="magnifying-glass">
|
||||
Clearly define what the task should accomplish
|
||||
</Card>
|
||||
<Card title="One Goal Per Task" icon="check-double">
|
||||
Each task should focus on a single objective
|
||||
</Card>
|
||||
<Card title="Provide Context" icon="circle-info">
|
||||
Include necessary background information
|
||||
</Card>
|
||||
<Card title="Define Success" icon="trophy">
|
||||
Specify what a successful outcome looks like
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Tip>
|
||||
Break complex goals into multiple smaller tasks rather than creating one large, complex task.
|
||||
</Tip>
|
||||
|
||||
## Common Task Mistakes
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Vague Instructions" icon="question">
|
||||
Unclear about what the agent should do
|
||||
</Card>
|
||||
<Card title="Too Many Objectives" icon="list-ol">
|
||||
Asking for too many things in one task
|
||||
</Card>
|
||||
<Card title="Missing Context" icon="puzzle-piece-missing">
|
||||
Not providing necessary background information
|
||||
</Card>
|
||||
<Card title="Unrealistic Expectations" icon="mountain-sun">
|
||||
Asking for tasks beyond agent capabilities
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll learn about creating your first complete agent application.
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
title: "Creating Your First Agent"
|
||||
description: "A step-by-step guide to building your first AI agent"
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
# Creating Your First Agent
|
||||
|
||||
In this lesson, we'll walk through the process of building a simple AI agent. We'll focus on practical implementation without complex programming.
|
||||
|
||||
## What We'll Build
|
||||
|
||||
We'll create a basic research assistant agent that can:
|
||||
- Understand simple instructions
|
||||
- Respond to questions
|
||||
- Provide helpful information
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, make sure you have:
|
||||
|
||||
1. A basic understanding of the concepts from previous lessons
|
||||
2. Python installed on your computer (if following the code examples)
|
||||
3. An OpenAI API key (or access to another supported language model)
|
||||
|
||||
## Step 1: Installation
|
||||
|
||||
First, install the PraisonAI package:
|
||||
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
|
||||
## Step 2: Setup Your Environment
|
||||
|
||||
Create a file called `first_agent.py` and set up your API key:
|
||||
|
||||
```python
|
||||
import os
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Set your API key
|
||||
# Option 1: Set it in your environment (recommended)
|
||||
# export OPENAI_API_KEY=your_key_here
|
||||
|
||||
# Option 2: Set it in your code (not recommended for production)
|
||||
# os.environ["OPENAI_API_KEY"] = "your_key_here"
|
||||
```
|
||||
|
||||
## Step 3: Define Your Agent
|
||||
|
||||
Now, let's create a simple agent:
|
||||
|
||||
```python
|
||||
# Create a research assistant agent
|
||||
research_assistant = Agent(
|
||||
name="ResearchAssistant",
|
||||
instructions="""
|
||||
You are a helpful research assistant that provides clear,
|
||||
accurate information on various topics. When answering:
|
||||
|
||||
1. Be concise and to the point
|
||||
2. Explain complex concepts in simple terms
|
||||
3. When appropriate, organize information with bullet points
|
||||
4. If you don't know something, admit it instead of guessing
|
||||
"""
|
||||
)
|
||||
```
|
||||
|
||||
## Step 4: Start Your Agent
|
||||
|
||||
Now let's use our agent to answer a question:
|
||||
|
||||
```python
|
||||
# Start the agent with a specific query
|
||||
response = research_assistant.start("Explain how solar panels work in simple terms")
|
||||
|
||||
# Print the response
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Step 5: Run Your Agent
|
||||
|
||||
Save the file and run it from your terminal:
|
||||
|
||||
```bash
|
||||
python first_agent.py
|
||||
```
|
||||
|
||||
You should see the agent's response explaining how solar panels work in simple terms.
|
||||
|
||||
## Experimenting with Your Agent
|
||||
|
||||
Try changing the question to see how your agent responds to different topics:
|
||||
|
||||
```python
|
||||
# Try different questions
|
||||
response = research_assistant.start("What are the benefits of exercise?")
|
||||
# or
|
||||
response = research_assistant.start("How does artificial intelligence work?")
|
||||
```
|
||||
|
||||
## Modifying Agent Behavior
|
||||
|
||||
You can change how your agent behaves by adjusting its instructions:
|
||||
|
||||
```python
|
||||
# Create an agent with different instructions
|
||||
creative_writer = Agent(
|
||||
name="CreativeWriter",
|
||||
instructions="""
|
||||
You are a creative writer that specializes in short, engaging stories.
|
||||
Your writing should:
|
||||
|
||||
1. Include vivid descriptions
|
||||
2. Have interesting characters
|
||||
3. Include some dialogue
|
||||
4. Have a clear beginning, middle, and end
|
||||
"""
|
||||
)
|
||||
|
||||
# Ask for a story
|
||||
story = creative_writer.start("Write a short story about a lost dog finding its way home")
|
||||
print(story)
|
||||
```
|
||||
|
||||
## Examining How It Works
|
||||
|
||||
What's happening behind the scenes:
|
||||
|
||||
1. The agent receives your instructions and query
|
||||
2. The language model (like GPT-4) processes the information
|
||||
3. The model generates a response based on the instructions and query
|
||||
4. The response is returned to you
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Your Instructions] --> B[Agent]
|
||||
C[Your Query] --> B
|
||||
B --> D[Language Model]
|
||||
D --> E[Generated Response]
|
||||
E --> F[Output to You]
|
||||
```
|
||||
|
||||
## Common Challenges
|
||||
|
||||
If you encounter issues, check these common problems:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="API Key Issues" icon="key">
|
||||
Make sure your API key is set correctly
|
||||
</Card>
|
||||
<Card title="Connection Problems" icon="wifi">
|
||||
Check your internet connection
|
||||
</Card>
|
||||
<Card title="Unclear Instructions" icon="circle-question">
|
||||
Try making your instructions more specific
|
||||
</Card>
|
||||
<Card title="Rate Limits" icon="hand">
|
||||
You might be making too many API calls
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you've created your first agent, you can:
|
||||
- Experiment with different instructions
|
||||
- Try more complex queries
|
||||
- Add specialized capabilities (we'll cover this in upcoming lessons)
|
||||
- Create agents for specific use cases
|
||||
|
||||
Congratulations on creating your first AI agent! In the next lesson, we'll explore how to add tools to enhance your agent's capabilities.
|
||||
@@ -0,0 +1,275 @@
|
||||
---
|
||||
title: "Adding Tools to Agents"
|
||||
description: "Enhancing your agents with specialized capabilities"
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
# Adding Tools to Agents
|
||||
|
||||
In this lesson, we'll learn how to enhance your agents by adding tools. Tools allow agents to perform specific actions beyond just generating text, making them much more useful for real-world tasks.
|
||||
|
||||
## What You'll Learn
|
||||
|
||||
By the end of this lesson, you'll understand:
|
||||
- What agent tools are and why they're useful
|
||||
- How to create simple tools for your agents
|
||||
- How to integrate tools with your agents
|
||||
- Best practices for tool design
|
||||
|
||||
## Understanding Agent Tools
|
||||
|
||||
Tools give your agents the ability to:
|
||||
- Perform calculations
|
||||
- Access specific information
|
||||
- Interact with external systems
|
||||
- Generate different types of content
|
||||
|
||||
<Tabs>
|
||||
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents duckduckgo-search
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agent with Tool">
|
||||
Create `app.py`
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
# 1. Define the tool
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
# 2. Assign the tool to an agent
|
||||
search_agent = Agent(
|
||||
instructions="Perform internet searches to collect relevant information.",
|
||||
tools=[internet_search_tool] # <--- Tool Assignment
|
||||
)
|
||||
|
||||
# 3. Start Agent
|
||||
search_agent.start("Search about AI job trends in 2025")
|
||||
```
|
||||
|
||||
```python Multiple Agents
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
# 1. Define the tool
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
# 2. Assign the tool to an agent
|
||||
search_agent = Agent(
|
||||
instructions="Search about AI job trends in 2025",
|
||||
tools=[internet_search_tool] # <--- Tool Assignment
|
||||
)
|
||||
|
||||
blog_agent = Agent(
|
||||
instructions="Write a blog article based on the previous agent's search results."
|
||||
)
|
||||
|
||||
# 3. Start Agents
|
||||
agents = PraisonAIAgents(agents=[search_agent, blog_agent])
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package and duckduckgo_search package:
|
||||
```bash Terminal
|
||||
pip install praisonai duckduckgo_search
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Custom Tool">
|
||||
<Info>
|
||||
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
|
||||
</Info>
|
||||
Create a new file `tools.py` with the following content:
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# 1. Tool
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Agent">
|
||||
|
||||
Create a new file `agents.yaml` with the following content:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
topic: create movie script about cat in mars
|
||||
roles:
|
||||
scriptwriter:
|
||||
backstory: Expert in dialogue and script structure, translating concepts into
|
||||
scripts.
|
||||
goal: Write a movie script about a cat in Mars
|
||||
role: Scriptwriter
|
||||
tools:
|
||||
- internet_search_tool # <-- Tool assigned to Agent here
|
||||
tasks:
|
||||
scriptwriting_task:
|
||||
description: Turn the story concept into a production-ready movie script,
|
||||
including dialogue and scene details.
|
||||
expected_output: Final movie script with dialogue and scene details.
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
|
||||
## Creating Custom Tool
|
||||
<Steps>
|
||||
<Step>
|
||||
Create any function that you want to use as a tool, that performs a specific task.
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
Assign the tool to an agent
|
||||
```python
|
||||
data_agent = Agent(
|
||||
instructions="Search about AI job trends in 2025",
|
||||
tools=[internet_search_tool], # <-- Tool Assignment
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Card title="That's it!">
|
||||
<Check>You have created a custom tool and assigned it to an agent.</Check>
|
||||
</Card>
|
||||
|
||||
## When Does the Agent Use Tools?
|
||||
|
||||
The agent decides when to use tools based on:
|
||||
1. The nature of the user's request
|
||||
2. The tools available to it
|
||||
3. The instructions you've provided
|
||||
|
||||
If your agent isn't using tools when expected, you might need to:
|
||||
- Make your instructions more explicit about when to use tools
|
||||
- Provide more descriptive tool definitions
|
||||
- Ensure the tools are appropriate for the task
|
||||
|
||||
## Tool Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Specific Purpose" icon="bullseye">
|
||||
Each tool should have a clear, specific purpose
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="shield-check">
|
||||
Tools should handle errors gracefully
|
||||
</Card>
|
||||
<Card title="Descriptive Names" icon="tag">
|
||||
Use clear names that indicate functionality
|
||||
</Card>
|
||||
<Card title="Clear Documentation" icon="file-lines">
|
||||
Include detailed descriptions and examples
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Real-World Tool Examples
|
||||
|
||||
In production systems, you might create tools for:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Database Access" icon="database">
|
||||
Retrieve or store information in databases
|
||||
</Card>
|
||||
<Card title="API Integration" icon="link">
|
||||
Connect to external services
|
||||
</Card>
|
||||
<Card title="File Operations" icon="folder">
|
||||
Read from or write to files
|
||||
</Card>
|
||||
<Card title="Image Generation" icon="image">
|
||||
Create images based on descriptions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Advanced Tool Concepts
|
||||
|
||||
As you become more comfortable with tools, you can explore:
|
||||
- Tools that call other tools
|
||||
- Tools with complex parameters
|
||||
- Tools that maintain state
|
||||
- Dynamically generated tools
|
||||
|
||||
In the next lesson, we'll explore how to create a multi-agent system for more complex tasks.
|
||||
@@ -0,0 +1,218 @@
|
||||
---
|
||||
title: "Building a Multi-Agent System"
|
||||
description: "Creating a system with multiple cooperative agents"
|
||||
icon: "users"
|
||||
---
|
||||
|
||||
# Building a Multi-Agent System
|
||||
|
||||
In this lesson, we'll create a simple multi-agent system where several agents work together to accomplish a task. This approach allows you to divide complex problems into smaller, more manageable pieces.
|
||||
|
||||
## What We'll Build
|
||||
|
||||
We'll create a content creation system with three specialized agents:
|
||||
1. A research agent to gather information
|
||||
2. A writing agent to create content
|
||||
3. An editing agent to improve and refine the content
|
||||
|
||||
## Step 1: Setting Up
|
||||
|
||||
First, let's import the necessary modules and set up our environment:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Make sure your API key is set in your environment:
|
||||
# export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
|
||||
## Step 2: Creating Specialized Agents
|
||||
|
||||
Now, let's create our three specialized agents:
|
||||
|
||||
```python
|
||||
# Research Agent
|
||||
research_agent = Agent(
|
||||
name="Researcher",
|
||||
instructions="""
|
||||
You are a research specialist who excels at finding relevant information.
|
||||
Your job is to:
|
||||
1. Thoroughly research the given topic
|
||||
2. Identify key facts, statistics, and insights
|
||||
3. Organize the information in a clear, structured format
|
||||
4. Provide accurate information with no fabrications
|
||||
5. Focus on the most relevant and current information
|
||||
"""
|
||||
)
|
||||
|
||||
# Writing Agent
|
||||
writing_agent = Agent(
|
||||
name="Writer",
|
||||
instructions="""
|
||||
You are a content writer who creates engaging, reader-friendly content.
|
||||
Your job is to:
|
||||
1. Use the research provided to create well-structured content
|
||||
2. Write in a clear, engaging style
|
||||
3. Include an attention-grabbing introduction
|
||||
4. Organize the content with appropriate headings
|
||||
5. Conclude with a summary and call-to-action when appropriate
|
||||
"""
|
||||
)
|
||||
|
||||
# Editing Agent
|
||||
editing_agent = Agent(
|
||||
name="Editor",
|
||||
instructions="""
|
||||
You are an editor who refines and improves content.
|
||||
Your job is to:
|
||||
1. Correct any grammatical or spelling errors
|
||||
2. Improve clarity and flow
|
||||
3. Ensure consistency in tone and style
|
||||
4. Check for logical structure and organization
|
||||
5. Enhance readability for the target audience
|
||||
"""
|
||||
)
|
||||
```
|
||||
|
||||
## Step 3: Creating the Multi-Agent System
|
||||
|
||||
Now, let's combine these agents into a multi-agent system:
|
||||
|
||||
```python
|
||||
# Create a multi-agent system
|
||||
content_team = PraisonAIAgents(
|
||||
agents=[research_agent, writing_agent, editing_agent]
|
||||
)
|
||||
```
|
||||
|
||||
## Step 4: Setting Up the Workflow
|
||||
|
||||
Next, we need to define how our agents will work together:
|
||||
|
||||
```python
|
||||
# Define a topic
|
||||
topic = "The Benefits of Regular Exercise"
|
||||
|
||||
# Start the multi-agent process
|
||||
results = content_team.start(
|
||||
f"""
|
||||
Task: Create a comprehensive blog post about {topic}
|
||||
|
||||
Process:
|
||||
1. Researcher: Research {topic} and provide key information including:
|
||||
- Main benefits of exercise (physical and mental)
|
||||
- Recommended exercise guidelines
|
||||
- Scientific studies supporting the benefits
|
||||
- Common misconceptions
|
||||
|
||||
2. Writer: Use the research to create a 500-word blog post about {topic} with:
|
||||
- An engaging introduction
|
||||
- Clear sections with headings
|
||||
- Practical advice for readers
|
||||
- A compelling conclusion
|
||||
|
||||
3. Editor: Review and improve the blog post by:
|
||||
- Correcting any errors
|
||||
- Enhancing clarity and flow
|
||||
- Ensuring a consistent tone
|
||||
- Making the content more engaging
|
||||
"""
|
||||
)
|
||||
|
||||
# Print the final result
|
||||
print(results)
|
||||
```
|
||||
|
||||
## Understanding the Workflow
|
||||
|
||||
Let's examine how the multi-agent system works:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Start] --> B[Research Agent]
|
||||
B --> C[Writing Agent]
|
||||
C --> D[Editing Agent]
|
||||
D --> E[Final Output]
|
||||
```
|
||||
|
||||
1. The research agent gathers and organizes relevant information
|
||||
2. The writing agent uses that research to create the initial content
|
||||
3. The editing agent refines and improves the content
|
||||
4. The final polished content is returned
|
||||
|
||||
## Customizing Agent Interactions
|
||||
|
||||
You can customize how agents interact by modifying the process instructions. For example, you could add feedback loops:
|
||||
|
||||
```python
|
||||
process_with_feedback = """
|
||||
Task: Create a comprehensive blog post about {topic}
|
||||
|
||||
Process:
|
||||
1. Researcher: Research {topic} and provide key information
|
||||
|
||||
2. Writer: Use the research to create a blog post
|
||||
|
||||
3. Editor: Review the blog post and provide feedback
|
||||
|
||||
4. Writer: Revise the blog post based on the editor's feedback
|
||||
|
||||
5. Editor: Make final improvements to the revised blog post
|
||||
"""
|
||||
```
|
||||
|
||||
## Alternative Agent Configurations
|
||||
|
||||
You can organize multi-agent systems in different ways:
|
||||
|
||||
### Parallel Processing
|
||||
|
||||
```python
|
||||
parallel_process = """
|
||||
Task: Create a marketing campaign for a new product
|
||||
|
||||
Process:
|
||||
1. Market Researcher: Research the target market and competitors
|
||||
Content Researcher: Research the product features and benefits
|
||||
[These tasks happen in parallel]
|
||||
|
||||
2. Strategy Agent: Use both research results to create a marketing strategy
|
||||
|
||||
3. Content Creator: Create the marketing materials based on the strategy
|
||||
"""
|
||||
```
|
||||
|
||||
### Expert Panel
|
||||
|
||||
```python
|
||||
expert_panel = """
|
||||
Task: Evaluate a business idea
|
||||
|
||||
Process:
|
||||
1. Financial Expert: Analyze financial viability
|
||||
Market Expert: Analyze market potential
|
||||
Technical Expert: Analyze technical feasibility
|
||||
[These assessments happen in parallel]
|
||||
|
||||
2. Coordinator: Compile all expert opinions into a final recommendation
|
||||
"""
|
||||
```
|
||||
|
||||
## Best Practices for Multi-Agent Systems
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Role Definition" icon="user-tag">
|
||||
Define exactly what each agent is responsible for
|
||||
</Card>
|
||||
<Card title="Explicit Handoffs" icon="arrow-right-arrow-left">
|
||||
Specify how information passes between agents
|
||||
</Card>
|
||||
<Card title="Avoid Redundancy" icon="copy">
|
||||
Don't have multiple agents do the same work
|
||||
</Card>
|
||||
<Card title="Include Error Handling" icon="triangle-exclamation">
|
||||
Plan for cases where an agent might fail
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll learn how to create a conversational agent that can maintain context across multiple interactions.
|
||||
@@ -0,0 +1,193 @@
|
||||
---
|
||||
title: "Building Conversational Agents"
|
||||
description: "Creating agents that maintain context in conversations"
|
||||
icon: "comments"
|
||||
---
|
||||
|
||||
# Building Conversational Agents
|
||||
|
||||
In this lesson, we'll learn how to create conversational agents that can maintain context across multiple interactions. This is essential for creating assistants that feel natural to interact with.
|
||||
|
||||
## What Makes a Good Conversational Agent?
|
||||
|
||||
A good conversational agent should:
|
||||
- Remember previous parts of the conversation
|
||||
- Understand context and references
|
||||
- Provide coherent, relevant responses
|
||||
- Maintain a consistent personality
|
||||
|
||||
## Creating a Simple Conversational Agent
|
||||
|
||||
Let's build a basic conversational agent:
|
||||
|
||||
```python
|
||||
# Note: TODO: This Feature yet to be developed
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a conversational agent
|
||||
chat_agent = Agent(
|
||||
name="Conversational Assistant",
|
||||
instructions="""
|
||||
You are a friendly, helpful conversational assistant.
|
||||
|
||||
When chatting with users:
|
||||
1. Maintain a warm, friendly tone
|
||||
2. Remember information shared earlier in the conversation
|
||||
3. Ask clarifying questions when needed
|
||||
4. Keep responses concise but informative
|
||||
5. Be helpful while respecting boundaries
|
||||
"""
|
||||
)
|
||||
|
||||
# Start a conversation
|
||||
response = chat_agent.start("Hi there! My name is Jamie.")
|
||||
print(response)
|
||||
|
||||
# Continue the conversation
|
||||
response = chat_agent.continue("What can you help me with today?")
|
||||
print(response)
|
||||
|
||||
# The agent should remember the user's name
|
||||
response = chat_agent.continue("Can you remember my name?")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## How Context Works
|
||||
|
||||
PraisonAI automatically manages conversation context for you:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[User Message 1] --> B[Agent]
|
||||
B --> C[Response 1]
|
||||
D[User Message 2] --> E[Agent + Context]
|
||||
E --> F[Response 2]
|
||||
G[User Message 3] --> H[Agent + More Context]
|
||||
H --> I[Response 3]
|
||||
```
|
||||
|
||||
The agent maintains a memory of the conversation, allowing it to refer back to previous messages.
|
||||
|
||||
## Conversation Settings
|
||||
|
||||
You can customize how your conversational agent behaves:
|
||||
|
||||
```python
|
||||
# Create an agent with specific conversation settings
|
||||
custom_chat_agent = Agent(
|
||||
name="Custom Chat Assistant",
|
||||
instructions="You are a helpful assistant",
|
||||
memory_size=10, # Remember the last 10 messages
|
||||
temperature=0.7 # Slightly more creative in responses
|
||||
)
|
||||
```
|
||||
|
||||
## Handling Different Types of Conversations
|
||||
|
||||
Different use cases require different conversation styles:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Customer Support" icon="headset">
|
||||
- Professional and helpful tone
|
||||
- Focus on problem resolution
|
||||
- Remember customer details
|
||||
</Card>
|
||||
<Card title="Educational Tutor" icon="graduation-cap">
|
||||
- Patient and explanatory
|
||||
- Builds on previous lessons
|
||||
- Adjusts to learning pace
|
||||
</Card>
|
||||
<Card title="Personal Assistant" icon="calendar">
|
||||
- Remembers preferences
|
||||
- Provides reminders
|
||||
- Handles scheduling
|
||||
</Card>
|
||||
<Card title="Companion Chat" icon="user-group">
|
||||
- More casual tone
|
||||
- Focuses on engagement
|
||||
- Shows personality
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example: Customer Support Agent
|
||||
|
||||
Let's create a specialized customer support agent:
|
||||
|
||||
```python
|
||||
support_agent = Agent(
|
||||
name="Support Agent",
|
||||
instructions="""
|
||||
You are a customer support specialist for a tech company.
|
||||
|
||||
When helping customers:
|
||||
1. Greet them professionally
|
||||
2. Show empathy for their issues
|
||||
3. Ask for necessary information to troubleshoot
|
||||
4. Provide clear step-by-step solutions
|
||||
5. Confirm if the issue is resolved
|
||||
6. End with an offer for additional help
|
||||
|
||||
Remember product details and customer information throughout the conversation.
|
||||
"""
|
||||
)
|
||||
|
||||
# Example conversation
|
||||
print(support_agent.start("Hi, I'm having trouble logging into my account."))
|
||||
print(support_agent.continue("My username is user123."))
|
||||
print(support_agent.continue("I've tried resetting my password but I'm not receiving the email."))
|
||||
```
|
||||
|
||||
## Building Multi-Turn Conversations
|
||||
|
||||
To create engaging multi-turn conversations, consider:
|
||||
|
||||
1. **Appropriate follow-up questions**: Keep the conversation flowing
|
||||
2. **Acknowledgment**: Reference what the user has said
|
||||
3. **Progressive disclosure**: Don't overwhelm with information at once
|
||||
4. **Conversation repair**: Gracefully handle misunderstandings
|
||||
|
||||
## Example: Multi-Turn Educational Conversation
|
||||
|
||||
```python
|
||||
tutor_agent = Agent(
|
||||
name="Math Tutor",
|
||||
instructions="""
|
||||
You are a patient, encouraging math tutor.
|
||||
|
||||
When teaching:
|
||||
1. Gauge the student's current understanding
|
||||
2. Explain concepts using clear, simple language
|
||||
3. Provide examples to illustrate points
|
||||
4. Ask questions to check understanding
|
||||
5. Give positive reinforcement for progress
|
||||
|
||||
Adapt your explanations based on the student's responses.
|
||||
"""
|
||||
)
|
||||
|
||||
# Example tutoring session
|
||||
print(tutor_agent.start("Can you help me understand algebra?"))
|
||||
print(tutor_agent.continue("I'm struggling with equations like 2x + 5 = 13"))
|
||||
print(tutor_agent.continue("So I subtract 5 from both sides first?"))
|
||||
print(tutor_agent.continue("Then I divide by 2 to get x = 4?"))
|
||||
print(tutor_agent.continue("Could you give me another example to practice?"))
|
||||
```
|
||||
|
||||
## Conversation Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Transitions" icon="arrow-right">
|
||||
Signal when changing topics
|
||||
</Card>
|
||||
<Card title="Manageable Chunks" icon="layer-group">
|
||||
Break complex information into smaller pieces
|
||||
</Card>
|
||||
<Card title="Engagement Checks" icon="hand">
|
||||
Periodically confirm understanding
|
||||
</Card>
|
||||
<Card title="Personality Consistency" icon="masks-theater">
|
||||
Maintain a consistent tone and style
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build agents that can search and retrieve information from external sources.
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
title: "Building Research Agents"
|
||||
description: "Creating agents that can gather and analyze information"
|
||||
icon: "magnifying-glass"
|
||||
---
|
||||
|
||||
# Building Research Agents
|
||||
|
||||
In this lesson, we'll build agents specialized in gathering, analyzing, and summarizing information. Research agents are valuable for quickly obtaining insights on various topics.
|
||||
|
||||
## What is a Research Agent?
|
||||
|
||||
A research agent is designed to:
|
||||
- Find relevant information on specific topics
|
||||
- Analyze and synthesize data
|
||||
- Present findings in a clear, structured format
|
||||
- Answer questions based on gathered information
|
||||
|
||||
## Creating a Basic Research Agent
|
||||
|
||||
Let's start by building a simple research agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic research agent
|
||||
research_agent = Agent(
|
||||
name="ResearchAgent",
|
||||
instructions="""
|
||||
You are a research specialist who finds and summarizes information.
|
||||
|
||||
When researching topics:
|
||||
1. Focus on finding accurate, current information
|
||||
2. Organize findings in a logical structure
|
||||
3. Identify key points and insights
|
||||
4. Cite sources when available
|
||||
5. Present information in a clear, concise format
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the research agent
|
||||
research_results = research_agent.start("Research the impact of renewable energy on reducing carbon emissions")
|
||||
print(research_results)
|
||||
```
|
||||
|
||||
## Adding Web Search Capability
|
||||
|
||||
To make our research agent more powerful, let's add web search capability:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tool
|
||||
|
||||
# Define a web search function (simulated for this example)
|
||||
def web_search(query):
|
||||
"""
|
||||
Simulated web search function.
|
||||
In a real application, this would connect to a search API.
|
||||
|
||||
Args:
|
||||
query (str): The search query
|
||||
|
||||
Returns:
|
||||
str: Search results
|
||||
"""
|
||||
# This is just a simulation - in a real application, you'd call a search API
|
||||
if "renewable energy" in query.lower():
|
||||
return """
|
||||
Search results for 'renewable energy carbon emissions':
|
||||
|
||||
1. According to the IEA, renewable energy prevented 2.1 billion tonnes of CO2 emissions in 2022.
|
||||
|
||||
2. Solar and wind power generate electricity with 95-98% lower carbon emissions than coal-based electricity.
|
||||
|
||||
3. The IPCC reports that renewable energy could deliver more than half of the emission reductions needed by 2030.
|
||||
"""
|
||||
else:
|
||||
return f"Search results for '{query}' (simulated data)"
|
||||
|
||||
# Create the web search tool
|
||||
search_tool = Tool(
|
||||
name="web_search",
|
||||
function=web_search,
|
||||
description="Search the web for current information on a topic"
|
||||
)
|
||||
|
||||
# Create a research agent with web search capability
|
||||
enhanced_research_agent = Agent(
|
||||
name="EnhancedResearchAgent",
|
||||
instructions="""
|
||||
You are a research specialist who finds and summarizes information.
|
||||
|
||||
When researching topics:
|
||||
1. Use the web_search tool to find current information
|
||||
2. Analyze and synthesize the search results
|
||||
3. Organize findings in a logical structure
|
||||
4. Identify key points and insights
|
||||
5. Present information in a clear, concise format
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the enhanced research agent
|
||||
enhanced_results = enhanced_research_agent.start("What is the impact of renewable energy on carbon emissions?")
|
||||
print(enhanced_results)
|
||||
```
|
||||
|
||||
## Research Agent with Structured Output
|
||||
|
||||
For more organized research results, we can instruct the agent to provide structured output:
|
||||
|
||||
```python
|
||||
structured_research_agent = Agent(
|
||||
name="StructuredResearchAgent",
|
||||
instructions="""
|
||||
You are a research specialist who finds and organizes information.
|
||||
|
||||
When researching topics:
|
||||
1. Use available tools to find current information
|
||||
2. Analyze and synthesize the findings
|
||||
|
||||
Always structure your response in this format:
|
||||
|
||||
## Summary
|
||||
[Brief 2-3 sentence overview of the topic]
|
||||
|
||||
## Key Facts
|
||||
- [Important fact 1]
|
||||
- [Important fact 2]
|
||||
- [Important fact 3]
|
||||
|
||||
## Analysis
|
||||
[Deeper analysis of the information, including implications]
|
||||
|
||||
## Sources
|
||||
[List of sources if available]
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the structured research agent
|
||||
structured_results = structured_research_agent.start("Research the latest advancements in quantum computing")
|
||||
print(structured_results)
|
||||
```
|
||||
|
||||
## Specialized Research Agents
|
||||
|
||||
Different research tasks require different approaches. Here are some specialized research agents:
|
||||
|
||||
### Comparison Research Agent
|
||||
|
||||
```python
|
||||
comparison_agent = Agent(
|
||||
name="ComparisonAgent",
|
||||
instructions="""
|
||||
You are a research specialist who compares different options or topics.
|
||||
|
||||
When comparing items:
|
||||
1. Identify the key criteria for comparison
|
||||
2. Research each option thoroughly
|
||||
3. Create a clear side-by-side comparison
|
||||
4. Highlight advantages and disadvantages of each option
|
||||
5. Provide a balanced conclusion
|
||||
|
||||
Present your findings in a structured table format when appropriate.
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the comparison agent
|
||||
comparison_results = comparison_agent.start("Compare solar and wind energy for residential use")
|
||||
print(comparison_results)
|
||||
```
|
||||
|
||||
### Literature Review Agent
|
||||
|
||||
```python
|
||||
literature_agent = Agent(
|
||||
name="LiteratureAgent",
|
||||
instructions="""
|
||||
You are a research specialist who reviews academic and professional literature.
|
||||
|
||||
When reviewing literature:
|
||||
1. Identify key papers, articles, and studies on the topic
|
||||
2. Summarize the main findings and methodologies
|
||||
3. Identify trends, agreements, and contradictions
|
||||
4. Evaluate the strength of evidence
|
||||
5. Highlight gaps in current research
|
||||
|
||||
Structure your review in a clear, academic format.
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the literature review agent
|
||||
literature_results = literature_agent.start("Review recent research on artificial intelligence in healthcare")
|
||||
print(literature_results)
|
||||
```
|
||||
|
||||
## Research Process Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Define Scope" icon="bullseye">
|
||||
Set clear boundaries for the research
|
||||
</Card>
|
||||
<Card title="Verify Information" icon="check-double">
|
||||
Cross-check facts from multiple sources
|
||||
</Card>
|
||||
<Card title="Consider Bias" icon="scale-balanced">
|
||||
Be aware of potential biases in sources
|
||||
</Card>
|
||||
<Card title="Prioritize Relevance" icon="filter">
|
||||
Focus on information most relevant to the query
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build agents that can assist with creative tasks like content creation.
|
||||
@@ -0,0 +1,252 @@
|
||||
---
|
||||
title: "Content Creation Agents"
|
||||
description: "Building agents that generate various types of content"
|
||||
icon: "pen-to-square"
|
||||
---
|
||||
|
||||
# Content Creation Agents
|
||||
|
||||
Content creation agents can help generate various types of content, from blog posts to marketing materials. In this lesson, we'll learn how to build effective content creation agents.
|
||||
|
||||
## What is a Content Creation Agent?
|
||||
|
||||
A content creation agent is designed to:
|
||||
- Generate written content based on specific requirements
|
||||
- Structure content in appropriate formats
|
||||
- Adapt tone and style to match the target audience
|
||||
- Create content that achieves specific goals (inform, persuade, entertain)
|
||||
|
||||
## Creating a Basic Content Creation Agent
|
||||
|
||||
Let's start with a simple content creation agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic content creation agent
|
||||
content_agent = Agent(
|
||||
name="ContentCreator",
|
||||
instructions="""
|
||||
You are a versatile content creator who specializes in writing engaging material.
|
||||
|
||||
When creating content:
|
||||
1. Understand the purpose and target audience
|
||||
2. Create a logical structure with clear sections
|
||||
3. Use an engaging, appropriate writing style
|
||||
4. Include a strong introduction and conclusion
|
||||
5. Format content for easy readability
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the content creation agent
|
||||
blog_post = content_agent.start(
|
||||
"""
|
||||
Create a blog post about the benefits of meditation.
|
||||
Target audience: Busy professionals
|
||||
Length: Approximately 500 words
|
||||
Tone: Informative but conversational
|
||||
"""
|
||||
)
|
||||
print(blog_post)
|
||||
```
|
||||
|
||||
## Specialized Content Creation Agents
|
||||
|
||||
Different types of content require different approaches. Let's create specialized agents for various content needs:
|
||||
|
||||
### Blog Post Agent
|
||||
|
||||
```python
|
||||
blog_agent = Agent(
|
||||
name="BlogWriter",
|
||||
instructions="""
|
||||
You are a blog post writer who creates engaging, informative articles.
|
||||
|
||||
When writing blog posts:
|
||||
1. Create attention-grabbing headlines
|
||||
2. Start with a compelling introduction
|
||||
3. Use subheadings to organize content
|
||||
4. Include relevant examples and evidence
|
||||
5. Incorporate a clear call-to-action at the end
|
||||
|
||||
Format your content with proper Markdown formatting including:
|
||||
- Headings (## for main sections, ### for subsections)
|
||||
- Bullet points for lists
|
||||
- *Italic* for emphasis
|
||||
- **Bold** for important points
|
||||
- > Blockquotes for notable quotes
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the blog agent
|
||||
blog_content = blog_agent.start(
|
||||
"""
|
||||
Topic: 5 Ways to Improve Your Productivity
|
||||
Target audience: Remote workers
|
||||
Style: Practical, actionable advice
|
||||
Length: 800 words
|
||||
Include: Tips, examples, and research-backed information
|
||||
"""
|
||||
)
|
||||
print(blog_content)
|
||||
```
|
||||
|
||||
### Social Media Content Agent
|
||||
|
||||
```python
|
||||
social_media_agent = Agent(
|
||||
name="SocialMediaCreator",
|
||||
instructions="""
|
||||
You are a social media content creator who crafts engaging posts.
|
||||
|
||||
When creating social media content:
|
||||
1. Create attention-grabbing, concise content
|
||||
2. Adapt to the specific platform requirements
|
||||
3. Include relevant hashtags when appropriate
|
||||
4. Craft content that encourages engagement
|
||||
5. Consider visual elements that would pair well with the text
|
||||
|
||||
For each platform, follow these guidelines:
|
||||
- Twitter/X: 280 characters max, punchy, relevant hashtags
|
||||
- LinkedIn: Professional tone, industry insights, 1-3 paragraphs
|
||||
- Instagram: Visual-focused descriptions, emoji-friendly, hashtags
|
||||
- Facebook: Conversational, can be longer, question-based engagement
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the social media agent
|
||||
social_content = social_media_agent.start(
|
||||
"""
|
||||
Create posts for Twitter, LinkedIn, and Facebook announcing:
|
||||
|
||||
Event: Free Webinar on "Future of AI in Business"
|
||||
Date: March 15, 2025
|
||||
Time: 2:00 PM EST
|
||||
Registration link: example.com/webinar
|
||||
Key speakers: Dr. Jane Smith, AI Ethics Expert & Tom Johnson, Business AI Implementation Specialist
|
||||
"""
|
||||
)
|
||||
print(social_content)
|
||||
```
|
||||
|
||||
### Email Campaign Agent
|
||||
|
||||
```python
|
||||
email_agent = Agent(
|
||||
name="EmailWriter",
|
||||
instructions="""
|
||||
You are an email marketing specialist who creates effective email campaigns.
|
||||
|
||||
When writing marketing emails:
|
||||
1. Create compelling subject lines that increase open rates
|
||||
2. Write engaging opening lines that hook the reader
|
||||
3. Keep content concise and focused on a single main message
|
||||
4. Include clear calls-to-action
|
||||
5. Use a tone appropriate for the brand and audience
|
||||
|
||||
Structure your emails with:
|
||||
- Subject line
|
||||
- Greeting
|
||||
- Opening hook
|
||||
- Main content (2-3 paragraphs maximum)
|
||||
- Call-to-action
|
||||
- Sign-off
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the email agent
|
||||
email_content = email_agent.start(
|
||||
"""
|
||||
Create a promotional email for:
|
||||
|
||||
Product: Premium Fitness Subscription
|
||||
Key benefit: Personalized workout plans and nutrition advice
|
||||
Special offer: 30% off first 3 months
|
||||
Target audience: Health-conscious professionals aged 25-45
|
||||
CTA: Sign up for the discounted offer
|
||||
Tone: Motivational but not aggressive
|
||||
"""
|
||||
)
|
||||
print(email_content)
|
||||
```
|
||||
|
||||
## Content Creation with Templates
|
||||
|
||||
Templates can help create more consistent content. Let's build an agent that works with templates:
|
||||
|
||||
```python
|
||||
template_agent = Agent(
|
||||
name="TemplateWriter",
|
||||
instructions="""
|
||||
You are a content creator who works with templates to create consistent content.
|
||||
|
||||
When filling a template:
|
||||
1. Maintain the overall structure of the template
|
||||
2. Replace placeholder text with appropriate content
|
||||
3. Ensure consistency in tone and style
|
||||
4. Adapt content to the specific requirements
|
||||
5. Review for coherence and flow
|
||||
|
||||
Always preserve formatting elements like headings, lists, and emphasis.
|
||||
"""
|
||||
)
|
||||
|
||||
# Example template
|
||||
product_review_template = """
|
||||
# {Product Name} Review: {Brief Opinion}
|
||||
|
||||
## Quick Summary
|
||||
**Rating:** {Rating}/10
|
||||
**Price:** {Price Range}
|
||||
**Recommended For:** {Target User}
|
||||
|
||||
## What We Liked
|
||||
- {Positive Point 1}
|
||||
- {Positive Point 2}
|
||||
- {Positive Point 3}
|
||||
|
||||
## What Could Be Better
|
||||
- {Negative Point 1}
|
||||
- {Negative Point 2}
|
||||
|
||||
## Bottom Line
|
||||
{Conclusion Paragraph}
|
||||
|
||||
"""
|
||||
|
||||
# Use the template agent
|
||||
filled_template = template_agent.start(
|
||||
f"""
|
||||
Fill the following template for a product review:
|
||||
|
||||
{product_review_template}
|
||||
|
||||
Product: Wireless Noise-Cancelling Headphones XZ200
|
||||
Key features: 30-hour battery life, active noise cancellation, voice assistant integration
|
||||
Price: $249.99
|
||||
Target audience: Commuters and office workers
|
||||
Notable pros: Sound quality, comfort, battery life
|
||||
Notable cons: Price, occasional Bluetooth connectivity issues
|
||||
"""
|
||||
)
|
||||
print(filled_template)
|
||||
```
|
||||
|
||||
## Content Creation Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Know Your Audience" icon="users">
|
||||
Understand who will consume the content
|
||||
</Card>
|
||||
<Card title="Clear Purpose" icon="bullseye">
|
||||
Define what the content should achieve
|
||||
</Card>
|
||||
<Card title="Consistent Voice" icon="comment">
|
||||
Maintain a consistent tone and style
|
||||
</Card>
|
||||
<Card title="Readability" icon="eye">
|
||||
Make content easy to scan and understand
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build AI agents that can analyze and work with data.
|
||||
@@ -0,0 +1,333 @@
|
||||
---
|
||||
title: "Data Analysis Agents"
|
||||
description: "Creating agents that analyze and interpret data"
|
||||
icon: "chart-line"
|
||||
---
|
||||
|
||||
# Data Analysis Agents
|
||||
|
||||
Data analysis agents can help process, analyze, and extract insights from data. In this lesson, we'll learn how to build agents that can work with data effectively.
|
||||
|
||||
## What is a Data Analysis Agent?
|
||||
|
||||
A data analysis agent is designed to:
|
||||
- Process and interpret data
|
||||
- Identify patterns and trends
|
||||
- Generate insights and recommendations
|
||||
- Present findings in an understandable format
|
||||
|
||||
## Creating a Basic Data Analysis Agent
|
||||
|
||||
Let's start by building a simple data analysis agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic data analysis agent
|
||||
data_analysis_agent = Agent(
|
||||
name="DataAnalyst",
|
||||
instructions="""
|
||||
You are a data analysis specialist who interprets and explains data.
|
||||
|
||||
When analyzing data:
|
||||
1. First understand what the data represents
|
||||
2. Identify key patterns, trends, or anomalies
|
||||
3. Generate meaningful insights
|
||||
4. Explain findings in simple, clear language
|
||||
5. Provide actionable recommendations when appropriate
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the data analysis agent with sample data
|
||||
sample_data = """
|
||||
Monthly Sales Data (2024):
|
||||
January: $12,500
|
||||
February: $13,200
|
||||
March: $15,800
|
||||
April: $14,300
|
||||
May: $16,700
|
||||
June: $18,900
|
||||
"""
|
||||
|
||||
analysis = data_analysis_agent.start(
|
||||
f"""
|
||||
Analyze the following sales data and provide insights:
|
||||
|
||||
{sample_data}
|
||||
|
||||
Questions to answer:
|
||||
1. What is the overall sales trend?
|
||||
2. Which month had the highest sales?
|
||||
3. What is the average monthly sales?
|
||||
4. What recommendations would you make based on this data?
|
||||
"""
|
||||
)
|
||||
print(analysis)
|
||||
```
|
||||
|
||||
## Adding Data Processing Tools
|
||||
|
||||
Let's enhance our agent with basic data processing capabilities:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tool
|
||||
|
||||
# Define a simple calculation tool
|
||||
def calculate_statistics(data_string):
|
||||
"""
|
||||
Calculate basic statistics from a string of numbers.
|
||||
|
||||
Args:
|
||||
data_string (str): A string with numbers separated by commas
|
||||
|
||||
Returns:
|
||||
str: Statistical summary
|
||||
"""
|
||||
try:
|
||||
# Convert string to list of numbers
|
||||
data = [float(x.strip()) for x in data_string.split(',')]
|
||||
|
||||
# Calculate statistics
|
||||
total = sum(data)
|
||||
average = total / len(data)
|
||||
minimum = min(data)
|
||||
maximum = max(data)
|
||||
|
||||
return f"""
|
||||
Statistical summary:
|
||||
- Count: {len(data)}
|
||||
- Sum: {total}
|
||||
- Average: {average:.2f}
|
||||
- Minimum: {minimum}
|
||||
- Maximum: {maximum}
|
||||
- Range: {maximum - minimum}
|
||||
"""
|
||||
except Exception as e:
|
||||
return f"Error processing data: {str(e)}"
|
||||
|
||||
# Create the tool
|
||||
stats_tool = Tool(
|
||||
name="calculate_statistics",
|
||||
function=calculate_statistics,
|
||||
description="Calculate basic statistics from a list of numbers (comma-separated)"
|
||||
)
|
||||
|
||||
# Create an agent with the statistics tool
|
||||
enhanced_data_agent = Agent(
|
||||
name="EnhancedDataAnalyst",
|
||||
instructions="""
|
||||
You are a data analysis specialist who interprets and explains data.
|
||||
|
||||
When analyzing data:
|
||||
1. First understand what the data represents
|
||||
2. Use the calculate_statistics tool for numerical data
|
||||
3. Identify key patterns, trends, or anomalies
|
||||
4. Generate meaningful insights
|
||||
5. Explain findings in simple, clear language
|
||||
6. Provide actionable recommendations when appropriate
|
||||
""",
|
||||
tools=[stats_tool]
|
||||
)
|
||||
|
||||
# Use the enhanced data agent
|
||||
numerical_data = "12500, 13200, 15800, 14300, 16700, 18900"
|
||||
enhanced_analysis = enhanced_data_agent.start(
|
||||
f"""
|
||||
Analyze the following monthly sales data for the first half of 2024:
|
||||
|
||||
{numerical_data}
|
||||
|
||||
Provide a complete analysis with trends and recommendations.
|
||||
"""
|
||||
)
|
||||
print(enhanced_analysis)
|
||||
```
|
||||
|
||||
## Specialized Data Analysis Agents
|
||||
|
||||
Different analysis tasks require specialized approaches. Let's create some specialized agents:
|
||||
|
||||
### Market Trend Analysis Agent
|
||||
|
||||
```python
|
||||
market_analysis_agent = Agent(
|
||||
name="MarketAnalyst",
|
||||
instructions="""
|
||||
You are a market trend analyst who specializes in identifying patterns and making predictions.
|
||||
|
||||
When analyzing market data:
|
||||
1. Identify long-term trends and short-term patterns
|
||||
2. Compare data points to industry benchmarks
|
||||
3. Identify potential causes for changes
|
||||
4. Assess future implications
|
||||
5. Provide strategic recommendations
|
||||
|
||||
Present your analysis with clear sections for:
|
||||
- Overall Market Assessment
|
||||
- Key Trends Identified
|
||||
- Growth Opportunities
|
||||
- Risk Factors
|
||||
- Strategic Recommendations
|
||||
""",
|
||||
tools=[stats_tool]
|
||||
)
|
||||
|
||||
# Use the market analysis agent
|
||||
market_data = """
|
||||
Industry Growth Rates (2021-2024):
|
||||
2021: 3.2%
|
||||
2022: 2.8%
|
||||
2023: 4.5%
|
||||
2024: 5.1%
|
||||
|
||||
Our Company Growth:
|
||||
2021: 2.9%
|
||||
2022: 3.1%
|
||||
2023: 4.8%
|
||||
2024: 6.3%
|
||||
|
||||
Competitor A Growth:
|
||||
2021: 3.5%
|
||||
2022: 3.7%
|
||||
2023: 4.2%
|
||||
2024: 4.5%
|
||||
|
||||
Competitor B Growth:
|
||||
2021: 3.0%
|
||||
2022: 2.5%
|
||||
2023: 5.0%
|
||||
2024: 5.8%
|
||||
"""
|
||||
|
||||
market_analysis = market_analysis_agent.start(
|
||||
f"""
|
||||
Analyze the following market and company growth data:
|
||||
|
||||
{market_data}
|
||||
|
||||
Provide a comprehensive market analysis and strategic recommendations.
|
||||
"""
|
||||
)
|
||||
print(market_analysis)
|
||||
```
|
||||
|
||||
### Customer Data Analysis Agent
|
||||
|
||||
```python
|
||||
customer_analysis_agent = Agent(
|
||||
name="CustomerAnalyst",
|
||||
instructions="""
|
||||
You are a customer data analyst who specializes in understanding customer behavior.
|
||||
|
||||
When analyzing customer data:
|
||||
1. Identify customer segments and patterns
|
||||
2. Analyze purchasing behavior
|
||||
3. Evaluate customer satisfaction metrics
|
||||
4. Identify opportunities to improve customer experience
|
||||
5. Recommend strategies for customer retention and growth
|
||||
|
||||
Present your analysis with sections for:
|
||||
- Customer Segmentation
|
||||
- Behavior Patterns
|
||||
- Key Insights
|
||||
- Recommended Actions
|
||||
""",
|
||||
tools=[stats_tool]
|
||||
)
|
||||
|
||||
# Use the customer analysis agent
|
||||
customer_data = """
|
||||
Customer Segments by Age:
|
||||
18-24: 15% of customers (Avg. Purchase: $45)
|
||||
25-34: 32% of customers (Avg. Purchase: $78)
|
||||
35-44: 28% of customers (Avg. Purchase: $92)
|
||||
45-54: 18% of customers (Avg. Purchase: $85)
|
||||
55+: 7% of customers (Avg. Purchase: $65)
|
||||
|
||||
Customer Satisfaction:
|
||||
Very Satisfied: 42%
|
||||
Satisfied: 35%
|
||||
Neutral: 15%
|
||||
Dissatisfied: 6%
|
||||
Very Dissatisfied: 2%
|
||||
|
||||
Repeat Purchase Rate:
|
||||
One-time: 40%
|
||||
2-5 purchases: 35%
|
||||
6-10 purchases: 15%
|
||||
10+ purchases: 10%
|
||||
"""
|
||||
|
||||
customer_analysis = customer_analysis_agent.start(
|
||||
f"""
|
||||
Analyze the following customer data:
|
||||
|
||||
{customer_data}
|
||||
|
||||
Provide insights on customer segments, behavior patterns, and recommendations to improve customer retention.
|
||||
"""
|
||||
)
|
||||
print(customer_analysis)
|
||||
```
|
||||
|
||||
## Data Visualization Recommendations
|
||||
|
||||
While our agents can't directly create visualizations, they can recommend appropriate visualization types:
|
||||
|
||||
```python
|
||||
visualization_agent = Agent(
|
||||
name="VisualizationAdvisor",
|
||||
instructions="""
|
||||
You are a data visualization specialist who helps select the best ways to visually represent data.
|
||||
|
||||
When recommending visualizations:
|
||||
1. Understand the nature of the data (categorical, numerical, time-series, etc.)
|
||||
2. Consider the key relationships or patterns to highlight
|
||||
3. Recommend the most appropriate chart or graph type
|
||||
4. Explain why your recommendation is effective
|
||||
5. Provide suggestions for layout, color scheme, and labeling
|
||||
|
||||
Common visualization types to consider:
|
||||
- Line charts (for trends over time)
|
||||
- Bar charts (for comparing categories)
|
||||
- Pie charts (for showing composition, use sparingly)
|
||||
- Scatter plots (for showing relationships between variables)
|
||||
- Heatmaps (for showing patterns in complex data)
|
||||
- Box plots (for showing distributions)
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the visualization agent
|
||||
viz_recommendations = visualization_agent.start(
|
||||
"""
|
||||
I have the following data and need visualization recommendations:
|
||||
|
||||
1. Monthly sales data for the past year
|
||||
2. Customer satisfaction ratings across 5 product categories
|
||||
3. Market share compared to 3 competitors
|
||||
4. Customer age distribution
|
||||
|
||||
What visualizations would you recommend for each of these datasets and why?
|
||||
"""
|
||||
)
|
||||
print(viz_recommendations)
|
||||
```
|
||||
|
||||
## Data Analysis Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Data Quality" icon="shield-check">
|
||||
Ensure data is accurate and complete
|
||||
</Card>
|
||||
<Card title="Context Matters" icon="circle-info">
|
||||
Consider external factors affecting data
|
||||
</Card>
|
||||
<Card title="Clear Communication" icon="comments">
|
||||
Present findings in understandable terms
|
||||
</Card>
|
||||
<Card title="Actionable Insights" icon="bolt">
|
||||
Focus on insights that lead to action
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build AI agents that can assist with customer support tasks.
|
||||
@@ -0,0 +1,260 @@
|
||||
---
|
||||
title: "Customer Support Agents"
|
||||
description: "Building agents that handle customer inquiries and issues"
|
||||
icon: "headset"
|
||||
---
|
||||
|
||||
# Customer Support Agents
|
||||
|
||||
Customer support agents can handle inquiries, resolve issues, and provide assistance to users. In this lesson, we'll learn how to build effective customer support agents.
|
||||
|
||||
## What is a Customer Support Agent?
|
||||
|
||||
A customer support agent is designed to:
|
||||
- Answer frequently asked questions
|
||||
- Troubleshoot common problems
|
||||
- Provide information about products or services
|
||||
- Collect information for support tickets
|
||||
- Guide users through processes or procedures
|
||||
|
||||
## Creating a Basic Customer Support Agent
|
||||
|
||||
Let's start by building a simple customer support agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic customer support agent
|
||||
support_agent = Agent(
|
||||
name="SupportAgent",
|
||||
instructions="""
|
||||
You are a helpful customer support representative for a software company.
|
||||
|
||||
When helping customers:
|
||||
1. Greet them professionally and warmly
|
||||
2. Understand their issue completely before attempting to solve it
|
||||
3. Provide clear, step-by-step solutions when possible
|
||||
4. Maintain a friendly, patient tone throughout
|
||||
5. If you cannot solve the issue, explain how to escalate it
|
||||
|
||||
Our software product is a productivity app with features for:
|
||||
- Task management
|
||||
- Calendar scheduling
|
||||
- Note-taking
|
||||
- Team collaboration
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the support agent
|
||||
response = support_agent.start("I'm having trouble syncing my calendar with my phone. Can you help?")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Adding a Knowledge Base
|
||||
|
||||
Let's enhance our agent with a simple knowledge base to answer common questions:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, KnowledgeBase
|
||||
|
||||
# Create a simple knowledge base
|
||||
faq_kb = KnowledgeBase()
|
||||
|
||||
# Add FAQ content (in a real scenario, you would load this from files)
|
||||
faq_kb.add_text("""
|
||||
# Frequently Asked Questions
|
||||
|
||||
## Account Issues
|
||||
|
||||
### How do I reset my password?
|
||||
To reset your password:
|
||||
1. Go to the login page
|
||||
2. Click on "Forgot Password"
|
||||
3. Enter your email address
|
||||
4. Follow the instructions sent to your email
|
||||
|
||||
### How do I change my email address?
|
||||
To change your email address:
|
||||
1. Log in to your account
|
||||
2. Go to Settings > Account
|
||||
3. Click on "Change Email"
|
||||
4. Enter your new email and confirm with your password
|
||||
|
||||
## Subscription and Billing
|
||||
|
||||
### What subscription plans do you offer?
|
||||
We offer three plans:
|
||||
- Basic: $9.99/month - Includes core features for individuals
|
||||
- Pro: $19.99/month - Includes advanced features and team capabilities for up to 5 users
|
||||
- Enterprise: Custom pricing - Full feature set with advanced security and support
|
||||
|
||||
### How do I cancel my subscription?
|
||||
To cancel your subscription:
|
||||
1. Log in to your account
|
||||
2. Go to Settings > Billing
|
||||
3. Click "Cancel Subscription"
|
||||
4. Follow the confirmation steps
|
||||
|
||||
## Technical Issues
|
||||
|
||||
### Why isn't my calendar syncing?
|
||||
Common reasons for calendar sync issues:
|
||||
1. Outdated app version - Try updating the app
|
||||
2. Account permission issues - Check sync permissions in Settings > Integrations
|
||||
3. Internet connectivity problems - Ensure you have a stable connection
|
||||
|
||||
### How do I export my data?
|
||||
To export your data:
|
||||
1. Go to Settings > Data
|
||||
2. Click "Export Data"
|
||||
3. Choose the data types you want to export
|
||||
4. Select your preferred format (CSV or JSON)
|
||||
5. Click "Export" and save the file
|
||||
""")
|
||||
|
||||
# Create an agent with the knowledge base
|
||||
kb_support_agent = Agent(
|
||||
name="KnowledgeBaseAgent",
|
||||
instructions="""
|
||||
You are a helpful customer support representative with access to our FAQ knowledge base.
|
||||
|
||||
When helping customers:
|
||||
1. Greet them professionally and warmly
|
||||
2. Search the knowledge base for relevant information
|
||||
3. Provide clear, accurate answers based on the knowledge base
|
||||
4. If the knowledge base doesn't cover the question, provide general helpful guidance
|
||||
5. Maintain a friendly, supportive tone throughout
|
||||
""",
|
||||
knowledge_base=faq_kb
|
||||
)
|
||||
|
||||
# Use the knowledge base support agent
|
||||
kb_response = kb_support_agent.start("How do I cancel my subscription?")
|
||||
print(kb_response)
|
||||
```
|
||||
|
||||
## Creating a Troubleshooting Agent
|
||||
|
||||
Let's create an agent specialized in technical troubleshooting:
|
||||
|
||||
```python
|
||||
troubleshooting_agent = Agent(
|
||||
name="TroubleshootingAgent",
|
||||
instructions="""
|
||||
You are a technical support specialist who helps users troubleshoot problems.
|
||||
|
||||
When troubleshooting:
|
||||
1. Ask clarifying questions to understand the exact issue
|
||||
2. Identify the most likely causes of the problem
|
||||
3. Provide step-by-step solutions, starting with the simplest fixes
|
||||
4. Explain what each step does and why it might help
|
||||
5. Confirm if the issue is resolved or suggest next steps
|
||||
|
||||
Common troubleshooting areas:
|
||||
- Login and account access issues
|
||||
- App installation and updates
|
||||
- Feature functionality problems
|
||||
- Data synchronization
|
||||
- Performance issues
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the troubleshooting agent
|
||||
troubleshooting_response = troubleshooting_agent.start("The app keeps crashing when I try to open it on my iPhone")
|
||||
print(troubleshooting_response)
|
||||
```
|
||||
|
||||
## Building a Conversational Support Agent
|
||||
|
||||
Let's create a support agent that can handle multi-turn conversations:
|
||||
|
||||
```python
|
||||
conversational_support = Agent(
|
||||
name="ConversationalSupport",
|
||||
instructions="""
|
||||
You are a customer support representative who handles support conversations.
|
||||
|
||||
When handling support conversations:
|
||||
1. Maintain context throughout the conversation
|
||||
2. Ask follow-up questions when needed
|
||||
3. Verify understanding before providing solutions
|
||||
4. Be patient with users who may be frustrated
|
||||
5. Summarize the conversation and next steps at the end
|
||||
|
||||
Our product is a mobile banking app with features for:
|
||||
- Account balance checking
|
||||
- Money transfers
|
||||
- Bill payments
|
||||
- Mobile check deposits
|
||||
- Budget tracking
|
||||
"""
|
||||
)
|
||||
|
||||
# Start a support conversation
|
||||
initial_response = conversational_support.start("I can't find where to deposit checks in the app")
|
||||
print("Initial Response:", initial_response)
|
||||
|
||||
# Continue the conversation
|
||||
follow_up_response = conversational_support.continue("I'm using version 2.5 of the app on Android")
|
||||
print("Follow-up Response:", follow_up_response)
|
||||
|
||||
# Further continuation
|
||||
resolution_response = conversational_support.continue("I found the deposit button now, but it's giving me an error when I try to take a photo")
|
||||
print("Resolution Response:", resolution_response)
|
||||
```
|
||||
|
||||
## Support Ticket Creation Agent
|
||||
|
||||
Let's create an agent that can gather information for support tickets:
|
||||
|
||||
```python
|
||||
ticket_agent = Agent(
|
||||
name="TicketCreationAgent",
|
||||
instructions="""
|
||||
You are a support ticket creation specialist who gathers the necessary information to create support tickets.
|
||||
|
||||
When creating a ticket:
|
||||
1. Collect the customer's name and contact information
|
||||
2. Identify the category of the issue
|
||||
3. Gather a detailed description of the problem
|
||||
4. Determine the severity level
|
||||
5. Collect relevant technical details (device, software version, etc.)
|
||||
6. Organize all information in a structured ticket format
|
||||
|
||||
Present the final ticket in a clearly formatted structure.
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the ticket creation agent
|
||||
ticket = ticket_agent.start(
|
||||
"""
|
||||
Create a support ticket for the following issue:
|
||||
|
||||
Customer: Jane Smith
|
||||
Email: [email protected]
|
||||
Issue: Cannot access premium features after payment
|
||||
Details: Completed payment yesterday, received confirmation email, but premium features are still locked in the app
|
||||
Using: iPhone 13, app version 3.2.1
|
||||
"""
|
||||
)
|
||||
print(ticket)
|
||||
```
|
||||
|
||||
## Customer Support Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Empathy First" icon="heart">
|
||||
Show understanding before offering solutions
|
||||
</Card>
|
||||
<Card title="Clear Communication" icon="comment">
|
||||
Use simple language, avoid jargon
|
||||
</Card>
|
||||
<Card title="Consistent Responses" icon="equals">
|
||||
Provide consistent answers to similar questions
|
||||
</Card>
|
||||
<Card title="Know Escalation Paths" icon="arrow-up-right">
|
||||
Have clear processes for escalating complex issues
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build AI agents that can assist with personal productivity tasks.
|
||||
@@ -0,0 +1,270 @@
|
||||
---
|
||||
title: "Personal Assistant Agents"
|
||||
description: "Building agents that help with personal tasks and productivity"
|
||||
icon: "calendar-check"
|
||||
---
|
||||
|
||||
# Personal Assistant Agents
|
||||
|
||||
Personal assistant agents can help users manage tasks, organize information, and increase productivity. In this lesson, we'll learn how to build effective personal assistant agents.
|
||||
|
||||
## What is a Personal Assistant Agent?
|
||||
|
||||
A personal assistant agent is designed to:
|
||||
- Manage tasks and reminders
|
||||
- Organize information
|
||||
- Answer questions
|
||||
- Provide recommendations
|
||||
- Help with personal productivity
|
||||
|
||||
## Creating a Basic Personal Assistant Agent
|
||||
|
||||
Let's start by building a simple personal assistant agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic personal assistant agent
|
||||
assistant_agent = Agent(
|
||||
name="PersonalAssistant",
|
||||
instructions="""
|
||||
You are a helpful personal assistant who helps users manage tasks and information.
|
||||
|
||||
When assisting users:
|
||||
1. Be concise and efficient in your responses
|
||||
2. Prioritize user requests based on importance and urgency
|
||||
3. Maintain a helpful, friendly tone
|
||||
4. Remember important information the user shares
|
||||
5. Proactively suggest relevant information when appropriate
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the personal assistant agent
|
||||
response = assistant_agent.start("I need to plan a meeting with my team next Tuesday at 2 PM")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Task Management Assistant
|
||||
|
||||
Let's create an agent specialized in task management:
|
||||
|
||||
```python
|
||||
task_agent = Agent(
|
||||
name="TaskManager",
|
||||
instructions="""
|
||||
You are a task management assistant who helps users organize and prioritize tasks.
|
||||
|
||||
When managing tasks:
|
||||
1. Help identify and clarify tasks
|
||||
2. Assist with prioritization
|
||||
3. Break down complex tasks into manageable steps
|
||||
4. Track deadlines and progress
|
||||
5. Provide reminders and follow-ups
|
||||
|
||||
For each task, collect:
|
||||
- Task description
|
||||
- Priority (High, Medium, Low)
|
||||
- Deadline (if applicable)
|
||||
- Dependencies (other tasks that must be completed first)
|
||||
- Estimated time required
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the task management agent
|
||||
task_response = task_agent.start(
|
||||
"""
|
||||
I need help organizing these tasks for the week:
|
||||
|
||||
- Prepare quarterly report (due Friday)
|
||||
- Meet with client about new project (Wednesday, 2 PM)
|
||||
- Review team's project proposals
|
||||
- Finish budget planning for next quarter
|
||||
- Send feedback on marketing materials
|
||||
"""
|
||||
)
|
||||
print(task_response)
|
||||
```
|
||||
|
||||
## Information Organization Assistant
|
||||
|
||||
Let's create an agent that helps organize information:
|
||||
|
||||
```python
|
||||
info_agent = Agent(
|
||||
name="InformationOrganizer",
|
||||
instructions="""
|
||||
You are an information organization assistant who helps users structure and categorize information.
|
||||
|
||||
When organizing information:
|
||||
1. Identify the main categories and topics
|
||||
2. Create logical groupings
|
||||
3. Suggest clear labels and headers
|
||||
4. Establish relationships between different pieces of information
|
||||
5. Present information in a structured, easily navigable format
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the information organization agent
|
||||
info_response = info_agent.start(
|
||||
"""
|
||||
Help me organize my research notes on climate change:
|
||||
|
||||
- Rising sea levels affecting coastal cities
|
||||
- Carbon dioxide levels increasing annually
|
||||
- Renewable energy adoption statistics by country
|
||||
- Impact of deforestation on carbon sequestration
|
||||
- Climate policy differences between EU and US
|
||||
- Economic impacts of extreme weather events
|
||||
- Public opinion polls on climate action
|
||||
- Arctic ice sheet measurements over 50 years
|
||||
- Agricultural adaptations to changing climate
|
||||
"""
|
||||
)
|
||||
print(info_response)
|
||||
```
|
||||
|
||||
## Daily Planning Assistant
|
||||
|
||||
Let's create an agent that helps with daily planning:
|
||||
|
||||
```python
|
||||
planning_agent = Agent(
|
||||
name="DailyPlanner",
|
||||
instructions="""
|
||||
You are a daily planning assistant who helps users organize their day efficiently.
|
||||
|
||||
When helping with daily planning:
|
||||
1. Prioritize tasks based on importance and deadlines
|
||||
2. Consider time constraints and commitments
|
||||
3. Suggest efficient scheduling
|
||||
4. Allow for breaks and transitions
|
||||
5. Balance work tasks with personal needs
|
||||
|
||||
Create a structured daily plan with time blocks and priorities.
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the daily planning agent
|
||||
planning_response = planning_agent.start(
|
||||
"""
|
||||
Help me plan my day tomorrow. I have:
|
||||
|
||||
- A team meeting from 9:30-10:30 AM
|
||||
- A report due by end of day
|
||||
- Emails to catch up on (about 1 hour's worth)
|
||||
- Lunch with a colleague at 12:30 PM
|
||||
- A dentist appointment at 3:00 PM (will take about 1 hour including travel)
|
||||
- Need to prepare a presentation for Friday
|
||||
|
||||
I typically work from 8:30 AM to 5:30 PM and prefer to have short breaks between tasks.
|
||||
"""
|
||||
)
|
||||
print(planning_response)
|
||||
```
|
||||
|
||||
## Decision Support Assistant
|
||||
|
||||
Let's create an agent that helps with decision-making:
|
||||
|
||||
```python
|
||||
decision_agent = Agent(
|
||||
name="DecisionSupport",
|
||||
instructions="""
|
||||
You are a decision support assistant who helps users make informed choices.
|
||||
|
||||
When supporting decisions:
|
||||
1. Help clarify the decision to be made
|
||||
2. Identify relevant criteria and factors
|
||||
3. Present pros and cons for each option
|
||||
4. Ask questions to understand preferences and priorities
|
||||
5. Provide a structured analysis without making the final decision
|
||||
|
||||
Present options with balanced information to help the user make their own informed choice.
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the decision support agent
|
||||
decision_response = decision_agent.start(
|
||||
"""
|
||||
I'm trying to decide whether to buy a new laptop now or wait 3 months.
|
||||
|
||||
Current situation:
|
||||
- My current laptop is 4 years old and running slow
|
||||
- It still works but has battery issues
|
||||
- I use it daily for work (programming and video calls)
|
||||
- I've heard new models are coming out in 3 months
|
||||
- My budget is around $1,500
|
||||
|
||||
What should I consider in making this decision?
|
||||
"""
|
||||
)
|
||||
print(decision_response)
|
||||
```
|
||||
|
||||
## Recommendation Assistant
|
||||
|
||||
Let's create an agent that provides personalized recommendations:
|
||||
|
||||
```python
|
||||
recommendation_agent = Agent(
|
||||
name="RecommendationAssistant",
|
||||
instructions="""
|
||||
You are a recommendation assistant who provides personalized suggestions.
|
||||
|
||||
When making recommendations:
|
||||
1. Understand the user's preferences and requirements
|
||||
2. Consider constraints (budget, time, location, etc.)
|
||||
3. Provide diverse options that match the criteria
|
||||
4. Explain why each recommendation might be suitable
|
||||
5. Give enough detail for the user to evaluate options
|
||||
|
||||
For each recommendation, include:
|
||||
- A brief description
|
||||
- Key features or highlights
|
||||
- Why it matches the user's needs
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the recommendation agent
|
||||
recommendation_response = recommendation_agent.start(
|
||||
"""
|
||||
Can you recommend some books for me? I enjoy:
|
||||
|
||||
- Science fiction and fantasy
|
||||
- Books with complex, morally gray characters
|
||||
- Intricate world-building
|
||||
- Books that explore philosophical themes
|
||||
|
||||
I've recently read and enjoyed:
|
||||
- "The Fifth Season" by N.K. Jemisin
|
||||
- "Dune" by Frank Herbert
|
||||
- "The Lies of Locke Lamora" by Scott Lynch
|
||||
"""
|
||||
)
|
||||
print(recommendation_response)
|
||||
```
|
||||
|
||||
## Personal Assistant Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Respect Privacy" icon="lock">
|
||||
Be careful with personal information
|
||||
</Card>
|
||||
<Card title="Customize Interactions" icon="sliders">
|
||||
Adapt to the user's preferences
|
||||
</Card>
|
||||
<Card title="Clear Communication" icon="comment">
|
||||
Keep responses direct and easy to understand
|
||||
</Card>
|
||||
<Card title="Contextual Awareness" icon="puzzle-piece">
|
||||
Remember relevant context from previous interactions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to deploy and share your AI agents with others.
|
||||
@@ -0,0 +1,342 @@
|
||||
---
|
||||
title: "Deploying Agents"
|
||||
description: "How to deploy and share your AI agents with others"
|
||||
icon: "rocket"
|
||||
---
|
||||
|
||||
# Deploying Agents
|
||||
|
||||
After creating your AI agents, the next step is deploying them for use by yourself or others. In this final lesson, we'll explore different deployment options and best practices.
|
||||
|
||||
## Deployment Options
|
||||
|
||||
There are several ways to deploy your AI agents:
|
||||
|
||||
### 1. Local Deployment
|
||||
|
||||
Running your agents locally is the simplest approach:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def run_local_agent():
|
||||
agent = Agent(
|
||||
name="SimpleAgent",
|
||||
instructions="You are a helpful assistant that answers questions concisely.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
while True:
|
||||
user_input = input("Ask a question (type 'exit' to quit): ")
|
||||
if user_input.lower() == 'exit':
|
||||
break
|
||||
|
||||
response = agent.start(user_input)
|
||||
print("\nAgent response:")
|
||||
print(response)
|
||||
print("\n" + "-"*50 + "\n")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_local_agent()
|
||||
```
|
||||
|
||||
### 2. Web Application Deployment
|
||||
|
||||
You can deploy your agents as part of a web application:
|
||||
|
||||
```python
|
||||
from flask import Flask, request, jsonify
|
||||
from praisonaiagents import Agent
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Create agent once at startup
|
||||
support_agent = Agent(
|
||||
name="SupportAgent",
|
||||
instructions="You are a customer support agent that helps users with product questions.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
@app.route('/api/support', methods=['POST'])
|
||||
def get_support():
|
||||
data = request.json
|
||||
user_query = data.get('query', '')
|
||||
|
||||
if not user_query:
|
||||
return jsonify({"error": "No query provided"}), 400
|
||||
|
||||
try:
|
||||
response = support_agent.start(user_query)
|
||||
return jsonify({"response": response})
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
```
|
||||
|
||||
### 3. Serverless Function Deployment
|
||||
|
||||
For scalable, event-driven deployments, serverless functions work well:
|
||||
|
||||
```python
|
||||
# Example AWS Lambda function
|
||||
import json
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Initialize agent outside the handler for reuse across invocations
|
||||
agent = Agent(
|
||||
name="ServerlessAgent",
|
||||
instructions="You provide concise, helpful responses to user questions.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
def lambda_handler(event, context):
|
||||
try:
|
||||
# Get the user query from the event
|
||||
body = json.loads(event.get('body', '{}'))
|
||||
user_query = body.get('query', '')
|
||||
|
||||
if not user_query:
|
||||
return {
|
||||
'statusCode': 400,
|
||||
'body': json.dumps({'error': 'No query provided'})
|
||||
}
|
||||
|
||||
# Process with the agent
|
||||
response = agent.start(user_query)
|
||||
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'body': json.dumps({'response': response})
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'statusCode': 500,
|
||||
'body': json.dumps({'error': str(e)})
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variables and Security
|
||||
|
||||
When deploying agents, it's crucial to handle API keys and secrets securely:
|
||||
|
||||
```python
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
# Access API key from environment variable
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
|
||||
# Create agent with API key
|
||||
agent = Agent(
|
||||
name="SecureAgent",
|
||||
instructions="You are a helpful assistant.",
|
||||
llm="gpt-4o-mini", # Using the specified model
|
||||
api_key=api_key # Pass API key securely
|
||||
)
|
||||
```
|
||||
|
||||
## Creating a Simple Chat Interface
|
||||
|
||||
Here's a simple command-line chat interface for your agent:
|
||||
|
||||
```python
|
||||
import os
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def create_chat_interface():
|
||||
# Initialize agent
|
||||
agent = Agent(
|
||||
name="ChatAgent",
|
||||
instructions="""
|
||||
You are a conversational assistant that maintains context throughout the conversation.
|
||||
Respond in a helpful, concise manner.
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
print("Chat with AI Assistant (type 'exit' to quit)")
|
||||
print("-" * 50)
|
||||
|
||||
# Start conversation
|
||||
conversation_active = True
|
||||
first_message = True
|
||||
|
||||
while conversation_active:
|
||||
# Get user input
|
||||
user_message = input("You: ")
|
||||
|
||||
# Check if user wants to exit
|
||||
if user_message.lower() == 'exit':
|
||||
print("Goodbye!")
|
||||
conversation_active = False
|
||||
continue
|
||||
|
||||
# Get agent response
|
||||
try:
|
||||
if first_message:
|
||||
response = agent.start(user_message)
|
||||
first_message = False
|
||||
else:
|
||||
response = agent.continue(user_message)
|
||||
|
||||
print("\nAssistant:", response)
|
||||
print("\n" + "-" * 50)
|
||||
except Exception as e:
|
||||
print(f"Error: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_chat_interface()
|
||||
```
|
||||
|
||||
## Scaling Considerations
|
||||
|
||||
As you deploy agents for wider use, consider these scaling factors:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Rate Limiting" icon="gauge-high">
|
||||
Implement rate limiting to manage API usage and costs
|
||||
</Card>
|
||||
<Card title="Caching" icon="database">
|
||||
Cache common responses to improve performance and reduce API calls
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="triangle-exclamation">
|
||||
Implement robust error handling for API failures
|
||||
</Card>
|
||||
<Card title="Monitoring" icon="chart-line">
|
||||
Set up monitoring for usage patterns and performance issues
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Best Practices for Deployment
|
||||
|
||||
### 1. Testing Before Deployment
|
||||
|
||||
Always test your agents thoroughly before deployment:
|
||||
|
||||
```python
|
||||
def test_agent_functionality():
|
||||
"""Test basic agent functionality with various inputs"""
|
||||
agent = Agent(
|
||||
name="TestAgent",
|
||||
instructions="You are a helpful assistant for testing.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
test_cases = [
|
||||
"What is artificial intelligence?",
|
||||
"How do I reset my password?",
|
||||
"Tell me about machine learning"
|
||||
]
|
||||
|
||||
for test_case in test_cases:
|
||||
print(f"\nTesting: {test_case}")
|
||||
response = agent.start(test_case)
|
||||
print(f"Response: {response[:100]}...") # Print first 100 chars
|
||||
|
||||
# Add assertions or validation logic here
|
||||
assert len(response) > 0, "Response should not be empty"
|
||||
```
|
||||
|
||||
### 2. Documentation
|
||||
|
||||
Create clear documentation for users of your agent:
|
||||
|
||||
```python
|
||||
"""
|
||||
# Customer Support Agent API
|
||||
|
||||
This API provides access to an AI customer support agent
|
||||
that can answer questions about our products.
|
||||
|
||||
## Authentication
|
||||
|
||||
Include your API key in the request header:
|
||||
```
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
```
|
||||
|
||||
## Endpoints
|
||||
|
||||
POST /api/support
|
||||
- Request body: {"query": "Your question here"}
|
||||
- Response: {"response": "Agent's answer"}
|
||||
|
||||
## Example
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://api.example.com/api/support",
|
||||
headers={"Authorization": "Bearer YOUR_API_KEY"},
|
||||
json={"query": "How do I reset my password?"}
|
||||
)
|
||||
|
||||
print(response.json())
|
||||
```
|
||||
"""
|
||||
```
|
||||
|
||||
### 3. Version Control
|
||||
|
||||
Implement version control for your agents to track changes:
|
||||
|
||||
```python
|
||||
class VersionedAgent:
|
||||
def __init__(self, name, version, instructions):
|
||||
self.name = name
|
||||
self.version = version
|
||||
self.agent = Agent(
|
||||
name=f"{name}_v{version}",
|
||||
instructions=instructions,
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
def get_response(self, query):
|
||||
response = self.agent.start(query)
|
||||
return {
|
||||
"agent_name": self.name,
|
||||
"version": self.version,
|
||||
"response": response,
|
||||
"timestamp": datetime.now().isoformat()
|
||||
}
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
Congratulations on completing the AI Agents Course! You've learned how to:
|
||||
|
||||
1. Understand different types of AI agents and their architectures
|
||||
2. Create effective agent instructions and tools
|
||||
3. Implement memory and context for your agents
|
||||
4. Build specialized agents for various tasks
|
||||
5. Create multi-agent systems
|
||||
6. Deploy your agents for real-world use
|
||||
|
||||
As AI agent technology continues to evolve, keep experimenting with new capabilities and use cases. Remember that the best agents are those that effectively solve real problems for users while being trustworthy, reliable, and helpful.
|
||||
|
||||
We hope this course has provided you with the knowledge and skills to build powerful AI agents that enhance productivity and creativity!
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Join the Community" icon="users">
|
||||
Participate in discussions and share your agent projects
|
||||
</Card>
|
||||
<Card title="Stay Updated" icon="newspaper">
|
||||
Follow updates in AI agent technology and new features
|
||||
</Card>
|
||||
<Card title="Share Your Feedback" icon="comment">
|
||||
Let us know how you're using agents and what you'd like to learn next
|
||||
</Card>
|
||||
<Card title="Build Real Solutions" icon="lightbulb">
|
||||
Apply your knowledge to build solutions for real-world problems
|
||||
</Card>
|
||||
</CardGroup>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 134 KiB |
@@ -0,0 +1,416 @@
|
||||
---
|
||||
title: "Deploying to AWS"
|
||||
sidebarTitle: "AWS"
|
||||
description: "Deploy PraisonAI agents to Amazon Web Services for scalable production environments"
|
||||
icon: "aws"
|
||||
---
|
||||
|
||||
# Deploying PraisonAI Agents to AWS
|
||||
|
||||
This guide provides step-by-step instructions for deploying PraisonAI agents to Amazon Web Services (AWS), offering multiple deployment options to suit different requirements.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- AWS account with appropriate permissions
|
||||
- AWS CLI installed and configured
|
||||
- Docker installed on your local machine (for container-based deployments)
|
||||
- Basic knowledge of AWS services and cloud deployment
|
||||
|
||||
## Deployment Options
|
||||
|
||||
There are several ways to deploy PraisonAI agents to AWS:
|
||||
|
||||
1. **AWS Lambda with API Gateway** (for serverless deployments)
|
||||
2. **Amazon ECS/Fargate** (for containerized deployments)
|
||||
3. **Amazon EC2** (for traditional VM-based deployments)
|
||||
4. **AWS App Runner** (for simplified container deployments)
|
||||
|
||||
## Option 1: Deploying to EC2 (Traditional VM)
|
||||
|
||||
<Steps>
|
||||
<Step title="Launch an EC2 Instance">
|
||||
1. Go to the AWS Management Console
|
||||
2. Navigate to EC2 and click "Launch Instance"
|
||||
3. Choose Amazon Linux 2 or Ubuntu Server
|
||||
4. Select an instance type (t2.micro for testing, t2.medium or larger for production)
|
||||
5. Configure security groups to allow HTTP/HTTPS traffic
|
||||
6. Launch the instance and connect to it via SSH
|
||||
</Step>
|
||||
|
||||
<Step title="Set Up the Environment">
|
||||
```bash
|
||||
# Update system packages
|
||||
sudo apt update && sudo apt upgrade -y
|
||||
|
||||
# Install Python and pip
|
||||
sudo apt install -y python3 python3-pip
|
||||
|
||||
# Install required packages
|
||||
pip3 install "praisonaiagents[api]>=0.0.79"
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create the API Application">
|
||||
Create a file named `api.py`:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=8080, host="0.0.0.0")
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set Up a Systemd Service">
|
||||
Create a systemd service file to run your application as a background service:
|
||||
|
||||
```bash
|
||||
sudo nano /etc/systemd/system/praisonai-agent.service
|
||||
```
|
||||
|
||||
Add the following content:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=PraisonAI Agent API Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=ubuntu
|
||||
WorkingDirectory=/home/ubuntu
|
||||
Environment="OPENAI_API_KEY=your_api_key"
|
||||
ExecStart=/usr/bin/python3 /home/ubuntu/api.py
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
Enable and start the service:
|
||||
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable praisonai-agent
|
||||
sudo systemctl start praisonai-agent
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set Up Nginx as a Reverse Proxy">
|
||||
```bash
|
||||
# Install Nginx
|
||||
sudo apt install -y nginx
|
||||
|
||||
# Create a configuration file
|
||||
sudo nano /etc/nginx/sites-available/praisonai-agent
|
||||
```
|
||||
|
||||
Add the following configuration:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name your_domain.com;
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Enable the site and restart Nginx:
|
||||
|
||||
```bash
|
||||
sudo ln -s /etc/nginx/sites-available/praisonai-agent /etc/nginx/sites-enabled/
|
||||
sudo nginx -t
|
||||
sudo systemctl restart nginx
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Option 2: Deploying with Docker and ECS/Fargate
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Run the application
|
||||
CMD ["python", "api.py"]
|
||||
```
|
||||
|
||||
Create a `requirements.txt` file:
|
||||
```
|
||||
praisonaiagents[api]>=0.0.79
|
||||
```
|
||||
|
||||
Create your `api.py` file:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=8080, host="0.0.0.0")
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Build and Push the Docker Image to ECR">
|
||||
```bash
|
||||
# Create an ECR repository
|
||||
aws ecr create-repository --repository-name praisonai-agent
|
||||
|
||||
# Get the login command
|
||||
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com
|
||||
|
||||
# Build the Docker image
|
||||
docker build -t praisonai-agent .
|
||||
|
||||
# Tag the image
|
||||
docker tag praisonai-agent:latest YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest
|
||||
|
||||
# Push the image to ECR
|
||||
docker push YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create an ECS Cluster and Task Definition">
|
||||
```bash
|
||||
# Create an ECS cluster
|
||||
aws ecs create-cluster --cluster-name praisonai-cluster
|
||||
|
||||
# Create a task definition (JSON file)
|
||||
cat > task-definition.json << EOF
|
||||
{
|
||||
"family": "praisonai-agent",
|
||||
"networkMode": "awsvpc",
|
||||
"executionRoleArn": "arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/ecsTaskExecutionRole",
|
||||
"containerDefinitions": [
|
||||
{
|
||||
"name": "praisonai-agent",
|
||||
"image": "YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest",
|
||||
"essential": true,
|
||||
"portMappings": [
|
||||
{
|
||||
"containerPort": 8080,
|
||||
"hostPort": 8080,
|
||||
"protocol": "tcp"
|
||||
}
|
||||
],
|
||||
"environment": [
|
||||
{
|
||||
"name": "OPENAI_API_KEY",
|
||||
"value": "your_api_key"
|
||||
}
|
||||
],
|
||||
"logConfiguration": {
|
||||
"logDriver": "awslogs",
|
||||
"options": {
|
||||
"awslogs-group": "/ecs/praisonai-agent",
|
||||
"awslogs-region": "us-east-1",
|
||||
"awslogs-stream-prefix": "ecs"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"requiresCompatibilities": [
|
||||
"FARGATE"
|
||||
],
|
||||
"cpu": "256",
|
||||
"memory": "512"
|
||||
}
|
||||
EOF
|
||||
|
||||
# Register the task definition
|
||||
aws ecs register-task-definition --cli-input-json file://task-definition.json
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a Fargate Service">
|
||||
```bash
|
||||
# Create a service
|
||||
aws ecs create-service \
|
||||
--cluster praisonai-cluster \
|
||||
--service-name praisonai-service \
|
||||
--task-definition praisonai-agent:1 \
|
||||
--desired-count 1 \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "awsvpcConfiguration={subnets=[subnet-12345678],securityGroups=[sg-12345678],assignPublicIp=ENABLED}" \
|
||||
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef,containerName=praisonai-agent,containerPort=8080"
|
||||
```
|
||||
|
||||
Note: You'll need to create an Application Load Balancer and target group before running this command.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Multi-Agent Deployment
|
||||
|
||||
For deploying multiple agents, you can use a single service with different endpoints:
|
||||
|
||||
```python
|
||||
# multi-agent-api.py
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=8080, host="0.0.0.0")
|
||||
stock_agent.launch(path="/stock", port=8080, host="0.0.0.0")
|
||||
travel_agent.launch(path="/travel", port=8080, host="0.0.0.0")
|
||||
```
|
||||
|
||||
## Option 3: Serverless Deployment with AWS Lambda
|
||||
|
||||
For lightweight agents that don't require long-running processes, you can use AWS Lambda with API Gateway:
|
||||
|
||||
```python
|
||||
# lambda_function.py
|
||||
from praisonaiagents import Agent
|
||||
import json
|
||||
|
||||
# Initialize the agent outside the handler for better cold start performance
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
|
||||
def lambda_handler(event, context):
|
||||
try:
|
||||
# Extract the message from the event
|
||||
body = json.loads(event.get('body', '{}'))
|
||||
message = body.get('message', '')
|
||||
|
||||
# Process the message with the agent
|
||||
response = agent.process(message)
|
||||
|
||||
# Return the response
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'headers': {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
},
|
||||
'body': json.dumps({
|
||||
'response': response
|
||||
})
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'statusCode': 500,
|
||||
'headers': {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
},
|
||||
'body': json.dumps({
|
||||
'error': str(e)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Scaling and Performance
|
||||
|
||||
### Auto Scaling
|
||||
|
||||
For EC2 deployments, set up an Auto Scaling group:
|
||||
|
||||
```bash
|
||||
# Create a launch template
|
||||
aws ec2 create-launch-template \
|
||||
--launch-template-name praisonai-template \
|
||||
--version-description "Initial version" \
|
||||
--launch-template-data '{"ImageId":"ami-12345678","InstanceType":"t2.medium","UserData":"#!/bin/bash\ncd /home/ubuntu\npython3 api.py &"}'
|
||||
|
||||
# Create an Auto Scaling group
|
||||
aws autoscaling create-auto-scaling-group \
|
||||
--auto-scaling-group-name praisonai-asg \
|
||||
--launch-template "LaunchTemplateName=praisonai-template,Version=1" \
|
||||
--min-size 1 \
|
||||
--max-size 5 \
|
||||
--desired-capacity 2 \
|
||||
--vpc-zone-identifier "subnet-12345678,subnet-87654321" \
|
||||
--target-group-arns "arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef"
|
||||
```
|
||||
|
||||
### Load Balancing
|
||||
|
||||
Set up an Application Load Balancer to distribute traffic:
|
||||
|
||||
```bash
|
||||
# Create a load balancer
|
||||
aws elbv2 create-load-balancer \
|
||||
--name praisonai-alb \
|
||||
--subnets subnet-12345678 subnet-87654321 \
|
||||
--security-groups sg-12345678
|
||||
|
||||
# Create a target group
|
||||
aws elbv2 create-target-group \
|
||||
--name praisonai-tg \
|
||||
--protocol HTTP \
|
||||
--port 8080 \
|
||||
--vpc-id vpc-12345678 \
|
||||
--target-type instance
|
||||
|
||||
# Create a listener
|
||||
aws elbv2 create-listener \
|
||||
--load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:loadbalancer/app/praisonai-alb/1234567890abcdef \
|
||||
--protocol HTTP \
|
||||
--port 80 \
|
||||
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef
|
||||
```
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Secret Management**: Use AWS Secrets Manager for API keys
|
||||
```bash
|
||||
# Store a secret
|
||||
aws secretsmanager create-secret \
|
||||
--name OPENAI_API_KEY \
|
||||
--secret-string "your_api_key"
|
||||
```
|
||||
|
||||
2. **IAM Roles**: Use the principle of least privilege
|
||||
3. **VPC**: Deploy in a private subnet with controlled access
|
||||
4. **WAF**: Set up AWS WAF to protect against common web exploits
|
||||
5. **API Gateway**: Implement request validation and throttling
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
1. **CloudWatch**: Set up dashboards and alarms
|
||||
```bash
|
||||
# Create a CloudWatch alarm for high CPU utilization
|
||||
aws cloudwatch put-metric-alarm \
|
||||
--alarm-name praisonai-high-cpu \
|
||||
--alarm-description "Alarm when CPU exceeds 80%" \
|
||||
--metric-name CPUUtilization \
|
||||
--namespace AWS/EC2 \
|
||||
--statistic Average \
|
||||
--period 300 \
|
||||
--threshold 80 \
|
||||
--comparison-operator GreaterThanThreshold \
|
||||
--dimensions Name=AutoScalingGroupName,Value=praisonai-asg \
|
||||
--evaluation-periods 2 \
|
||||
--alarm-actions arn:aws:sns:us-east-1:YOUR_AWS_ACCOUNT_ID:praisonai-alerts
|
||||
```
|
||||
|
||||
2. **X-Ray**: Enable tracing for detailed request analysis
|
||||
3. **CloudTrail**: Monitor API calls for security analysis
|
||||
4. **Log Insights**: Query and analyze logs with CloudWatch Log Insights
|
||||
@@ -0,0 +1,223 @@
|
||||
---
|
||||
title: "Deploying PraisonAI Agents as APIs"
|
||||
sidebarTitle: "API Deployment"
|
||||
description: "Learn how to deploy PraisonAI agents as RESTful APIs for production environments"
|
||||
icon: "server"
|
||||
---
|
||||
|
||||
PraisonAI agents can be easily deployed as RESTful APIs, allowing you to integrate them into various applications and services. This guide covers how to deploy both single and multiple agents as APIs.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
Make sure you have the required packages installed:
|
||||
```bash
|
||||
pip install "praisonaiagents[api]"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY="your_api_key"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy a Simple Agent API">
|
||||
Create a file named `simple-api.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=3030)
|
||||
```
|
||||
</Step>
|
||||
<Step title="Run the API Server">
|
||||
```bash
|
||||
python simple-api.py
|
||||
```
|
||||
|
||||
Your API will be available at `http://localhost:3030/ask`
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Making API Requests
|
||||
|
||||
Once your agent is deployed, you can make POST requests to interact with it:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3030/ask \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "What is artificial intelligence?"}'
|
||||
```
|
||||
|
||||
The response will be in JSON format:
|
||||
|
||||
```json
|
||||
{
|
||||
"response": "Artificial intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think and learn like humans. It encompasses various technologies including machine learning, natural language processing, computer vision, and robotics. AI systems can perform tasks that typically require human intelligence such as understanding natural language, recognizing patterns, solving problems, and making decisions."
|
||||
}
|
||||
```
|
||||
|
||||
## Multi-Agent API Deployment
|
||||
|
||||
You can deploy multiple agents on the same server, each with its own endpoint:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=3030)
|
||||
stock_agent.launch(path="/stock", port=3030)
|
||||
travel_agent.launch(path="/travel", port=3030)
|
||||
```
|
||||
|
||||
With this setup, you can access:
|
||||
- Weather agent at `http://localhost:3030/weather`
|
||||
- Stock agent at `http://localhost:3030/stock`
|
||||
- Travel agent at `http://localhost:3030/travel`
|
||||
|
||||
## Production Deployment Options
|
||||
|
||||
For production environments, consider the following deployment options:
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3030
|
||||
|
||||
CMD ["python", "api.py"]
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create requirements.txt">
|
||||
```
|
||||
praisonaiagents[api]>=0.0.79
|
||||
```
|
||||
</Step>
|
||||
<Step title="Build and Run Docker Container">
|
||||
```bash
|
||||
docker build -t praisonai-api .
|
||||
docker run -p 3030:3030 -e OPENAI_API_KEY=your_api_key praisonai-api
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Cloud Deployment
|
||||
|
||||
#### Deploying to AWS
|
||||
|
||||
<Steps>
|
||||
<Step title="Create an EC2 Instance">
|
||||
Launch an EC2 instance with Ubuntu or Amazon Linux.
|
||||
</Step>
|
||||
<Step title="Install Dependencies">
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y python3-pip
|
||||
pip install "praisonaiagents[api]"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Configure Security Group">
|
||||
Make sure to open port 3030 in your security group settings.
|
||||
</Step>
|
||||
<Step title="Run with Systemd">
|
||||
Create a systemd service file for automatic startup and management.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
#### Deploying to Google Cloud Run
|
||||
|
||||
<Steps>
|
||||
<Step title="Build Docker Image">
|
||||
```bash
|
||||
docker build -t gcr.io/your-project/praisonai-api .
|
||||
```
|
||||
</Step>
|
||||
<Step title="Push to Container Registry">
|
||||
```bash
|
||||
docker push gcr.io/your-project/praisonai-api
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy to Cloud Run">
|
||||
```bash
|
||||
gcloud run deploy praisonai-api \
|
||||
--image gcr.io/your-project/praisonai-api \
|
||||
--platform managed \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars="OPENAI_API_KEY=your_api_key"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## API Configuration Options
|
||||
|
||||
When launching your agent as an API, you can customize various parameters:
|
||||
|
||||
```python
|
||||
agent.launch(
|
||||
path="/custom-endpoint", # API endpoint path
|
||||
port=8080, # Port number
|
||||
host="0.0.0.0", # Host address (0.0.0.0 for external access)
|
||||
debug=True, # Enable debug mode
|
||||
cors_origins=["*"], # CORS configuration
|
||||
api_key="your-api-key" # Optional API key for authentication
|
||||
)
|
||||
```
|
||||
|
||||
## Securing Your API
|
||||
|
||||
For production deployments, consider implementing:
|
||||
|
||||
1. **API Key Authentication**: Require API keys for all requests
|
||||
2. **Rate Limiting**: Limit the number of requests per client
|
||||
3. **HTTPS**: Use SSL/TLS certificates for encrypted communication
|
||||
4. **Input Validation**: Validate all input data before processing
|
||||
|
||||
## Monitoring and Scaling
|
||||
|
||||
For production environments, consider:
|
||||
|
||||
1. **Load Balancing**: Distribute traffic across multiple instances
|
||||
2. **Auto-Scaling**: Automatically adjust resources based on demand
|
||||
3. **Logging**: Implement comprehensive logging for debugging
|
||||
4. **Monitoring**: Set up alerts for errors and performance issues
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="RESTful API" icon="server">
|
||||
Deploy your agents as standard RESTful APIs for easy integration.
|
||||
</Card>
|
||||
<Card title="Multi-Agent Support" icon="users">
|
||||
Deploy multiple agents with different endpoints on the same server.
|
||||
</Card>
|
||||
<Card title="Customizable" icon="gear">
|
||||
Configure ports, paths, CORS settings, and more.
|
||||
</Card>
|
||||
<Card title="Production-Ready" icon="rocket">
|
||||
Easily deploy to Docker, AWS, Google Cloud, or other cloud platforms.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,248 @@
|
||||
---
|
||||
title: "Deploying to Google Cloud"
|
||||
sidebarTitle: "Google Cloud"
|
||||
description: "Deploy PraisonAI agents to Google Cloud Platform for scalable production environments"
|
||||
icon: "google"
|
||||
---
|
||||
|
||||
# Deploying PraisonAI Agents to Google Cloud
|
||||
|
||||
This guide provides step-by-step instructions for deploying PraisonAI agents to Google Cloud Platform using Cloud Run, which offers a serverless environment for containerized applications.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Google Cloud account with billing enabled
|
||||
- Google Cloud SDK installed and configured
|
||||
- Docker installed on your local machine
|
||||
- Basic knowledge of containerization and cloud deployment
|
||||
|
||||
## Deployment Options
|
||||
|
||||
There are several ways to deploy PraisonAI agents to Google Cloud:
|
||||
|
||||
1. **Google Cloud Run** (recommended for most use cases)
|
||||
2. **Google Compute Engine** (for custom VM requirements)
|
||||
3. **Google Kubernetes Engine** (for complex, scalable deployments)
|
||||
|
||||
This guide focuses on Cloud Run as it's the simplest and most cost-effective option for most deployments.
|
||||
|
||||
## Deploying to Google Cloud Run
|
||||
|
||||
<Steps>
|
||||
<Step title="Prepare Your Application">
|
||||
Create a simple API file named `api.py`:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=8080, host="0.0.0.0")
|
||||
```
|
||||
|
||||
Note: Cloud Run expects your application to listen on the port defined by the `PORT` environment variable, which defaults to 8080.
|
||||
</Step>
|
||||
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Set environment variables
|
||||
ENV PORT=8080
|
||||
|
||||
# Run the application
|
||||
CMD exec python api.py
|
||||
```
|
||||
|
||||
Create a `requirements.txt` file:
|
||||
```
|
||||
praisonaiagents[api]>=0.0.79
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Build and Push the Docker Image">
|
||||
```bash
|
||||
# Build the Docker image
|
||||
docker build -t gcr.io/YOUR_PROJECT_ID/praisonai-agent .
|
||||
|
||||
# Configure Docker to use Google Cloud credentials
|
||||
gcloud auth configure-docker
|
||||
|
||||
# Push the image to Google Container Registry
|
||||
docker push gcr.io/YOUR_PROJECT_ID/praisonai-agent
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Deploy to Cloud Run">
|
||||
```bash
|
||||
gcloud run deploy praisonai-agent \
|
||||
--image gcr.io/YOUR_PROJECT_ID/praisonai-agent \
|
||||
--platform managed \
|
||||
--region us-central1 \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars="OPENAI_API_KEY=your_api_key"
|
||||
```
|
||||
|
||||
Note: For production deployments, it's recommended to use Secret Manager for API keys instead of environment variables.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Multi-Agent Deployment
|
||||
|
||||
For deploying multiple agents, you can use a single Cloud Run service with different endpoints:
|
||||
|
||||
```python
|
||||
# multi-agent-api.py
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=8080, host="0.0.0.0")
|
||||
stock_agent.launch(path="/stock", port=8080, host="0.0.0.0")
|
||||
travel_agent.launch(path="/travel", port=8080, host="0.0.0.0")
|
||||
```
|
||||
|
||||
## Scaling and Performance
|
||||
|
||||
Google Cloud Run automatically scales based on traffic, from zero to many instances. You can configure:
|
||||
|
||||
- **Minimum instances**: Keep a certain number of instances warm to avoid cold starts
|
||||
- **Maximum instances**: Limit the number of instances to control costs
|
||||
- **Memory allocation**: Allocate more memory for complex agents
|
||||
- **CPU allocation**: Allocate dedicated CPUs for compute-intensive workloads
|
||||
|
||||
```bash
|
||||
gcloud run services update praisonai-agent \
|
||||
--min-instances=1 \
|
||||
--max-instances=10 \
|
||||
--memory=2Gi \
|
||||
--cpu=1
|
||||
```
|
||||
|
||||
## Continuous Deployment
|
||||
|
||||
Set up continuous deployment with Cloud Build:
|
||||
|
||||
```yaml
|
||||
# cloudbuild.yaml
|
||||
steps:
|
||||
# Build the container image
|
||||
- name: 'gcr.io/cloud-builders/docker'
|
||||
args: ['build', '-t', 'gcr.io/$PROJECT_ID/praisonai-agent', '.']
|
||||
# Push the container image to Container Registry
|
||||
- name: 'gcr.io/cloud-builders/docker'
|
||||
args: ['push', 'gcr.io/$PROJECT_ID/praisonai-agent']
|
||||
# Deploy container image to Cloud Run
|
||||
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
|
||||
entrypoint: gcloud
|
||||
args:
|
||||
- 'run'
|
||||
- 'deploy'
|
||||
- 'praisonai-agent'
|
||||
- '--image'
|
||||
- 'gcr.io/$PROJECT_ID/praisonai-agent'
|
||||
- '--region'
|
||||
- 'us-central1'
|
||||
- '--platform'
|
||||
- 'managed'
|
||||
- '--allow-unauthenticated'
|
||||
substitutions:
|
||||
_REGION: us-central1
|
||||
images:
|
||||
- 'gcr.io/$PROJECT_ID/praisonai-agent'
|
||||
```
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
Google Cloud provides comprehensive monitoring and logging capabilities:
|
||||
|
||||
- **Cloud Monitoring**: Set up dashboards and alerts for your deployed agents
|
||||
- **Cloud Logging**: View and analyze logs from your applications
|
||||
- **Error Reporting**: Automatically detect and group errors
|
||||
|
||||
Access logs through the Google Cloud Console or using the gcloud command:
|
||||
|
||||
```bash
|
||||
gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=praisonai-agent" --limit=10
|
||||
```
|
||||
|
||||
## Cost Optimization
|
||||
|
||||
Cloud Run charges based on the resources your service uses only when it's processing requests. To optimize costs:
|
||||
|
||||
1. Set appropriate memory and CPU allocations
|
||||
2. Configure minimum instances based on traffic patterns
|
||||
3. Use regional deployments closest to your users
|
||||
4. Implement caching for frequent requests
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Secret Management**: Store API keys and credentials in Secret Manager
|
||||
```bash
|
||||
# Create a secret
|
||||
echo -n "your_api_key" | gcloud secrets create openai-api-key --data-file=-
|
||||
|
||||
# Grant access to the Cloud Run service
|
||||
gcloud secrets add-iam-policy-binding openai-api-key \
|
||||
--member=serviceAccount:YOUR_SERVICE_ACCOUNT \
|
||||
--role=roles/secretmanager.secretAccessor
|
||||
|
||||
# Reference in deployment
|
||||
gcloud run deploy praisonai-agent \
|
||||
--image gcr.io/YOUR_PROJECT_ID/praisonai-agent \
|
||||
--set-secrets=OPENAI_API_KEY=openai-api-key:latest
|
||||
```
|
||||
|
||||
2. **Service Identity**: Use dedicated service accounts with minimal permissions
|
||||
3. **Network Security**: Configure VPC Service Controls for sensitive deployments
|
||||
4. **API Authentication**: Implement authentication for your API endpoints
|
||||
|
||||
## All in One
|
||||
|
||||
```bash
|
||||
gcloud init
|
||||
gcloud services enable run.googleapis.com
|
||||
gcloud services enable containerregistry.googleapis.com
|
||||
gcloud services enable cloudbuild.googleapis.com
|
||||
|
||||
export OPENAI_MODEL_NAME="gpt-4o"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
export OPENAI_API_BASE="https://api.openai.com/v1"
|
||||
|
||||
yes | gcloud auth configure-docker us-central1-docker.pkg.dev
|
||||
gcloud artifacts repositories create praisonai-repository --repository-format=docker --location=us-central1
|
||||
|
||||
PROJECT_ID=$(gcloud config get-value project)
|
||||
TAG="latest"
|
||||
docker build --platform linux/amd64 -t gcr.io/${PROJECT_ID}/praisonai-app:${TAG} .
|
||||
docker tag gcr.io/${PROJECT_ID}/praisonai-app:${TAG} us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
|
||||
docker push us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
|
||||
|
||||
gcloud run deploy praisonai-service \
|
||||
--image us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG} \
|
||||
--platform managed \
|
||||
--region us-central1 \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars OPENAI_MODEL_NAME=${OPENAI_MODEL_NAME},OPENAI_API_KEY=${OPENAI_API_KEY},OPENAI_API_BASE=${OPENAI_API_BASE}
|
||||
```
|
||||
@@ -0,0 +1,405 @@
|
||||
---
|
||||
title: "Deploying MCP Servers"
|
||||
sidebarTitle: "MCP Servers"
|
||||
description: "Learn how to deploy Model Context Protocol (MCP) servers for production environments"
|
||||
icon: "server-rack"
|
||||
---
|
||||
|
||||
# Deploying MCP Servers
|
||||
|
||||
This guide focuses on deploying Model Context Protocol (MCP) servers for production environments. MCP servers allow AI models to access tools and external systems through a standardized protocol.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
Make sure you have the required packages installed:
|
||||
```bash
|
||||
pip install "praisonaiagents[mcp]"
|
||||
```
|
||||
|
||||
For the multi-agent example with search capabilities:
|
||||
```bash
|
||||
pip install "praisonaiagents[mcp]" duckduckgo-search
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create MCP Server Files">
|
||||
**Single Agent MCP Server**
|
||||
|
||||
Create a file named `simple-mcp-server.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="Create a Tweet based on the topic provided")
|
||||
agent.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
|
||||
**Multi-Agent MCP Server with Custom Tools**
|
||||
|
||||
Create a file named `simple-mcp-multi-agents-server.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
agent = Agent(instructions="You Search the internet for information", tools=[internet_search_tool])
|
||||
agent2 = Agent(instructions="You Summarise the information")
|
||||
|
||||
agents = Agents(agents=[agent, agent2])
|
||||
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
|
||||
**Simple Multi-Agent MCP Server**
|
||||
|
||||
Create a file named `simple-multi-agents-server.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents
|
||||
|
||||
agent = Agent(instructions="You Search the internet for information")
|
||||
agent2 = Agent(instructions="You Summarise the information")
|
||||
|
||||
agents = Agents(agents=[agent, agent2])
|
||||
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
agent = Agent(instructions="You Search the internet for information", tools=[internet_search_tool])
|
||||
agent2 = Agent(instructions="You Summarise the information")
|
||||
|
||||
agents = Agents(agents=[agent, agent2])
|
||||
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Containerization with Docker
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Expose the port
|
||||
EXPOSE 8080
|
||||
|
||||
# Run the MCP server
|
||||
CMD ["python", "simple-mcp-server.py"]
|
||||
```
|
||||
|
||||
Create a `requirements.txt` file:
|
||||
```
|
||||
praisonaiagents[mcp]
|
||||
duckduckgo-search # Only needed for the multi-agent example
|
||||
```
|
||||
</Step>
|
||||
<Step title="Build and Run the Docker Container">
|
||||
```bash
|
||||
# Build the Docker image
|
||||
docker build -t mcp-server .
|
||||
|
||||
# Run the container
|
||||
docker run -p 8080:8080 -e OPENAI_API_KEY=your_api_key mcp-server
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Cloud Deployment
|
||||
|
||||
### AWS Elastic Container Service (ECS)
|
||||
|
||||
<Steps>
|
||||
<Step title="Push Docker Image to ECR">
|
||||
```bash
|
||||
# Create an ECR repository
|
||||
aws ecr create-repository --repository-name mcp-server
|
||||
|
||||
# Authenticate Docker to ECR
|
||||
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com
|
||||
|
||||
# Tag and push the image
|
||||
docker tag mcp-server:latest YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest
|
||||
docker push YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create ECS Task Definition">
|
||||
```json
|
||||
{
|
||||
"family": "mcp-server",
|
||||
"networkMode": "awsvpc",
|
||||
"executionRoleArn": "arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/ecsTaskExecutionRole",
|
||||
"containerDefinitions": [
|
||||
{
|
||||
"name": "mcp-server",
|
||||
"image": "YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest",
|
||||
"essential": true,
|
||||
"portMappings": [
|
||||
{
|
||||
"containerPort": 8080,
|
||||
"hostPort": 8080,
|
||||
"protocol": "tcp"
|
||||
}
|
||||
],
|
||||
"environment": [
|
||||
{
|
||||
"name": "OPENAI_API_KEY",
|
||||
"value": "your_api_key"
|
||||
}
|
||||
],
|
||||
"logConfiguration": {
|
||||
"logDriver": "awslogs",
|
||||
"options": {
|
||||
"awslogs-group": "/ecs/mcp-server",
|
||||
"awslogs-region": "us-east-1",
|
||||
"awslogs-stream-prefix": "ecs"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"requiresCompatibilities": [
|
||||
"FARGATE"
|
||||
],
|
||||
"cpu": "256",
|
||||
"memory": "512"
|
||||
}
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy to ECS">
|
||||
```bash
|
||||
# Create a service
|
||||
aws ecs create-service \
|
||||
--cluster your-cluster \
|
||||
--service-name mcp-server \
|
||||
--task-definition mcp-server:1 \
|
||||
--desired-count 1 \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "awsvpcConfiguration={subnets=[subnet-12345678],securityGroups=[sg-12345678],assignPublicIp=ENABLED}" \
|
||||
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/mcp-server-tg/1234567890abcdef,containerName=mcp-server,containerPort=8080"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Google Cloud Run
|
||||
|
||||
<Steps>
|
||||
<Step title="Push Docker Image to Google Container Registry">
|
||||
```bash
|
||||
# Configure Docker to use Google Cloud credentials
|
||||
gcloud auth configure-docker
|
||||
|
||||
# Build and tag the image
|
||||
docker build -t gcr.io/YOUR_PROJECT_ID/mcp-server .
|
||||
|
||||
# Push the image
|
||||
docker push gcr.io/YOUR_PROJECT_ID/mcp-server
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy to Cloud Run">
|
||||
```bash
|
||||
gcloud run deploy mcp-server \
|
||||
--image gcr.io/YOUR_PROJECT_ID/mcp-server \
|
||||
--platform managed \
|
||||
--region us-central1 \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars="OPENAI_API_KEY=your_api_key"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Production Configuration
|
||||
|
||||
### Security
|
||||
|
||||
For production deployments, implement these security measures:
|
||||
|
||||
1. **API Key Authentication**:
|
||||
```python
|
||||
agent.launch(port=8080, host="0.0.0.0", protocol="mcp", api_key="your-secret-key")
|
||||
```
|
||||
|
||||
2. **HTTPS with SSL/TLS**:
|
||||
Set up a reverse proxy like Nginx with SSL certificates:
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name your-mcp-server.com;
|
||||
|
||||
ssl_certificate /path/to/cert.pem;
|
||||
ssl_certificate_key /path/to/key.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Secret Management**:
|
||||
Use environment variables or a secrets manager for API keys:
|
||||
```bash
|
||||
# AWS Secrets Manager
|
||||
aws secretsmanager create-secret \
|
||||
--name OPENAI_API_KEY \
|
||||
--secret-string "your_api_key"
|
||||
|
||||
# Google Secret Manager
|
||||
echo -n "your_api_key" | gcloud secrets create openai-api-key --data-file=-
|
||||
```
|
||||
|
||||
### Scaling
|
||||
|
||||
For high-traffic MCP servers, consider these scaling strategies:
|
||||
|
||||
1. **Load Balancing**:
|
||||
Deploy multiple instances behind a load balancer.
|
||||
|
||||
2. **Auto Scaling**:
|
||||
Configure auto-scaling based on CPU/memory usage or request count.
|
||||
|
||||
3. **Resource Allocation**:
|
||||
Allocate sufficient CPU and memory for your MCP servers:
|
||||
```bash
|
||||
# AWS ECS
|
||||
aws ecs update-service \
|
||||
--cluster your-cluster \
|
||||
--service mcp-server \
|
||||
--desired-count 3
|
||||
|
||||
# Google Cloud Run
|
||||
gcloud run services update mcp-server \
|
||||
--min-instances=2 \
|
||||
--max-instances=10 \
|
||||
--memory=2Gi \
|
||||
--cpu=1
|
||||
```
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
Set up comprehensive monitoring for your MCP servers:
|
||||
|
||||
1. **Application Logging**:
|
||||
```python
|
||||
import logging
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
handlers=[
|
||||
logging.FileHandler("mcp-server.log"),
|
||||
logging.StreamHandler()
|
||||
]
|
||||
)
|
||||
|
||||
logger = logging.getLogger("mcp-server")
|
||||
```
|
||||
|
||||
2. **Health Checks**:
|
||||
Create a health check endpoint:
|
||||
```python
|
||||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/health')
|
||||
def health_check():
|
||||
return {"status": "healthy"}, 200
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8081)
|
||||
```
|
||||
|
||||
3. **Metrics Collection**:
|
||||
Use Prometheus or similar tools to collect metrics.
|
||||
|
||||
## Testing MCP Servers
|
||||
|
||||
Before deploying to production, thoroughly test your MCP server:
|
||||
|
||||
```python
|
||||
import requests
|
||||
import json
|
||||
|
||||
def test_mcp_server():
|
||||
url = "http://localhost:8080/v1/chat/completions"
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
data = {
|
||||
"messages": [
|
||||
{"role": "user", "content": "Create a tweet about artificial intelligence"}
|
||||
]
|
||||
}
|
||||
|
||||
response = requests.post(url, headers=headers, data=json.dumps(data))
|
||||
|
||||
print(f"Status Code: {response.status_code}")
|
||||
print(f"Response: {response.json()}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_mcp_server()
|
||||
```
|
||||
|
||||
## Deployment Checklist
|
||||
|
||||
Before going live with your MCP server, ensure you've addressed these items:
|
||||
|
||||
- [ ] Implemented proper authentication
|
||||
- [ ] Set up HTTPS with valid SSL certificates
|
||||
- [ ] Configured proper logging and monitoring
|
||||
- [ ] Tested the server under load
|
||||
- [ ] Implemented rate limiting
|
||||
- [ ] Secured all API keys and credentials
|
||||
- [ ] Set up automated backups
|
||||
- [ ] Created a disaster recovery plan
|
||||
- [ ] Documented the deployment process
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Containerized Deployment" icon="docker">
|
||||
Package your MCP servers in Docker containers for consistent deployment.
|
||||
</Card>
|
||||
<Card title="Cloud-Ready" icon="cloud">
|
||||
Deploy to AWS, Google Cloud, or other cloud providers with ease.
|
||||
</Card>
|
||||
<Card title="Scalable Architecture" icon="server">
|
||||
Scale your MCP servers to handle production workloads.
|
||||
</Card>
|
||||
<Card title="Security-Focused" icon="shield">
|
||||
Implement best practices for secure MCP server deployments.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: "Deploying Multi-Agent Systems as APIs"
|
||||
sidebarTitle: "Multi-Agent Deployment"
|
||||
description: "Learn how to deploy PraisonAI multi-agent systems as RESTful APIs for production environments"
|
||||
icon: "network-wired"
|
||||
---
|
||||
|
||||
# Deploying Multi-Agent Systems as APIs
|
||||
|
||||
PraisonAI allows you to deploy sophisticated multi-agent systems as RESTful APIs, enabling seamless integration with various applications and services. This guide covers different approaches to deploying multi-agent systems.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
Make sure you have the required packages installed:
|
||||
```bash
|
||||
pip install "praisonaiagents[api]>=0.0.81"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY="your_api_key"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy a Multi-Agent System">
|
||||
Create a file named `multi-agents-api.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents, Tools
|
||||
|
||||
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
|
||||
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
|
||||
agents = Agents(agents=[research_agent, summarise_agent])
|
||||
agents.launch(path="/agents", port=3030)
|
||||
```
|
||||
</Step>
|
||||
<Step title="Run the API Server">
|
||||
```bash
|
||||
python multi-agents-api.py
|
||||
```
|
||||
|
||||
Your multi-agent API will be available at `http://localhost:3030/agents`
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Making API Requests
|
||||
|
||||
Once your multi-agent system is deployed, you can make POST requests to interact with it:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3030/agents \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "What are the latest developments in AI in 2024?"}'
|
||||
```
|
||||
|
||||
The response will include the collaborative output from both the research and summarization agents:
|
||||
|
||||
```json
|
||||
{
|
||||
"response": "# Latest AI Developments in 2024\n\n- Multimodal AI models have become mainstream, combining text, image, audio, and video understanding\n- Significant advancements in AI reasoning capabilities with models like GPT-4o and Claude 3\n- Increased focus on AI alignment and safety research\n- Emergence of specialized AI agents for specific domains\n- Growth in open-source AI models and frameworks\n- Regulatory frameworks for AI being established globally"
|
||||
}
|
||||
```
|
||||
|
||||
## Multiple Agent Groups
|
||||
|
||||
You can deploy multiple agent groups on the same server, each with its own endpoint:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents, Tools
|
||||
|
||||
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
|
||||
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
|
||||
agents = Agents(agents=[research_agent, summarise_agent])
|
||||
agents2 = Agents(agents=[research_agent])
|
||||
agents.launch(path="/agents", port=3030)
|
||||
agents2.launch(path="/agents2", port=3030)
|
||||
```
|
||||
|
||||
With this setup, you can access:
|
||||
- The full agent group at `http://localhost:3030/agents`
|
||||
- Just the research agent at `http://localhost:3030/agents2`
|
||||
|
||||
## Independent Multi-Agent Deployment
|
||||
|
||||
You can also deploy multiple independent agents on the same server:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=3030)
|
||||
stock_agent.launch(path="/stock", port=3030)
|
||||
travel_agent.launch(path="/travel", port=3030)
|
||||
```
|
||||
|
||||
## Production Deployment Options
|
||||
|
||||
For production environments, consider the following deployment options:
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3030
|
||||
|
||||
CMD ["python", "multi-agents-api.py"]
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create requirements.txt">
|
||||
```
|
||||
praisonaiagents[api]>=0.0.81
|
||||
```
|
||||
</Step>
|
||||
<Step title="Build and Run Docker Container">
|
||||
```bash
|
||||
docker build -t praisonai-multi-agent .
|
||||
docker run -p 3030:3030 -e OPENAI_API_KEY=your_api_key praisonai-multi-agent
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Cloud Deployment
|
||||
|
||||
For detailed cloud deployment instructions, refer to:
|
||||
- [AWS Deployment Guide](/deploy/aws)
|
||||
- [Google Cloud Deployment Guide](/deploy/googlecloud)
|
||||
|
||||
## Scaling Multi-Agent Systems
|
||||
|
||||
When deploying multi-agent systems to production, consider these scaling strategies:
|
||||
|
||||
1. **Horizontal Scaling**: Deploy multiple instances behind a load balancer
|
||||
2. **Vertical Scaling**: Allocate more CPU and memory resources for complex agent interactions
|
||||
3. **Caching**: Implement response caching for frequently asked questions
|
||||
4. **Asynchronous Processing**: Use message queues for handling long-running agent tasks
|
||||
|
||||
## API Configuration Options
|
||||
|
||||
When launching your multi-agent system as an API, you can customize various parameters:
|
||||
|
||||
```python
|
||||
agents.launch(
|
||||
path="/custom-endpoint", # API endpoint path
|
||||
port=8080, # Port number
|
||||
host="0.0.0.0", # Host address (0.0.0.0 for external access)
|
||||
debug=True, # Enable debug mode
|
||||
cors_origins=["*"], # CORS configuration
|
||||
api_key="your-api-key" # Optional API key for authentication
|
||||
)
|
||||
```
|
||||
|
||||
## Securing Your Multi-Agent API
|
||||
|
||||
For production deployments, consider implementing:
|
||||
|
||||
1. **API Key Authentication**: Require API keys for all requests
|
||||
2. **Rate Limiting**: Limit the number of requests per client
|
||||
3. **HTTPS**: Use SSL/TLS certificates for encrypted communication
|
||||
4. **Input Validation**: Validate all input data before processing
|
||||
5. **Output Filtering**: Implement content filtering for agent responses
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
For production environments, consider:
|
||||
|
||||
1. **Centralized Logging**: Collect logs from all agents in a central location
|
||||
2. **Performance Metrics**: Track response times and resource usage
|
||||
3. **Error Tracking**: Monitor and alert on agent failures
|
||||
4. **Usage Analytics**: Track which agents are used most frequently
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Collaborative Agents" icon="users-gear">
|
||||
Deploy agent systems that collaborate to solve complex problems.
|
||||
</Card>
|
||||
<Card title="Specialized Endpoints" icon="sitemap">
|
||||
Create dedicated endpoints for different agent groups or individual agents.
|
||||
</Card>
|
||||
<Card title="Tool Integration" icon="screwdriver-wrench">
|
||||
Deploy agents with specialized tools like web search capabilities.
|
||||
</Card>
|
||||
<Card title="Scalable Architecture" icon="server">
|
||||
Scale your multi-agent systems to handle production workloads.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -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.2.1 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.
|
||||
@@ -65,14 +65,14 @@ def basic(): # Basic Mode
|
||||
def advanced(): # Advanced Mode with options
|
||||
praisonai = PraisonAI(
|
||||
agent_file="agents.yaml",
|
||||
framework="autogen",
|
||||
framework="autogen", # use AG2 framework (Formerly AutoGen)
|
||||
)
|
||||
praisonai.run()
|
||||
|
||||
def auto(): # Full Automatic Mode
|
||||
praisonai = PraisonAI(
|
||||
auto="Create a movie script about car in mars",
|
||||
framework="autogen"
|
||||
framework="autogen" # use AG2 framework
|
||||
)
|
||||
print(praisonai.framework)
|
||||
praisonai.run()
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
---
|
||||
title: "Climate Impact"
|
||||
description: "Learn how to create AI agents for climate impact analysis and adaptation strategies."
|
||||
icon: "cloud-sun"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Monitor[Environmental Monitor]
|
||||
Monitor --> Urban[Urban Analyzer]
|
||||
Urban --> Climate[Climate Modeler]
|
||||
Climate --> Impact[Impact Predictor]
|
||||
Impact --> Strategy[Strategy Generator]
|
||||
Strategy --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Monitor fill:#2E8B57,color:#fff
|
||||
style Urban fill:#2E8B57,color:#fff
|
||||
style Climate fill:#2E8B57,color:#fff
|
||||
style Impact fill:#2E8B57,color:#fff
|
||||
style Strategy fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Climate Impact Analysis?
|
||||
|
||||
Climate Impact Analysis is a systematic process of collecting environmental data, analyzing urban factors, modeling microclimates, predicting impacts, and generating adaptation strategies. This helps cities and communities understand and prepare for climate change effects, ensuring sustainable urban development and public health.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Environmental Monitoring" icon="temperature-high">
|
||||
Collection of temperature, humidity, and air quality data with trend analysis.
|
||||
</Card>
|
||||
<Card title="Urban Analysis" icon="city">
|
||||
Assessment of building density, green spaces, traffic flow, and heat islands.
|
||||
</Card>
|
||||
<Card title="Climate Modeling" icon="chart-line">
|
||||
Microclimate modeling for different urban locations with temperature and air quality impacts.
|
||||
</Card>
|
||||
<Card title="Impact Prediction" icon="chart-mixed">
|
||||
Prediction of health impacts, energy consumption, and livability scores.
|
||||
</Card>
|
||||
<Card title="Adaptation Strategies" icon="leaf">
|
||||
Generation of location-specific strategies for climate adaptation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def collect_environmental_data():
|
||||
"""Simulates environmental data collection"""
|
||||
data = {
|
||||
"temperature": {
|
||||
"current": 25 + (time.time() % 10),
|
||||
"historical": [24, 25, 26, 24, 23],
|
||||
"trend": "increasing"
|
||||
},
|
||||
"humidity": {
|
||||
"current": 60 + (time.time() % 20),
|
||||
"historical": [65, 62, 58, 63, 61],
|
||||
"trend": "stable"
|
||||
},
|
||||
"air_quality": {
|
||||
"pm25": 35 + (time.time() % 15),
|
||||
"co2": 415 + (time.time() % 30),
|
||||
"trend": "deteriorating"
|
||||
}
|
||||
}
|
||||
return data
|
||||
|
||||
def analyze_urban_factors():
|
||||
"""Simulates urban environment analysis"""
|
||||
factors = {
|
||||
"building_density": 75 + (time.time() % 20),
|
||||
"green_spaces": 25 + (time.time() % 10),
|
||||
"traffic_flow": {
|
||||
"peak_hours": [8, 17],
|
||||
"congestion_level": "high"
|
||||
},
|
||||
"heat_islands": [
|
||||
{"location": "downtown", "intensity": "high"},
|
||||
{"location": "industrial", "intensity": "medium"}
|
||||
]
|
||||
}
|
||||
return factors
|
||||
|
||||
def model_microclimate(env_data: Dict, urban_factors: Dict):
|
||||
"""Models microclimate conditions"""
|
||||
models = []
|
||||
locations = ["downtown", "residential", "industrial", "parks"]
|
||||
|
||||
for location in locations:
|
||||
models.append({
|
||||
"location": location,
|
||||
"temperature_delta": 2 + (time.time() % 3),
|
||||
"air_quality_impact": "moderate" if "park" in location else "significant",
|
||||
"humidity_variation": 5 + (time.time() % 5)
|
||||
})
|
||||
return models
|
||||
|
||||
def predict_impacts(models: List[Dict]):
|
||||
"""Predicts climate impacts"""
|
||||
predictions = []
|
||||
for model in models:
|
||||
predictions.append({
|
||||
"location": model["location"],
|
||||
"health_impact": "high" if model["air_quality_impact"] == "significant" else "medium",
|
||||
"energy_consumption": {
|
||||
"cooling_need": model["temperature_delta"] * 10,
|
||||
"trend": "increasing" if model["temperature_delta"] > 2.5 else "stable"
|
||||
},
|
||||
"livability_score": 70 - (model["temperature_delta"] * 5)
|
||||
})
|
||||
return predictions
|
||||
|
||||
def generate_adaptation_strategies(predictions: List[Dict]):
|
||||
"""Generates adaptation strategies"""
|
||||
strategies = []
|
||||
for pred in predictions:
|
||||
if pred["health_impact"] == "high":
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"increase_green_spaces",
|
||||
"traffic_reduction",
|
||||
"building_retrofitting"
|
||||
],
|
||||
"priority": "immediate",
|
||||
"cost_estimate": "high"
|
||||
})
|
||||
else:
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"tree_planting",
|
||||
"cool_roofs"
|
||||
],
|
||||
"priority": "medium",
|
||||
"cost_estimate": "moderate"
|
||||
})
|
||||
return strategies
|
||||
|
||||
# Create specialized agents
|
||||
environmental_monitor = Agent(
|
||||
name="Environmental Monitor",
|
||||
role="Data Collection",
|
||||
goal="Collect environmental data",
|
||||
instructions="Monitor and collect climate data",
|
||||
tools=[collect_environmental_data]
|
||||
)
|
||||
|
||||
urban_analyzer = Agent(
|
||||
name="Urban Analyzer",
|
||||
role="Urban Analysis",
|
||||
goal="Analyze urban environment",
|
||||
instructions="Assess urban factors affecting climate",
|
||||
tools=[analyze_urban_factors]
|
||||
)
|
||||
|
||||
climate_modeler = Agent(
|
||||
name="Climate Modeler",
|
||||
role="Climate Modeling",
|
||||
goal="Model microclimate conditions",
|
||||
instructions="Create detailed climate models",
|
||||
tools=[model_microclimate]
|
||||
)
|
||||
|
||||
impact_predictor = Agent(
|
||||
name="Impact Predictor",
|
||||
role="Impact Analysis",
|
||||
goal="Predict climate impacts",
|
||||
instructions="Assess potential climate impacts",
|
||||
tools=[predict_impacts]
|
||||
)
|
||||
|
||||
strategy_generator = Agent(
|
||||
name="Strategy Generator",
|
||||
role="Strategy Development",
|
||||
goal="Generate adaptation strategies",
|
||||
instructions="Develop climate adaptation strategies",
|
||||
tools=[generate_adaptation_strategies]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
monitoring_task = Task(
|
||||
name="collect_data",
|
||||
description="Collect environmental data",
|
||||
expected_output="Environmental measurements",
|
||||
agent=environmental_monitor,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_urban"]
|
||||
)
|
||||
|
||||
urban_task = Task(
|
||||
name="analyze_urban",
|
||||
description="Analyze urban factors",
|
||||
expected_output="Urban analysis",
|
||||
agent=urban_analyzer,
|
||||
next_tasks=["model_climate"]
|
||||
)
|
||||
|
||||
modeling_task = Task(
|
||||
name="model_climate",
|
||||
description="Model microclimate",
|
||||
expected_output="Climate models",
|
||||
agent=climate_modeler,
|
||||
context=[monitoring_task, urban_task],
|
||||
next_tasks=["predict_impacts"]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_impacts",
|
||||
description="Predict climate impacts",
|
||||
expected_output="Impact predictions",
|
||||
agent=impact_predictor,
|
||||
next_tasks=["generate_strategies"]
|
||||
)
|
||||
|
||||
strategy_task = Task(
|
||||
name="generate_strategies",
|
||||
description="Generate adaptation strategies",
|
||||
expected_output="Adaptation strategies",
|
||||
agent=strategy_generator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"immediate": ["collect_data"], # Continuous monitoring for high priority
|
||||
"medium": "", # End workflow for medium priority
|
||||
"low": "" # End workflow for low priority
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[environmental_monitor, urban_analyzer, climate_modeler,
|
||||
impact_predictor, strategy_generator],
|
||||
tasks=[monitoring_task, urban_task, modeling_task,
|
||||
prediction_task, strategy_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Climate Impact Prediction Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nClimate Impact Analysis Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
title: "Code Analysis Agent"
|
||||
description: "Learn how to create AI agents for comprehensive code analysis and quality assessment."
|
||||
icon: "code-merge"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Code Analyzer]
|
||||
Analyzer --> Quality[Quality Assessment]
|
||||
Quality --> Metrics[Core Metrics]
|
||||
Metrics --> Technical[Technical Review]
|
||||
Technical --> Recommendations[Recommendations]
|
||||
Recommendations --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Quality fill:#2E8B57,color:#fff
|
||||
style Metrics fill:#2E8B57,color:#fff
|
||||
style Technical fill:#2E8B57,color:#fff
|
||||
style Recommendations fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Code Analysis?
|
||||
|
||||
Code Analysis is a systematic process of evaluating source code to assess its quality, maintainability, performance, and security. This helps developers and organizations maintain high code standards and identify areas for improvement.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quality Assessment" icon="chart-simple">
|
||||
Comprehensive evaluation of code quality with numerical scoring.
|
||||
</Card>
|
||||
<Card title="Core Metrics Analysis" icon="gauge">
|
||||
Analysis of architecture, maintainability, performance, and security.
|
||||
</Card>
|
||||
<Card title="Technical Assessment" icon="code">
|
||||
Review of tech stack, complexity, and best practices adherence.
|
||||
</Card>
|
||||
<Card title="Risk Assessment" icon="shield">
|
||||
Identification of potential risks and security vulnerabilities.
|
||||
</Card>
|
||||
<Card title="Recommendations" icon="lightbulb">
|
||||
Actionable suggestions for improvements and enhancements.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents gitingest
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `code_analysis.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
from gitingest import ingest
|
||||
|
||||
class CodeMetrics(BaseModel):
|
||||
category: str
|
||||
score: int
|
||||
findings: List[str]
|
||||
|
||||
class CodeAnalysisReport(BaseModel):
|
||||
overall_quality: int
|
||||
code_metrics: List[CodeMetrics]
|
||||
architecture_score: int
|
||||
maintainability_score: int
|
||||
performance_score: int
|
||||
security_score: int
|
||||
test_coverage: int
|
||||
key_strengths: List[str]
|
||||
improvement_areas: List[str]
|
||||
tech_stack: List[str]
|
||||
recommendations: List[str]
|
||||
complexity_metrics: Dict[str, int]
|
||||
best_practices: List[Dict[str, str]]
|
||||
potential_risks: List[str]
|
||||
documentation_quality: int
|
||||
|
||||
code_analyzer = Agent(
|
||||
role="Code Analysis Expert",
|
||||
goal="Provide comprehensive code evaluation and recommendations",
|
||||
backstory="""Expert code analyst specializing in architecture review,
|
||||
best practices, and technical debt assessment.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
code_analysis_task = Task(
|
||||
description="""Analyze code repository and provide structured evaluation:
|
||||
|
||||
1. Overall Quality (0-100)
|
||||
2. Core Metrics Analysis:
|
||||
- Architecture and Design
|
||||
- Code Maintainability
|
||||
- Performance Optimization
|
||||
- Security Practices
|
||||
- Test Coverage
|
||||
3. Technical Assessment:
|
||||
- Technology Stack Review
|
||||
- Code Complexity Analysis
|
||||
- Best Practices Adherence
|
||||
- Risk Assessment
|
||||
4. Recommendations:
|
||||
- Key Improvements
|
||||
- Architecture Suggestions
|
||||
- Security Enhancements""",
|
||||
expected_output="Detailed code analysis report with metrics and recommendations",
|
||||
agent=code_analyzer,
|
||||
output_pydantic=CodeAnalysisReport
|
||||
)
|
||||
|
||||
def analyze_code(code_source: str) -> CodeAnalysisReport:
|
||||
"""
|
||||
Analyze code from directory path or GitHub URL
|
||||
"""
|
||||
# Ingest code content
|
||||
summary, tree, content = ingest(code_source)
|
||||
|
||||
# Concatenate context into structured format
|
||||
context_text = f"""
|
||||
CODE REPOSITORY ANALYSIS
|
||||
=======================
|
||||
|
||||
SUMMARY
|
||||
-------
|
||||
{summary}
|
||||
|
||||
REPOSITORY STRUCTURE
|
||||
-------------------
|
||||
{tree}
|
||||
|
||||
SOURCE CODE
|
||||
-----------
|
||||
{content}
|
||||
"""
|
||||
|
||||
# Initialize and run analysis
|
||||
agents = PraisonAIAgents(
|
||||
agents=[code_analyzer],
|
||||
tasks=[code_analysis_task]
|
||||
)
|
||||
|
||||
return agents.start(context_text)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
code_source = "https://github.com/openai/openai-python/tree/main/src/openai/cli/_api/chat" # GitHub URL or local directory
|
||||
result = analyze_code(code_source)
|
||||
print(result)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding the Output
|
||||
|
||||
The code analysis generates a comprehensive report with the following components:
|
||||
|
||||
- Overall Quality Score (0-100)
|
||||
- Core Metrics Analysis
|
||||
- Architecture and Design Score
|
||||
- Code Maintainability Score
|
||||
- Performance Score
|
||||
- Security Score
|
||||
- Test Coverage Percentage
|
||||
- Technical Assessment
|
||||
- Technology Stack
|
||||
- Complexity Metrics
|
||||
- Best Practices Review
|
||||
- Risk Assessment
|
||||
- Recommendations
|
||||
- Key Improvements
|
||||
- Architecture Suggestions
|
||||
- Security Enhancements
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
<Card title="API Reference" icon="code" href="/api-reference">
|
||||
Explore the complete API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,316 @@
|
||||
---
|
||||
title: "Crypto Validator"
|
||||
description: "Learn how to create AI agents for post-quantum cryptographic scheme validation and security analysis."
|
||||
icon: "key"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Crypto Analyzer]
|
||||
Analyzer --> Quantum[Attack Simulator]
|
||||
Analyzer --> Perf[Performance Benchmarker]
|
||||
Quantum --> Security[Implementation Assessor]
|
||||
Perf --> Security
|
||||
Security --> Compliance[Compliance Validator]
|
||||
Compliance --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Quantum fill:#2E8B57,color:#fff
|
||||
style Perf fill:#2E8B57,color:#fff
|
||||
style Security fill:#2E8B57,color:#fff
|
||||
style Compliance fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Post-Quantum Cryptography?
|
||||
|
||||
Post-quantum cryptography focuses on developing cryptographic systems that are secure against both quantum and classical computers. This involves analyzing cryptographic schemes, simulating quantum attacks, and ensuring compliance with security standards.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Cryptographic Analysis" icon="shield-check">
|
||||
Analyze quantum-resistant cryptographic schemes including lattice-based encryption and multivariate signatures.
|
||||
</Card>
|
||||
<Card title="Attack Simulation" icon="bug">
|
||||
Test resistance against quantum attacks including Grover's algorithm and Shor's algorithm.
|
||||
</Card>
|
||||
<Card title="Performance Testing" icon="gauge-high">
|
||||
Benchmark key generation, encryption/decryption speeds, and throughput metrics.
|
||||
</Card>
|
||||
<Card title="Security Assessment" icon="lock">
|
||||
Evaluate implementation security including side-channel resistance and hardening measures.
|
||||
</Card>
|
||||
<Card title="Compliance Validation" icon="certificate">
|
||||
Verify compliance with NIST PQC, Common Criteria, and FIPS standards.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_cryptographic_scheme():
|
||||
"""Simulates cryptographic scheme analysis"""
|
||||
schemes = [
|
||||
{
|
||||
"name": "lattice_based",
|
||||
"type": "encryption",
|
||||
"key_size": 2048,
|
||||
"security_level": "AES-256 equivalent",
|
||||
"parameters": {
|
||||
"lattice_dimension": 1024,
|
||||
"modulus": "q = 2^32 - 1",
|
||||
"error_distribution": "discrete_gaussian"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "multivariate",
|
||||
"type": "signature",
|
||||
"key_size": 4096,
|
||||
"security_level": "SHA-384 equivalent",
|
||||
"parameters": {
|
||||
"variables": 128,
|
||||
"equations": 128,
|
||||
"field_size": "2^8"
|
||||
}
|
||||
}
|
||||
]
|
||||
return schemes[int(time.time()) % 2]
|
||||
|
||||
def simulate_quantum_attacks(scheme: Dict):
|
||||
"""Simulates quantum attack scenarios"""
|
||||
attacks = {
|
||||
"grover_search": {
|
||||
"effectiveness": "reduced",
|
||||
"quantum_speedup": "quadratic",
|
||||
"estimated_qubits": 2048,
|
||||
"time_complexity": "O(2^n/2)"
|
||||
},
|
||||
"shor_algorithm": {
|
||||
"effectiveness": "ineffective",
|
||||
"quantum_speedup": "none",
|
||||
"vulnerability": "resistant",
|
||||
"classical_hardness": "maintained"
|
||||
},
|
||||
"quantum_hidden_subgroup": {
|
||||
"effectiveness": "partial",
|
||||
"applicability": "limited",
|
||||
"mitigation": "parameter_adjustment"
|
||||
}
|
||||
}
|
||||
return attacks
|
||||
|
||||
def benchmark_performance(scheme: Dict):
|
||||
"""Benchmarks cryptographic performance"""
|
||||
benchmarks = {
|
||||
"key_generation": {
|
||||
"time": 0.5 + (time.time() % 1) / 10, # seconds
|
||||
"memory": 128 + (int(time.time()) % 64) # MB
|
||||
},
|
||||
"encryption_speed": {
|
||||
"small_message": 0.001 + (time.time() % 1) / 1000, # seconds
|
||||
"large_message": 0.1 + (time.time() % 1) / 10 # seconds
|
||||
},
|
||||
"decryption_speed": {
|
||||
"small_message": 0.002 + (time.time() % 1) / 1000,
|
||||
"large_message": 0.15 + (time.time() % 1) / 10
|
||||
},
|
||||
"throughput": {
|
||||
"encryption": 100 + (int(time.time()) % 50), # MB/s
|
||||
"decryption": 80 + (int(time.time()) % 40) # MB/s
|
||||
}
|
||||
}
|
||||
return benchmarks
|
||||
|
||||
def assess_implementation(scheme: Dict, benchmarks: Dict):
|
||||
"""Assesses implementation security"""
|
||||
assessment = {
|
||||
"side_channel_resistance": {
|
||||
"timing_attacks": "protected",
|
||||
"power_analysis": "partial_vulnerability",
|
||||
"cache_attacks": "mitigated"
|
||||
},
|
||||
"implementation_hardening": {
|
||||
"constant_time": True,
|
||||
"memory_protection": True,
|
||||
"error_handling": "secure"
|
||||
},
|
||||
"compiler_optimizations": {
|
||||
"safety": "verified",
|
||||
"performance_impact": -0.05 + (time.time() % 1) / 10
|
||||
}
|
||||
}
|
||||
return assessment
|
||||
|
||||
def validate_compliance(scheme: Dict, assessment: Dict):
|
||||
"""Validates compliance and standards"""
|
||||
compliance = {
|
||||
"nist_pqc": {
|
||||
"status": "submitted",
|
||||
"round": 3,
|
||||
"requirements_met": True
|
||||
},
|
||||
"common_criteria": {
|
||||
"evaluation_level": "EAL4+",
|
||||
"protection_profile": "compliant"
|
||||
},
|
||||
"fips_140_3": {
|
||||
"security_level": 3,
|
||||
"validation_status": "in_process"
|
||||
}
|
||||
}
|
||||
return compliance
|
||||
|
||||
# Create specialized agents
|
||||
crypto_analyzer = Agent(
|
||||
name="Crypto Analyzer",
|
||||
role="Cryptographic Analysis",
|
||||
goal="Analyze cryptographic schemes",
|
||||
instructions="Evaluate quantum-resistant cryptographic schemes",
|
||||
tools=[analyze_cryptographic_scheme]
|
||||
)
|
||||
|
||||
attack_simulator = Agent(
|
||||
name="Attack Simulator",
|
||||
role="Attack Simulation",
|
||||
goal="Simulate quantum attacks",
|
||||
instructions="Test resistance against quantum attacks",
|
||||
tools=[simulate_quantum_attacks]
|
||||
)
|
||||
|
||||
performance_benchmarker = Agent(
|
||||
name="Performance Benchmarker",
|
||||
role="Performance Testing",
|
||||
goal="Benchmark cryptographic performance",
|
||||
instructions="Measure performance metrics",
|
||||
tools=[benchmark_performance]
|
||||
)
|
||||
|
||||
implementation_assessor = Agent(
|
||||
name="Implementation Assessor",
|
||||
role="Implementation Assessment",
|
||||
goal="Assess implementation security",
|
||||
instructions="Evaluate implementation security",
|
||||
tools=[assess_implementation]
|
||||
)
|
||||
|
||||
compliance_validator = Agent(
|
||||
name="Compliance Validator",
|
||||
role="Compliance Validation",
|
||||
goal="Validate standards compliance",
|
||||
instructions="Verify compliance with standards",
|
||||
tools=[validate_compliance]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_crypto",
|
||||
description="Analyze cryptographic scheme",
|
||||
expected_output="Cryptographic analysis",
|
||||
agent=crypto_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["simulate_attacks", "benchmark_performance"]
|
||||
)
|
||||
|
||||
attack_task = Task(
|
||||
name="simulate_attacks",
|
||||
description="Simulate quantum attacks",
|
||||
expected_output="Attack simulation results",
|
||||
agent=attack_simulator,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
benchmark_task = Task(
|
||||
name="benchmark_performance",
|
||||
description="Benchmark performance",
|
||||
expected_output="Performance benchmarks",
|
||||
agent=performance_benchmarker,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
assessment_task = Task(
|
||||
name="assess_implementation",
|
||||
description="Assess implementation",
|
||||
expected_output="Implementation assessment",
|
||||
agent=implementation_assessor,
|
||||
context=[attack_task, benchmark_task],
|
||||
next_tasks=["validate_compliance"]
|
||||
)
|
||||
|
||||
compliance_task = Task(
|
||||
name="validate_compliance",
|
||||
description="Validate compliance",
|
||||
expected_output="Compliance validation",
|
||||
agent=compliance_validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"compliant": "", # End workflow if compliant
|
||||
"non_compliant": ["assess_implementation"] # Reassess if non-compliant
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[crypto_analyzer, attack_simulator, performance_benchmarker,
|
||||
implementation_assessor, compliance_validator],
|
||||
tasks=[analysis_task, attack_task, benchmark_task,
|
||||
assessment_task, compliance_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Quantum-Resistant Cryptography Validation Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nCryptography Validation Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,302 @@
|
||||
---
|
||||
title: "DeFi Market Maker"
|
||||
description: "Learn how to create AI agents for decentralized finance market making and arbitrage."
|
||||
icon: "chart-line"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Market[Market Analyzer]
|
||||
Market --> Arbitrage[Arbitrage Detector]
|
||||
Market --> Liquidity[Liquidity Optimizer]
|
||||
Arbitrage --> Risk[Risk Assessor]
|
||||
Liquidity --> Risk
|
||||
Risk --> Executor[Trade Executor]
|
||||
Executor --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Market fill:#2E8B57,color:#fff
|
||||
style Arbitrage fill:#2E8B57,color:#fff
|
||||
style Liquidity fill:#2E8B57,color:#fff
|
||||
style Risk fill:#2E8B57,color:#fff
|
||||
style Executor fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is DeFi Market Making?
|
||||
|
||||
Decentralized Finance (DeFi) market making involves providing liquidity to decentralized exchanges and automatically executing trades to capture arbitrage opportunities. This requires real-time analysis of market conditions, optimization of liquidity positions, and risk management.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Market Analysis" icon="chart-candlestick">
|
||||
Real-time analysis of liquidity pools, market volatility, trading volumes, and gas prices.
|
||||
</Card>
|
||||
<Card title="Arbitrage Detection" icon="magnifying-glass-dollar">
|
||||
Identification of profitable trading opportunities across different liquidity pools.
|
||||
</Card>
|
||||
<Card title="Liquidity Optimization" icon="water">
|
||||
Optimization of liquidity distribution and pool ratios for maximum efficiency.
|
||||
</Card>
|
||||
<Card title="Risk Assessment" icon="shield-halved">
|
||||
Comprehensive risk analysis including impermanent loss and smart contract risks.
|
||||
</Card>
|
||||
<Card title="Trade Execution" icon="money-bill-transfer">
|
||||
Automated execution of optimized trades with performance monitoring.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_market_conditions():
|
||||
"""Simulates market analysis"""
|
||||
conditions = {
|
||||
"liquidity_pools": {
|
||||
"pool_A": {
|
||||
"token_0": {"balance": 1000000, "price": 1.0},
|
||||
"token_1": {"balance": 500000, "price": 2.0},
|
||||
"total_value_locked": 2000000
|
||||
},
|
||||
"pool_B": {
|
||||
"token_0": {"balance": 800000, "price": 1.0},
|
||||
"token_1": {"balance": 400000, "price": 2.0},
|
||||
"total_value_locked": 1600000
|
||||
}
|
||||
},
|
||||
"market_volatility": 0.15 + (time.time() % 10) / 100,
|
||||
"trading_volume_24h": 5000000 + (time.time() % 1000000),
|
||||
"gas_prices": 50 + (time.time() % 30)
|
||||
}
|
||||
return conditions
|
||||
|
||||
def detect_arbitrage():
|
||||
"""Simulates arbitrage opportunity detection"""
|
||||
opportunities = [
|
||||
{
|
||||
"path": ["pool_A", "pool_B"],
|
||||
"profit_potential": 0.02 + (time.time() % 5) / 100,
|
||||
"required_capital": 10000,
|
||||
"execution_cost": 50,
|
||||
"risk_level": "low"
|
||||
},
|
||||
{
|
||||
"path": ["pool_B", "pool_C"],
|
||||
"profit_potential": 0.03 + (time.time() % 5) / 100,
|
||||
"required_capital": 20000,
|
||||
"execution_cost": 75,
|
||||
"risk_level": "medium"
|
||||
}
|
||||
]
|
||||
return opportunities[int(time.time()) % 2]
|
||||
|
||||
def optimize_liquidity(market_conditions: Dict):
|
||||
"""Optimizes liquidity distribution"""
|
||||
optimizations = {
|
||||
"pool_A": {
|
||||
"target_ratio": 2.0,
|
||||
"suggested_actions": [
|
||||
{
|
||||
"action": "rebalance",
|
||||
"token": "token_1",
|
||||
"amount": 10000,
|
||||
"direction": "add"
|
||||
}
|
||||
],
|
||||
"expected_improvement": 0.05
|
||||
},
|
||||
"pool_B": {
|
||||
"target_ratio": 1.8,
|
||||
"suggested_actions": [
|
||||
{
|
||||
"action": "rebalance",
|
||||
"token": "token_0",
|
||||
"amount": 5000,
|
||||
"direction": "remove"
|
||||
}
|
||||
],
|
||||
"expected_improvement": 0.03
|
||||
}
|
||||
}
|
||||
return optimizations
|
||||
|
||||
def assess_risks(arbitrage: Dict, optimizations: Dict):
|
||||
"""Assesses potential risks"""
|
||||
risk_assessment = {
|
||||
"impermanent_loss_risk": 0.1 + (time.time() % 5) / 100,
|
||||
"smart_contract_risk": "low",
|
||||
"market_manipulation_risk": "medium" if arbitrage["profit_potential"] > 0.025 else "low",
|
||||
"gas_price_risk": "high" if arbitrage["execution_cost"] > 60 else "medium",
|
||||
"mitigation_strategies": [
|
||||
"implement_slippage_protection",
|
||||
"set_maximum_gas_price",
|
||||
"use_multiple_liquidity_sources"
|
||||
]
|
||||
}
|
||||
return risk_assessment
|
||||
|
||||
def execute_trades(arbitrage: Dict, risks: Dict):
|
||||
"""Simulates trade execution"""
|
||||
execution_results = {
|
||||
"status": "success" if time.time() % 2 == 0 else "failed",
|
||||
"executed_volume": arbitrage["required_capital"] * 0.95,
|
||||
"actual_profit": arbitrage["profit_potential"] * 0.9,
|
||||
"gas_used": arbitrage["execution_cost"] * 1.1,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
return execution_results
|
||||
|
||||
# Create specialized agents
|
||||
market_analyzer = Agent(
|
||||
name="Market Analyzer",
|
||||
role="Market Analysis",
|
||||
goal="Analyze market conditions",
|
||||
instructions="Monitor and analyze DeFi market conditions",
|
||||
tools=[analyze_market_conditions]
|
||||
)
|
||||
|
||||
arbitrage_detector = Agent(
|
||||
name="Arbitrage Detector",
|
||||
role="Arbitrage Detection",
|
||||
goal="Detect arbitrage opportunities",
|
||||
instructions="Identify profitable trading opportunities",
|
||||
tools=[detect_arbitrage]
|
||||
)
|
||||
|
||||
liquidity_optimizer = Agent(
|
||||
name="Liquidity Optimizer",
|
||||
role="Liquidity Optimization",
|
||||
goal="Optimize liquidity distribution",
|
||||
instructions="Optimize pool liquidity ratios",
|
||||
tools=[optimize_liquidity]
|
||||
)
|
||||
|
||||
risk_assessor = Agent(
|
||||
name="Risk Assessor",
|
||||
role="Risk Assessment",
|
||||
goal="Assess trading risks",
|
||||
instructions="Evaluate potential risks and mitigation strategies",
|
||||
tools=[assess_risks]
|
||||
)
|
||||
|
||||
trade_executor = Agent(
|
||||
name="Trade Executor",
|
||||
role="Trade Execution",
|
||||
goal="Execute optimized trades",
|
||||
instructions="Execute trades based on analysis",
|
||||
tools=[execute_trades]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
market_task = Task(
|
||||
name="analyze_market",
|
||||
description="Analyze market conditions",
|
||||
expected_output="Market analysis",
|
||||
agent=market_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["detect_arbitrage", "optimize_liquidity"]
|
||||
)
|
||||
|
||||
arbitrage_task = Task(
|
||||
name="detect_arbitrage",
|
||||
description="Detect arbitrage opportunities",
|
||||
expected_output="Arbitrage opportunities",
|
||||
agent=arbitrage_detector,
|
||||
next_tasks=["assess_risks"]
|
||||
)
|
||||
|
||||
liquidity_task = Task(
|
||||
name="optimize_liquidity",
|
||||
description="Optimize liquidity",
|
||||
expected_output="Liquidity optimization",
|
||||
agent=liquidity_optimizer,
|
||||
context=[market_task],
|
||||
next_tasks=["assess_risks"]
|
||||
)
|
||||
|
||||
risk_task = Task(
|
||||
name="assess_risks",
|
||||
description="Assess trading risks",
|
||||
expected_output="Risk assessment",
|
||||
agent=risk_assessor,
|
||||
context=[arbitrage_task, liquidity_task],
|
||||
next_tasks=["execute_trades"]
|
||||
)
|
||||
|
||||
execution_task = Task(
|
||||
name="execute_trades",
|
||||
description="Execute trades",
|
||||
expected_output="Trade execution results",
|
||||
agent=trade_executor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"success": ["analyze_market"], # Continue monitoring if successful
|
||||
"failed": ["optimize_liquidity"] # Reoptimize if failed
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[market_analyzer, arbitrage_detector, liquidity_optimizer,
|
||||
risk_assessor, trade_executor],
|
||||
tasks=[market_task, arbitrage_task, liquidity_task,
|
||||
risk_task, execution_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting DeFi Market Making Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nMarket Making Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -87,6 +87,86 @@ icon: "code"
|
||||
>
|
||||
Learn how to create AI agents for multilingual content generation and cultural adaptation.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Climate Impact"
|
||||
icon="cloud-sun"
|
||||
href="/examples/climate-impact"
|
||||
>
|
||||
Learn how to create AI agents for climate impact analysis and adaptation strategies.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Space Mission"
|
||||
icon="rocket"
|
||||
href="/examples/space-mission"
|
||||
>
|
||||
Learn how to create AI agents for space mission planning and resource optimization.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Neural Architecture"
|
||||
icon="network-wired"
|
||||
href="/examples/neural-architecture"
|
||||
>
|
||||
Learn how to create AI agents for neural architecture search and optimization.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="DeFi Market Maker"
|
||||
icon="money-bill-trend-up"
|
||||
href="/examples/defi-market-maker"
|
||||
>
|
||||
Learn how to create AI agents for decentralized finance market making and liquidity provision.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Quantum Optimiser"
|
||||
icon="atom"
|
||||
href="/examples/quantum-optimiser"
|
||||
>
|
||||
Learn how to create AI agents for quantum computing optimization and algorithm design.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Medicine Protocol"
|
||||
icon="prescription-bottle-medical"
|
||||
href="/examples/medicine-protocol"
|
||||
>
|
||||
Learn how to create AI agents for medical protocol optimization and drug discovery.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Crypto Validator"
|
||||
icon="key"
|
||||
href="/examples/crypto-validator"
|
||||
>
|
||||
Learn how to create AI agents for cryptocurrency validation and blockchain security.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Research Assistant"
|
||||
icon="microscope"
|
||||
href="/examples/research-assistant"
|
||||
>
|
||||
Learn how to create AI agents for research analysis and experiment design.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Vulnerability Detection"
|
||||
icon="shield-check"
|
||||
href="/examples/vulnerability-detection"
|
||||
>
|
||||
Learn how to create AI agents for vulnerability detection and analysis.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Healthcare Diagnosis"
|
||||
icon="stethoscope"
|
||||
href="/examples/healthcare-diagnosis"
|
||||
>
|
||||
Learn how to create AI agents for medical diagnosis and treatment recommendations.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## What's Next?
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
---
|
||||
title: "Hackathon Judge Agent"
|
||||
description: "Learn how to create AI agents for evaluating hackathon projects through video demonstrations."
|
||||
icon: "trophy"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Judge[Hackathon Judge]
|
||||
Judge --> Scores[Project Scores]
|
||||
Scores --> Analysis[Detailed Analysis]
|
||||
Analysis --> Feedback[Feedback]
|
||||
Feedback --> Recommendations[Recommendations]
|
||||
Recommendations --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Judge fill:#2E8B57,color:#fff
|
||||
style Scores fill:#2E8B57,color:#fff
|
||||
style Analysis fill:#2E8B57,color:#fff
|
||||
style Feedback fill:#2E8B57,color:#fff
|
||||
style Recommendations fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Hackathon Project Evaluation?
|
||||
|
||||
Hackathon Project Evaluation is an automated process for assessing hackathon projects through video demonstrations. It provides comprehensive scoring across multiple dimensions including innovation, technical complexity, and presentation quality, helping organizers make informed decisions and providing valuable feedback to participants.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Project Scoring" icon="star">
|
||||
Comprehensive scoring system across multiple dimensions (0-100).
|
||||
</Card>
|
||||
<Card title="Technical Analysis" icon="microchip">
|
||||
Evaluation of technical complexity and implementation quality.
|
||||
</Card>
|
||||
<Card title="Innovation Assessment" icon="lightbulb">
|
||||
Analysis of creativity and unique project features.
|
||||
</Card>
|
||||
<Card title="Market Analysis" icon="chart-line">
|
||||
Assessment of market potential and scalability.
|
||||
</Card>
|
||||
<Card title="Detailed Feedback" icon="comments">
|
||||
Constructive feedback and specific recommendations for improvement.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents opencv-python moviepy
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `hackathon_judge.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
import os
|
||||
import json
|
||||
|
||||
class ProjectEvaluation(BaseModel):
|
||||
innovation_score: int # 0-100
|
||||
technical_complexity: int # 0-100
|
||||
presentation_quality: int # 0-100
|
||||
user_experience: int # 0-100
|
||||
completeness: int # 0-100
|
||||
overall_score: int # 0-100
|
||||
key_strengths: List[str]
|
||||
areas_for_improvement: List[str]
|
||||
notable_features: List[str]
|
||||
technical_highlights: List[str]
|
||||
recommendations: List[str]
|
||||
market_potential: str
|
||||
scalability_assessment: str
|
||||
|
||||
# Create Vision Analysis Agent
|
||||
hackathon_judge = Agent(
|
||||
name="HackathonJudge",
|
||||
role="Technical Project Evaluator",
|
||||
goal="Evaluate hackathon projects through video demonstrations",
|
||||
backstory="""You are an experienced hackathon judge and technical expert.
|
||||
You excel at evaluating innovation, technical implementation, and presentation quality.
|
||||
You provide constructive feedback and identify both strengths and areas for improvement.""",
|
||||
llm="gpt-4o-mini", # Using vision-capable model
|
||||
self_reflect=False,
|
||||
knowledge=""
|
||||
)
|
||||
|
||||
def evaluate_project(video_path: str) -> ProjectEvaluation:
|
||||
"""
|
||||
Evaluate a hackathon project based on its video demonstration
|
||||
"""
|
||||
evaluation_task = Task(
|
||||
name="project_evaluation",
|
||||
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
|
||||
|
||||
1. Score the following aspects (0-100):
|
||||
- Innovation and Creativity
|
||||
- Technical Complexity
|
||||
- Presentation Quality
|
||||
- User Experience
|
||||
- Project Completeness
|
||||
|
||||
2. Identify:
|
||||
- Key strengths and standout features
|
||||
- Areas that could be improved
|
||||
- Notable technical implementations
|
||||
- Market potential and scalability
|
||||
|
||||
3. Provide:
|
||||
- Specific recommendations for improvement
|
||||
- Technical suggestions
|
||||
- Potential future enhancements""",
|
||||
expected_output="Detailed project evaluation with scores and feedback",
|
||||
agent=hackathon_judge,
|
||||
output_pydantic=ProjectEvaluation,
|
||||
images=[video_path] # Video input for multimodal analysis
|
||||
)
|
||||
|
||||
# Initialize and run evaluation
|
||||
agents = PraisonAIAgents(
|
||||
agents=[hackathon_judge],
|
||||
tasks=[evaluation_task],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
response = agents.start()
|
||||
|
||||
try:
|
||||
# If response contains task_results, extract the Pydantic model directly
|
||||
if isinstance(response, dict) and 'task_results' in response:
|
||||
task_output = response['task_results'][0]
|
||||
if hasattr(task_output, 'pydantic'):
|
||||
return task_output.pydantic
|
||||
elif hasattr(task_output, 'raw'):
|
||||
# Extract JSON from raw string if it's wrapped in ```json
|
||||
raw_text = task_output.raw
|
||||
if raw_text.startswith('```json'):
|
||||
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
|
||||
evaluation_data = json.loads(raw_text)
|
||||
else:
|
||||
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
|
||||
# If response is a string, try to parse it as JSON
|
||||
elif isinstance(response, str):
|
||||
evaluation_data = json.loads(response)
|
||||
# If response is a dict with task_status
|
||||
elif isinstance(response, dict) and 'task_status' in response:
|
||||
content = response['task_status']
|
||||
if isinstance(content, dict):
|
||||
evaluation_data = content
|
||||
else:
|
||||
evaluation_data = json.loads(content) if isinstance(content, str) else content
|
||||
else:
|
||||
evaluation_data = response
|
||||
|
||||
print(f"Debug - Parsed evaluation_data: {evaluation_data}")
|
||||
|
||||
# Create and return ProjectEvaluation instance
|
||||
return ProjectEvaluation(
|
||||
innovation_score=int(evaluation_data.get('innovation_score', 0)),
|
||||
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
|
||||
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
|
||||
user_experience=int(evaluation_data.get('user_experience', 0)),
|
||||
completeness=int(evaluation_data.get('completeness', 0)),
|
||||
overall_score=int(evaluation_data.get('overall_score', 0)),
|
||||
key_strengths=evaluation_data.get('key_strengths', []),
|
||||
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
|
||||
notable_features=evaluation_data.get('notable_features', []),
|
||||
technical_highlights=evaluation_data.get('technical_highlights', []),
|
||||
recommendations=evaluation_data.get('recommendations', []),
|
||||
market_potential=str(evaluation_data.get('market_potential', '')),
|
||||
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Debug - Raw response: {response}")
|
||||
print(f"Error processing response: {e}")
|
||||
raise
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
video_path = os.path.join(current_dir, "presentation.mp4")
|
||||
result = evaluate_project(video_path) # Now returns ProjectEvaluation directly
|
||||
|
||||
print("\nHackathon Project Evaluation")
|
||||
print("===========================")
|
||||
print(f"\nOverall Score: {result.overall_score}/100")
|
||||
print("\nDetailed Scores:")
|
||||
print(f"Innovation: {result.innovation_score}/100")
|
||||
print(f"Technical Complexity: {result.technical_complexity}/100")
|
||||
print(f"Presentation: {result.presentation_quality}/100")
|
||||
print(f"User Experience: {result.user_experience}/100")
|
||||
print(f"Completeness: {result.completeness}/100")
|
||||
|
||||
print("\nKey Strengths:")
|
||||
for strength in result.key_strengths:
|
||||
print(f"- {strength}")
|
||||
|
||||
print("\nAreas for Improvement:")
|
||||
for area in result.areas_for_improvement:
|
||||
print(f"- {area}")
|
||||
|
||||
print("\nTechnical Highlights:")
|
||||
for highlight in result.technical_highlights:
|
||||
print(f"- {highlight}")
|
||||
|
||||
print("\nRecommendations:")
|
||||
for rec in result.recommendations:
|
||||
print(f"- {rec}")
|
||||
|
||||
print(f"\nMarket Potential: {result.market_potential}")
|
||||
print(f"\nScalability Assessment: {result.scalability_assessment}")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding the Output
|
||||
|
||||
The hackathon project evaluation generates a comprehensive report with the following components:
|
||||
|
||||
- Scoring Metrics (0-100)
|
||||
- Innovation Score
|
||||
- Technical Complexity
|
||||
- Presentation Quality
|
||||
- User Experience
|
||||
- Project Completeness
|
||||
- Overall Score
|
||||
- Qualitative Analysis
|
||||
- Key Strengths
|
||||
- Areas for Improvement
|
||||
- Notable Features
|
||||
- Technical Highlights
|
||||
- Strategic Assessment
|
||||
- Recommendations
|
||||
- Market Potential
|
||||
- Scalability Assessment
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
<Card title="API Reference" icon="code" href="/api-reference">
|
||||
Explore the complete API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,300 @@
|
||||
---
|
||||
title: "Medicine Protocol"
|
||||
description: "Learn how to create AI agents for personalized medicine protocol generation and analysis."
|
||||
icon: "stethoscope"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Genetic[Genetic Analyzer]
|
||||
In --> History[Patient History]
|
||||
Genetic --> Interaction[Drug Interaction]
|
||||
History --> Interaction
|
||||
Interaction --> Protocol[Protocol Generator]
|
||||
Protocol --> Simulation[Effectiveness Simulator]
|
||||
Simulation --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Genetic fill:#2E8B57,color:#fff
|
||||
style History fill:#2E8B57,color:#fff
|
||||
style Interaction fill:#2E8B57,color:#fff
|
||||
style Protocol fill:#2E8B57,color:#fff
|
||||
style Simulation fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Personalized Medicine?
|
||||
|
||||
Personalized medicine is an approach that tailors medical treatment to individual characteristics of each patient. It involves analyzing genetic markers, patient history, and drug interactions to create optimized treatment protocols.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Genetic Analysis" icon="dna">
|
||||
Deep analysis of genetic markers including metabolism genes, risk factors, and drug response markers.
|
||||
</Card>
|
||||
<Card title="Patient History" icon="notes-medical">
|
||||
Comprehensive evaluation of medical conditions, medications, allergies, and family history.
|
||||
</Card>
|
||||
<Card title="Drug Interaction" icon="pills">
|
||||
Analysis of potential drug interactions based on genetic data and patient history.
|
||||
</Card>
|
||||
<Card title="Protocol Generation" icon="file-medical">
|
||||
Creation of personalized treatment protocols with dosage adjustments and monitoring plans.
|
||||
</Card>
|
||||
<Card title="Treatment Simulation" icon="chart-line">
|
||||
Prediction of treatment effectiveness, side effects, and adherence probability.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_genetic_markers():
|
||||
"""Simulates genetic marker analysis"""
|
||||
markers = {
|
||||
"metabolism_genes": {
|
||||
"CYP2D6": "rapid_metabolizer",
|
||||
"CYP2C19": "normal_metabolizer",
|
||||
"DPYD": "poor_metabolizer"
|
||||
},
|
||||
"risk_factors": {
|
||||
"cardiovascular": "elevated",
|
||||
"diabetes": "low",
|
||||
"autoimmune": "moderate"
|
||||
},
|
||||
"drug_response_markers": {
|
||||
"TPMT": "high_sensitivity",
|
||||
"HLA-B*5701": "negative",
|
||||
"UGT1A1": "normal"
|
||||
}
|
||||
}
|
||||
return markers
|
||||
|
||||
def evaluate_patient_history():
|
||||
"""Simulates patient history evaluation"""
|
||||
history = {
|
||||
"conditions": [
|
||||
{"name": "hypertension", "duration": "5_years", "severity": "moderate"},
|
||||
{"name": "arthritis", "duration": "2_years", "severity": "mild"}
|
||||
],
|
||||
"medications": [
|
||||
{"name": "lisinopril", "response": "good", "side_effects": "minimal"},
|
||||
{"name": "methotrexate", "response": "moderate", "side_effects": "mild"}
|
||||
],
|
||||
"allergies": ["penicillin", "sulfa"],
|
||||
"family_history": ["diabetes", "heart_disease"]
|
||||
}
|
||||
return history
|
||||
|
||||
def analyze_drug_interactions(genetic_data: Dict, patient_history: Dict):
|
||||
"""Analyzes potential drug interactions"""
|
||||
interactions = []
|
||||
medications = [med["name"] for med in patient_history["medications"]]
|
||||
|
||||
for med in medications:
|
||||
interactions.append({
|
||||
"medication": med,
|
||||
"genetic_impact": "significant" if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer" else "normal",
|
||||
"risk_level": "high" if med in patient_history["allergies"] else "low",
|
||||
"monitoring_needed": True if genetic_data["metabolism_genes"]["DPYD"] == "poor_metabolizer" else False
|
||||
})
|
||||
return interactions
|
||||
|
||||
def generate_protocol(genetic_data: Dict, interactions: List[Dict]):
|
||||
"""Generates treatment protocol"""
|
||||
protocol = {
|
||||
"primary_treatment": {
|
||||
"medication": "custom_formulation_A",
|
||||
"dosage": "adjusted_based_on_metabolism",
|
||||
"frequency": "twice_daily",
|
||||
"monitoring": {
|
||||
"type": "blood_levels",
|
||||
"frequency": "weekly"
|
||||
}
|
||||
},
|
||||
"alternatives": [
|
||||
{
|
||||
"medication": "custom_formulation_B",
|
||||
"conditions": ["genetic_compatibility", "no_interactions"]
|
||||
}
|
||||
],
|
||||
"precautions": []
|
||||
}
|
||||
|
||||
if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer":
|
||||
protocol["precautions"].append("increase_monitoring_frequency")
|
||||
|
||||
if any(i["risk_level"] == "high" for i in interactions):
|
||||
protocol["precautions"].append("alternative_medication_needed")
|
||||
|
||||
return protocol
|
||||
|
||||
def simulate_effectiveness(protocol: Dict):
|
||||
"""Simulates treatment effectiveness"""
|
||||
simulation = {
|
||||
"efficacy_prediction": 0.85 + (time.time() % 2) / 10,
|
||||
"side_effect_risk": 0.15 + (time.time() % 1) / 10,
|
||||
"adherence_probability": 0.9 + (time.time() % 1) / 10,
|
||||
"expected_outcomes": [
|
||||
"symptom_reduction_80_percent",
|
||||
"minimal_side_effects",
|
||||
"good_tolerance"
|
||||
]
|
||||
}
|
||||
return simulation
|
||||
|
||||
# Create specialized agents
|
||||
genetic_analyzer = Agent(
|
||||
name="Genetic Analyzer",
|
||||
role="Genetic Analysis",
|
||||
goal="Analyze genetic markers",
|
||||
instructions="Evaluate genetic markers and variants",
|
||||
tools=[analyze_genetic_markers]
|
||||
)
|
||||
|
||||
history_analyzer = Agent(
|
||||
name="History Analyzer",
|
||||
role="History Analysis",
|
||||
goal="Analyze patient history",
|
||||
instructions="Evaluate medical history and conditions",
|
||||
tools=[evaluate_patient_history]
|
||||
)
|
||||
|
||||
interaction_analyzer = Agent(
|
||||
name="Interaction Analyzer",
|
||||
role="Drug Interaction",
|
||||
goal="Analyze drug interactions",
|
||||
instructions="Evaluate potential drug interactions",
|
||||
tools=[analyze_drug_interactions]
|
||||
)
|
||||
|
||||
protocol_generator = Agent(
|
||||
name="Protocol Generator",
|
||||
role="Protocol Generation",
|
||||
goal="Generate treatment protocol",
|
||||
instructions="Create personalized treatment protocol",
|
||||
tools=[generate_protocol]
|
||||
)
|
||||
|
||||
effectiveness_simulator = Agent(
|
||||
name="Effectiveness Simulator",
|
||||
role="Treatment Simulation",
|
||||
goal="Simulate treatment effectiveness",
|
||||
instructions="Predict treatment outcomes",
|
||||
tools=[simulate_effectiveness]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
genetic_task = Task(
|
||||
name="analyze_genetics",
|
||||
description="Analyze genetic markers",
|
||||
expected_output="Genetic analysis",
|
||||
agent=genetic_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_history"]
|
||||
)
|
||||
|
||||
history_task = Task(
|
||||
name="analyze_history",
|
||||
description="Analyze patient history",
|
||||
expected_output="History analysis",
|
||||
agent=history_analyzer,
|
||||
next_tasks=["analyze_interactions"]
|
||||
)
|
||||
|
||||
interaction_task = Task(
|
||||
name="analyze_interactions",
|
||||
description="Analyze drug interactions",
|
||||
expected_output="Interaction analysis",
|
||||
agent=interaction_analyzer,
|
||||
context=[genetic_task, history_task],
|
||||
next_tasks=["generate_protocol"]
|
||||
)
|
||||
|
||||
protocol_task = Task(
|
||||
name="generate_protocol",
|
||||
description="Generate treatment protocol",
|
||||
expected_output="Treatment protocol",
|
||||
agent=protocol_generator,
|
||||
context=[genetic_task, interaction_task],
|
||||
next_tasks=["simulate_effectiveness"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_effectiveness",
|
||||
description="Simulate treatment effectiveness",
|
||||
expected_output="Effectiveness simulation",
|
||||
agent=effectiveness_simulator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": "", # End workflow if high effectiveness
|
||||
"medium": ["generate_protocol"], # Adjust protocol if medium
|
||||
"low": ["analyze_interactions"] # Reanalyze if low
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[genetic_analyzer, history_analyzer, interaction_analyzer,
|
||||
protocol_generator, effectiveness_simulator],
|
||||
tasks=[genetic_task, history_task, interaction_task,
|
||||
protocol_task, simulation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Personalized Medicine Protocol Generation...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nProtocol Generation Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,284 @@
|
||||
---
|
||||
title: "Neural Architecture"
|
||||
description: "Learn how to create AI agents for neural architecture search and optimization."
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Hardware[Hardware Analyzer]
|
||||
Hardware --> Generator[Architecture Generator]
|
||||
Generator --> Hyperparams[Hyperparameter Optimizer]
|
||||
Hyperparams --> Performance[Performance Estimator]
|
||||
Performance --> Deployment[Deployment Optimizer]
|
||||
Deployment --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Hardware fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Hyperparams fill:#2E8B57,color:#fff
|
||||
style Performance fill:#2E8B57,color:#fff
|
||||
style Deployment fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Neural Architecture Search?
|
||||
|
||||
Neural Architecture Search (NAS) is an automated process for designing optimal neural network architectures. It involves analyzing hardware constraints, generating candidate architectures, optimizing hyperparameters, and configuring deployment settings to create efficient and performant models.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Hardware Analysis" icon="microchip">
|
||||
Analysis of GPU memory, compute capability, bandwidth, and thermal constraints.
|
||||
</Card>
|
||||
<Card title="Architecture Generation" icon="diagram-project">
|
||||
Creation of candidate architectures including transformers and CNNs with optimized structures.
|
||||
</Card>
|
||||
<Card title="Hyperparameter Tuning" icon="sliders">
|
||||
Optimization of learning rates, batch sizes, optimizers, and regularization parameters.
|
||||
</Card>
|
||||
<Card title="Performance Estimation" icon="gauge-high">
|
||||
Prediction of model accuracy, training time, memory requirements, and FLOPS.
|
||||
</Card>
|
||||
<Card title="Deployment Optimization" icon="rocket">
|
||||
Configuration of quantization, pruning, and batching for efficient deployment.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_hardware_constraints():
|
||||
"""Simulates hardware analysis"""
|
||||
constraints = {
|
||||
"gpu_memory": 16 * 1024, # MB
|
||||
"compute_capability": "7.5",
|
||||
"memory_bandwidth": 900, # GB/s
|
||||
"tensor_cores": True,
|
||||
"max_power_consumption": 300, # Watts
|
||||
"thermal_limits": 85 # Celsius
|
||||
}
|
||||
return constraints
|
||||
|
||||
def generate_architecture_candidates():
|
||||
"""Generates candidate architectures"""
|
||||
candidates = [
|
||||
{
|
||||
"type": "transformer",
|
||||
"layers": 12 + (int(time.time()) % 6),
|
||||
"attention_heads": 8,
|
||||
"embedding_dim": 512,
|
||||
"estimated_params": 125_000_000
|
||||
},
|
||||
{
|
||||
"type": "cnn",
|
||||
"layers": 50 + (int(time.time()) % 50),
|
||||
"filters": [64, 128, 256, 512],
|
||||
"estimated_params": 25_000_000
|
||||
}
|
||||
]
|
||||
return candidates[int(time.time()) % 2]
|
||||
|
||||
def optimize_hyperparameters(architecture: Dict):
|
||||
"""Optimizes hyperparameters"""
|
||||
optimization = {
|
||||
"learning_rate": 0.001 + (time.time() % 9) / 10000,
|
||||
"batch_size": 32 * (1 + int(time.time()) % 4),
|
||||
"optimizer": "adam",
|
||||
"weight_decay": 0.0001,
|
||||
"dropout_rate": 0.1 + (time.time() % 3) / 10,
|
||||
"activation": "gelu" if architecture["type"] == "transformer" else "relu"
|
||||
}
|
||||
return optimization
|
||||
|
||||
def estimate_performance(architecture: Dict, hyperparams: Dict):
|
||||
"""Estimates model performance"""
|
||||
performance = {
|
||||
"estimated_accuracy": 0.85 + (time.time() % 10) / 100,
|
||||
"estimated_training_time": {
|
||||
"hours": 24 + (int(time.time()) % 24),
|
||||
"gpu_hours": 96
|
||||
},
|
||||
"memory_requirements": {
|
||||
"training": architecture["estimated_params"] * 4 / (1024 * 1024), # GB
|
||||
"inference": architecture["estimated_params"] * 2 / (1024 * 1024) # GB
|
||||
},
|
||||
"flops_count": architecture["estimated_params"] * 2
|
||||
}
|
||||
return performance
|
||||
|
||||
def optimize_deployment(architecture: Dict, performance: Dict):
|
||||
"""Optimizes deployment configuration"""
|
||||
deployment = {
|
||||
"quantization": {
|
||||
"method": "dynamic",
|
||||
"precision": "int8",
|
||||
"estimated_speedup": 2.5
|
||||
},
|
||||
"pruning": {
|
||||
"method": "magnitude",
|
||||
"target_sparsity": 0.3,
|
||||
"estimated_size_reduction": 0.6
|
||||
},
|
||||
"batching": {
|
||||
"max_batch_size": 32,
|
||||
"dynamic_batching": True
|
||||
}
|
||||
}
|
||||
return deployment
|
||||
|
||||
# Create specialized agents
|
||||
hardware_analyzer = Agent(
|
||||
name="Hardware Analyzer",
|
||||
role="Hardware Analysis",
|
||||
goal="Analyze hardware constraints",
|
||||
instructions="Evaluate available hardware resources",
|
||||
tools=[analyze_hardware_constraints]
|
||||
)
|
||||
|
||||
architecture_generator = Agent(
|
||||
name="Architecture Generator",
|
||||
role="Architecture Generation",
|
||||
goal="Generate neural architectures",
|
||||
instructions="Create candidate neural architectures",
|
||||
tools=[generate_architecture_candidates]
|
||||
)
|
||||
|
||||
hyperparameter_optimizer = Agent(
|
||||
name="Hyperparameter Optimizer",
|
||||
role="Hyperparameter Optimization",
|
||||
goal="Optimize hyperparameters",
|
||||
instructions="Find optimal hyperparameter settings",
|
||||
tools=[optimize_hyperparameters]
|
||||
)
|
||||
|
||||
performance_estimator = Agent(
|
||||
name="Performance Estimator",
|
||||
role="Performance Estimation",
|
||||
goal="Estimate model performance",
|
||||
instructions="Predict model performance metrics",
|
||||
tools=[estimate_performance]
|
||||
)
|
||||
|
||||
deployment_optimizer = Agent(
|
||||
name="Deployment Optimizer",
|
||||
role="Deployment Optimization",
|
||||
goal="Optimize deployment settings",
|
||||
instructions="Configure optimal deployment",
|
||||
tools=[optimize_deployment]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
hardware_task = Task(
|
||||
name="analyze_hardware",
|
||||
description="Analyze hardware constraints",
|
||||
expected_output="Hardware analysis",
|
||||
agent=hardware_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["generate_architecture"]
|
||||
)
|
||||
|
||||
architecture_task = Task(
|
||||
name="generate_architecture",
|
||||
description="Generate architecture candidates",
|
||||
expected_output="Architecture candidates",
|
||||
agent=architecture_generator,
|
||||
next_tasks=["optimize_hyperparameters"]
|
||||
)
|
||||
|
||||
hyperparameter_task = Task(
|
||||
name="optimize_hyperparameters",
|
||||
description="Optimize hyperparameters",
|
||||
expected_output="Hyperparameter settings",
|
||||
agent=hyperparameter_optimizer,
|
||||
context=[architecture_task],
|
||||
next_tasks=["estimate_performance"]
|
||||
)
|
||||
|
||||
performance_task = Task(
|
||||
name="estimate_performance",
|
||||
description="Estimate performance",
|
||||
expected_output="Performance estimates",
|
||||
agent=performance_estimator,
|
||||
context=[architecture_task, hyperparameter_task],
|
||||
next_tasks=["optimize_deployment"]
|
||||
)
|
||||
|
||||
deployment_task = Task(
|
||||
name="optimize_deployment",
|
||||
description="Optimize deployment",
|
||||
expected_output="Deployment configuration",
|
||||
agent=deployment_optimizer,
|
||||
context=[architecture_task, performance_task],
|
||||
task_type="decision",
|
||||
condition={
|
||||
"success": ["generate_architecture"], # Try new architecture
|
||||
"failure": ["optimize_hyperparameters"] # Reoptimize hyperparameters
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[hardware_analyzer, architecture_generator, hyperparameter_optimizer,
|
||||
performance_estimator, deployment_optimizer],
|
||||
tasks=[hardware_task, architecture_task, hyperparameter_task,
|
||||
performance_task, deployment_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Neural Architecture Search Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nArchitecture Search Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,279 @@
|
||||
---
|
||||
title: "Quantum Optimiser"
|
||||
description: "Learn how to create AI agents for quantum circuit optimization and performance analysis."
|
||||
icon: "atom"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Circuit Analyzer]
|
||||
Analyzer --> Finder[Optimization Finder]
|
||||
Finder --> Optimizer[Circuit Optimizer]
|
||||
Optimizer --> Benchmarker[Performance Benchmarker]
|
||||
Benchmarker --> Validator[Results Validator]
|
||||
Validator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Finder fill:#2E8B57,color:#fff
|
||||
style Optimizer fill:#2E8B57,color:#fff
|
||||
style Benchmarker fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Quantum Circuit Optimization?
|
||||
|
||||
Quantum circuit optimization is the process of improving quantum algorithms by reducing circuit depth, minimizing gate count, and enhancing execution efficiency while maintaining computational fidelity. This is crucial for making quantum algorithms practical on real quantum hardware.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Circuit Analysis" icon="microchip">
|
||||
Deep analysis of quantum circuit metrics including depth, gate counts, and qubit usage.
|
||||
</Card>
|
||||
<Card title="Optimization Detection" icon="magnifying-glass">
|
||||
Identification of optimization opportunities through gate reduction and parallel execution.
|
||||
</Card>
|
||||
<Card title="Performance Simulation" icon="gauge-high">
|
||||
Simulation of optimization results with improvement metrics and success probabilities.
|
||||
</Card>
|
||||
<Card title="Benchmark Testing" icon="chart-line">
|
||||
Comprehensive benchmarking of execution time, fidelity, and resource usage.
|
||||
</Card>
|
||||
<Card title="Result Validation" icon="check-double">
|
||||
Validation of optimization results ensuring performance gains and fidelity maintenance.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_quantum_circuit():
|
||||
"""Simulates quantum circuit analysis"""
|
||||
circuit_metrics = {
|
||||
"depth": 15 + (int(time.time()) % 10),
|
||||
"gates": {
|
||||
"single_qubit": 25 + (int(time.time()) % 15),
|
||||
"two_qubit": 10 + (int(time.time()) % 8),
|
||||
"measurement": 5 + (int(time.time()) % 3)
|
||||
},
|
||||
"qubits": 8 + (int(time.time()) % 4)
|
||||
}
|
||||
return circuit_metrics
|
||||
|
||||
def identify_optimization_opportunities(metrics: Dict):
|
||||
"""Identifies potential optimization areas"""
|
||||
opportunities = []
|
||||
if metrics["depth"] > 20:
|
||||
opportunities.append({
|
||||
"type": "depth_reduction",
|
||||
"potential": "high",
|
||||
"technique": "parallel_gates"
|
||||
})
|
||||
if metrics["gates"]["two_qubit"] > 15:
|
||||
opportunities.append({
|
||||
"type": "gate_reduction",
|
||||
"potential": "medium",
|
||||
"technique": "gate_decomposition"
|
||||
})
|
||||
return opportunities
|
||||
|
||||
def simulate_optimization(opportunities: List[Dict]):
|
||||
"""Simulates optimization results"""
|
||||
results = []
|
||||
for opt in opportunities:
|
||||
improvement = {
|
||||
"high": 0.3 + (time.time() % 2) / 10,
|
||||
"medium": 0.2 + (time.time() % 2) / 10,
|
||||
"low": 0.1 + (time.time() % 2) / 10
|
||||
}
|
||||
results.append({
|
||||
"type": opt["type"],
|
||||
"improvement": improvement[opt["potential"]],
|
||||
"success_probability": 0.8 + (time.time() % 2) / 10
|
||||
})
|
||||
return results
|
||||
|
||||
def benchmark_performance(original: Dict, optimized: List[Dict]):
|
||||
"""Benchmarks optimization performance"""
|
||||
benchmarks = {
|
||||
"execution_time": {
|
||||
"original": 100 + (int(time.time()) % 50),
|
||||
"optimized": 70 + (int(time.time()) % 30)
|
||||
},
|
||||
"fidelity": {
|
||||
"original": 0.9 + (time.time() % 1) / 10,
|
||||
"optimized": 0.85 + (time.time() % 1) / 10
|
||||
},
|
||||
"resource_usage": {
|
||||
"original": original["qubits"],
|
||||
"optimized": original["qubits"] - len(optimized)
|
||||
}
|
||||
}
|
||||
return benchmarks
|
||||
|
||||
def validate_results(benchmarks: Dict):
|
||||
"""Validates optimization results"""
|
||||
validations = {
|
||||
"performance_gain": (benchmarks["execution_time"]["original"] -
|
||||
benchmarks["execution_time"]["optimized"]) /
|
||||
benchmarks["execution_time"]["original"],
|
||||
"fidelity_maintained": benchmarks["fidelity"]["optimized"] > 0.8,
|
||||
"resource_efficient": benchmarks["resource_usage"]["optimized"] <
|
||||
benchmarks["resource_usage"]["original"]
|
||||
}
|
||||
return validations
|
||||
|
||||
# Create specialized agents
|
||||
circuit_analyzer = Agent(
|
||||
name="Circuit Analyzer",
|
||||
role="Circuit Analysis",
|
||||
goal="Analyze quantum circuit structure",
|
||||
instructions="Evaluate quantum circuit metrics",
|
||||
tools=[analyze_quantum_circuit]
|
||||
)
|
||||
|
||||
optimization_finder = Agent(
|
||||
name="Optimization Finder",
|
||||
role="Optimization Discovery",
|
||||
goal="Identify optimization opportunities",
|
||||
instructions="Find potential optimization techniques",
|
||||
tools=[identify_optimization_opportunities]
|
||||
)
|
||||
|
||||
optimizer = Agent(
|
||||
name="Circuit Optimizer",
|
||||
role="Circuit Optimization",
|
||||
goal="Optimize quantum circuit",
|
||||
instructions="Apply optimization techniques",
|
||||
tools=[simulate_optimization]
|
||||
)
|
||||
|
||||
benchmarker = Agent(
|
||||
name="Performance Benchmarker",
|
||||
role="Performance Analysis",
|
||||
goal="Benchmark optimization results",
|
||||
instructions="Measure performance improvements",
|
||||
tools=[benchmark_performance]
|
||||
)
|
||||
|
||||
validator = Agent(
|
||||
name="Results Validator",
|
||||
role="Validation",
|
||||
goal="Validate optimization results",
|
||||
instructions="Ensure optimization quality",
|
||||
tools=[validate_results]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_circuit",
|
||||
description="Analyze quantum circuit",
|
||||
expected_output="Circuit metrics",
|
||||
agent=circuit_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["find_optimizations"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="find_optimizations",
|
||||
description="Find optimization opportunities",
|
||||
expected_output="Optimization opportunities",
|
||||
agent=optimization_finder,
|
||||
next_tasks=["optimize_circuit"]
|
||||
)
|
||||
|
||||
optimization_execution_task = Task(
|
||||
name="optimize_circuit",
|
||||
description="Execute circuit optimization",
|
||||
expected_output="Optimization results",
|
||||
agent=optimizer,
|
||||
next_tasks=["benchmark_performance"]
|
||||
)
|
||||
|
||||
benchmark_task = Task(
|
||||
name="benchmark_performance",
|
||||
description="Benchmark optimization",
|
||||
expected_output="Performance metrics",
|
||||
agent=benchmarker,
|
||||
next_tasks=["validate_results"],
|
||||
context=[analysis_task, optimization_execution_task]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_results",
|
||||
description="Validate optimization results",
|
||||
expected_output="Validation results",
|
||||
agent=validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"True": "", # End workflow if validation passes
|
||||
"False": ["find_optimizations"] # Retry optimization if validation fails
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[circuit_analyzer, optimization_finder, optimizer,
|
||||
benchmarker, validator],
|
||||
tasks=[analysis_task, optimization_task, optimization_execution_task,
|
||||
benchmark_task, validation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Quantum Algorithm Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nOptimization Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,274 @@
|
||||
---
|
||||
title: "Research Assistant"
|
||||
description: "Learn how to create AI agents for research analysis and experiment design."
|
||||
icon: "microscope"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Paper Analyzer]
|
||||
Analyzer --> Gap[Gap Identifier]
|
||||
Gap --> Designer[Experiment Designer]
|
||||
Designer --> Validator[Methodology Validator]
|
||||
Validator --> Impact[Impact Predictor]
|
||||
Impact --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Gap fill:#2E8B57,color:#fff
|
||||
style Designer fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Impact fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Research Analysis?
|
||||
|
||||
Research Analysis is a systematic process of analyzing scientific papers, identifying knowledge gaps, designing experiments, validating methodologies, and predicting research impact. This helps researchers make informed decisions about their research direction and experimental design.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Paper Analysis" icon="book">
|
||||
Analysis of research papers with topic identification and impact assessment.
|
||||
</Card>
|
||||
<Card title="Gap Identification" icon="magnifying-glass">
|
||||
Discovery of research gaps with significance and potential evaluation.
|
||||
</Card>
|
||||
<Card title="Experiment Design" icon="flask">
|
||||
Creation of experimental methodologies with resource planning.
|
||||
</Card>
|
||||
<Card title="Methodology Validation" icon="check-double">
|
||||
Validation of experimental design with statistical power and feasibility checks.
|
||||
</Card>
|
||||
<Card title="Impact Prediction" icon="chart-line">
|
||||
Prediction of research impact with novelty and breakthrough probability.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_research_papers():
|
||||
"""Simulates research paper analysis"""
|
||||
papers = [
|
||||
{
|
||||
"topic": "quantum_computing",
|
||||
"gaps": ["error_correction", "scalability"],
|
||||
"methodology": "experimental",
|
||||
"impact_factor": 8.5
|
||||
},
|
||||
{
|
||||
"topic": "machine_learning",
|
||||
"gaps": ["interpretability", "robustness"],
|
||||
"methodology": "theoretical",
|
||||
"impact_factor": 7.8
|
||||
}
|
||||
]
|
||||
return papers[int(time.time()) % 2]
|
||||
|
||||
def identify_knowledge_gaps(papers: Dict):
|
||||
"""Identifies research gaps"""
|
||||
gaps = []
|
||||
for gap in papers["gaps"]:
|
||||
gaps.append({
|
||||
"area": gap,
|
||||
"significance": "high" if papers["impact_factor"] > 8 else "medium",
|
||||
"research_potential": 0.8 + (time.time() % 2) / 10
|
||||
})
|
||||
return gaps
|
||||
|
||||
def design_experiment(gaps: List[Dict]):
|
||||
"""Designs experimental methodology"""
|
||||
experiments = []
|
||||
for gap in gaps:
|
||||
experiments.append({
|
||||
"area": gap["area"],
|
||||
"methodology": {
|
||||
"type": "quantitative",
|
||||
"duration": "3_months",
|
||||
"resources_needed": ["equipment_A", "dataset_B"],
|
||||
"expected_outcome": "validation_metrics"
|
||||
},
|
||||
"priority": gap["significance"]
|
||||
})
|
||||
return experiments
|
||||
|
||||
def validate_methodology(experiments: List[Dict]):
|
||||
"""Validates experimental design"""
|
||||
validations = []
|
||||
for exp in experiments:
|
||||
validations.append({
|
||||
"area": exp["area"],
|
||||
"statistical_power": 0.9 + (time.time() % 1) / 10,
|
||||
"resource_feasibility": 0.8 + (time.time() % 1) / 10,
|
||||
"ethical_compliance": True,
|
||||
"recommendations": []
|
||||
})
|
||||
return validations
|
||||
|
||||
def predict_impact(experiments: List[Dict], validations: List[Dict]):
|
||||
"""Predicts research impact"""
|
||||
predictions = []
|
||||
for exp, val in zip(experiments, validations):
|
||||
predictions.append({
|
||||
"area": exp["area"],
|
||||
"potential_impact": val["statistical_power"] * 10,
|
||||
"novelty_score": 0.7 + (time.time() % 3) / 10,
|
||||
"breakthrough_probability": 0.5 + (time.time() % 4) / 10
|
||||
})
|
||||
return predictions
|
||||
|
||||
# Create specialized agents
|
||||
paper_analyzer = Agent(
|
||||
name="Paper Analyzer",
|
||||
role="Research Analysis",
|
||||
goal="Analyze research papers",
|
||||
instructions="Review and analyze scientific papers",
|
||||
tools=[analyze_research_papers]
|
||||
)
|
||||
|
||||
gap_identifier = Agent(
|
||||
name="Gap Identifier",
|
||||
role="Gap Analysis",
|
||||
goal="Identify knowledge gaps",
|
||||
instructions="Identify research opportunities",
|
||||
tools=[identify_knowledge_gaps]
|
||||
)
|
||||
|
||||
experiment_designer = Agent(
|
||||
name="Experiment Designer",
|
||||
role="Experimental Design",
|
||||
goal="Design research experiments",
|
||||
instructions="Create experimental methodologies",
|
||||
tools=[design_experiment]
|
||||
)
|
||||
|
||||
methodology_validator = Agent(
|
||||
name="Methodology Validator",
|
||||
role="Validation",
|
||||
goal="Validate experimental design",
|
||||
instructions="Ensure methodology validity",
|
||||
tools=[validate_methodology]
|
||||
)
|
||||
|
||||
impact_predictor = Agent(
|
||||
name="Impact Predictor",
|
||||
role="Impact Analysis",
|
||||
goal="Predict research impact",
|
||||
instructions="Assess potential impact",
|
||||
tools=[predict_impact]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_papers",
|
||||
description="Analyze research papers",
|
||||
expected_output="Paper analysis results",
|
||||
agent=paper_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["identify_gaps"]
|
||||
)
|
||||
|
||||
gap_task = Task(
|
||||
name="identify_gaps",
|
||||
description="Identify knowledge gaps",
|
||||
expected_output="Research gaps",
|
||||
agent=gap_identifier,
|
||||
next_tasks=["design_experiments"]
|
||||
)
|
||||
|
||||
design_task = Task(
|
||||
name="design_experiments",
|
||||
description="Design experiments",
|
||||
expected_output="Experimental designs",
|
||||
agent=experiment_designer,
|
||||
next_tasks=["validate_methodology"]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_methodology",
|
||||
description="Validate methodology",
|
||||
expected_output="Validation results",
|
||||
agent=methodology_validator,
|
||||
next_tasks=["predict_impact"]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_impact",
|
||||
description="Predict research impact",
|
||||
expected_output="Impact predictions",
|
||||
agent=impact_predictor,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": "", # End workflow if high impact
|
||||
"medium": ["design_experiments"], # Refine if medium impact
|
||||
"low": ["identify_gaps"] # Restart if low impact
|
||||
},
|
||||
context=[design_task, validation_task]
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[paper_analyzer, gap_identifier, experiment_designer,
|
||||
methodology_validator, impact_predictor],
|
||||
tasks=[analysis_task, gap_task, design_task,
|
||||
validation_task, prediction_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Research Assistant Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nResearch Analysis Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,313 @@
|
||||
---
|
||||
title: "Space Mission"
|
||||
description: "Learn how to create AI agents for space mission planning and resource optimization."
|
||||
icon: "rocket"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Mission[Mission Analyzer]
|
||||
Mission --> Resources[Resource Calculator]
|
||||
Resources --> Contingency[Contingency Planner]
|
||||
Contingency --> Optimizer[Resource Optimizer]
|
||||
Optimizer --> Simulator[Scenario Simulator]
|
||||
Simulator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Mission fill:#2E8B57,color:#fff
|
||||
style Resources fill:#2E8B57,color:#fff
|
||||
style Contingency fill:#2E8B57,color:#fff
|
||||
style Optimizer fill:#2E8B57,color:#fff
|
||||
style Simulator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Space Mission Planning?
|
||||
|
||||
Space Mission Planning is a complex process that involves analyzing mission parameters, calculating resource requirements, planning contingencies, optimizing resource allocation, and simulating various scenarios. This ensures the safety and success of space missions by carefully managing resources and preparing for potential emergencies.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mission Analysis" icon="satellite">
|
||||
Analysis of mission duration, crew size, orbital parameters, and objectives.
|
||||
</Card>
|
||||
<Card title="Resource Calculation" icon="calculator">
|
||||
Computation of life support, power, and propellant requirements.
|
||||
</Card>
|
||||
<Card title="Contingency Planning" icon="shield">
|
||||
Planning for power failures, life support malfunctions, and other emergencies.
|
||||
</Card>
|
||||
<Card title="Resource Optimization" icon="chart-line">
|
||||
Optimization of resource allocation with buffers for contingencies.
|
||||
</Card>
|
||||
<Card title="Scenario Simulation" icon="vr-cardboard">
|
||||
Simulation of nominal operations and emergency scenarios.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_mission_parameters():
|
||||
"""Simulates mission parameter analysis"""
|
||||
parameters = {
|
||||
"duration": 180, # days
|
||||
"crew_size": 4,
|
||||
"orbital_parameters": {
|
||||
"altitude": 400, # km
|
||||
"inclination": 51.6, # degrees
|
||||
"period": 92.68 # minutes
|
||||
},
|
||||
"mission_objectives": [
|
||||
"scientific_research",
|
||||
"satellite_deployment",
|
||||
"space_station_maintenance"
|
||||
]
|
||||
}
|
||||
return parameters
|
||||
|
||||
def calculate_resource_requirements(params: Dict):
|
||||
"""Calculates required resources"""
|
||||
requirements = {
|
||||
"life_support": {
|
||||
"oxygen": params["duration"] * params["crew_size"] * 0.84, # kg
|
||||
"water": params["duration"] * params["crew_size"] * 2.5, # liters
|
||||
"food": params["duration"] * params["crew_size"] * 1.8 # kg
|
||||
},
|
||||
"power": {
|
||||
"daily_consumption": 30 + (params["crew_size"] * 5), # kWh
|
||||
"peak_demand": 45 + (params["crew_size"] * 8), # kW
|
||||
"backup_capacity": 72 # hours
|
||||
},
|
||||
"propellant": {
|
||||
"main_engine": 2000, # kg
|
||||
"attitude_control": 500, # kg
|
||||
"reserve": 300 # kg
|
||||
}
|
||||
}
|
||||
return requirements
|
||||
|
||||
def plan_contingencies(requirements: Dict):
|
||||
"""Plans contingency scenarios"""
|
||||
contingencies = [
|
||||
{
|
||||
"scenario": "power_failure",
|
||||
"probability": 0.05,
|
||||
"impact": "critical",
|
||||
"resources_needed": {
|
||||
"backup_power": requirements["power"]["daily_consumption"] * 3,
|
||||
"repair_equipment": ["solar_panel_kit", "power_distribution_unit"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "life_support_malfunction",
|
||||
"probability": 0.03,
|
||||
"impact": "severe",
|
||||
"resources_needed": {
|
||||
"oxygen_reserve": requirements["life_support"]["oxygen"] * 0.2,
|
||||
"repair_parts": ["filter_system", "pressure_regulators"]
|
||||
}
|
||||
}
|
||||
]
|
||||
return contingencies[int(time.time()) % 2]
|
||||
|
||||
def optimize_allocation(requirements: Dict, contingencies: Dict):
|
||||
"""Optimizes resource allocation"""
|
||||
allocation = {
|
||||
"primary_resources": {
|
||||
"life_support": {
|
||||
"nominal": requirements["life_support"],
|
||||
"buffer": 0.15 # 15% buffer
|
||||
},
|
||||
"power": {
|
||||
"nominal": requirements["power"],
|
||||
"buffer": 0.2 # 20% buffer
|
||||
}
|
||||
},
|
||||
"contingency_resources": {
|
||||
"type": contingencies["scenario"],
|
||||
"allocation": contingencies["resources_needed"],
|
||||
"priority": "high" if contingencies["impact"] == "critical" else "medium"
|
||||
}
|
||||
}
|
||||
return allocation
|
||||
|
||||
def simulate_mission_scenarios(allocation: Dict):
|
||||
"""Simulates various mission scenarios"""
|
||||
scenarios = {
|
||||
"nominal_operations": {
|
||||
"success_rate": 0.95,
|
||||
"resource_utilization": 0.85,
|
||||
"efficiency_rating": 0.9
|
||||
},
|
||||
"emergency_scenarios": [
|
||||
{
|
||||
"type": "power_reduction",
|
||||
"duration": 48, # hours
|
||||
"impact": "moderate",
|
||||
"resolution_success": 0.88
|
||||
},
|
||||
{
|
||||
"type": "life_support_adjustment",
|
||||
"duration": 24, # hours
|
||||
"impact": "minor",
|
||||
"resolution_success": 0.92
|
||||
}
|
||||
]
|
||||
}
|
||||
return scenarios
|
||||
|
||||
# Create specialized agents
|
||||
mission_analyzer = Agent(
|
||||
name="Mission Analyzer",
|
||||
role="Mission Analysis",
|
||||
goal="Analyze mission parameters",
|
||||
instructions="Evaluate mission requirements and constraints",
|
||||
tools=[analyze_mission_parameters]
|
||||
)
|
||||
|
||||
resource_calculator = Agent(
|
||||
name="Resource Calculator",
|
||||
role="Resource Calculation",
|
||||
goal="Calculate resource requirements",
|
||||
instructions="Determine required resources for mission",
|
||||
tools=[calculate_resource_requirements]
|
||||
)
|
||||
|
||||
contingency_planner = Agent(
|
||||
name="Contingency Planner",
|
||||
role="Contingency Planning",
|
||||
goal="Plan for contingencies",
|
||||
instructions="Develop contingency scenarios and plans",
|
||||
tools=[plan_contingencies]
|
||||
)
|
||||
|
||||
resource_optimizer = Agent(
|
||||
name="Resource Optimizer",
|
||||
role="Resource Optimization",
|
||||
goal="Optimize resource allocation",
|
||||
instructions="Optimize resource distribution",
|
||||
tools=[optimize_allocation]
|
||||
)
|
||||
|
||||
scenario_simulator = Agent(
|
||||
name="Scenario Simulator",
|
||||
role="Scenario Simulation",
|
||||
goal="Simulate mission scenarios",
|
||||
instructions="Simulate various mission scenarios",
|
||||
tools=[simulate_mission_scenarios]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
mission_task = Task(
|
||||
name="analyze_mission",
|
||||
description="Analyze mission parameters",
|
||||
expected_output="Mission parameters",
|
||||
agent=mission_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["calculate_resources"]
|
||||
)
|
||||
|
||||
resource_task = Task(
|
||||
name="calculate_resources",
|
||||
description="Calculate resource requirements",
|
||||
expected_output="Resource requirements",
|
||||
agent=resource_calculator,
|
||||
next_tasks=["plan_contingencies"]
|
||||
)
|
||||
|
||||
contingency_task = Task(
|
||||
name="plan_contingencies",
|
||||
description="Plan contingencies",
|
||||
expected_output="Contingency plans",
|
||||
agent=contingency_planner,
|
||||
context=[resource_task],
|
||||
next_tasks=["optimize_resources"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="optimize_resources",
|
||||
description="Optimize resource allocation",
|
||||
expected_output="Resource allocation",
|
||||
agent=resource_optimizer,
|
||||
context=[resource_task, contingency_task],
|
||||
next_tasks=["simulate_scenarios"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_scenarios",
|
||||
description="Simulate scenarios",
|
||||
expected_output="Simulation results",
|
||||
agent=scenario_simulator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"nominal_operations": "", # End workflow if nominal
|
||||
"emergency_scenarios": ["optimize_resources"] # Reoptimize if emergency
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[mission_analyzer, resource_calculator, contingency_planner,
|
||||
resource_optimizer, scenario_simulator],
|
||||
tasks=[mission_task, resource_task, contingency_task,
|
||||
optimization_task, simulation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Space Mission Resource Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nResource Optimization Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,277 @@
|
||||
---
|
||||
title: "Vulnerability Detection"
|
||||
description: "Learn how to create AI agents for vulnerability detection and analysis."
|
||||
icon: "shield-check"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Scanner[Pattern Scanner]
|
||||
Scanner --> Vector[Vector Analyzer]
|
||||
Vector --> Simulator[Exploit Simulator]
|
||||
Simulator --> Generator[Signature Generator]
|
||||
Generator --> Validator[Finding Validator]
|
||||
Validator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Scanner fill:#2E8B57,color:#fff
|
||||
style Vector fill:#2E8B57,color:#fff
|
||||
style Simulator fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Vulnerability Detection?
|
||||
|
||||
Vulnerability Detection is a systematic process of identifying, analyzing, and validating security vulnerabilities in code. It involves pattern scanning, attack vector analysis, exploitation simulation, signature generation, and finding validation to ensure robust security measures are in place.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Pattern Scanning" icon="magnifying-glass">
|
||||
Detection of buffer overflows, SQL injections, and race conditions.
|
||||
</Card>
|
||||
<Card title="Attack Vector Analysis" icon="route">
|
||||
Analysis of attack paths, complexity, and CVSS scores.
|
||||
</Card>
|
||||
<Card title="Exploit Simulation" icon="bug">
|
||||
Simulation of exploitation attempts with success rate and detection time.
|
||||
</Card>
|
||||
<Card title="Signature Generation" icon="fingerprint">
|
||||
Creation of vulnerability signatures with reliability metrics.
|
||||
</Card>
|
||||
<Card title="Finding Validation" icon="check-double">
|
||||
Validation of findings with confidence and reproducibility scores.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def scan_code_patterns():
|
||||
"""Simulates code pattern scanning"""
|
||||
patterns = [
|
||||
{
|
||||
"type": "buffer_overflow",
|
||||
"severity": "critical",
|
||||
"location": "memory_management",
|
||||
"frequency": 3
|
||||
},
|
||||
{
|
||||
"type": "sql_injection",
|
||||
"severity": "high",
|
||||
"location": "database_interface",
|
||||
"frequency": 2
|
||||
},
|
||||
{
|
||||
"type": "race_condition",
|
||||
"severity": "medium",
|
||||
"location": "thread_handling",
|
||||
"frequency": 1
|
||||
}
|
||||
]
|
||||
return patterns[int(time.time()) % 3]
|
||||
|
||||
def analyze_attack_vectors(pattern: Dict):
|
||||
"""Analyzes potential attack vectors"""
|
||||
vectors = []
|
||||
severity_scores = {"critical": 9.5, "high": 8.0, "medium": 6.5}
|
||||
base_score = severity_scores[pattern["type"]]
|
||||
|
||||
vectors.append({
|
||||
"type": pattern["type"],
|
||||
"attack_path": f"exploit_{pattern['location']}",
|
||||
"complexity": "high" if pattern["frequency"] < 2 else "medium",
|
||||
"cvss_score": base_score + (time.time() % 1)
|
||||
})
|
||||
return vectors
|
||||
|
||||
def simulate_exploitation(vectors: List[Dict]):
|
||||
"""Simulates exploitation attempts"""
|
||||
results = []
|
||||
for vector in vectors:
|
||||
results.append({
|
||||
"vector": vector["type"],
|
||||
"success_rate": 0.7 + (time.time() % 3) / 10,
|
||||
"detection_time": 100 + (int(time.time()) % 50),
|
||||
"mitigation_possible": vector["complexity"] != "high"
|
||||
})
|
||||
return results
|
||||
|
||||
def generate_signatures(results: List[Dict]):
|
||||
"""Generates vulnerability signatures"""
|
||||
signatures = []
|
||||
for result in results:
|
||||
signatures.append({
|
||||
"pattern": f"signature_{result['vector']}",
|
||||
"reliability": result['success_rate'],
|
||||
"false_positive_rate": 0.1 + (time.time() % 2) / 10,
|
||||
"detection_speed": result['detection_time']
|
||||
})
|
||||
return signatures
|
||||
|
||||
def validate_findings(signatures: List[Dict]):
|
||||
"""Validates vulnerability findings"""
|
||||
validations = []
|
||||
for sig in signatures:
|
||||
validations.append({
|
||||
"signature": sig["pattern"],
|
||||
"confidence": sig["reliability"] * (1 - sig["false_positive_rate"]),
|
||||
"reproducibility": 0.8 + (time.time() % 2) / 10,
|
||||
"severity": "critical" if sig["reliability"] > 0.8 else "high"
|
||||
})
|
||||
return validations
|
||||
|
||||
# Create specialized agents
|
||||
pattern_scanner = Agent(
|
||||
name="Pattern Scanner",
|
||||
role="Code Analysis",
|
||||
goal="Scan for suspicious patterns",
|
||||
instructions="Analyze code for potential vulnerabilities",
|
||||
tools=[scan_code_patterns]
|
||||
)
|
||||
|
||||
vector_analyzer = Agent(
|
||||
name="Vector Analyzer",
|
||||
role="Attack Vector Analysis",
|
||||
goal="Analyze attack vectors",
|
||||
instructions="Identify potential attack paths",
|
||||
tools=[analyze_attack_vectors]
|
||||
)
|
||||
|
||||
exploit_simulator = Agent(
|
||||
name="Exploit Simulator",
|
||||
role="Exploitation Testing",
|
||||
goal="Simulate exploitation attempts",
|
||||
instructions="Test potential vulnerabilities",
|
||||
tools=[simulate_exploitation]
|
||||
)
|
||||
|
||||
signature_generator = Agent(
|
||||
name="Signature Generator",
|
||||
role="Signature Creation",
|
||||
goal="Generate vulnerability signatures",
|
||||
instructions="Create detection signatures",
|
||||
tools=[generate_signatures]
|
||||
)
|
||||
|
||||
finding_validator = Agent(
|
||||
name="Finding Validator",
|
||||
role="Validation",
|
||||
goal="Validate findings",
|
||||
instructions="Verify vulnerability findings",
|
||||
tools=[validate_findings]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
scanning_task = Task(
|
||||
name="scan_patterns",
|
||||
description="Scan code patterns",
|
||||
expected_output="Suspicious patterns",
|
||||
agent=pattern_scanner,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_vectors"]
|
||||
)
|
||||
|
||||
vector_task = Task(
|
||||
name="analyze_vectors",
|
||||
description="Analyze attack vectors",
|
||||
expected_output="Attack vectors",
|
||||
agent=vector_analyzer,
|
||||
next_tasks=["simulate_exploits"]
|
||||
)
|
||||
|
||||
simulation_task = Task(
|
||||
name="simulate_exploits",
|
||||
description="Simulate exploits",
|
||||
expected_output="Exploitation results",
|
||||
agent=exploit_simulator,
|
||||
next_tasks=["generate_signatures"]
|
||||
)
|
||||
|
||||
signature_task = Task(
|
||||
name="generate_signatures",
|
||||
description="Generate signatures",
|
||||
expected_output="Vulnerability signatures",
|
||||
agent=signature_generator,
|
||||
next_tasks=["validate_findings"]
|
||||
)
|
||||
|
||||
validation_task = Task(
|
||||
name="validate_findings",
|
||||
description="Validate findings",
|
||||
expected_output="Validation results",
|
||||
agent=finding_validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"critical": ["scan_patterns"], # Continue scanning if critical
|
||||
"high": ["analyze_vectors"], # Reanalyze if high
|
||||
"medium": "" # End workflow if medium
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[pattern_scanner, vector_analyzer, exploit_simulator,
|
||||
signature_generator, finding_validator],
|
||||
tasks=[scanning_task, vector_task, simulation_task,
|
||||
signature_task, validation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Vulnerability Detection Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nVulnerability Detection Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -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>
|
||||
Loaded 100 of 597 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user