.windsurfrules
1 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. 2 3 Feel free to rename or restructure to suit your project's Node.js conventions. 4 5 --- 6 7 ## Folder Structure 8 9 ``` 10 praisonai-ts/ 11 ├── package.json 12 ├── tsconfig.json 13 ├── src/ 14 │ ├── index.ts 15 │ ├── main.ts 16 │ ├── agent/ 17 │ │ └── agent.ts 18 │ ├── agents/ 19 │ │ ├── agents.ts 20 │ │ └── autoagents.ts 21 │ ├── knowledge/ 22 │ │ ├── chunking.ts 23 │ │ └── knowledge.ts 24 │ ├── llm/ 25 │ │ └── llm.ts 26 │ ├── memory/ 27 │ │ └── memory.ts 28 │ ├── process/ 29 │ │ └── process.ts 30 │ ├── task/ 31 │ │ └── task.ts 32 │ └── tools/ 33 │ ├── README.md 34 │ ├── index.ts 35 │ ├── test.ts 36 │ ├── arxivTools.ts 37 │ ├── calculatorTools.ts 38 │ ├── csvTools.ts 39 │ ├── duckdbTools.ts 40 │ ├── duckduckgoTools.ts 41 │ ├── excelTools.ts 42 │ ├── fileTools.ts 43 │ ├── jsonTools.ts 44 │ ├── newspaperTools.ts 45 │ ├── pandasTools.ts 46 │ ├── pythonTools.ts 47 │ ├── shellTools.ts 48 │ ├── spiderTools.ts 49 │ ├── tools.ts 50 │ ├── wikipediaTools.ts 51 │ ├── xmlTools.ts 52 │ ├── yamlTools.ts 53 │ └── yfinanceTools.ts 54 └── ... 55 ``` 56 57 Below is a **high-level table** describing the main files/folders, the classes or functions inside them, their parameters, and return values. 58 59 --- 60 61 | **File / Folder** | **Contents** | **Functions / Classes** | **Parameters** | **Return** | **Purpose** | 62 |-----------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 63 | **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. | 64 | **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. | 65 | **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. | 66 | **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. | 67 | **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. | 68 | **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). | 69 | **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. | 70 | **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(...)`. | 71 | **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. | 72 | **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. | 73 | **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. | 74 | **src/tools/README.md** | Short README describing how to write "tools" in JS/TS. | - | - | - | Provides docs for tool developers. | 75 | **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"`). | 76 | **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. | 77 | **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. | 78 79 --- 80 81 ### Notes on `aisdk` Integration 82 83 1. In the Python code, many calls like `litellm` or `OpenAI(api_key=...)` appear. In **Node**, replace that with something like: 84 ```ts 85 import { generateText } from "aisdk"; 86 87 async function callLLM(prompt: string) { 88 const { text } = await generateText({ 89 model: "gpt-4o-mini", 90 prompt, 91 // other config like temperature, maxTokens, etc. 92 }); 93 return text; 94 } 95 ``` 96 2. The `LLM` class in `llm.ts` can wrap `generateText` calls: 97 ```ts 98 import { generateText } from "aisdk"; 99 100 export class LLM { 101 model: string; 102 103 constructor(model: string) { 104 this.model = model; 105 } 106 107 async response(prompt: string, temperature=0.7): Promise<string> { 108 const { text } = await generateText({ 109 model: this.model, 110 prompt, 111 temperature 112 }); 113 return text; 114 } 115 } 116 ``` 117 118 3. Agents or tasks can reference the `LLM` instance or call `aisdk` directly. 119 120 --- 121 122 ### Summary 123 124 - **Each folder** in `praisonaiagents/` is mapped to a corresponding **subfolder in TypeScript**. 125 - **Classes** or **functions** mirror the Python classes, with the same constructor parameters and method signatures in a TypeScript style. 126 - **Return types** are changed from Python style (`dict`, `list`) to TypeScript style (`object`, `Record<string,any>`, `Promise<void>`, etc.). 127 - **Use `aisdk`** in place of `litellm` / `openai`. 128 - **Tool files** replicate exactly what the Python code does, but in TypeScript (e.g., `arxivTools.ts`, `calculatorTools.ts`, etc.). 129 - **Add any third-party TS libs** needed (`node-fetch`, `cheerio`, `duckdb`, `yaml`, `xml2js`, etc.). 130 131 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. 132 133 134 Let me provide a detailed breakdown of the PraisonAI Agents python library based on the code. 135 Need to build the same for TypeScript. 136 137 # 1. Directory Structure Overview 138 139 ``` 140 praisonai-python/ 141 ├── __init__.py # Package initialization, exports main components 142 ├── main.py # Core functionality, display handlers 143 ├── agent/ # Individual agent functionality 144 ├── agents/ # Multi-agent management 145 ├── knowledge/ # Knowledge base and chunking 146 ├── llm/ # Language model interface 147 ├── memory/ # Memory management 148 ├── process/ # Process execution handling 149 ├── task/ # Task definition and handling 150 └── tools/ # Various utility tools 151 ``` 152 153 # 2. Main Components 154 155 ## a. Core Agent Classes 156 - `Agent`: Individual AI agent with specific capabilities 157 - `PraisonAIAgents`: Manager class for multiple agents 158 - `AutoAgents`: Automatic agent creation and management 159 - `Task`: Task definition and execution 160 - `Tools`: Utility functions and capabilities 161 162 ## b. Key Functionalities 163 1. Task Management 164 2. Memory Management 165 3. Knowledge Base 166 4. LLM Integration 167 5. Process Control 168 6. Tool Integration 169 170 # 3. Key Classes & Functions 171 172 ## 3.1 PraisonAIAgents Class 173 Main class for managing multiple agents. 174 175 ```python 176 class PraisonAIAgents: 177 def __init__(self, 178 agents, # List of agents 179 tasks=None, # List of tasks 180 verbose=0, # Verbosity level 181 completion_checker=None, # Custom completion checker 182 max_retries=5, # Maximum retry attempts 183 process="sequential", # Process type 184 manager_llm=None, # LLM model for management 185 memory=False, # Enable memory 186 memory_config=None, # Memory configuration 187 embedder=None, # Custom embedder 188 user_id=None, # User identifier 189 max_iter=10 # Maximum iterations 190 ) 191 ``` 192 193 ## 3.2 Task Class 194 Defines individual tasks for agents. 195 196 ```python 197 class Task: 198 def __init__(self, 199 description: str, # Task description 200 expected_output: str = None, # Expected output 201 agent: Agent = None, # Assigned agent 202 name: str = None, # Task name 203 tools: List = None, # Available tools 204 context: List = None, # Task context 205 async_execution: bool = False, # Async execution 206 config: Dict = None, # Configuration 207 output_file: str = None, # Output file path 208 output_json: bool = False, # JSON output flag 209 output_pydantic: bool = False, # Pydantic output flag 210 callback: Callable = None, # Callback function 211 status: str = "not started", # Task status 212 result: TaskOutput = None, # Task result 213 create_directory: bool = False, # Create output directory 214 id: int = None, # Task ID 215 images: List[str] = None, # Image paths 216 next_tasks: List[str] = None, # Next tasks 217 task_type: str = "task", # Task type 218 condition: Dict = None, # Task conditions 219 is_start: bool = False, # Start task flag 220 loop_state: Dict = None, # Loop state 221 memory=None, # Memory instance 222 quality_check: bool = True, # Enable quality check 223 input_file: str = None, # Input file path 224 rerun: bool = False # Allow task rerun 225 ) 226 ``` 227 228 ## 3.3 Memory Management 229 230 ```python 231 class Memory: 232 def __init__(self, 233 config: Dict[str, Any], # Memory configuration 234 verbose: int = 0 # Verbosity level 235 ) 236 237 def store_long_term(self, 238 text: str, # Text to store 239 metadata: Dict = None, # Additional metadata 240 completeness: float = None, # Completeness score 241 relevance: float = None, # Relevance score 242 clarity: float = None, # Clarity score 243 accuracy: float = None, # Accuracy score 244 weights: Dict = None, # Score weights 245 evaluator_quality: float = None # Overall quality 246 ) 247 ``` 248 249 # 4. Tools Library 250 251 ## 4.1 Available Tools Categories 252 253 1. **File Operations** 254 - CSV Tools 255 - Excel Tools 256 - JSON Tools 257 - YAML Tools 258 - XML Tools 259 - File Tools 260 261 2. **Web & Data** 262 - ArXiv Tools 263 - Wikipedia Tools 264 - DuckDuckGo Tools 265 - Spider Tools 266 - Newspaper Tools 267 268 3. **Data Analysis** 269 - Pandas Tools 270 - DuckDB Tools 271 - Calculator Tools 272 273 4. **System & Development** 274 - Shell Tools 275 - Python Tools 276 277 5. **Financial** 278 - YFinance Tools 279 280 ## 4.2 Example Tool Class (YFinanceTools) 281 282 ```python 283 class YFinanceTools: 284 def get_stock_price(self, symbol: str) -> Dict[str, float]: 285 """Get current stock price and metrics""" 286 287 def get_stock_info(self, symbol: str) -> Dict: 288 """Get detailed stock information""" 289 290 def get_historical_data(self, 291 symbol: str, 292 period: str = "1y", 293 interval: str = "1d", 294 start: Optional[datetime] = None, 295 end: Optional[datetime] = None 296 ) -> List[Dict[str, Any]]: 297 """Get historical price data""" 298 ``` 299 300 # 5. Configuration 301 302 ## 5.1 Memory Configuration Example 303 ```python 304 memory_config = { 305 "provider": "rag", # Memory provider type 306 "use_embedding": True, # Use embeddings 307 "storage": { 308 "type": "sqlite", 309 "path": "./.praison/memory.db" 310 }, 311 "rag_db_path": "./.praison/chroma_db" 312 } 313 ``` 314 315 ## 5.2 Process Types 316 - "sequential": Tasks execute in sequence 317 - "workflow": Tasks execute based on workflow rules 318 - "hierarchical": Tasks execute in hierarchical order 319 320 # 6. Output Formats 321 322 ## 6.1 TaskOutput 323 ```python 324 class TaskOutput(BaseModel): 325 description: str 326 summary: Optional[str] 327 raw: str 328 pydantic: Optional[BaseModel] 329 json_dict: Optional[Dict[str, Any]] 330 agent: str 331 output_format: Literal["RAW", "JSON", "Pydantic"] 332 ``` 333 334 # 7. Task Types 335 1. Regular Task 336 2. Decision Task 337 3. Loop Task 338 4. Workflow Task 339 340 Each task type has specific behaviors and attributes for different use cases. 341 342 # 8. Error Handling 343 344 The library includes comprehensive error handling with: 345 - Error logging 346 - Retry mechanisms 347 - Fallback strategies 348 - Error display functions 349 350 # 9. Display Functions 351 352 ```python 353 def display_interaction(message, response, markdown=True) 354 def display_self_reflection(message: str) 355 def display_instruction(message: str) 356 def display_tool_call(message: str) 357 def display_error(message: str) 358 def display_generating(content: str) 359 ```