praisonai 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,16 @@
1
+ /**
2
+ * Agent Module - Core agent classes for PraisonAI
3
+ *
4
+ * The primary exports are:
5
+ * - Agent: Single agent with instructions, tools, and optional persistence
6
+ * - Agents: Multi-agent orchestration (alias for PraisonAIAgents)
7
+ * - Workflow: Step-based workflow execution (from workflows module)
8
+ */
9
+ export { Agent, PraisonAIAgents, Agents } from './simple';
10
+ export type { SimpleAgentConfig, PraisonAIAgentsConfig } from './simple';
11
+ export { Task } from './types';
12
+ export type { TaskConfig, AgentConfig as TaskAgentConfig } from './types';
13
+ /**
14
+ * @deprecated Task mode is no longer needed. Use Agent with role/goal/backstory instead.
15
+ */
1
16
  export declare function setTaskMode(enabled: boolean): void;
2
- export { Agent, PraisonAIAgents, Task } from './proxy';
3
- export type { ProxyAgentConfig } from './proxy';
4
- export type { AgentConfig } from './types';
5
- export type { TaskConfig } from './types';
6
- export type { PraisonAIAgentsConfig, SimpleAgentConfig } from './simple';
@@ -1,13 +1,31 @@
1
1
  "use strict";
2
+ /**
3
+ * Agent Module - Core agent classes for PraisonAI
4
+ *
5
+ * The primary exports are:
6
+ * - Agent: Single agent with instructions, tools, and optional persistence
7
+ * - Agents: Multi-agent orchestration (alias for PraisonAIAgents)
8
+ * - Workflow: Step-based workflow execution (from workflows module)
9
+ */
2
10
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Task = exports.PraisonAIAgents = exports.Agent = void 0;
11
+ exports.Task = exports.Agents = exports.PraisonAIAgents = exports.Agent = void 0;
4
12
  exports.setTaskMode = setTaskMode;
5
- // Export implementation based on mode
13
+ // Core exports - the main API surface
14
+ var simple_1 = require("./simple");
15
+ Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return simple_1.Agent; } });
16
+ Object.defineProperty(exports, "PraisonAIAgents", { enumerable: true, get: function () { return simple_1.PraisonAIAgents; } });
17
+ Object.defineProperty(exports, "Agents", { enumerable: true, get: function () { return simple_1.Agents; } });
18
+ // Task support (for advanced use cases)
19
+ var types_1 = require("./types");
20
+ Object.defineProperty(exports, "Task", { enumerable: true, get: function () { return types_1.Task; } });
21
+ // Legacy compatibility - setTaskMode is deprecated but kept for backward compat
6
22
  let useTaskMode = false;
23
+ /**
24
+ * @deprecated Task mode is no longer needed. Use Agent with role/goal/backstory instead.
25
+ */
7
26
  function setTaskMode(enabled) {
27
+ if (enabled) {
28
+ console.warn('setTaskMode() is deprecated. Use Agent({ role, goal, backstory }) instead of task mode.');
29
+ }
8
30
  useTaskMode = enabled;
9
31
  }
10
- var proxy_1 = require("./proxy");
11
- Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return proxy_1.Agent; } });
12
- Object.defineProperty(exports, "PraisonAIAgents", { enumerable: true, get: function () { return proxy_1.PraisonAIAgents; } });
13
- Object.defineProperty(exports, "Task", { enumerable: true, get: function () { return proxy_1.Task; } });
@@ -1,13 +1,77 @@
1
+ import type { DbAdapter } from '../db/types';
2
+ /**
3
+ * Agent Configuration
4
+ *
5
+ * The Agent class is the primary entry point for PraisonAI.
6
+ * It supports both simple instruction-based agents and advanced configurations.
7
+ *
8
+ * @example Simple usage (3 lines)
9
+ * ```typescript
10
+ * import { Agent } from 'praisonai';
11
+ * const agent = new Agent({ instructions: "You are helpful" });
12
+ * await agent.chat("Hello!");
13
+ * ```
14
+ *
15
+ * @example With tools (5 lines)
16
+ * ```typescript
17
+ * const getWeather = (city: string) => `Weather in ${city}: 20°C`;
18
+ * const agent = new Agent({
19
+ * instructions: "You provide weather info",
20
+ * tools: [getWeather]
21
+ * });
22
+ * await agent.chat("Weather in Paris?");
23
+ * ```
24
+ *
25
+ * @example With persistence (4 lines)
26
+ * ```typescript
27
+ * import { Agent, db } from 'praisonai';
28
+ * const agent = new Agent({
29
+ * instructions: "You are helpful",
30
+ * db: db("sqlite:./data.db"),
31
+ * sessionId: "my-session"
32
+ * });
33
+ * await agent.chat("Hello!");
34
+ * ```
35
+ */
1
36
  export interface SimpleAgentConfig {
37
+ /** Agent instructions/system prompt (required) */
2
38
  instructions: string;
39
+ /** Agent name (auto-generated if not provided) */
3
40
  name?: string;
41
+ /** Enable verbose logging (default: true) */
4
42
  verbose?: boolean;
43
+ /** Enable pretty output formatting */
5
44
  pretty?: boolean;
45
+ /**
46
+ * LLM model to use. Accepts:
47
+ * - Model name: "gpt-4o-mini", "claude-3-sonnet"
48
+ * - Provider/model: "openai/gpt-4o", "anthropic/claude-3"
49
+ * Default: "gpt-4o-mini"
50
+ */
6
51
  llm?: string;
52
+ /** Enable markdown formatting in responses */
7
53
  markdown?: boolean;
54
+ /** Enable streaming responses (default: true) */
8
55
  stream?: boolean;
56
+ /**
57
+ * Tools available to the agent.
58
+ * Can be plain functions (auto-schema) or OpenAI tool definitions.
59
+ */
9
60
  tools?: any[] | Function[];
61
+ /** Map of tool function implementations */
10
62
  toolFunctions?: Record<string, Function>;
63
+ /** Database adapter for persistence */
64
+ db?: DbAdapter;
65
+ /** Session ID for conversation persistence */
66
+ sessionId?: string;
67
+ /** Run ID for tracing (auto-generated if not provided) */
68
+ runId?: string;
69
+ /** Agent role (advanced mode) */
70
+ role?: string;
71
+ /** Agent goal (advanced mode) */
72
+ goal?: string;
73
+ /** Agent backstory (advanced mode) */
74
+ backstory?: string;
11
75
  }
