-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.cursorrules
More file actions
359 lines (303 loc) · 34.2 KB
/
.cursorrules
File metadata and controls
359 lines (303 loc) · 34.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
Below is an example **TypeScript/Node.js** folder structure replicating the Python package's layout. Each subfolder matches the Python counterpart (`agent`, `agents`, `knowledge`, etc.). All "LLM" or "litellm" references are replaced by **`aisdk`** usage.
Feel free to rename or restructure to suit your project's Node.js conventions.
---
## Folder Structure
```
praisonai-ts/
├── package.json
├── tsconfig.json
├── src/
│ ├── index.ts
│ ├── main.ts
│ ├── agent/
│ │ └── agent.ts
│ ├── agents/
│ │ ├── agents.ts
│ │ └── autoagents.ts
│ ├── knowledge/
│ │ ├── chunking.ts
│ │ └── knowledge.ts
│ ├── llm/
│ │ └── llm.ts
│ ├── memory/
│ │ └── memory.ts
│ ├── process/
│ │ └── process.ts
│ ├── task/
│ │ └── task.ts
│ └── tools/
│ ├── README.md
│ ├── index.ts
│ ├── test.ts
│ ├── arxivTools.ts
│ ├── calculatorTools.ts
│ ├── csvTools.ts
│ ├── duckdbTools.ts
│ ├── duckduckgoTools.ts
│ ├── excelTools.ts
│ ├── fileTools.ts
│ ├── jsonTools.ts
│ ├── newspaperTools.ts
│ ├── pandasTools.ts
│ ├── pythonTools.ts
│ ├── shellTools.ts
│ ├── spiderTools.ts
│ ├── tools.ts
│ ├── wikipediaTools.ts
│ ├── xmlTools.ts
│ ├── yamlTools.ts
│ └── yfinanceTools.ts
└── ...
```
Below is a **high-level table** describing the main files/folders, the classes or functions inside them, their parameters, and return values.
---
| **File / Folder** | **Contents** | **Functions / Classes** | **Parameters** | **Return** | **Purpose** |
|-----------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **src/index.ts** | Main entry point that re-exports key classes/functions | - Typically re-exports `Agent`, `Agents`, `Task`, etc. | - | - | Provides a simple import path for consumers. |
| **src/main.ts** | Equivalent of `main.py`, sets up logging, callbacks, registers display callbacks, and integrates with `aisdk` if needed | - `registerDisplayCallback(type: string, callbackFn, isAsync: boolean): void`<br/>- `executeCallback(type: string, ...args): Promise<void>`<br/>- `displayInteraction(...)`, `displayError(...)`, etc. <br/>- Possibly some global logs array or error logs. | Depending on the function, e.g. `registerDisplayCallback` → `(type, fn, isAsync)` | Varies by function type. Typically `void` or `Promise<void>` | Central place for logging and "display callbacks," mirroring the Python approach (prints, error logs, etc.). Uses or references `aisdk` for generating text if needed. |
| **src/agent/agent.ts** | Contains `Agent` class, mirroring `agent.py`. Handles single-agent logic, possible references to LLM calls via `aisdk`. | - `class Agent`<br/> - constructor(name: string, role: string, goal: string, ...)<br/> - `chat(...)`: main method for handling "chat" or LLM calls<br/> - `achat(...)`: async method, if needed | **constructor**: `(name, role, goal, tools, ... )` etc. <br/>**chat**: `(prompt: string, ...)` <br/>**achat**: `(prompt: string, ...)` | `Promise<string>` or `string` for the chat methods. | Encapsulates a single agent's role, name, and the methods for calling the LLM using `aisdk`. Also may manage context, tools, roles, etc. |
| **src/agents/agents.ts** | Contains `PraisonAIAgents` (like `agents.py`). Manages multiple agents, tasks, memory, process type, etc. | - `class PraisonAIAgents`<br/> - constructor(agents: Agent[], tasks?: Task[], ...)<br/> - `addTask(task: Task)`: number<br/> - `executeTask(taskId: number)`: TaskOutput<br/> - `runTask(taskId: number)`: void<br/> - `runAllTasks()`: void<br/> - `start(...)`: starts them all<br/> - `getTaskResult(...)` | The constructor takes arrays of `Agent`, optional tasks, manager config, memory config, etc. Other methods take Task IDs. | Most methods return `void`, or a `Promise<void>`, or a custom object. | Coordinates multiple agents and tasks in a "manager" style. The top-level orchestrator for tasks and agent interactions. |
| **src/agents/autoagents.ts** | The `AutoAgents` class, an advanced manager that can auto-create tasks/agents from instructions. Uses `aisdk` to parse config. | - `class AutoAgents extends PraisonAIAgents`<br/> - constructor(instructions: string, tools?: any[], ...)<br/> - `_generateConfig(...)`<br/> - `_createAgentsAndTasks(...)`<br/> - `start()`: overrides the parent to handle auto generation<br/> - etc. | Takes user instructions, tools, config (like memory usage, manager LLM, etc.). | Typically `Promise<object>` or `void` for the `start()` method. | High-level convenience for automatically generating agent/task configuration from user instructions. |
| **src/knowledge/chunking.ts** | `Chunking` class for text chunking. Similar logic to the Python version. | - `class Chunking`<br/> - constructor(chunkerType: string, ... )<br/> - `chunk(text: string | string[], addContext: boolean, contextParams: any): Chunk[]`<br/> - Possibly `_get_overlap_refinery(...)`, etc. | Similar to Python (chunkerType, chunkSize, etc.). | Returns an array of chunked text or objects describing the chunk. | Manages chunking text for memory or knowledge base usage (like large documents). |
| **src/knowledge/knowledge.ts** | `Knowledge` class for storing & retrieving data from memory, chunking, vector DB, etc. | - `class Knowledge`<br/> - constructor(config: any, verbose?: number)<br/> - `store(content: string, userId?: string, ...): any`<br/> - `search(query: string, ...): any`<br/> - `deleteAll(...)`: etc. | Takes a config object for local or external DB. Methods get or store docs, do RAG searching, etc. | Return types typically objects or arrays. | Central interface to handle knowledge storage, chunking, retrieval, e.g. vector store, RAG. |
| **src/llm/llm.ts** | `LLM` class referencing **`aisdk`** instead of `litellm`. Basic usage of `generateText` or `streamText`. | - `class LLM`<br/> - constructor(options: { model: string, apiKey?: string, ... })<br/> - `response(prompt: string, ...): Promise<string>` (calls `aisdk.generateText`)<br/> - possibly `streamResponse(...)` if needed | `model, prompt, temperature, ...` | `Promise<string>` for final text. | The bridging layer between your code and `aisdk`, so `Agent` can call `LLM.response(...)`. |
| **src/memory/memory.ts** | `Memory` class for short-term or long-term memory references, entity memory, user memory, etc. | - `class Memory`<br/> - constructor(config: MemoryConfig, verbose?: number)<br/> - `storeShortTerm(...)`, `storeLongTerm(...)`, `searchShortTerm(...)`, etc.<br/> - `buildContextForTask(...)` | Varies, e.g. `(text: string, metadata?: any)` | Typically `void` or some object referencing stored docs. | Takes a config describing how/where memory is stored: local DB, RAG, or `aisdk` embeddings. |
| **src/process/process.ts** | `Process` class that handles sequential or workflow processes between tasks. | - `class Process`<br/> - constructor(tasks: Map<number, Task>, agents: Agent[], ... )<br/> - `sequential()`, `workflow()`, `hierarchical()`, etc. | Receives tasks, agents, process type. | Returns an iterator or array describing the next tasks to run. | Logic for ordering tasks in "sequential", "hierarchical", or "workflow" modes. |
| **src/task/task.ts** | `Task` class for describing a single piece of work, the agent assigned, context, etc. | - `class Task`<br/> - constructor(description: string, expectedOutput?: string, ... )<br/> - `executeCallback(taskOutput: TaskOutput)`, `storeInMemory(...)`, etc. | The constructor has many options: `(description, expectedOutput, agent, tools, ...)`. | Methods return `void`, or custom objects. | Encapsulates a single unit of work, references an agent, has optional callback, memory usage, etc. |
| **src/tools/README.md** | Short README describing how to write "tools" in JS/TS. | - | - | - | Provides docs for tool developers. |
| **src/tools/index.ts** | Entry point that re-exports tool functions (like `internetSearch`, `getArxivPaper`, etc.) | - Possibly a map of `functionName -> import`<br/> - `import * as calculatorTools from './calculatorTools'`, etc. | - | - | Simplifies import of tools (e.g. `import { getArticle } from "praisonai/tools"`). |
| **src/tools/test.ts** | Script for running each tool's internal test or example. | - Typically a script that `import ... from './someTool.ts'` then tries them. | - | - | Quick local tests. |
| **src/tools/arxivTools.ts** | Example "arxiv_tools.py" logic in TS. Searching arXiv, returning results. | - `function searchArxiv(query: string, ...): Promise<any[]>`<br/> - `function getArxivPaper(id: string): Promise<any>` etc. | `(query, maxResults=10, ... )` | `Promise<ArxivPaper[]>` or something like that. | Tools for searching and retrieving from arXiv. |
---
### Notes on `aisdk` Integration
1. In the Python code, many calls like `litellm` or `OpenAI(api_key=...)` appear. In **Node**, replace that with something like:
```ts
import { generateText } from "aisdk";
async function callLLM(prompt: string) {
const { text } = await generateText({
model: "gpt-4o-mini",
prompt,
// other config like temperature, maxTokens, etc.
});
return text;
}
```
2. The `LLM` class in `llm.ts` can wrap `generateText` calls:
```ts
import { generateText } from "aisdk";
export class LLM {
model: string;
constructor(model: string) {
this.model = model;
}
async response(prompt: string, temperature=0.7): Promise<string> {
const { text } = await generateText({
model: this.model,
prompt,
temperature
});
return text;
}
}
```
3. Agents or tasks can reference the `LLM` instance or call `aisdk` directly.
---
### Summary
- **Each folder** in `praisonaiagents/` is mapped to a corresponding **subfolder in TypeScript**.
- **Classes** or **functions** mirror the Python classes, with the same constructor parameters and method signatures in a TypeScript style.
- **Return types** are changed from Python style (`dict`, `list`) to TypeScript style (`object`, `Record<string,any>`, `Promise<void>`, etc.).
- **Use `aisdk`** in place of `litellm` / `openai`.
- **Tool files** replicate exactly what the Python code does, but in TypeScript (e.g., `arxivTools.ts`, `calculatorTools.ts`, etc.).
- **Add any third-party TS libs** needed (`node-fetch`, `cheerio`, `duckdb`, `yaml`, `xml2js`, etc.).
This gives a **1-to-1** replication of the Python package's structure, now in a Node/TypeScript environment with **aisdk** for large language model calls.
Let me provide a detailed breakdown of the PraisonAI Agents python library based on the code.
Need to build the same for TypeScript.
# 1. Directory Structure Overview
```
praisonai-python/
├── __init__.py # Package initialization, exports main components
├── main.py # Core functionality, display handlers
├── agent/ # Individual agent functionality
├── agents/ # Multi-agent management
├── knowledge/ # Knowledge base and chunking
├── llm/ # Language model interface
├── memory/ # Memory management
├── process/ # Process execution handling
├── task/ # Task definition and handling
└── tools/ # Various utility tools
```
# 2. Main Components
## a. Core Agent Classes
- `Agent`: Individual AI agent with specific capabilities
- `PraisonAIAgents`: Manager class for multiple agents
- `AutoAgents`: Automatic agent creation and management
- `Task`: Task definition and execution
- `Tools`: Utility functions and capabilities
## b. Key Functionalities
1. Task Management
2. Memory Management
3. Knowledge Base
4. LLM Integration
5. Process Control
6. Tool Integration
# 3. Key Classes & Functions
## 3.1 PraisonAIAgents Class
Main class for managing multiple agents.
```python
class PraisonAIAgents:
def __init__(self,
agents, # List of agents
tasks=None, # List of tasks
verbose=0, # Verbosity level
completion_checker=None, # Custom completion checker
max_retries=5, # Maximum retry attempts
process="sequential", # Process type
manager_llm=None, # LLM model for management
memory=False, # Enable memory
memory_config=None, # Memory configuration
embedder=None, # Custom embedder
user_id=None, # User identifier
max_iter=10 # Maximum iterations
)
```
## 3.2 Task Class
Defines individual tasks for agents.
```python
class Task:
def __init__(self,
description: str, # Task description
expected_output: str = None, # Expected output
agent: Agent = None, # Assigned agent
name: str = None, # Task name
tools: List = None, # Available tools
context: List = None, # Task context
async_execution: bool = False, # Async execution
config: Dict = None, # Configuration
output_file: str = None, # Output file path
output_json: bool = False, # JSON output flag
output_pydantic: bool = False, # Pydantic output flag
callback: Callable = None, # Callback function
status: str = "not started", # Task status
result: TaskOutput = None, # Task result
create_directory: bool = False, # Create output directory
id: int = None, # Task ID
images: List[str] = None, # Image paths
next_tasks: List[str] = None, # Next tasks
task_type: str = "task", # Task type
condition: Dict = None, # Task conditions
is_start: bool = False, # Start task flag
loop_state: Dict = None, # Loop state
memory=None, # Memory instance
quality_check: bool = True, # Enable quality check
input_file: str = None, # Input file path
rerun: bool = False # Allow task rerun
)
```
## 3.3 Memory Management
```python
class Memory:
def __init__(self,
config: Dict[str, Any], # Memory configuration
verbose: int = 0 # Verbosity level
)
def store_long_term(self,
text: str, # Text to store
metadata: Dict = None, # Additional metadata
completeness: float = None, # Completeness score
relevance: float = None, # Relevance score
clarity: float = None, # Clarity score
accuracy: float = None, # Accuracy score
weights: Dict = None, # Score weights
evaluator_quality: float = None # Overall quality
)
```
# 4. Tools Library
## 4.1 Available Tools Categories
1. **File Operations**
- CSV Tools
- Excel Tools
- JSON Tools
- YAML Tools
- XML Tools
- File Tools
2. **Web & Data**
- ArXiv Tools
- Wikipedia Tools
- DuckDuckGo Tools
- Spider Tools
- Newspaper Tools
3. **Data Analysis**
- Pandas Tools
- DuckDB Tools
- Calculator Tools
4. **System & Development**
- Shell Tools
- Python Tools
5. **Financial**
- YFinance Tools
## 4.2 Example Tool Class (YFinanceTools)
```python
class YFinanceTools:
def get_stock_price(self, symbol: str) -> Dict[str, float]:
"""Get current stock price and metrics"""
def get_stock_info(self, symbol: str) -> Dict:
"""Get detailed stock information"""
def get_historical_data(self,
symbol: str,
period: str = "1y",
interval: str = "1d",
start: Optional[datetime] = None,
end: Optional[datetime] = None
) -> List[Dict[str, Any]]:
"""Get historical price data"""
```
# 5. Configuration
## 5.1 Memory Configuration Example
```python
memory_config = {
"provider": "rag", # Memory provider type
"use_embedding": True, # Use embeddings
"storage": {
"type": "sqlite",
"path": "./.praison/memory.db"
},
"rag_db_path": "./.praison/chroma_db"
}
```
## 5.2 Process Types
- "sequential": Tasks execute in sequence
- "workflow": Tasks execute based on workflow rules
- "hierarchical": Tasks execute in hierarchical order
# 6. Output Formats
## 6.1 TaskOutput
```python
class TaskOutput(BaseModel):
description: str
summary: Optional[str]
raw: str
pydantic: Optional[BaseModel]
json_dict: Optional[Dict[str, Any]]
agent: str
output_format: Literal["RAW", "JSON", "Pydantic"]
```
# 7. Task Types
1. Regular Task
2. Decision Task
3. Loop Task
4. Workflow Task
Each task type has specific behaviors and attributes for different use cases.
# 8. Error Handling
The library includes comprehensive error handling with:
- Error logging
- Retry mechanisms
- Fallback strategies
- Error display functions
# 9. Display Functions
```python
def display_interaction(message, response, markdown=True)
def display_self_reflection(message: str)
def display_instruction(message: str)
def display_tool_call(message: str)
def display_error(message: str)
def display_generating(content: str)
```