mirror of
https://github.com/MervinPraison/praisonai-js.git
synced 2026-11-07 06:05:57 -10:00
Copy praisonai-ts from the monorepo into standalone public repo with CI workflow and hub-mode callers from github-automation-template v1.1.0. Co-authored-by: Cursor <[email protected]>
360 lines
34 KiB
Plaintext
360 lines
34 KiB
Plaintext
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)
|
|
```
|