12
76
  export declare class Agent {
13
77
  private instructions;
@@ -20,6 +84,10 @@ export declare class Agent {
20
84
  private llmService;
21
85
  private tools?;
22
86
  private toolFunctions;
87
+ private dbAdapter?;
88
+ private sessionId;
89
+ private runId;
90
+ private messages;
23
91
  constructor(config: SimpleAgentConfig);
24
92
  private createSystemPrompt;
25
93
  /**
@@ -49,9 +117,24 @@ export declare class Agent {
49
117
  start(prompt: string, previousResult?: string): Promise<string>;
50
118
  chat(prompt: string, previousResult?: string): Promise<string>;
51
119
  execute(previousResult?: string): Promise<string>;
120
+ /**
121
+ * Persist a message to the database
122
+ */
123
+ private persistMessage;
124
+ /**
125
+ * Get the session ID for this agent
126
+ */
127
+ getSessionId(): string;
128
+ /**
129
+ * Get the run ID for this agent
130
+ */
131
+ getRunId(): string;
52
132
  getResult(): string | null;
53
133
  getInstructions(): string;
54
134
  }
135
+ /**
136
+ * Configuration for multi-agent orchestration
137
+ */
55
138
  export interface PraisonAIAgentsConfig {
56
139
  agents: Agent[];
57
140
  tasks?: string[];
@@ -59,15 +142,59 @@ export interface PraisonAIAgentsConfig {
59
142
  pretty?: boolean;
60
143
  process?: 'sequential' | 'parallel';
61
144
  }
145
+ /**
146
+ * Multi-agent orchestration class
147
+ *
148
+ * @example Simple array syntax
149
+ * ```typescript
150
+ * import { Agent, Agents } from 'praisonai';
151
+ *
152
+ * const researcher = new Agent({ instructions: "Research the topic" });
153
+ * const writer = new Agent({ instructions: "Write based on research" });
154
+ *
155
+ * const agents = new Agents([researcher, writer]);
156
+ * await agents.start();
157
+ * ```
158
+ *
159
+ * @example Config object syntax
160
+ * ```typescript
161
+ * const agents = new Agents({
162
+ * agents: [researcher, writer],
163
+ * process: 'parallel'
164
+ * });
165
+ * ```
166
+ */
62
167
  export declare class PraisonAIAgents {
63
168
  private agents;
64
169
  private tasks;
65
170
  private verbose;
66
171
  private pretty;
67
172
  private process;
68
- constructor(config: PraisonAIAgentsConfig);
173
+ /**
174
+ * Create a multi-agent orchestration
175
+ * @param configOrAgents - Either an array of agents or a config object
176
+ */
177
+ constructor(configOrAgents: PraisonAIAgentsConfig | Agent[]);
69
178
  private generateTasks;
70
179
  private executeSequential;
71
180
  start(): Promise<string[]>;
72
181
  chat(): Promise<string[]>;
73
182
  }
183
+ /**
184
+ * Agents - Alias for PraisonAIAgents
185
+ *
186
+ * This is the recommended class name for multi-agent orchestration.
187
+ * PraisonAIAgents is kept for backward compatibility.
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * import { Agent, Agents } from 'praisonai';
192
+ *
193
+ * const agents = new Agents([
194
+ * new Agent({ instructions: "Research the topic" }),
195
+ * new Agent({ instructions: "Write based on research" })
196
+ * ]);
197
+ * await agents.start();
198
+ * ```
199
+ */
200
+ export declare const Agents: typeof PraisonAIAgents;
@@ -1,19 +1,41 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PraisonAIAgents = exports.Agent = void 0;
3
+ exports.Agents = exports.PraisonAIAgents = exports.Agent = void 0;
4
4
  const openai_1 = require("../llm/openai");
5
5
  const logger_1 = require("../utils/logger");
6
+ const crypto_1 = require("crypto");
6
7
  class Agent {
7
8
  constructor(config) {
8
9
  this.toolFunctions = {};
9
- this.instructions = config.instructions;
10
+ this.messages = [];
11
+ // Build instructions from either simple or advanced mode
12
+ if (config.instructions) {
13
+ this.instructions = config.instructions;
14
+ }
15
+ else if (config.role || config.goal || config.backstory) {
16
+ // Advanced mode: construct instructions from role/goal/backstory
17
+ const parts = [];
18
+ if (config.role)
19
+ parts.push(`You are a ${config.role}.`);
20
+ if (config.goal)
21
+ parts.push(`Your goal is: ${config.goal}`);
22
+ if (config.backstory)
23
+ parts.push(`Background: ${config.backstory}`);
24
+ this.instructions = parts.join('\n');
25
+ }
26
+ else {
27
+ this.instructions = 'You are a helpful AI assistant.';
28
+ }
10
29
  this.name = config.name || `Agent_${Math.random().toString(36).substr(2, 9)}`;
11
30
  this.verbose = config.verbose ?? process.env.PRAISON_VERBOSE !== 'false';
12
31
  this.pretty = config.pretty ?? process.env.PRAISON_PRETTY === 'true';
13
- this.llm = config.llm || 'gpt-4o-mini';
32
+ this.llm = config.llm || process.env.OPENAI_MODEL_NAME || process.env.PRAISONAI_MODEL || 'gpt-4o-mini';
14
33
  this.markdown = config.markdown ?? true;
15
34
  this.stream = config.stream ?? true;
16
35
  this.tools = config.tools;
36
+ this.dbAdapter = config.db;
37
+ this.sessionId = config.sessionId || (0, crypto_1.randomUUID)();
38
+ this.runId = config.runId || (0, crypto_1.randomUUID)();
17
39
  this.llmService = new openai_1.OpenAIService(this.llm);
18
40
  // Configure logging
19
41
  logger_1.Logger.setVerbose(this.verbose);
@@ -250,12 +272,54 @@ class Agent {
250
272
  }
251
273
  }
252
274
  async chat(prompt, previousResult) {
253
- return this.start(prompt, previousResult);
275
+ // Persist user message if db is configured
276
+ if (this.dbAdapter) {
277
+ await this.persistMessage('user', prompt);
278
+ }
279
+ const response = await this.start(prompt, previousResult);
280
+ // Persist assistant response if db is configured
281
+ if (this.dbAdapter) {
282
+ await this.persistMessage('assistant', response);
283
+ }
284
+ return response;
254
285
  }
255
286
  async execute(previousResult) {
256
287
  // For backward compatibility and multi-agent support
257
288
  return this.start(this.instructions, previousResult);
258
289
  }
290
+ /**
291
+ * Persist a message to the database
292
+ */
293
+ async persistMessage(role, content) {
294
+ if (!this.dbAdapter)
295
+ return;
296
+ try {
297
+ const message = {
298
+ id: (0, crypto_1.randomUUID)(),
299
+ sessionId: this.sessionId,
300
+ runId: this.runId,
301
+ role,
302
+ content,
303
+ createdAt: Date.now()
304
+ };
305
+ await this.dbAdapter.saveMessage(message);
306
+ }
307
+ catch (error) {
308
+ await logger_1.Logger.warn('Failed to persist message:', error);
309
+ }
310
+ }
311
+ /**
312
+ * Get the session ID for this agent
313
+ */
314
+ getSessionId() {
315
+ return this.sessionId;
316
+ }
317
+ /**
318
+ * Get the run ID for this agent
319
+ */
320
+ getRunId() {
321
+ return this.runId;
322
+ }
259
323
  getResult() {
260
324
  return null;
261
325
  }
@@ -264,8 +328,38 @@ class Agent {
264
328
  }
265
329
  }
266
330
  exports.Agent = Agent;
331
+ /**
332
+ * Multi-agent orchestration class
333
+ *
334
+ * @example Simple array syntax
335
+ * ```typescript
336
+ * import { Agent, Agents } from 'praisonai';
337
+ *
338
+ * const researcher = new Agent({ instructions: "Research the topic" });
339
+ * const writer = new Agent({ instructions: "Write based on research" });
340
+ *
341
+ * const agents = new Agents([researcher, writer]);
342
+ * await agents.start();
343
+ * ```
344
+ *
345
+ * @example Config object syntax
346
+ * ```typescript
347
+ * const agents = new Agents({
348
+ * agents: [researcher, writer],
349
+ * process: 'parallel'
350
+ * });
351
+ * ```
352
+ */
267
353
  class PraisonAIAgents {
268
- constructor(config) {
354
+ /**
355
+ * Create a multi-agent orchestration
356
+ * @param configOrAgents - Either an array of agents or a config object
357
+ */
358
+ constructor(configOrAgents) {
359
+ // Support array syntax: new Agents([a1, a2])
360
+ const config = Array.isArray(configOrAgents)
361
+ ? { agents: configOrAgents }
362
+ : configOrAgents;
269
363
  this.agents = config.agents;
270
364
  this.verbose = config.verbose ?? process.env.PRAISON_VERBOSE !== 'false';
271
365
  this.pretty = config.pretty ?? process.env.PRAISON_PRETTY === 'true';
@@ -331,3 +425,21 @@ class PraisonAIAgents {
331
425
  }
332
426
  }
333
427
  exports.PraisonAIAgents = PraisonAIAgents;
428
+ /**
429
+ * Agents - Alias for PraisonAIAgents
430
+ *
431
+ * This is the recommended class name for multi-agent orchestration.
432
+ * PraisonAIAgents is kept for backward compatibility.
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * import { Agent, Agents } from 'praisonai';
437
+ *
438
+ * const agents = new Agents([
439
+ * new Agent({ instructions: "Research the topic" }),
440
+ * new Agent({ instructions: "Write based on research" })
441
+ * ]);
442
+ * await agents.start();
443
+ * ```
444
+ */
445
+ exports.Agents = PraisonAIAgents;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Agent command - Run a single agent with instructions
3
+ *
4
+ * Usage:
5
+ * praisonai-ts agent chat "Hello, how are you?"
6
+ * praisonai-ts agent run --instructions "You are helpful" "Tell me a joke"
7
+ */
8
+ export interface AgentOptions {
9
+ instructions?: string;
10
+ model?: string;
11
+ stream?: boolean;
12
+ verbose?: boolean;
13
+ profile?: string;
14
+ config?: string;
15
+ output?: 'json' | 'text' | 'pretty';
16
+ json?: boolean;
17
+ sessionId?: string;
18
+ }
19
+ /**
20
+ * Execute agent chat subcommand
21
+ */
22
+ export declare function executeChat(args: string[], options: AgentOptions): Promise<void>;
23
+ /**
24
+ * Execute agent run subcommand (same as chat but requires instructions)
25
+ */
26
+ export declare function executeRun(args: string[], options: AgentOptions): Promise<void>;
27
+ /**
28
+ * Main execute function - routes to subcommands
29
+ */
30
+ export declare function execute(args: string[], options: AgentOptions): Promise<void>;
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ /**
3
+ * Agent command - Run a single agent with instructions
4
+ *
5
+ * Usage:
6
+ * praisonai-ts agent chat "Hello, how are you?"
7
+ * praisonai-ts agent run --instructions "You are helpful" "Tell me a joke"
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.executeChat = executeChat;
44
+ exports.executeRun = executeRun;
45
+ exports.execute = execute;
46
+ const agent_1 = require("../../agent");
47
+ const resolve_1 = require("../config/resolve");
48
+ const json_1 = require("../output/json");
49
+ const pretty = __importStar(require("../output/pretty"));
50
+ const cli_spec_1 = require("../spec/cli-spec");
51
+ const errors_1 = require("../output/errors");
52
+ /**
53
+ * Execute agent chat subcommand
54
+ */
55
+ async function executeChat(args, options) {
56
+ const prompt = args[0];
57
+ if (!prompt) {
58
+ if (options.json || options.output === 'json') {
59
+ (0, json_1.printError)(errors_1.ERROR_CODES.MISSING_ARG, 'Please provide a prompt');
60
+ }
61
+ else {
62
+ await pretty.error('Please provide a prompt');
63
+ }
64
+ process.exit(cli_spec_1.EXIT_CODES.INVALID_ARGUMENTS);
65
+ }
66
+ const config = (0, resolve_1.resolveConfig)({
67
+ configPath: options.config,
68
+ profile: options.profile,
69
+ model: options.model,
70
+ verbose: options.verbose,
71
+ stream: options.stream
72
+ });
73
+ const startTime = Date.now();
74
+ const outputFormat = options.json ? 'json' : (options.output || 'pretty');
75
+ try {
76
+ const agent = new agent_1.Agent({
77
+ instructions: options.instructions || 'You are a helpful AI assistant.',
78
+ llm: config.model,
79
+ stream: config.stream && outputFormat !== 'json',
80
+ verbose: config.verbose,
81
+ sessionId: options.sessionId
82
+ });
83
+ const response = await agent.chat(prompt);
84
+ const duration = Date.now() - startTime;
85
+ if (outputFormat === 'json') {
86
+ (0, json_1.outputJson)((0, json_1.formatSuccess)({
87
+ response,
88
+ agent: agent.name,
89
+ sessionId: agent.getSessionId()
90
+ }, {
91
+ duration_ms: duration,
92
+ model: config.model
93
+ }));
94
+ }
95
+ else if (outputFormat === 'text') {
96
+ console.log(response);
97
+ }
98
+ else {
99
+ // Pretty output - response already printed if streaming
100
+ if (!config.stream) {
101
+ console.log(response);
102
+ }
103
+ console.log(); // Newline
104
+ await pretty.dim(`Completed in ${duration}ms`);
105
+ }
106
+ }
107
+ catch (error) {
108
+ const cliError = (0, errors_1.normalizeError)(error);
109
+ if (outputFormat === 'json') {
110
+ (0, json_1.outputJson)((0, json_1.formatError)(cliError.code, cliError.message, cliError.details));
111
+ }
112
+ else {
113
+ await pretty.error(cliError.message);
114
+ if (config.verbose && error instanceof Error && error.stack) {
115
+ await pretty.dim(error.stack);
116
+ }
117
+ }
118
+ process.exit(cliError.exitCode);
119
+ }
120
+ }
121
+ /**
122
+ * Execute agent run subcommand (same as chat but requires instructions)
123
+ */
124
+ async function executeRun(args, options) {
125
+ if (!options.instructions) {
126
+ if (options.json || options.output === 'json') {
127
+ (0, json_1.printError)(errors_1.ERROR_CODES.MISSING_ARG, 'Please provide --instructions');
128
+ }
129
+ else {
130
+ await pretty.error('Please provide --instructions');
131
+ }
132
+ process.exit(cli_spec_1.EXIT_CODES.INVALID_ARGUMENTS);
133
+ }
134
+ return executeChat(args, options);
135
+ }
136
+ /**
137
+ * Main execute function - routes to subcommands
138
+ */
139
+ async function execute(args, options) {
140
+ const subcommand = args[0];
141
+ const subArgs = args.slice(1);
142
+ switch (subcommand) {
143
+ case 'chat':
144
+ return executeChat(subArgs, options);
145
+ case 'run':
146
+ return executeRun(subArgs, options);
147
+ default:
148
+ // If no subcommand, treat the first arg as a prompt for chat
149
+ if (subcommand) {
150
+ return executeChat(args, options);
151
+ }
152
+ if (options.json || options.output === 'json') {
153
+ (0, json_1.printError)(errors_1.ERROR_CODES.MISSING_ARG, 'Please provide a subcommand (chat, run) or a prompt');
154
+ }
155
+ else {
156
+ await pretty.error('Usage: praisonai-ts agent [chat|run] <prompt>');
157
+ await pretty.info(' agent chat "Hello" - Chat with default agent');
158
+ await pretty.info(' agent run --instructions "..." "Hello" - Run with custom instructions');
159
+ }
160
+ process.exit(cli_spec_1.EXIT_CODES.INVALID_ARGUMENTS);
161
+ }
162
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Agents command - Run multi-agent orchestration
3
+ *
4
+ * Usage:
5
+ * praisonai-ts agents run --agents "researcher,writer" "Research AI trends"
6
+ */
7
+ export interface AgentsOptions {
8
+ agents?: string;
9
+ process?: 'sequential' | 'parallel';
10
+ model?: string;
11
+ verbose?: boolean;
12
+ profile?: string;
13
+ config?: string;
14
+ output?: 'json' | 'text' | 'pretty';
15
+ json?: boolean;
16
+ }
17
+ /**
18
+ * Execute agents run subcommand
19
+ */
20
+ export declare function executeRun(args: string[], options: AgentsOptions): Promise<void>;
21
+ /**
22
+ * Main execute function - routes to subcommands
23
+ */
24
+ export declare function execute(args: string[], options: AgentsOptions): Promise<void>;
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ /**
3
+ * Agents command - Run multi-agent orchestration
4
+ *
5
+ * Usage:
6
+ * praisonai-ts agents run --agents "researcher,writer" "Research AI trends"
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.executeRun = executeRun;
43
+ exports.execute = execute;
44
+ const agent_1 = require("../../agent");
45
+ const resolve_1 = require("../config/resolve");
46
+ const json_1 = require("../output/json");
47
+ const pretty = __importStar(require("../output/pretty"));
48
+ const cli_spec_1 = require("../spec/cli-spec");
49
+ const errors_1 = require("../output/errors");
50
+ /**
51
+ * Parse agent definitions from comma-separated string
52
+ */
53
+ function parseAgentDefinitions(agentsStr) {
54
+ return agentsStr.split(',').map(s => s.trim()).filter(s => s.length > 0);
55
+ }
56
+ /**
57
+ * Execute agents run subcommand
58
+ */
59
+ async function executeRun(args, options) {
60
+ const prompt = args[0];
61
+ if (!prompt) {
62
+ if (options.json || options.output === 'json') {
63
+ (0, json_1.printError)(errors_1.ERROR_CODES.MISSING_ARG, 'Please provide a prompt/task');
64
+ }
65
+ else {
66
+ await pretty.error('Please provide a prompt/task');
67
+ }
68
+ process.exit(cli_spec_1.EXIT_CODES.INVALID_ARGUMENTS);
69
+ }
70
+ const config = (0, resolve_1.resolveConfig)({
71
+ configPath: options.config,
72
+ profile: options.profile,
73
+ model: options.model,
74
+ verbose: options.verbose
75
+ });
76
+ const startTime = Date.now();
77
+ const outputFormat = options.json ? 'json' : (options.output || 'pretty');
78
+ try {
79
+ // Create agents from definitions or use defaults
80
+ let agentList;
81
+ if (options.agents) {
82
+ const definitions = parseAgentDefinitions(options.agents);
83
+ agentList = definitions.map((instructions, i) => new agent_1.Agent({
84
+ instructions,
85
+ name: `Agent_${i + 1}`,
86
+ llm: config.model,
87
+ verbose: config.verbose
88
+ }));
89
+ }
90
+ else {
91
+ // Default: create a researcher and writer
92
+ agentList = [
93
+ new agent_1.Agent({
94
+ instructions: `Research the following topic thoroughly: ${prompt}`,
95
+ name: 'Researcher',
96
+ llm: config.model,
97
+ verbose: config.verbose
98
+ }),
99
+ new agent_1.Agent({
100
+ instructions: 'Summarize and write a clear report based on the research provided.',
101
+ name: 'Writer',
102
+ llm: config.model,
103
+ verbose: config.verbose
104
+ })
105
+ ];
106
+ }
107
+ if (outputFormat !== 'json') {
108
+ await pretty.heading(`Running ${agentList.length} agents (${options.process || 'sequential'})`);
109
+ }
110
+ const agents = new agent_1.Agents({
111
+ agents: agentList,
112
+ process: options.process || 'sequential',
113
+ verbose: config.verbose
114
+ });
115
+ const results = await agents.start();
116
+ const duration = Date.now() - startTime;
117
+ if (outputFormat === 'json') {
118
+ (0, json_1.outputJson)((0, json_1.formatSuccess)({
119
+ results,
120
+ agentCount: agentList.length,
121
+ process: options.process || 'sequential'
122
+ }, {
123
+ duration_ms: duration,
124
+ model: config.model
125
+ }));
126
+ }
127
+ else if (outputFormat === 'text') {
128
+ results.forEach((result, i) => {
129
+ console.log(`\n--- Agent ${i + 1} ---\n${result}`);
130
+ });
131
+ }
132
+ else {
133
+ // Pretty output
134
+ console.log();
135
+ await pretty.success(`Completed ${agentList.length} agents in ${duration}ms`);
136
+ }
137
+ }
138
+ catch (error) {
139
+ const cliError = (0, errors_1.normalizeError)(error);
140
+ if (outputFormat === 'json') {
141
+ (0, json_1.outputJson)((0, json_1.formatError)(cliError.code, cliError.message, cliError.details));
142
+ }
143
+ else {
144
+ await pretty.error(cliError.message);
145
+ if (config.verbose && error instanceof Error && error.stack) {
146
+ await pretty.dim(error.stack);
147
+ }
148
+ }
149
+ process.exit(cliError.exitCode);
150
+ }
151
+ }
152
+ /**
153
+ * Main execute function - routes to subcommands
154
+ */
155
+ async function execute(args, options) {
156
+ const subcommand = args[0];
157
+ const subArgs = args.slice(1);
158
+ switch (subcommand) {
159
+ case 'run':
160
+ return executeRun(subArgs, options);
161
+ default:
162
+ // If no subcommand, treat as run
163
+ if (subcommand) {
164
+ return executeRun(args, options);
165
+ }
166
+ if (options.json || options.output === 'json') {
167
+ (0, json_1.printError)(errors_1.ERROR_CODES.MISSING_ARG, 'Please provide a task/prompt');
168
+ }
169
+ else {
170
+ await pretty.error('Usage: praisonai-ts agents [run] <task>');
171
+ await pretty.info(' agents run "Research AI" - Run with default agents');
172
+ await pretty.info(' agents run --agents "..." "Research AI" - Run with custom agents');
173
+ await pretty.info(' agents run --process parallel "Research AI" - Run in parallel');
174
+ }
175
+ process.exit(cli_spec_1.EXIT_CODES.INVALID_ARGUMENTS);
176
+ }
177
+ }
@@ -1,5 +1,14 @@
1
1
  /**
2
2
  * Database Module - Exports for persistence layer
3
+ *
4
+ * Usage (Python-like simplicity):
5
+ * import { db } from 'praisonai';
6
+ *
7
+ * const agent = new Agent({
8
+ * instructions: "You are helpful",
9
+ * db: db("sqlite:./data.db"), // URL-style string
10
+ * sessionId: "my-session"
11
+ * });
3
12
  */
4
13
  export * from './types';
5
14
  export { MemoryDbAdapter } from './memory-adapter';
@@ -17,7 +26,17 @@ export declare function getDefaultDbAdapter(): DbAdapter;
17
26
  */
18
27
  export declare function setDefaultDbAdapter(adapter: DbAdapter): void;
19
28
  /**
20
- * Shortcut function for creating a database adapter
21
- * Usage: db({ type: 'memory' }) or db({ type: 'sqlite', path: './data.db' })
29
+ * Factory function for creating a database adapter
30
+ *
31
+ * Accepts either:
32
+ * - URL string: db("sqlite:./data.db"), db("postgres://..."), db("redis://...")
33
+ * - Config object: db({ type: 'sqlite', path: './data.db' })
34
+ *
35
+ * Examples:
36
+ * db("sqlite:./data.db") // SQLite file
37
+ * db("postgres://localhost/mydb") // PostgreSQL
38
+ * db("redis://localhost:6379") // Redis
39
+ * db("memory:") // In-memory (default)
40
+ * db() // In-memory (default)
22
41
  */
23
- export declare function db(config?: DbConfig): DbAdapter;
42
+ export declare function db(configOrUrl?: string | DbConfig): DbAdapter;
package/dist/db/index.js CHANGED
@@ -1,6 +1,15 @@
1
1
  "use strict";
2
2
  /**
3
3
  * Database Module - Exports for persistence layer
4
+ *
5
+ * Usage (Python-like simplicity):
6
+ * import { db } from 'praisonai';
7
+ *
8
+ * const agent = new Agent({
9
+ * instructions: "You are helpful",
10
+ * db: db("sqlite:./data.db"), // URL-style string
11
+ * sessionId: "my-session"
12
+ * });
4
13
  */
5
14
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
15
  if (k2 === undefined) k2 = k;
@@ -28,6 +37,51 @@ Object.defineProperty(exports, "MemoryDbAdapter", { enumerable: true, get: funct
28
37
  const memory_adapter_2 = require("./memory-adapter");
29
38
  // Default adapter instance
30
39
  let defaultAdapter = null;
40
+ /**
41
+ * Parse a database URL string into a DbConfig
42
+ * Supports: sqlite:./path, postgres://..., redis://..., memory:
43
+ */
44
+ function parseDbUrl(url) {
45
+ // Handle memory shorthand
46
+ if (url === 'memory' || url === 'memory:' || url === ':memory:') {
47
+ return { type: 'memory' };
48
+ }
49
+ // Handle sqlite: prefix
50
+ if (url.startsWith('sqlite:')) {
51
+ const path = url.slice(7); // Remove 'sqlite:'
52
+ return { type: 'sqlite', path: path || ':memory:' };
53
+ }
54
+ // Handle postgres:// or postgresql://
55
+ if (url.startsWith('postgres://') || url.startsWith('postgresql://')) {
56
+ return { type: 'postgres', connectionString: url };
57
+ }
58
+ // Handle neon:// (Neon Postgres)
59
+ if (url.startsWith('neon://')) {
60
+ // Convert neon:// to postgres:// for compatibility
61
+ const connectionString = url.replace('neon://', 'postgres://');
62
+ return { type: 'postgres', connectionString };
63
+ }
64
+ // Handle redis:// or rediss://
65
+ if (url.startsWith('redis://') || url.startsWith('rediss://')) {
66
+ return { type: 'redis', connectionString: url };
67
+ }
68
+ // Handle upstash:// (Upstash Redis)
69
+ if (url.startsWith('upstash://')) {
70
+ // Convert upstash:// to rediss:// for compatibility
71
+ const connectionString = url.replace('upstash://', 'rediss://');
72
+ return { type: 'redis', connectionString };
73
+ }
74
+ // Default: treat as file path for sqlite
75
+ if (url.endsWith('.db') || url.endsWith('.sqlite') || url.endsWith('.sqlite3')) {
76
+ return { type: 'sqlite', path: url };
77
+ }
78
+ throw new Error(`Invalid database URL: ${url}\n` +
79
+ `Supported formats:\n` +
80
+ ` - sqlite:./data.db\n` +
81
+ ` - postgres://user:pass@host:port/db\n` +
82
+ ` - redis://host:port\n` +
83
+ ` - memory:`);
84
+ }
31
85
  /**
32
86
  * Create a database adapter based on configuration
33
87
  */
@@ -35,15 +89,21 @@ function createDbAdapter(config) {
35
89
  switch (config.type) {
36
90
  case 'memory':
37
91
  return new memory_adapter_2.MemoryDbAdapter();
38
- case 'sqlite':
39
- // SQLite adapter would be implemented here
40
- throw new Error('SQLite adapter not yet implemented. Use memory adapter for now.');
41
- case 'postgres':
42
- // PostgreSQL adapter would be implemented here
43
- throw new Error('PostgreSQL adapter not yet implemented. Use memory adapter for now.');
44
- case 'redis':
45
- // Redis adapter would be implemented here
46
- throw new Error('Redis adapter not yet implemented. Use memory adapter for now.');
92
+ case 'sqlite': {
93
+ // Lazy load SQLite adapter
94
+ const { SQLiteDbAdapter } = require('./sqlite');
95
+ return new SQLiteDbAdapter(config.path || ':memory:');
96
+ }
97
+ case 'postgres': {
98
+ // Lazy load Postgres adapter
99
+ const { PostgresDbAdapter } = require('./postgres');
100
+ return new PostgresDbAdapter(config.connectionString || '');
101
+ }
102
+ case 'redis': {
103
+ // Lazy load Redis adapter
104
+ const { RedisDbAdapter } = require('./redis');
105
+ return new RedisDbAdapter(config.connectionString || '');
106
+ }
47
107
  default:
48
108
  throw new Error(`Unknown database type: ${config.type}`);
49
109
  }
@@ -64,9 +124,23 @@ function setDefaultDbAdapter(adapter) {
64
124
  defaultAdapter = adapter;
65
125
  }
66
126
  /**
67
- * Shortcut function for creating a database adapter
68
- * Usage: db({ type: 'memory' }) or db({ type: 'sqlite', path: './data.db' })
127
+ * Factory function for creating a database adapter
128
+ *
129
+ * Accepts either:
130
+ * - URL string: db("sqlite:./data.db"), db("postgres://..."), db("redis://...")
131
+ * - Config object: db({ type: 'sqlite', path: './data.db' })
132
+ *
133
+ * Examples:
134
+ * db("sqlite:./data.db") // SQLite file
135
+ * db("postgres://localhost/mydb") // PostgreSQL
136
+ * db("redis://localhost:6379") // Redis
137
+ * db("memory:") // In-memory (default)
138
+ * db() // In-memory (default)
69
139
  */
70
- function db(config = { type: 'memory' }) {
71
- return createDbAdapter(config);
140
+ function db(configOrUrl = { type: 'memory' }) {
141
+ if (typeof configOrUrl === 'string') {
142
+ const config = parseDbUrl(configOrUrl);
143
+ return createDbAdapter(config);
144
+ }
145
+ return createDbAdapter(configOrUrl);
72
146
  }
package/dist/index.d.ts CHANGED
@@ -1,24 +1,64 @@
1
- export * from './agent';
2
- export * from './knowledge';
3
- export * from './llm';
4
- export * from './memory';
5
- export * from './process';
1
+ /**
2
+ * PraisonAI TypeScript SDK
3
+ *
4
+ * The primary API surface consists of three core classes:
5
+ * - Agent: Single AI agent with instructions, tools, and optional persistence
6
+ * - Agents: Multi-agent orchestration (sequential or parallel)
7
+ * - Workflow: Step-based workflow execution
8
+ *
9
+ * @example Quickstart (3 lines)
10
+ * ```typescript
11
+ * import { Agent } from 'praisonai';
12
+ * const agent = new Agent({ instructions: "You are helpful" });
13
+ * await agent.chat("Hello!");
14
+ * ```
15
+ *
16
+ * @example With tools (5 lines)
17
+ * ```typescript
18
+ * const getWeather = (city: string) => `Weather in ${city}: 20°C`;
19
+ * const agent = new Agent({ instructions: "You provide weather", tools: [getWeather] });
20
+ * await agent.chat("Weather in Paris?");
21
+ * ```
22
+ *
23
+ * @example With persistence (4 lines)
24
+ * ```typescript
25
+ * import { Agent, db } from 'praisonai';
26
+ * const agent = new Agent({ instructions: "You are helpful", db: db("sqlite:./data.db") });
27
+ * await agent.chat("Hello!");
28
+ * ```
29
+ *
30
+ * @example Multi-agent (6 lines)
31
+ * ```typescript
32
+ * import { Agent, Agents } from 'praisonai';
33
+ * const researcher = new Agent({ instructions: "Research the topic" });
34
+ * const writer = new Agent({ instructions: "Write based on research" });
35
+ * const agents = new Agents([researcher, writer]);
36
+ * await agents.start();
37
+ * ```
38
+ */
39
+ export { Agent, Agents, PraisonAIAgents } from './agent';
40
+ export type { SimpleAgentConfig, PraisonAIAgentsConfig } from './agent';
41
+ export { Workflow, parallel, route, loop, repeat } from './workflows';
42
+ export type { WorkflowStep, WorkflowContext, StepResult } from './workflows';
43
+ export { db, createDbAdapter, getDefaultDbAdapter, setDefaultDbAdapter } from './db';
44
+ export type { DbAdapter, DbConfig, DbMessage, DbRun, DbTrace } from './db';
6
45
  export { BaseTool, ToolResult, ToolValidationError, validateTool, createTool, FunctionTool, tool, ToolRegistry, getRegistry, registerTool, getTool, type ToolConfig, type ToolContext, type ToolParameters } from './tools';
7
46
  export * from './tools/arxivTools';
8
47
  export * from './tools/mcpSse';
9
48
  export * from './session';
10
- export * from './db';
11
- export * from './workflows';
49
+ export * from './knowledge';
50
+ export * from './llm';
51
+ export * from './process';
12
52
  export * from './guardrails';
13
53
  export { Handoff, handoff, handoffFilters, type HandoffConfig, type HandoffContext, type HandoffResult } from './agent/handoff';
14
54
  export { RouterAgent, createRouter, routeConditions, type RouterConfig, type RouteConfig, type RouteContext } from './agent/router';
15
55
  export { ContextAgent, createContextAgent, type ContextAgentConfig, type ContextMessage } from './agent/context';
16
- export { KnowledgeBase, createKnowledgeBase, type Document, type SearchResult, type EmbeddingProvider, type KnowledgeBaseConfig } from './knowledge/rag';
17
56
  export { accuracyEval, performanceEval, reliabilityEval, EvalSuite, type EvalResult, type PerformanceResult, type AccuracyEvalConfig, type PerformanceEvalConfig, type ReliabilityEvalConfig } from './eval';
18
57
  export { MemoryObservabilityAdapter, ConsoleObservabilityAdapter, setObservabilityAdapter, getObservabilityAdapter, type ObservabilityAdapter, type TraceContext, type SpanContext, type SpanData, type TraceData } from './observability';
19
58
  export { SkillManager, createSkillManager, parseSkillFile, type Skill, type SkillMetadata, type SkillDiscoveryOptions } from './skills';
20
59
  export { parseArgs, executeCommand, CLI_SPEC_VERSION } from './cli';
21
- export { Memory, createMemory, type MemoryEntry, type MemoryConfig, type SearchResult as MemorySearchResult } from './memory/memory';
60
+ export { Memory, createMemory } from './memory/memory';
61
+ export type { MemoryEntry, MemoryConfig } from './memory/memory';
22
62
  export { FileMemory, createFileMemory, type FileMemoryConfig, type FileMemoryEntry } from './memory/file-memory';
23
63
  export { AutoMemory, createAutoMemory, createLLMSummarizer, DEFAULT_POLICIES, type AutoMemoryConfig, type AutoMemoryPolicy, type AutoMemoryContext, type VectorStoreAdapter as AutoMemoryVectorStore, type KnowledgeBaseAdapter as AutoMemoryKnowledgeBase } from './memory/auto-memory';
24
64
  export { TelemetryCollector, getTelemetry, enableTelemetry, disableTelemetry, cleanupTelemetry, type TelemetryEvent, type TelemetryConfig } from './telemetry';
@@ -27,13 +67,12 @@ export { ImageAgent, createImageAgent, type ImageAgentConfig, type ImageGenerati
27
67
  export { DeepResearchAgent, createDeepResearchAgent, type DeepResearchConfig, type ResearchResponse, type Citation, type ReasoningStep } from './agent/research';
28
68
  export { QueryRewriterAgent, createQueryRewriterAgent, type QueryRewriterConfig, type RewriteResult, type RewriteStrategy } from './agent/query-rewriter';
29
69
  export { PromptExpanderAgent, createPromptExpanderAgent, type PromptExpanderConfig, type ExpandResult, type ExpandStrategy } from './agent/prompt-expander';
30
- export { Chunking, createChunking, type ChunkingConfig, type Chunk, type ChunkStrategy } from './knowledge/chunking';
31
70
  export { LLMGuardrail, createLLMGuardrail, type LLMGuardrailConfig, type LLMGuardrailResult } from './guardrails/llm-guardrail';
32
71
  export { Plan, PlanStep, TodoList, TodoItem, PlanStorage, createPlan, createTodoList, createPlanStorage, type PlanConfig, type PlanStepConfig, type TodoItemConfig, type PlanStatus, type TodoStatus } from './planning';
33
72
  export { BaseCache, MemoryCache, FileCache, createMemoryCache, createFileCache, type CacheConfig, type CacheEntry } from './cache';
34
73
  export { PubSub, EventEmitterPubSub, AgentEventBus, AgentEvents, createEventBus, createPubSub, type Event, type EventHandler } from './events';
35
74
  export { parseYAMLWorkflow, createWorkflowFromYAML, loadWorkflowFromFile, validateWorkflowDefinition, type YAMLWorkflowDefinition, type YAMLStepDefinition, type ParsedWorkflow } from './workflows/yaml-parser';
36
- export { SQLiteAdapter, createSQLiteAdapter, type SQLiteConfig, type DbMessage, type DbRun, type DbTrace } from './db/sqlite';
75
+ export { SQLiteAdapter, createSQLiteAdapter, type SQLiteConfig } from './db/sqlite';
37
76
  export { UpstashRedisAdapter, MemoryRedisAdapter, createUpstashRedis, createMemoryRedis, type RedisConfig, type RedisAdapter } from './db/redis';
38
77
  export { NeonPostgresAdapter, MemoryPostgresAdapter, PostgresSessionStorage, createNeonPostgres, createMemoryPostgres, createPostgresSessionStorage, type PostgresConfig, type PostgresAdapter } from './db/postgres';
39
78
  export { BaseVectorStore, MemoryVectorStore, createMemoryVectorStore, PineconeVectorStore, createPineconeStore, WeaviateVectorStore, createWeaviateStore, QdrantVectorStore, createQdrantStore, ChromaVectorStore, createChromaStore, type VectorDocument, type QueryResult as VectorQueryResult, type IndexStats } from './integrations/vector';
package/dist/index.js CHANGED
@@ -1,4 +1,42 @@
1
1
  "use strict";
2
+ /**
3
+ * PraisonAI TypeScript SDK
4
+ *
5
+ * The primary API surface consists of three core classes:
6
+ * - Agent: Single AI agent with instructions, tools, and optional persistence
7
+ * - Agents: Multi-agent orchestration (sequential or parallel)
8
+ * - Workflow: Step-based workflow execution
9
+ *
10
+ * @example Quickstart (3 lines)
11
+ * ```typescript
12
+ * import { Agent } from 'praisonai';
13
+ * const agent = new Agent({ instructions: "You are helpful" });
14
+ * await agent.chat("Hello!");
15
+ * ```
16
+ *
17
+ * @example With tools (5 lines)
18
+ * ```typescript
19
+ * const getWeather = (city: string) => `Weather in ${city}: 20°C`;
20
+ * const agent = new Agent({ instructions: "You provide weather", tools: [getWeather] });
21
+ * await agent.chat("Weather in Paris?");
22
+ * ```
23
+ *
24
+ * @example With persistence (4 lines)
25
+ * ```typescript
26
+ * import { Agent, db } from 'praisonai';
27
+ * const agent = new Agent({ instructions: "You are helpful", db: db("sqlite:./data.db") });
28
+ * await agent.chat("Hello!");
29
+ * ```
30
+ *
31
+ * @example Multi-agent (6 lines)
32
+ * ```typescript
33
+ * import { Agent, Agents } from 'praisonai';
34
+ * const researcher = new Agent({ instructions: "Research the topic" });
35
+ * const writer = new Agent({ instructions: "Write based on research" });
36
+ * const agents = new Agents([researcher, writer]);
37
+ * await agents.start();
38
+ * ```
39
+ */
2
40
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
41
  if (k2 === undefined) k2 = k;
4
42
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -14,18 +52,35 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
52
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
53
  };
16
54
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.ImageAgent = exports.createAutoAgents = exports.AutoAgents = exports.cleanupTelemetry = exports.disableTelemetry = exports.enableTelemetry = exports.getTelemetry = exports.TelemetryCollector = exports.DEFAULT_POLICIES = exports.createLLMSummarizer = exports.createAutoMemory = exports.AutoMemory = exports.createFileMemory = exports.FileMemory = exports.createMemory = exports.Memory = exports.CLI_SPEC_VERSION = exports.executeCommand = exports.parseArgs = exports.parseSkillFile = exports.createSkillManager = exports.SkillManager = exports.getObservabilityAdapter = exports.setObservabilityAdapter = exports.ConsoleObservabilityAdapter = exports.MemoryObservabilityAdapter = exports.EvalSuite = exports.reliabilityEval = exports.performanceEval = exports.accuracyEval = exports.createKnowledgeBase = exports.KnowledgeBase = exports.createContextAgent = exports.ContextAgent = exports.routeConditions = exports.createRouter = exports.RouterAgent = exports.handoffFilters = exports.handoff = exports.Handoff = exports.getTool = exports.registerTool = exports.getRegistry = exports.ToolRegistry = exports.tool = exports.FunctionTool = exports.createTool = exports.validateTool = exports.ToolValidationError = exports.BaseTool = void 0;
18
- exports.PineconeVectorStore = exports.createMemoryVectorStore = exports.MemoryVectorStore = exports.BaseVectorStore = exports.createPostgresSessionStorage = exports.createMemoryPostgres = exports.createNeonPostgres = exports.PostgresSessionStorage = exports.MemoryPostgresAdapter = exports.NeonPostgresAdapter = exports.createMemoryRedis = exports.createUpstashRedis = exports.MemoryRedisAdapter = exports.UpstashRedisAdapter = exports.createSQLiteAdapter = exports.SQLiteAdapter = exports.validateWorkflowDefinition = exports.loadWorkflowFromFile = exports.createWorkflowFromYAML = exports.parseYAMLWorkflow = exports.createPubSub = exports.createEventBus = exports.AgentEvents = exports.AgentEventBus = exports.EventEmitterPubSub = exports.PubSub = exports.createFileCache = exports.createMemoryCache = exports.FileCache = exports.MemoryCache = exports.BaseCache = exports.createPlanStorage = exports.createTodoList = exports.createPlan = exports.PlanStorage = exports.TodoItem = exports.TodoList = exports.PlanStep = exports.Plan = exports.createLLMGuardrail = exports.LLMGuardrail = exports.createChunking = exports.Chunking = exports.createPromptExpanderAgent = exports.PromptExpanderAgent = exports.createQueryRewriterAgent = exports.QueryRewriterAgent = exports.createDeepResearchAgent = exports.DeepResearchAgent = exports.createImageAgent = void 0;
19
- exports.InteractiveTUI = exports.MODEL_PRICING = exports.formatCost = exports.estimateTokens = exports.createCostTracker = exports.CostTracker = exports.isSlashCommand = exports.executeSlashCommand = exports.parseSlashCommand = exports.registerCommand = exports.createSlashCommandHandler = exports.SlashCommandHandler = exports.BaseProvider = exports.GoogleProvider = exports.AnthropicProvider = exports.OpenAIProvider = exports.getAvailableProviders = exports.isProviderAvailable = exports.parseModelString = exports.getDefaultProvider = exports.createProvider = exports.createGraphRAG = exports.GraphRAG = exports.GraphStore = exports.createLLMReranker = exports.createCrossEncoderReranker = exports.createCohereReranker = exports.LLMReranker = exports.CrossEncoderReranker = exports.CohereReranker = exports.BaseReranker = exports.createElevenLabsVoice = exports.createOpenAIVoice = exports.ElevenLabsVoiceProvider = exports.OpenAIVoiceProvider = exports.BaseVoiceProvider = exports.createLangfuseObservability = exports.createMemoryObservability = exports.createConsoleObservability = exports.LangfuseObservabilityProvider = exports.MemoryObservabilityProvider = exports.ConsoleObservabilityProvider = exports.BaseObservabilityProvider = exports.createChromaStore = exports.ChromaVectorStore = exports.createQdrantStore = exports.QdrantVectorStore = exports.createWeaviateStore = exports.WeaviateVectorStore = exports.createPineconeStore = void 0;
20
- exports.createN8NIntegration = exports.N8NIntegration = exports.externalAgentAsTool = exports.createExternalAgent = exports.getExternalAgentRegistry = exports.GenericExternalAgent = exports.AiderAgent = exports.CodexCliAgent = exports.GeminiCliAgent = exports.ClaudeCodeAgent = exports.BaseExternalAgent = exports.renderWorkflow = exports.createFlowDisplay = exports.FlowDisplay = exports.createFileCheckpointStorage = exports.FileCheckpointStorage = exports.MemoryCheckpointStorage = exports.createCheckpointManager = exports.CheckpointManager = exports.createFileJobStorage = exports.FileJobStorage = exports.MemoryJobStorage = exports.createJobQueue = exports.JobQueue = exports.cronExpressions = exports.createScheduler = exports.Scheduler = exports.MODE_POLICIES = exports.cliApprovalPrompt = exports.createAutonomyManager = exports.AutonomyManager = exports.DEFAULT_BLOCKED_PATHS = exports.DEFAULT_BLOCKED_COMMANDS = exports.CommandValidator = exports.sandboxExec = exports.createSandboxExecutor = exports.SandboxExecutor = exports.createDiffViewer = exports.DiffViewer = exports.createGitManager = exports.GitManager = exports.DEFAULT_IGNORE_PATTERNS = exports.getRepoTree = exports.createRepoMap = exports.RepoMap = exports.createHistoryManager = exports.HistoryManager = exports.createStatusDisplay = exports.StatusDisplay = exports.createInteractiveTUI = void 0;
21
- exports.getQuickContext = exports.createFastContext = exports.FastContext = exports.triggerN8NWebhook = void 0;
22
- // Export all public modules
23
- __exportStar(require("./agent"), exports);
24
- __exportStar(require("./knowledge"), exports);
25
- __exportStar(require("./llm"), exports);
26
- __exportStar(require("./memory"), exports);
27
- __exportStar(require("./process"), exports);
28
- // Export tools (excluding conflicting types)
55
+ exports.createAutoMemory = exports.AutoMemory = exports.createFileMemory = exports.FileMemory = exports.createMemory = exports.Memory = exports.CLI_SPEC_VERSION = exports.executeCommand = exports.parseArgs = exports.parseSkillFile = exports.createSkillManager = exports.SkillManager = exports.getObservabilityAdapter = exports.setObservabilityAdapter = exports.ConsoleObservabilityAdapter = exports.MemoryObservabilityAdapter = exports.EvalSuite = exports.reliabilityEval = exports.performanceEval = exports.accuracyEval = exports.createContextAgent = exports.ContextAgent = exports.routeConditions = exports.createRouter = exports.RouterAgent = exports.handoffFilters = exports.handoff = exports.Handoff = exports.getTool = exports.registerTool = exports.getRegistry = exports.ToolRegistry = exports.tool = exports.FunctionTool = exports.createTool = exports.validateTool = exports.ToolValidationError = exports.BaseTool = exports.setDefaultDbAdapter = exports.getDefaultDbAdapter = exports.createDbAdapter = exports.db = exports.repeat = exports.loop = exports.route = exports.parallel = exports.Workflow = exports.PraisonAIAgents = exports.Agents = exports.Agent = void 0;
56
+ exports.MemoryPostgresAdapter = exports.NeonPostgresAdapter = exports.createMemoryRedis = exports.createUpstashRedis = exports.MemoryRedisAdapter = exports.UpstashRedisAdapter = exports.createSQLiteAdapter = exports.SQLiteAdapter = exports.validateWorkflowDefinition = exports.loadWorkflowFromFile = exports.createWorkflowFromYAML = exports.parseYAMLWorkflow = exports.createPubSub = exports.createEventBus = exports.AgentEvents = exports.AgentEventBus = exports.EventEmitterPubSub = exports.PubSub = exports.createFileCache = exports.createMemoryCache = exports.FileCache = exports.MemoryCache = exports.BaseCache = exports.createPlanStorage = exports.createTodoList = exports.createPlan = exports.PlanStorage = exports.TodoItem = exports.TodoList = exports.PlanStep = exports.Plan = exports.createLLMGuardrail = exports.LLMGuardrail = exports.createPromptExpanderAgent = exports.PromptExpanderAgent = exports.createQueryRewriterAgent = exports.QueryRewriterAgent = exports.createDeepResearchAgent = exports.DeepResearchAgent = exports.createImageAgent = exports.ImageAgent = exports.createAutoAgents = exports.AutoAgents = exports.cleanupTelemetry = exports.disableTelemetry = exports.enableTelemetry = exports.getTelemetry = exports.TelemetryCollector = exports.DEFAULT_POLICIES = exports.createLLMSummarizer = void 0;
57
+ exports.parseSlashCommand = exports.registerCommand = exports.createSlashCommandHandler = exports.SlashCommandHandler = exports.BaseProvider = exports.GoogleProvider = exports.AnthropicProvider = exports.OpenAIProvider = exports.getAvailableProviders = exports.isProviderAvailable = exports.parseModelString = exports.getDefaultProvider = exports.createProvider = exports.createGraphRAG = exports.GraphRAG = exports.GraphStore = exports.createLLMReranker = exports.createCrossEncoderReranker = exports.createCohereReranker = exports.LLMReranker = exports.CrossEncoderReranker = exports.CohereReranker = exports.BaseReranker = exports.createElevenLabsVoice = exports.createOpenAIVoice = exports.ElevenLabsVoiceProvider = exports.OpenAIVoiceProvider = exports.BaseVoiceProvider = exports.createLangfuseObservability = exports.createMemoryObservability = exports.createConsoleObservability = exports.LangfuseObservabilityProvider = exports.MemoryObservabilityProvider = exports.ConsoleObservabilityProvider = exports.BaseObservabilityProvider = exports.createChromaStore = exports.ChromaVectorStore = exports.createQdrantStore = exports.QdrantVectorStore = exports.createWeaviateStore = exports.WeaviateVectorStore = exports.createPineconeStore = exports.PineconeVectorStore = exports.createMemoryVectorStore = exports.MemoryVectorStore = exports.BaseVectorStore = exports.createPostgresSessionStorage = exports.createMemoryPostgres = exports.createNeonPostgres = exports.PostgresSessionStorage = void 0;
58
+ exports.GeminiCliAgent = exports.ClaudeCodeAgent = exports.BaseExternalAgent = exports.renderWorkflow = exports.createFlowDisplay = exports.FlowDisplay = exports.createFileCheckpointStorage = exports.FileCheckpointStorage = exports.MemoryCheckpointStorage = exports.createCheckpointManager = exports.CheckpointManager = exports.createFileJobStorage = exports.FileJobStorage = exports.MemoryJobStorage = exports.createJobQueue = exports.JobQueue = exports.cronExpressions = exports.createScheduler = exports.Scheduler = exports.MODE_POLICIES = exports.cliApprovalPrompt = exports.createAutonomyManager = exports.AutonomyManager = exports.DEFAULT_BLOCKED_PATHS = exports.DEFAULT_BLOCKED_COMMANDS = exports.CommandValidator = exports.sandboxExec = exports.createSandboxExecutor = exports.SandboxExecutor = exports.createDiffViewer = exports.DiffViewer = exports.createGitManager = exports.GitManager = exports.DEFAULT_IGNORE_PATTERNS = exports.getRepoTree = exports.createRepoMap = exports.RepoMap = exports.createHistoryManager = exports.HistoryManager = exports.createStatusDisplay = exports.StatusDisplay = exports.createInteractiveTUI = exports.InteractiveTUI = exports.MODEL_PRICING = exports.formatCost = exports.estimateTokens = exports.createCostTracker = exports.CostTracker = exports.isSlashCommand = exports.executeSlashCommand = void 0;
59
+ exports.getQuickContext = exports.createFastContext = exports.FastContext = exports.triggerN8NWebhook = exports.createN8NIntegration = exports.N8NIntegration = exports.externalAgentAsTool = exports.createExternalAgent = exports.getExternalAgentRegistry = exports.GenericExternalAgent = exports.AiderAgent = exports.CodexCliAgent = void 0;
60
+ // ============================================================================
61
+ // CORE API - The main classes users should use
62
+ // ============================================================================
63
+ // Agent - Single agent with instructions, tools, and optional persistence
64
+ var agent_1 = require("./agent");
65
+ Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return agent_1.Agent; } });
66
+ Object.defineProperty(exports, "Agents", { enumerable: true, get: function () { return agent_1.Agents; } });
67
+ Object.defineProperty(exports, "PraisonAIAgents", { enumerable: true, get: function () { return agent_1.PraisonAIAgents; } });
68
+ // Workflow - Step-based workflow execution
69
+ var workflows_1 = require("./workflows");
70
+ Object.defineProperty(exports, "Workflow", { enumerable: true, get: function () { return workflows_1.Workflow; } });
71
+ Object.defineProperty(exports, "parallel", { enumerable: true, get: function () { return workflows_1.parallel; } });
72
+ Object.defineProperty(exports, "route", { enumerable: true, get: function () { return workflows_1.route; } });
73
+ Object.defineProperty(exports, "loop", { enumerable: true, get: function () { return workflows_1.loop; } });
74
+ Object.defineProperty(exports, "repeat", { enumerable: true, get: function () { return workflows_1.repeat; } });
75
+ // Database factory - Python-like db() shortcut
76
+ var db_1 = require("./db");
77
+ Object.defineProperty(exports, "db", { enumerable: true, get: function () { return db_1.db; } });
78
+ Object.defineProperty(exports, "createDbAdapter", { enumerable: true, get: function () { return db_1.createDbAdapter; } });
79
+ Object.defineProperty(exports, "getDefaultDbAdapter", { enumerable: true, get: function () { return db_1.getDefaultDbAdapter; } });
80
+ Object.defineProperty(exports, "setDefaultDbAdapter", { enumerable: true, get: function () { return db_1.setDefaultDbAdapter; } });
81
+ // ============================================================================
82
+ // TOOLS - Function tools and tool registry
83
+ // ============================================================================
29
84
  var tools_1 = require("./tools");
30
85
  Object.defineProperty(exports, "BaseTool", { enumerable: true, get: function () { return tools_1.BaseTool; } });
31
86
  Object.defineProperty(exports, "ToolValidationError", { enumerable: true, get: function () { return tools_1.ToolValidationError; } });
@@ -39,12 +94,22 @@ Object.defineProperty(exports, "registerTool", { enumerable: true, get: function
39
94
  Object.defineProperty(exports, "getTool", { enumerable: true, get: function () { return tools_1.getTool; } });
40
95
  __exportStar(require("./tools/arxivTools"), exports);
41
96
  __exportStar(require("./tools/mcpSse"), exports);
42
- // Export session management
97
+ // ============================================================================
98
+ // SESSION & MEMORY
99
+ // ============================================================================
43
100
  __exportStar(require("./session"), exports);
44
- // Export database adapters
45
- __exportStar(require("./db"), exports);
46
- // Export workflows
47
- __exportStar(require("./workflows"), exports);
101
+ // ============================================================================
102
+ // KNOWLEDGE & RAG
103
+ // ============================================================================
104
+ __exportStar(require("./knowledge"), exports);
105
+ // ============================================================================
106
+ // LLM PROVIDERS
107
+ // ============================================================================
108
+ __exportStar(require("./llm"), exports);
109
+ __exportStar(require("./process"), exports);
110
+ // ============================================================================
111
+ // WORKFLOWS (additional exports)
112
+ // ============================================================================
48
113
  // Export guardrails
49
114
  __exportStar(require("./guardrails"), exports);
50
115
  // Export handoff
@@ -61,10 +126,6 @@ Object.defineProperty(exports, "routeConditions", { enumerable: true, get: funct
61
126
  var context_1 = require("./agent/context");
62
127
  Object.defineProperty(exports, "ContextAgent", { enumerable: true, get: function () { return context_1.ContextAgent; } });
63
128
  Object.defineProperty(exports, "createContextAgent", { enumerable: true, get: function () { return context_1.createContextAgent; } });
64
- // Export knowledge base (RAG)
65
- var rag_1 = require("./knowledge/rag");
66
- Object.defineProperty(exports, "KnowledgeBase", { enumerable: true, get: function () { return rag_1.KnowledgeBase; } });
67
- Object.defineProperty(exports, "createKnowledgeBase", { enumerable: true, get: function () { return rag_1.createKnowledgeBase; } });
68
129
  // Export evaluation framework
69
130
  var eval_1 = require("./eval");
70
131
  Object.defineProperty(exports, "accuracyEval", { enumerable: true, get: function () { return eval_1.accuracyEval; } });
@@ -87,7 +148,7 @@ var cli_1 = require("./cli");
87
148
  Object.defineProperty(exports, "parseArgs", { enumerable: true, get: function () { return cli_1.parseArgs; } });
88
149
  Object.defineProperty(exports, "executeCommand", { enumerable: true, get: function () { return cli_1.executeCommand; } });
89
150
  Object.defineProperty(exports, "CLI_SPEC_VERSION", { enumerable: true, get: function () { return cli_1.CLI_SPEC_VERSION; } });
90
- // Export Memory
151
+ // Export Memory (explicit for convenience)
91
152
  var memory_1 = require("./memory/memory");
92
153
  Object.defineProperty(exports, "Memory", { enumerable: true, get: function () { return memory_1.Memory; } });
93
154
  Object.defineProperty(exports, "createMemory", { enumerable: true, get: function () { return memory_1.createMemory; } });
@@ -128,10 +189,6 @@ Object.defineProperty(exports, "createQueryRewriterAgent", { enumerable: true, g
128
189
  var prompt_expander_1 = require("./agent/prompt-expander");
129
190
  Object.defineProperty(exports, "PromptExpanderAgent", { enumerable: true, get: function () { return prompt_expander_1.PromptExpanderAgent; } });
130
191
  Object.defineProperty(exports, "createPromptExpanderAgent", { enumerable: true, get: function () { return prompt_expander_1.createPromptExpanderAgent; } });
131
- // Export Chunking
132
- var chunking_1 = require("./knowledge/chunking");
133
- Object.defineProperty(exports, "Chunking", { enumerable: true, get: function () { return chunking_1.Chunking; } });
134
- Object.defineProperty(exports, "createChunking", { enumerable: true, get: function () { return chunking_1.createChunking; } });
135
192
  // Export LLMGuardrail
136
193
  var llm_guardrail_1 = require("./guardrails/llm-guardrail");
137
194
  Object.defineProperty(exports, "LLMGuardrail", { enumerable: true, get: function () { return llm_guardrail_1.LLMGuardrail; } });
@@ -59,6 +59,27 @@ export declare class Workflow<TInput = any, TOutput = any> {
59
59
  * Add a step using a simpler syntax
60
60
  */
61
61
  step<TStepInput = any, TStepOutput = any>(name: string, execute: StepFunction<TStepInput, TStepOutput>): this;
62
+ /**
63
+ * Add an agent step to the workflow
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * import { Agent, Workflow } from 'praisonai';
68
+ *
69
+ * const researcher = new Agent({ instructions: "Research the topic" });
70
+ * const writer = new Agent({ instructions: "Write based on research" });
71
+ *
72
+ * const workflow = new Workflow("Research Pipeline")
73
+ * .agent(researcher, "Research AI trends")
74
+ * .agent(writer, "Write article based on research");
75
+ *
76
+ * await workflow.run("AI in 2025");
77
+ * ```
78
+ */
79
+ agent(agentInstance: {
80
+ chat: (prompt: string) => Promise<string>;
81
+ name?: string;
82
+ }, task?: string): this;
62
83
  /**
63
84
  * Run the workflow
64
85
  */
@@ -134,6 +134,37 @@ class Workflow {
134
134
  step(name, execute) {
135
135
  return this.addStep({ name, execute });
136
136
  }
137
+ /**
138
+ * Add an agent step to the workflow
139
+ *
140
+ * @example
141
+ * ```typescript
142
+ * import { Agent, Workflow } from 'praisonai';
143
+ *
144
+ * const researcher = new Agent({ instructions: "Research the topic" });
145
+ * const writer = new Agent({ instructions: "Write based on research" });
146
+ *
147
+ * const workflow = new Workflow("Research Pipeline")
148
+ * .agent(researcher, "Research AI trends")
149
+ * .agent(writer, "Write article based on research");
150
+ *
151
+ * await workflow.run("AI in 2025");
152
+ * ```
153
+ */
154
+ agent(agentInstance, task) {
155
+ const agentName = agentInstance.name || 'Agent';
156
+ const stepName = task ? `${agentName}: ${task.slice(0, 30)}...` : agentName;
157
+ return this.addStep({
158
+ name: stepName,
159
+ execute: async (input, context) => {
160
+ // Build prompt from task and previous step output
161
+ const prompt = task
162
+ ? `${task}\n\nInput: ${typeof input === 'string' ? input : JSON.stringify(input)}`
163
+ : typeof input === 'string' ? input : JSON.stringify(input);
164
+ return agentInstance.chat(prompt);
165
+ }
166
+ });
167
+ }
137
168
  /**
138
169
  * Run the workflow
139
170
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "praisonai",
3
- "version": "1.2.3",
3
+ "version": "1.3.0",
4
4
  "description": "PraisonAI TypeScript AI Agents Framework - Node.js, npm, and Javascript AI Agents Framework",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",