praisonai 1.3.0 ā 1.3.2
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.
- package/dist/agent/index.d.ts +3 -0
- package/dist/agent/index.js +8 -1
- package/dist/agent/router.d.ts +68 -4
- package/dist/agent/router.js +100 -4
- package/dist/agent/simple.d.ts +52 -1
- package/dist/agent/simple.js +124 -13
- package/dist/index.d.ts +4 -4
- package/dist/index.js +14 -7
- package/dist/llm/openai.d.ts +1 -0
- package/dist/llm/openai.js +30 -0
- package/dist/planning/index.d.ts +120 -0
- package/dist/planning/index.js +248 -1
- package/dist/telemetry/index.d.ts +73 -0
- package/dist/telemetry/index.js +101 -1
- package/package.json +1 -1
package/dist/agent/index.d.ts
CHANGED
|
@@ -4,10 +4,13 @@
|
|
|
4
4
|
* The primary exports are:
|
|
5
5
|
* - Agent: Single agent with instructions, tools, and optional persistence
|
|
6
6
|
* - Agents: Multi-agent orchestration (alias for PraisonAIAgents)
|
|
7
|
+
* - Router: Simplified keyword/pattern-based routing
|
|
7
8
|
* - Workflow: Step-based workflow execution (from workflows module)
|
|
8
9
|
*/
|
|
9
10
|
export { Agent, PraisonAIAgents, Agents } from './simple';
|
|
10
11
|
export type { SimpleAgentConfig, PraisonAIAgentsConfig } from './simple';
|
|
12
|
+
export { Router, RouterAgent, createRouter, routeConditions } from './router';
|
|
13
|
+
export type { RouterConfig, RouteConfig, RouteContext, SimpleRouterConfig, SimpleRouteConfig } from './router';
|
|
11
14
|
export { Task } from './types';
|
|
12
15
|
export type { TaskConfig, AgentConfig as TaskAgentConfig } from './types';
|
|
13
16
|
/**
|
package/dist/agent/index.js
CHANGED
|
@@ -5,16 +5,23 @@
|
|
|
5
5
|
* The primary exports are:
|
|
6
6
|
* - Agent: Single agent with instructions, tools, and optional persistence
|
|
7
7
|
* - Agents: Multi-agent orchestration (alias for PraisonAIAgents)
|
|
8
|
+
* - Router: Simplified keyword/pattern-based routing
|
|
8
9
|
* - Workflow: Step-based workflow execution (from workflows module)
|
|
9
10
|
*/
|
|
10
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
-
exports.Task = exports.Agents = exports.PraisonAIAgents = exports.Agent = void 0;
|
|
12
|
+
exports.Task = exports.routeConditions = exports.createRouter = exports.RouterAgent = exports.Router = exports.Agents = exports.PraisonAIAgents = exports.Agent = void 0;
|
|
12
13
|
exports.setTaskMode = setTaskMode;
|
|
13
14
|
// Core exports - the main API surface
|
|
14
15
|
var simple_1 = require("./simple");
|
|
15
16
|
Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return simple_1.Agent; } });
|
|
16
17
|
Object.defineProperty(exports, "PraisonAIAgents", { enumerable: true, get: function () { return simple_1.PraisonAIAgents; } });
|
|
17
18
|
Object.defineProperty(exports, "Agents", { enumerable: true, get: function () { return simple_1.Agents; } });
|
|
19
|
+
// Router exports
|
|
20
|
+
var router_1 = require("./router");
|
|
21
|
+
Object.defineProperty(exports, "Router", { enumerable: true, get: function () { return router_1.Router; } });
|
|
22
|
+
Object.defineProperty(exports, "RouterAgent", { enumerable: true, get: function () { return router_1.RouterAgent; } });
|
|
23
|
+
Object.defineProperty(exports, "createRouter", { enumerable: true, get: function () { return router_1.createRouter; } });
|
|
24
|
+
Object.defineProperty(exports, "routeConditions", { enumerable: true, get: function () { return router_1.routeConditions; } });
|
|
18
25
|
// Task support (for advanced use cases)
|
|
19
26
|
var types_1 = require("./types");
|
|
20
27
|
Object.defineProperty(exports, "Task", { enumerable: true, get: function () { return types_1.Task; } });
|
package/dist/agent/router.d.ts
CHANGED
|
@@ -1,12 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Router Agent - Route requests to specialized agents
|
|
3
|
+
*
|
|
4
|
+
* @example Simple usage (5 lines)
|
|
5
|
+
* ```typescript
|
|
6
|
+
* import { Agent, Router } from 'praisonai';
|
|
7
|
+
*
|
|
8
|
+
* const router = new Router({
|
|
9
|
+
* math: { agent: new Agent({ instructions: 'Math expert' }), keywords: ['calculate', 'math'] },
|
|
10
|
+
* code: { agent: new Agent({ instructions: 'Code expert' }), keywords: ['code', 'program'] }
|
|
11
|
+
* });
|
|
12
|
+
* await router.chat('Calculate 2+2'); // Routes to math agent
|
|
13
|
+
* ```
|
|
3
14
|
*/
|
|
4
15
|
import type { EnhancedAgent } from './enhanced';
|
|
16
|
+
import { Agent } from './simple';
|
|
17
|
+
type AnyAgent = Agent | EnhancedAgent;
|
|
5
18
|
export interface RouteConfig {
|
|
6
|
-
agent:
|
|
19
|
+
agent: AnyAgent;
|
|
7
20
|
condition: (input: string, context?: RouteContext) => boolean | Promise<boolean>;
|
|
8
21
|
priority?: number;
|
|
9
22
|
}
|
|
23
|
+
/** Simplified route definition */
|
|
24
|
+
export interface SimpleRouteConfig {
|
|
25
|
+
agent: AnyAgent;
|
|
26
|
+
keywords?: string[];
|
|
27
|
+
pattern?: RegExp;
|
|
28
|
+
priority?: number;
|
|
29
|
+
}
|
|
10
30
|
export interface RouteContext {
|
|
11
31
|
history?: string[];
|
|
12
32
|
metadata?: Record<string, any>;
|
|
@@ -14,9 +34,11 @@ export interface RouteContext {
|
|
|
14
34
|
export interface RouterConfig {
|
|
15
35
|
name?: string;
|
|
16
36
|
routes: RouteConfig[];
|
|
17
|
-
defaultAgent?:
|
|
37
|
+
defaultAgent?: AnyAgent;
|
|
18
38
|
verbose?: boolean;
|
|
19
39
|
}
|
|
40
|
+
/** Simplified router config - just a map of route name to config */
|
|
41
|
+
export type SimpleRouterConfig = Record<string, SimpleRouteConfig>;
|
|
20
42
|
/**
|
|
21
43
|
* Router Agent - Routes requests to the most appropriate agent
|
|
22
44
|
*/
|
|
@@ -30,9 +52,13 @@ export declare class RouterAgent {
|
|
|
30
52
|
* Route a request to the appropriate agent
|
|
31
53
|
*/
|
|
32
54
|
route(input: string, context?: RouteContext): Promise<{
|
|
33
|
-
agent:
|
|
55
|
+
agent: AnyAgent;
|
|
34
56
|
response: string;
|
|
35
57
|
} | null>;
|
|
58
|
+
/**
|
|
59
|
+
* Simplified chat method - routes and returns just the response
|
|
60
|
+
*/
|
|
61
|
+
chat(input: string, context?: RouteContext): Promise<string>;
|
|
36
62
|
/**
|
|
37
63
|
* Add a route
|
|
38
64
|
*/
|
|
@@ -72,6 +98,44 @@ export declare const routeConditions: {
|
|
|
72
98
|
or: (...conditions: Array<(input: string, context?: RouteContext) => boolean>) => (input: string, context?: RouteContext) => boolean;
|
|
73
99
|
};
|
|
74
100
|
/**
|
|
75
|
-
* Create a router agent
|
|
101
|
+
* Create a router agent (legacy API)
|
|
76
102
|
*/
|
|
77
103
|
export declare function createRouter(config: RouterConfig): RouterAgent;
|
|
104
|
+
/**
|
|
105
|
+
* Simplified Router class - uses keyword/pattern-based routing
|
|
106
|
+
*
|
|
107
|
+
* @example Simple usage (5 lines)
|
|
108
|
+
* ```typescript
|
|
109
|
+
* import { Agent, Router } from 'praisonai';
|
|
110
|
+
*
|
|
111
|
+
* const router = new Router({
|
|
112
|
+
* math: { agent: new Agent({ instructions: 'Math expert' }), keywords: ['calculate', 'math'] },
|
|
113
|
+
* code: { agent: new Agent({ instructions: 'Code expert' }), keywords: ['code', 'program'] }
|
|
114
|
+
* });
|
|
115
|
+
* await router.chat('Calculate 2+2'); // Routes to math agent
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
export declare class Router {
|
|
119
|
+
private routerAgent;
|
|
120
|
+
private agentMap;
|
|
121
|
+
constructor(config: SimpleRouterConfig, options?: {
|
|
122
|
+
default?: string;
|
|
123
|
+
verbose?: boolean;
|
|
124
|
+
});
|
|
125
|
+
/**
|
|
126
|
+
* Route and get response
|
|
127
|
+
*/
|
|
128
|
+
chat(input: string): Promise<string>;
|
|
129
|
+
/**
|
|
130
|
+
* Route and get full result with agent info
|
|
131
|
+
*/
|
|
132
|
+
route(input: string): Promise<{
|
|
133
|
+
agent: AnyAgent;
|
|
134
|
+
response: string;
|
|
135
|
+
} | null>;
|
|
136
|
+
/**
|
|
137
|
+
* Get agent by name
|
|
138
|
+
*/
|
|
139
|
+
getAgent(name: string): AnyAgent | undefined;
|
|
140
|
+
}
|
|
141
|
+
export {};
|
package/dist/agent/router.js
CHANGED
|
@@ -1,9 +1,20 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/**
|
|
3
3
|
* Router Agent - Route requests to specialized agents
|
|
4
|
+
*
|
|
5
|
+
* @example Simple usage (5 lines)
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import { Agent, Router } from 'praisonai';
|
|
8
|
+
*
|
|
9
|
+
* const router = new Router({
|
|
10
|
+
* math: { agent: new Agent({ instructions: 'Math expert' }), keywords: ['calculate', 'math'] },
|
|
11
|
+
* code: { agent: new Agent({ instructions: 'Code expert' }), keywords: ['code', 'program'] }
|
|
12
|
+
* });
|
|
13
|
+
* await router.chat('Calculate 2+2'); // Routes to math agent
|
|
14
|
+
* ```
|
|
4
15
|
*/
|
|
5
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.routeConditions = exports.RouterAgent = void 0;
|
|
17
|
+
exports.Router = exports.routeConditions = exports.RouterAgent = void 0;
|
|
7
18
|
exports.createRouter = createRouter;
|
|
8
19
|
/**
|
|
9
20
|
* Router Agent - Routes requests to the most appropriate agent
|
|
@@ -26,7 +37,9 @@ class RouterAgent {
|
|
|
26
37
|
console.log(`[Router] Routing to: ${route.agent.name}`);
|
|
27
38
|
}
|
|
28
39
|
const response = await route.agent.chat(input);
|
|
29
|
-
|
|
40
|
+
// Handle both Agent (returns string) and EnhancedAgent (returns ChatResult)
|
|
41
|
+
const responseText = typeof response === 'string' ? response : response.text;
|
|
42
|
+
return { agent: route.agent, response: responseText };
|
|
30
43
|
}
|
|
31
44
|
}
|
|
32
45
|
if (this.defaultAgent) {
|
|
@@ -34,10 +47,21 @@ class RouterAgent {
|
|
|
34
47
|
console.log(`[Router] Using default agent: ${this.defaultAgent.name}`);
|
|
35
48
|
}
|
|
36
49
|
const response = await this.defaultAgent.chat(input);
|
|
37
|
-
|
|
50
|
+
const responseText = typeof response === 'string' ? response : response.text;
|
|
51
|
+
return { agent: this.defaultAgent, response: responseText };
|
|
38
52
|
}
|
|
39
53
|
return null;
|
|
40
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Simplified chat method - routes and returns just the response
|
|
57
|
+
*/
|
|
58
|
+
async chat(input, context) {
|
|
59
|
+
const result = await this.route(input, context);
|
|
60
|
+
if (!result) {
|
|
61
|
+
throw new Error('No matching route found and no default agent configured');
|
|
62
|
+
}
|
|
63
|
+
return result.response;
|
|
64
|
+
}
|
|
41
65
|
/**
|
|
42
66
|
* Add a route
|
|
43
67
|
*/
|
|
@@ -106,8 +130,80 @@ exports.routeConditions = {
|
|
|
106
130
|
}
|
|
107
131
|
};
|
|
108
132
|
/**
|
|
109
|
-
* Create a router agent
|
|
133
|
+
* Create a router agent (legacy API)
|
|
110
134
|
*/
|
|
111
135
|
function createRouter(config) {
|
|
112
136
|
return new RouterAgent(config);
|
|
113
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Simplified Router class - uses keyword/pattern-based routing
|
|
140
|
+
*
|
|
141
|
+
* @example Simple usage (5 lines)
|
|
142
|
+
* ```typescript
|
|
143
|
+
* import { Agent, Router } from 'praisonai';
|
|
144
|
+
*
|
|
145
|
+
* const router = new Router({
|
|
146
|
+
* math: { agent: new Agent({ instructions: 'Math expert' }), keywords: ['calculate', 'math'] },
|
|
147
|
+
* code: { agent: new Agent({ instructions: 'Code expert' }), keywords: ['code', 'program'] }
|
|
148
|
+
* });
|
|
149
|
+
* await router.chat('Calculate 2+2'); // Routes to math agent
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
class Router {
|
|
153
|
+
constructor(config, options) {
|
|
154
|
+
this.agentMap = new Map();
|
|
155
|
+
const routes = [];
|
|
156
|
+
let defaultAgent;
|
|
157
|
+
for (const [name, routeConfig] of Object.entries(config)) {
|
|
158
|
+
this.agentMap.set(name, routeConfig.agent);
|
|
159
|
+
// Build condition from keywords or pattern
|
|
160
|
+
let condition;
|
|
161
|
+
if (routeConfig.keywords) {
|
|
162
|
+
condition = exports.routeConditions.keywords(routeConfig.keywords);
|
|
163
|
+
}
|
|
164
|
+
else if (routeConfig.pattern) {
|
|
165
|
+
condition = exports.routeConditions.pattern(routeConfig.pattern);
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
condition = exports.routeConditions.always();
|
|
169
|
+
}
|
|
170
|
+
routes.push({
|
|
171
|
+
agent: routeConfig.agent,
|
|
172
|
+
condition,
|
|
173
|
+
priority: routeConfig.priority
|
|
174
|
+
});
|
|
175
|
+
// Set default agent
|
|
176
|
+
if (options?.default === name) {
|
|
177
|
+
defaultAgent = routeConfig.agent;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// If no default specified, use first agent
|
|
181
|
+
if (!defaultAgent && routes.length > 0) {
|
|
182
|
+
defaultAgent = routes[0].agent;
|
|
183
|
+
}
|
|
184
|
+
this.routerAgent = new RouterAgent({
|
|
185
|
+
routes,
|
|
186
|
+
defaultAgent,
|
|
187
|
+
verbose: options?.verbose
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Route and get response
|
|
192
|
+
*/
|
|
193
|
+
async chat(input) {
|
|
194
|
+
return this.routerAgent.chat(input);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Route and get full result with agent info
|
|
198
|
+
*/
|
|
199
|
+
async route(input) {
|
|
200
|
+
return this.routerAgent.route(input);
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Get agent by name
|
|
204
|
+
*/
|
|
205
|
+
getAgent(name) {
|
|
206
|
+
return this.agentMap.get(name);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
exports.Router = Router;
|
package/dist/agent/simple.d.ts
CHANGED
|
@@ -62,10 +62,22 @@ export interface SimpleAgentConfig {
|
|
|
62
62
|
toolFunctions?: Record<string, Function>;
|
|
63
63
|
/** Database adapter for persistence */
|
|
64
64
|
db?: DbAdapter;
|
|
65
|
-
/** Session ID for conversation persistence */
|
|
65
|
+
/** Session ID for conversation persistence (auto-generated if not provided) */
|
|
66
66
|
sessionId?: string;
|
|
67
67
|
/** Run ID for tracing (auto-generated if not provided) */
|
|
68
68
|
runId?: string;
|
|
69
|
+
/** Max messages to restore from history (default: 100) */
|
|
70
|
+
historyLimit?: number;
|
|
71
|
+
/** Auto-restore conversation history from db (default: true) */
|
|
72
|
+
autoRestore?: boolean;
|
|
73
|
+
/** Auto-persist messages to db (default: true) */
|
|
74
|
+
autoPersist?: boolean;
|
|
75
|
+
/** Enable caching of responses */
|
|
76
|
+
cache?: boolean;
|
|
77
|
+
/** Cache TTL in seconds (default: 3600) */
|
|
78
|
+
cacheTTL?: number;
|
|
79
|
+
/** Enable telemetry tracking (default: false, opt-in) */
|
|
80
|
+
telemetry?: boolean;
|
|
69
81
|
/** Agent role (advanced mode) */
|
|
70
82
|
role?: string;
|
|
71
83
|
/** Agent goal (advanced mode) */
|
|
@@ -88,7 +100,31 @@ export declare class Agent {
|
|
|
88
100
|
private sessionId;
|
|
89
101
|
private runId;
|
|
90
102
|
private messages;
|
|
103
|
+
private dbInitialized;
|
|
104
|
+
private historyLimit;
|
|
105
|
+
private autoRestore;
|
|
106
|
+
private autoPersist;
|
|
107
|
+
private cache;
|
|
108
|
+
private cacheTTL;
|
|
109
|
+
private responseCache;
|
|
110
|
+
private telemetryEnabled;
|
|
91
111
|
constructor(config: SimpleAgentConfig);
|
|
112
|
+
/**
|
|
113
|
+
* Generate a session ID based on current hour and agent name (like Python SDK)
|
|
114
|
+
*/
|
|
115
|
+
private generateSessionId;
|
|
116
|
+
/**
|
|
117
|
+
* Initialize DB session - restore history on first chat (lazy)
|
|
118
|
+
*/
|
|
119
|
+
private initDbSession;
|
|
120
|
+
/**
|
|
121
|
+
* Get cached response if available and not expired
|
|
122
|
+
*/
|
|
123
|
+
private getCachedResponse;
|
|
124
|
+
/**
|
|
125
|
+
* Cache a response
|
|
126
|
+
*/
|
|
127
|
+
private cacheResponse;
|
|
92
128
|
private createSystemPrompt;
|
|
93
129
|
/**
|
|
94
130
|
* Register a tool function that can be called by the model
|
|
@@ -131,6 +167,21 @@ export declare class Agent {
|
|
|
131
167
|
getRunId(): string;
|
|
132
168
|
getResult(): string | null;
|
|
133
169
|
getInstructions(): string;
|
|
170
|
+
/**
|
|
171
|
+
* Get conversation history
|
|
172
|
+
*/
|
|
173
|
+
getHistory(): Array<{
|
|
174
|
+
role: string;
|
|
175
|
+
content: string | null;
|
|
176
|
+
}>;
|
|
177
|
+
/**
|
|
178
|
+
* Clear conversation history (in memory and optionally in DB)
|
|
179
|
+
*/
|
|
180
|
+
clearHistory(clearDb?: boolean): Promise<void>;
|
|
181
|
+
/**
|
|
182
|
+
* Clear response cache
|
|
183
|
+
*/
|
|
184
|
+
clearCache(): void;
|
|
134
185
|
}
|
|
135
186
|
/**
|
|
136
187
|
* Configuration for multi-agent orchestration
|
package/dist/agent/simple.js
CHANGED
|
@@ -8,6 +8,8 @@ class Agent {
|
|
|
8
8
|
constructor(config) {
|
|
9
9
|
this.toolFunctions = {};
|
|
10
10
|
this.messages = [];
|
|
11
|
+
this.dbInitialized = false;
|
|
12
|
+
this.responseCache = new Map();
|
|
11
13
|
// Build instructions from either simple or advanced mode
|
|
12
14
|
if (config.instructions) {
|
|
13
15
|
this.instructions = config.instructions;
|
|
@@ -34,8 +36,14 @@ class Agent {
|
|
|
34
36
|
this.stream = config.stream ?? true;
|
|
35
37
|
this.tools = config.tools;
|
|
36
38
|
this.dbAdapter = config.db;
|
|
37
|
-
this.sessionId = config.sessionId ||
|
|
39
|
+
this.sessionId = config.sessionId || this.generateSessionId();
|
|
38
40
|
this.runId = config.runId || (0, crypto_1.randomUUID)();
|
|
41
|
+
this.historyLimit = config.historyLimit ?? 100;
|
|
42
|
+
this.autoRestore = config.autoRestore ?? true;
|
|
43
|
+
this.autoPersist = config.autoPersist ?? true;
|
|
44
|
+
this.cache = config.cache ?? false;
|
|
45
|
+
this.cacheTTL = config.cacheTTL ?? 3600;
|
|
46
|
+
this.telemetryEnabled = config.telemetry ?? false;
|
|
39
47
|
this.llmService = new openai_1.OpenAIService(this.llm);
|
|
40
48
|
// Configure logging
|
|
41
49
|
logger_1.Logger.setVerbose(this.verbose);
|
|
@@ -85,6 +93,65 @@ class Agent {
|
|
|
85
93
|
}
|
|
86
94
|
}
|
|
87
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* Generate a session ID based on current hour and agent name (like Python SDK)
|
|
98
|
+
*/
|
|
99
|
+
generateSessionId() {
|
|
100
|
+
const now = new Date();
|
|
101
|
+
const hourStr = now.toISOString().slice(0, 13).replace(/[-T:]/g, '');
|
|
102
|
+
const hash = this.name ? this.name.slice(0, 6) : 'agent';
|
|
103
|
+
return `${hourStr}-${hash}`;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Initialize DB session - restore history on first chat (lazy)
|
|
107
|
+
*/
|
|
108
|
+
async initDbSession() {
|
|
109
|
+
if (this.dbInitialized || !this.dbAdapter || !this.autoRestore)
|
|
110
|
+
return;
|
|
111
|
+
try {
|
|
112
|
+
// Restore previous messages from DB
|
|
113
|
+
const history = await this.dbAdapter.getMessages(this.sessionId, this.historyLimit);
|
|
114
|
+
if (history.length > 0) {
|
|
115
|
+
this.messages = history.map(m => ({
|
|
116
|
+
role: m.role,
|
|
117
|
+
content: m.content
|
|
118
|
+
}));
|
|
119
|
+
logger_1.Logger.debug(`Restored ${history.length} messages from session ${this.sessionId}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
logger_1.Logger.warn('Failed to initialize DB session:', error);
|
|
124
|
+
}
|
|
125
|
+
this.dbInitialized = true;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Get cached response if available and not expired
|
|
129
|
+
*/
|
|
130
|
+
getCachedResponse(prompt) {
|
|
131
|
+
if (!this.cache)
|
|
132
|
+
return null;
|
|
133
|
+
const cacheKey = `${this.sessionId}:${prompt}`;
|
|
134
|
+
const cached = this.responseCache.get(cacheKey);
|
|
135
|
+
if (cached) {
|
|
136
|
+
const age = (Date.now() - cached.timestamp) / 1000;
|
|
137
|
+
if (age < this.cacheTTL) {
|
|
138
|
+
logger_1.Logger.debug('Cache hit for prompt');
|
|
139
|
+
return cached.response;
|
|
140
|
+
}
|
|
141
|
+
// Expired, remove it
|
|
142
|
+
this.responseCache.delete(cacheKey);
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Cache a response
|
|
148
|
+
*/
|
|
149
|
+
cacheResponse(prompt, response) {
|
|
150
|
+
if (!this.cache)
|
|
151
|
+
return;
|
|
152
|
+
const cacheKey = `${this.sessionId}:${prompt}`;
|
|
153
|
+
this.responseCache.set(cacheKey, { response, timestamp: Date.now() });
|
|
154
|
+
}
|
|
88
155
|
createSystemPrompt() {
|
|
89
156
|
let prompt = this.instructions;
|
|
90
157
|
if (this.markdown) {
|
|
@@ -210,20 +277,24 @@ class Agent {
|
|
|
210
277
|
if (previousResult) {
|
|
211
278
|
prompt = prompt.replace('{{previous}}', previousResult);
|
|
212
279
|
}
|
|
213
|
-
// Initialize messages array
|
|
280
|
+
// Initialize messages array with system prompt and conversation history
|
|
214
281
|
const messages = [
|
|
215
|
-
{ role: 'system', content: this.createSystemPrompt() }
|
|
216
|
-
{ role: 'user', content: prompt }
|
|
282
|
+
{ role: 'system', content: this.createSystemPrompt() }
|
|
217
283
|
];
|
|
284
|
+
// Add conversation history (excluding the current prompt which will be added below)
|
|
285
|
+
for (const msg of this.messages) {
|
|
286
|
+
if (msg.role && msg.content) {
|
|
287
|
+
messages.push({ role: msg.role, content: msg.content });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// Add current user prompt
|
|
291
|
+
messages.push({ role: 'user', content: prompt });
|
|
218
292
|
let finalResponse = '';
|
|
219
293
|
if (this.stream && !this.tools) {
|
|
220
|
-
// Use streaming
|
|
221
|
-
|
|
222
|
-
await this.llmService.streamText(prompt, this.createSystemPrompt(), 0.7, (token) => {
|
|
294
|
+
// Use streaming with full conversation history
|
|
295
|
+
finalResponse = await this.llmService.streamChat(messages, 0.7, (token) => {
|
|
223
296
|
process.stdout.write(token);
|
|
224
|
-
fullResponse += token;
|
|
225
297
|
});
|
|
226
|
-
finalResponse = fullResponse;
|
|
227
298
|
}
|
|
228
299
|
else if (this.tools) {
|
|
229
300
|
// Use tools (non-streaming for now to simplify implementation)
|
|
@@ -272,15 +343,28 @@ class Agent {
|
|
|
272
343
|
}
|
|
273
344
|
}
|
|
274
345
|
async chat(prompt, previousResult) {
|
|
275
|
-
//
|
|
276
|
-
|
|
346
|
+
// Lazy init: restore history on first chat (like Python SDK)
|
|
347
|
+
await this.initDbSession();
|
|
348
|
+
// Check cache first
|
|
349
|
+
const cached = this.getCachedResponse(prompt);
|
|
350
|
+
if (cached) {
|
|
351
|
+
return cached;
|
|
352
|
+
}
|
|
353
|
+
// Add user message to conversation history
|
|
354
|
+
this.messages.push({ role: 'user', content: prompt });
|
|
355
|
+
// Persist user message if db is configured and autoPersist is enabled
|
|
356
|
+
if (this.dbAdapter && this.autoPersist) {
|
|
277
357
|
await this.persistMessage('user', prompt);
|
|
278
358
|
}
|
|
279
359
|
const response = await this.start(prompt, previousResult);
|
|
280
|
-
//
|
|
281
|
-
|
|
360
|
+
// Add assistant response to history
|
|
361
|
+
this.messages.push({ role: 'assistant', content: response });
|
|
362
|
+
// Persist assistant response if db is configured and autoPersist is enabled
|
|
363
|
+
if (this.dbAdapter && this.autoPersist) {
|
|
282
364
|
await this.persistMessage('assistant', response);
|
|
283
365
|
}
|
|
366
|
+
// Cache the response
|
|
367
|
+
this.cacheResponse(prompt, response);
|
|
284
368
|
return response;
|
|
285
369
|
}
|
|
286
370
|
async execute(previousResult) {
|
|
@@ -326,6 +410,33 @@ class Agent {
|
|
|
326
410
|
getInstructions() {
|
|
327
411
|
return this.instructions;
|
|
328
412
|
}
|
|
413
|
+
/**
|
|
414
|
+
* Get conversation history
|
|
415
|
+
*/
|
|
416
|
+
getHistory() {
|
|
417
|
+
return [...this.messages];
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Clear conversation history (in memory and optionally in DB)
|
|
421
|
+
*/
|
|
422
|
+
async clearHistory(clearDb = true) {
|
|
423
|
+
this.messages = [];
|
|
424
|
+
if (clearDb && this.dbAdapter) {
|
|
425
|
+
try {
|
|
426
|
+
await this.dbAdapter.deleteMessages(this.sessionId);
|
|
427
|
+
logger_1.Logger.debug(`Cleared history for session ${this.sessionId}`);
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
logger_1.Logger.warn('Failed to clear DB history:', error);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Clear response cache
|
|
436
|
+
*/
|
|
437
|
+
clearCache() {
|
|
438
|
+
this.responseCache.clear();
|
|
439
|
+
}
|
|
329
440
|
}
|
|
330
441
|
exports.Agent = Agent;
|
|
331
442
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -36,8 +36,8 @@
|
|
|
36
36
|
* await agents.start();
|
|
37
37
|
* ```
|
|
38
38
|
*/
|
|
39
|
-
export { Agent, Agents, PraisonAIAgents } from './agent';
|
|
40
|
-
export type { SimpleAgentConfig, PraisonAIAgentsConfig } from './agent';
|
|
39
|
+
export { Agent, Agents, PraisonAIAgents, Router } from './agent';
|
|
40
|
+
export type { SimpleAgentConfig, PraisonAIAgentsConfig, SimpleRouterConfig, SimpleRouteConfig } from './agent';
|
|
41
41
|
export { Workflow, parallel, route, loop, repeat } from './workflows';
|
|
42
42
|
export type { WorkflowStep, WorkflowContext, StepResult } from './workflows';
|
|
43
43
|
export { db, createDbAdapter, getDefaultDbAdapter, setDefaultDbAdapter } from './db';
|
|
@@ -61,14 +61,14 @@ export { Memory, createMemory } from './memory/memory';
|
|
|
61
61
|
export type { MemoryEntry, MemoryConfig } from './memory/memory';
|
|
62
62
|
export { FileMemory, createFileMemory, type FileMemoryConfig, type FileMemoryEntry } from './memory/file-memory';
|
|
63
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';
|
|
64
|
-
export { TelemetryCollector, getTelemetry, enableTelemetry, disableTelemetry, cleanupTelemetry, type TelemetryEvent, type TelemetryConfig } from './telemetry';
|
|
64
|
+
export { TelemetryCollector, AgentTelemetry, getTelemetry, enableTelemetry, disableTelemetry, cleanupTelemetry, createAgentTelemetry, type TelemetryEvent, type TelemetryConfig, type AgentStats } from './telemetry';
|
|
65
65
|
export { AutoAgents, createAutoAgents, type AgentConfig, type TaskConfig, type TeamStructure, type AutoAgentsConfig } from './auto';
|
|
66
66
|
export { ImageAgent, createImageAgent, type ImageAgentConfig, type ImageGenerationConfig, type ImageAnalysisConfig } from './agent/image';
|
|
67
67
|
export { DeepResearchAgent, createDeepResearchAgent, type DeepResearchConfig, type ResearchResponse, type Citation, type ReasoningStep } from './agent/research';
|
|
68
68
|
export { QueryRewriterAgent, createQueryRewriterAgent, type QueryRewriterConfig, type RewriteResult, type RewriteStrategy } from './agent/query-rewriter';
|
|
69
69
|
export { PromptExpanderAgent, createPromptExpanderAgent, type PromptExpanderConfig, type ExpandResult, type ExpandStrategy } from './agent/prompt-expander';
|
|
70
70
|
export { LLMGuardrail, createLLMGuardrail, type LLMGuardrailConfig, type LLMGuardrailResult } from './guardrails/llm-guardrail';
|
|
71
|
-
export { Plan, PlanStep, TodoList, TodoItem, PlanStorage, createPlan, createTodoList, createPlanStorage, type PlanConfig, type PlanStepConfig, type TodoItemConfig, type PlanStatus, type TodoStatus } from './planning';
|
|
71
|
+
export { Plan, PlanStep, TodoList, TodoItem, PlanStorage, PlanningAgent, TaskAgent, createPlan, createTodoList, createPlanStorage, createPlanningAgent, createTaskAgent, type PlanConfig, type PlanStepConfig, type TodoItemConfig, type PlanStatus, type TodoStatus, type PlanningAgentConfig, type PlanResult } from './planning';
|
|
72
72
|
export { BaseCache, MemoryCache, FileCache, createMemoryCache, createFileCache, type CacheConfig, type CacheEntry } from './cache';
|
|
73
73
|
export { PubSub, EventEmitterPubSub, AgentEventBus, AgentEvents, createEventBus, createPubSub, type Event, type EventHandler } from './events';
|
|
74
74
|
export { parseYAMLWorkflow, createWorkflowFromYAML, loadWorkflowFromFile, validateWorkflowDefinition, type YAMLWorkflowDefinition, type YAMLStepDefinition, type ParsedWorkflow } from './workflows/yaml-parser';
|
package/dist/index.js
CHANGED
|
@@ -52,11 +52,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
52
52
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
53
53
|
};
|
|
54
54
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
|
-
exports.
|
|
56
|
-
exports.
|
|
57
|
-
exports.
|
|
58
|
-
exports.
|
|
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;
|
|
55
|
+
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.Router = exports.PraisonAIAgents = exports.Agents = exports.Agent = void 0;
|
|
56
|
+
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.createTaskAgent = exports.createPlanningAgent = exports.createPlanStorage = exports.createTodoList = exports.createPlan = exports.TaskAgent = exports.PlanningAgent = 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.createAgentTelemetry = exports.cleanupTelemetry = exports.disableTelemetry = exports.enableTelemetry = exports.getTelemetry = exports.AgentTelemetry = exports.TelemetryCollector = exports.DEFAULT_POLICIES = exports.createLLMSummarizer = exports.createAutoMemory = void 0;
|
|
57
|
+
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 = exports.MemoryPostgresAdapter = exports.NeonPostgresAdapter = exports.createMemoryRedis = exports.createUpstashRedis = exports.MemoryRedisAdapter = exports.UpstashRedisAdapter = exports.createSQLiteAdapter = void 0;
|
|
58
|
+
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 = exports.parseSlashCommand = exports.registerCommand = exports.createSlashCommandHandler = exports.SlashCommandHandler = exports.BaseProvider = exports.GoogleProvider = exports.AnthropicProvider = 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 = exports.GeminiCliAgent = exports.ClaudeCodeAgent = exports.BaseExternalAgent = exports.renderWorkflow = exports.createFlowDisplay = exports.FlowDisplay = exports.createFileCheckpointStorage = void 0;
|
|
60
60
|
// ============================================================================
|
|
61
61
|
// CORE API - The main classes users should use
|
|
62
62
|
// ============================================================================
|
|
@@ -65,6 +65,7 @@ var agent_1 = require("./agent");
|
|
|
65
65
|
Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return agent_1.Agent; } });
|
|
66
66
|
Object.defineProperty(exports, "Agents", { enumerable: true, get: function () { return agent_1.Agents; } });
|
|
67
67
|
Object.defineProperty(exports, "PraisonAIAgents", { enumerable: true, get: function () { return agent_1.PraisonAIAgents; } });
|
|
68
|
+
Object.defineProperty(exports, "Router", { enumerable: true, get: function () { return agent_1.Router; } });
|
|
68
69
|
// Workflow - Step-based workflow execution
|
|
69
70
|
var workflows_1 = require("./workflows");
|
|
70
71
|
Object.defineProperty(exports, "Workflow", { enumerable: true, get: function () { return workflows_1.Workflow; } });
|
|
@@ -162,13 +163,15 @@ Object.defineProperty(exports, "AutoMemory", { enumerable: true, get: function (
|
|
|
162
163
|
Object.defineProperty(exports, "createAutoMemory", { enumerable: true, get: function () { return auto_memory_1.createAutoMemory; } });
|
|
163
164
|
Object.defineProperty(exports, "createLLMSummarizer", { enumerable: true, get: function () { return auto_memory_1.createLLMSummarizer; } });
|
|
164
165
|
Object.defineProperty(exports, "DEFAULT_POLICIES", { enumerable: true, get: function () { return auto_memory_1.DEFAULT_POLICIES; } });
|
|
165
|
-
// Export Telemetry
|
|
166
|
+
// Export Telemetry (Agent-focused)
|
|
166
167
|
var telemetry_1 = require("./telemetry");
|
|
167
168
|
Object.defineProperty(exports, "TelemetryCollector", { enumerable: true, get: function () { return telemetry_1.TelemetryCollector; } });
|
|
169
|
+
Object.defineProperty(exports, "AgentTelemetry", { enumerable: true, get: function () { return telemetry_1.AgentTelemetry; } });
|
|
168
170
|
Object.defineProperty(exports, "getTelemetry", { enumerable: true, get: function () { return telemetry_1.getTelemetry; } });
|
|
169
171
|
Object.defineProperty(exports, "enableTelemetry", { enumerable: true, get: function () { return telemetry_1.enableTelemetry; } });
|
|
170
172
|
Object.defineProperty(exports, "disableTelemetry", { enumerable: true, get: function () { return telemetry_1.disableTelemetry; } });
|
|
171
173
|
Object.defineProperty(exports, "cleanupTelemetry", { enumerable: true, get: function () { return telemetry_1.cleanupTelemetry; } });
|
|
174
|
+
Object.defineProperty(exports, "createAgentTelemetry", { enumerable: true, get: function () { return telemetry_1.createAgentTelemetry; } });
|
|
172
175
|
// Export AutoAgents
|
|
173
176
|
var auto_1 = require("./auto");
|
|
174
177
|
Object.defineProperty(exports, "AutoAgents", { enumerable: true, get: function () { return auto_1.AutoAgents; } });
|
|
@@ -193,16 +196,20 @@ Object.defineProperty(exports, "createPromptExpanderAgent", { enumerable: true,
|
|
|
193
196
|
var llm_guardrail_1 = require("./guardrails/llm-guardrail");
|
|
194
197
|
Object.defineProperty(exports, "LLMGuardrail", { enumerable: true, get: function () { return llm_guardrail_1.LLMGuardrail; } });
|
|
195
198
|
Object.defineProperty(exports, "createLLMGuardrail", { enumerable: true, get: function () { return llm_guardrail_1.createLLMGuardrail; } });
|
|
196
|
-
// Export Planning
|
|
199
|
+
// Export Planning (simplified API)
|
|
197
200
|
var planning_1 = require("./planning");
|
|
198
201
|
Object.defineProperty(exports, "Plan", { enumerable: true, get: function () { return planning_1.Plan; } });
|
|
199
202
|
Object.defineProperty(exports, "PlanStep", { enumerable: true, get: function () { return planning_1.PlanStep; } });
|
|
200
203
|
Object.defineProperty(exports, "TodoList", { enumerable: true, get: function () { return planning_1.TodoList; } });
|
|
201
204
|
Object.defineProperty(exports, "TodoItem", { enumerable: true, get: function () { return planning_1.TodoItem; } });
|
|
202
205
|
Object.defineProperty(exports, "PlanStorage", { enumerable: true, get: function () { return planning_1.PlanStorage; } });
|
|
206
|
+
Object.defineProperty(exports, "PlanningAgent", { enumerable: true, get: function () { return planning_1.PlanningAgent; } });
|
|
207
|
+
Object.defineProperty(exports, "TaskAgent", { enumerable: true, get: function () { return planning_1.TaskAgent; } });
|
|
203
208
|
Object.defineProperty(exports, "createPlan", { enumerable: true, get: function () { return planning_1.createPlan; } });
|
|
204
209
|
Object.defineProperty(exports, "createTodoList", { enumerable: true, get: function () { return planning_1.createTodoList; } });
|
|
205
210
|
Object.defineProperty(exports, "createPlanStorage", { enumerable: true, get: function () { return planning_1.createPlanStorage; } });
|
|
211
|
+
Object.defineProperty(exports, "createPlanningAgent", { enumerable: true, get: function () { return planning_1.createPlanningAgent; } });
|
|
212
|
+
Object.defineProperty(exports, "createTaskAgent", { enumerable: true, get: function () { return planning_1.createTaskAgent; } });
|
|
206
213
|
// Export Cache
|
|
207
214
|
var cache_1 = require("./cache");
|
|
208
215
|
Object.defineProperty(exports, "BaseCache", { enumerable: true, get: function () { return cache_1.BaseCache; } });
|
package/dist/llm/openai.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ export declare class OpenAIService {
|
|
|
33
33
|
generateText(prompt: string, systemPrompt?: string, temperature?: number, tools?: ChatCompletionTool[], tool_choice?: ChatCompletionToolChoiceOption): Promise<string>;
|
|
34
34
|
generateChat(messages: ChatMessage[], temperature?: number, tools?: ChatCompletionTool[], tool_choice?: ChatCompletionToolChoiceOption): Promise<LLMResponse>;
|
|
35
35
|
streamText(prompt: string, systemPrompt: string | undefined, temperature: number | undefined, onToken: (token: string) => void, tools?: ChatCompletionTool[], tool_choice?: ChatCompletionToolChoiceOption, onToolCall?: (toolCall: any) => void): Promise<void>;
|
|
36
|
+
streamChat(messages: ChatMessage[], temperature: number | undefined, onToken: (token: string) => void): Promise<string>;
|
|
36
37
|
chatCompletion(messages: ChatMessage[], temperature?: number, tools?: ChatCompletionTool[], tool_choice?: ChatCompletionToolChoiceOption): Promise<LLMResponse>;
|
|
37
38
|
}
|
|
38
39
|
export {};
|
package/dist/llm/openai.js
CHANGED
|
@@ -230,6 +230,36 @@ class OpenAIService {
|
|
|
230
230
|
throw error;
|
|
231
231
|
}
|
|
232
232
|
}
|
|
233
|
+
async streamChat(messages, temperature = 0.7, onToken) {
|
|
234
|
+
await logger_1.Logger.debug('Starting chat stream with messages...', {
|
|
235
|
+
model: this.model,
|
|
236
|
+
messageCount: messages.length
|
|
237
|
+
});
|
|
238
|
+
try {
|
|
239
|
+
const openAIMessages = messages.map(convertToOpenAIMessage);
|
|
240
|
+
const stream = await this.getClient().then(client => client.chat.completions.create({
|
|
241
|
+
model: this.model,
|
|
242
|
+
temperature,
|
|
243
|
+
messages: openAIMessages,
|
|
244
|
+
stream: true
|
|
245
|
+
}));
|
|
246
|
+
let fullResponse = '';
|
|
247
|
+
for await (const chunk of stream) {
|
|
248
|
+
const delta = chunk.choices[0]?.delta;
|
|
249
|
+
if (delta?.content) {
|
|
250
|
+
const token = delta.content;
|
|
251
|
+
fullResponse += token;
|
|
252
|
+
onToken(token);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
await logger_1.Logger.debug('Chat stream completed');
|
|
256
|
+
return fullResponse;
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
await logger_1.Logger.error('Error in chat stream', error);
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
233
263
|
async chatCompletion(messages, temperature = 0.7, tools, tool_choice) {
|
|
234
264
|
await logger_1.Logger.startSpinner('Chat completion with OpenAI...');
|
|
235
265
|
try {
|
package/dist/planning/index.d.ts
CHANGED
|
@@ -131,3 +131,123 @@ export declare function createTodoList(name?: string): TodoList;
|
|
|
131
131
|
* Create a PlanStorage
|
|
132
132
|
*/
|
|
133
133
|
export declare function createPlanStorage(): PlanStorage;
|
|
134
|
+
/**
|
|
135
|
+
* PlanningAgent - Agent with built-in planning capabilities
|
|
136
|
+
*
|
|
137
|
+
* @example Simple usage (4 lines)
|
|
138
|
+
* ```typescript
|
|
139
|
+
* import { PlanningAgent } from 'praisonai';
|
|
140
|
+
*
|
|
141
|
+
* const agent = new PlanningAgent({ instructions: 'You break down tasks into steps' });
|
|
142
|
+
* const result = await agent.planAndExecute('Build a web scraper');
|
|
143
|
+
* console.log(result.plan); // The plan that was created
|
|
144
|
+
* console.log(result.results); // Results from each step
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export interface PlanningAgentConfig {
|
|
148
|
+
instructions?: string;
|
|
149
|
+
name?: string;
|
|
150
|
+
llm?: string;
|
|
151
|
+
verbose?: boolean;
|
|
152
|
+
maxSteps?: number;
|
|
153
|
+
}
|
|
154
|
+
export interface PlanResult {
|
|
155
|
+
plan: Plan;
|
|
156
|
+
results: string[];
|
|
157
|
+
success: boolean;
|
|
158
|
+
}
|
|
159
|
+
export declare class PlanningAgent {
|
|
160
|
+
private config;
|
|
161
|
+
private agent;
|
|
162
|
+
private currentPlan;
|
|
163
|
+
constructor(config?: PlanningAgentConfig);
|
|
164
|
+
private getAgent;
|
|
165
|
+
/**
|
|
166
|
+
* Create a plan for a task
|
|
167
|
+
*/
|
|
168
|
+
createPlan(task: string): Promise<Plan>;
|
|
169
|
+
/**
|
|
170
|
+
* Execute a single step
|
|
171
|
+
*/
|
|
172
|
+
executeStep(step: PlanStep): Promise<string>;
|
|
173
|
+
/**
|
|
174
|
+
* Plan and execute a task in one call
|
|
175
|
+
*/
|
|
176
|
+
planAndExecute(task: string): Promise<PlanResult>;
|
|
177
|
+
/**
|
|
178
|
+
* Get the current plan
|
|
179
|
+
*/
|
|
180
|
+
getPlan(): Plan | null;
|
|
181
|
+
/**
|
|
182
|
+
* Simple chat (without planning)
|
|
183
|
+
*/
|
|
184
|
+
chat(message: string): Promise<string>;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Create a planning agent
|
|
188
|
+
*/
|
|
189
|
+
export declare function createPlanningAgent(config?: PlanningAgentConfig): PlanningAgent;
|
|
190
|
+
/**
|
|
191
|
+
* TaskAgent - Agent with built-in todo list management
|
|
192
|
+
*
|
|
193
|
+
* @example Simple usage (4 lines)
|
|
194
|
+
* ```typescript
|
|
195
|
+
* import { TaskAgent } from 'praisonai';
|
|
196
|
+
*
|
|
197
|
+
* const agent = new TaskAgent();
|
|
198
|
+
* await agent.addTask('Fix critical bug', 'high');
|
|
199
|
+
* await agent.addTask('Write docs', 'medium');
|
|
200
|
+
* console.log(agent.getPendingTasks());
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
export declare class TaskAgent {
|
|
204
|
+
private todos;
|
|
205
|
+
private agent;
|
|
206
|
+
private config;
|
|
207
|
+
constructor(config?: {
|
|
208
|
+
name?: string;
|
|
209
|
+
llm?: string;
|
|
210
|
+
verbose?: boolean;
|
|
211
|
+
});
|
|
212
|
+
private getAgent;
|
|
213
|
+
/**
|
|
214
|
+
* Add a task
|
|
215
|
+
*/
|
|
216
|
+
addTask(content: string, priority?: 'low' | 'medium' | 'high'): TodoItem;
|
|
217
|
+
/**
|
|
218
|
+
* Complete a task by content (partial match)
|
|
219
|
+
*/
|
|
220
|
+
completeTask(contentMatch: string): boolean;
|
|
221
|
+
/**
|
|
222
|
+
* Get pending tasks
|
|
223
|
+
*/
|
|
224
|
+
getPendingTasks(): TodoItem[];
|
|
225
|
+
/**
|
|
226
|
+
* Get all tasks
|
|
227
|
+
*/
|
|
228
|
+
getAllTasks(): TodoItem[];
|
|
229
|
+
/**
|
|
230
|
+
* Get progress
|
|
231
|
+
*/
|
|
232
|
+
getProgress(): {
|
|
233
|
+
completed: number;
|
|
234
|
+
total: number;
|
|
235
|
+
percentage: number;
|
|
236
|
+
};
|
|
237
|
+
/**
|
|
238
|
+
* Clear all tasks
|
|
239
|
+
*/
|
|
240
|
+
clearTasks(): void;
|
|
241
|
+
/**
|
|
242
|
+
* Chat with AI about tasks
|
|
243
|
+
*/
|
|
244
|
+
chat(message: string): Promise<string>;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Create a task agent
|
|
248
|
+
*/
|
|
249
|
+
export declare function createTaskAgent(config?: {
|
|
250
|
+
name?: string;
|
|
251
|
+
llm?: string;
|
|
252
|
+
verbose?: boolean;
|
|
253
|
+
}): TaskAgent;
|
package/dist/planning/index.js
CHANGED
|
@@ -2,11 +2,46 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Planning System - Plans, Steps, and TodoLists
|
|
4
4
|
*/
|
|
5
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
6
|
+
if (k2 === undefined) k2 = k;
|
|
7
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
8
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
9
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
10
|
+
}
|
|
11
|
+
Object.defineProperty(o, k2, desc);
|
|
12
|
+
}) : (function(o, m, k, k2) {
|
|
13
|
+
if (k2 === undefined) k2 = k;
|
|
14
|
+
o[k2] = m[k];
|
|
15
|
+
}));
|
|
16
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
17
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
18
|
+
}) : function(o, v) {
|
|
19
|
+
o["default"] = v;
|
|
20
|
+
});
|
|
21
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
22
|
+
var ownKeys = function(o) {
|
|
23
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
24
|
+
var ar = [];
|
|
25
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
26
|
+
return ar;
|
|
27
|
+
};
|
|
28
|
+
return ownKeys(o);
|
|
29
|
+
};
|
|
30
|
+
return function (mod) {
|
|
31
|
+
if (mod && mod.__esModule) return mod;
|
|
32
|
+
var result = {};
|
|
33
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
34
|
+
__setModuleDefault(result, mod);
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
})();
|
|
5
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.PlanStorage = exports.TodoList = exports.TodoItem = exports.Plan = exports.PlanStep = void 0;
|
|
39
|
+
exports.TaskAgent = exports.PlanningAgent = exports.PlanStorage = exports.TodoList = exports.TodoItem = exports.Plan = exports.PlanStep = void 0;
|
|
7
40
|
exports.createPlan = createPlan;
|
|
8
41
|
exports.createTodoList = createTodoList;
|
|
9
42
|
exports.createPlanStorage = createPlanStorage;
|
|
43
|
+
exports.createPlanningAgent = createPlanningAgent;
|
|
44
|
+
exports.createTaskAgent = createTaskAgent;
|
|
10
45
|
/**
|
|
11
46
|
* PlanStep - A single step in a plan
|
|
12
47
|
*/
|
|
@@ -226,3 +261,215 @@ function createTodoList(name) {
|
|
|
226
261
|
function createPlanStorage() {
|
|
227
262
|
return new PlanStorage();
|
|
228
263
|
}
|
|
264
|
+
// Import Agent dynamically to avoid circular dependency
|
|
265
|
+
let AgentClass = null;
|
|
266
|
+
async function getAgentClass() {
|
|
267
|
+
if (!AgentClass) {
|
|
268
|
+
const { Agent } = await Promise.resolve().then(() => __importStar(require('../agent/simple')));
|
|
269
|
+
AgentClass = Agent;
|
|
270
|
+
}
|
|
271
|
+
return AgentClass;
|
|
272
|
+
}
|
|
273
|
+
class PlanningAgent {
|
|
274
|
+
constructor(config = {}) {
|
|
275
|
+
this.agent = null;
|
|
276
|
+
this.currentPlan = null;
|
|
277
|
+
this.config = {
|
|
278
|
+
instructions: config.instructions || 'You are a planning agent that breaks down complex tasks into steps.',
|
|
279
|
+
name: config.name || 'PlanningAgent',
|
|
280
|
+
llm: config.llm,
|
|
281
|
+
verbose: config.verbose ?? true,
|
|
282
|
+
maxSteps: config.maxSteps ?? 10
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
async getAgent() {
|
|
286
|
+
if (!this.agent) {
|
|
287
|
+
const Agent = await getAgentClass();
|
|
288
|
+
this.agent = new Agent({
|
|
289
|
+
name: this.config.name,
|
|
290
|
+
instructions: this.config.instructions,
|
|
291
|
+
llm: this.config.llm,
|
|
292
|
+
verbose: this.config.verbose
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
return this.agent;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Create a plan for a task
|
|
299
|
+
*/
|
|
300
|
+
async createPlan(task) {
|
|
301
|
+
const agent = await this.getAgent();
|
|
302
|
+
const planPrompt = `Create a step-by-step plan for: ${task}
|
|
303
|
+
|
|
304
|
+
Return ONLY a numbered list of steps, one per line. Example:
|
|
305
|
+
1. First step
|
|
306
|
+
2. Second step
|
|
307
|
+
3. Third step`;
|
|
308
|
+
const response = await agent.chat(planPrompt);
|
|
309
|
+
// Parse the response into steps
|
|
310
|
+
const plan = new Plan({ name: task });
|
|
311
|
+
const lines = response.split('\n').filter((l) => l.trim());
|
|
312
|
+
for (const line of lines) {
|
|
313
|
+
// Extract step description (remove numbering)
|
|
314
|
+
const match = line.match(/^\d+[\.\)]\s*(.+)/);
|
|
315
|
+
if (match) {
|
|
316
|
+
plan.addStep(new PlanStep({ description: match[1].trim() }));
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
this.currentPlan = plan;
|
|
320
|
+
return plan;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Execute a single step
|
|
324
|
+
*/
|
|
325
|
+
async executeStep(step) {
|
|
326
|
+
const agent = await this.getAgent();
|
|
327
|
+
step.start();
|
|
328
|
+
try {
|
|
329
|
+
const response = await agent.chat(`Execute this step: ${step.description}`);
|
|
330
|
+
step.complete();
|
|
331
|
+
return response;
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
step.fail();
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Plan and execute a task in one call
|
|
340
|
+
*/
|
|
341
|
+
async planAndExecute(task) {
|
|
342
|
+
const plan = await this.createPlan(task);
|
|
343
|
+
const results = [];
|
|
344
|
+
let success = true;
|
|
345
|
+
plan.start();
|
|
346
|
+
for (const step of plan.steps.slice(0, this.config.maxSteps)) {
|
|
347
|
+
try {
|
|
348
|
+
if (this.config.verbose) {
|
|
349
|
+
console.log(`[${plan.getProgress().percentage}%] Executing: ${step.description}`);
|
|
350
|
+
}
|
|
351
|
+
const result = await this.executeStep(step);
|
|
352
|
+
results.push(result);
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
success = false;
|
|
356
|
+
results.push(`Error: ${error}`);
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (success) {
|
|
361
|
+
plan.complete();
|
|
362
|
+
}
|
|
363
|
+
return { plan, results, success };
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Get the current plan
|
|
367
|
+
*/
|
|
368
|
+
getPlan() {
|
|
369
|
+
return this.currentPlan;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Simple chat (without planning)
|
|
373
|
+
*/
|
|
374
|
+
async chat(message) {
|
|
375
|
+
const agent = await this.getAgent();
|
|
376
|
+
return agent.chat(message);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
exports.PlanningAgent = PlanningAgent;
|
|
380
|
+
/**
|
|
381
|
+
* Create a planning agent
|
|
382
|
+
*/
|
|
383
|
+
function createPlanningAgent(config) {
|
|
384
|
+
return new PlanningAgent(config);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* TaskAgent - Agent with built-in todo list management
|
|
388
|
+
*
|
|
389
|
+
* @example Simple usage (4 lines)
|
|
390
|
+
* ```typescript
|
|
391
|
+
* import { TaskAgent } from 'praisonai';
|
|
392
|
+
*
|
|
393
|
+
* const agent = new TaskAgent();
|
|
394
|
+
* await agent.addTask('Fix critical bug', 'high');
|
|
395
|
+
* await agent.addTask('Write docs', 'medium');
|
|
396
|
+
* console.log(agent.getPendingTasks());
|
|
397
|
+
* ```
|
|
398
|
+
*/
|
|
399
|
+
class TaskAgent {
|
|
400
|
+
constructor(config) {
|
|
401
|
+
this.agent = null;
|
|
402
|
+
this.todos = new TodoList('Agent Tasks');
|
|
403
|
+
this.config = config || {};
|
|
404
|
+
}
|
|
405
|
+
async getAgent() {
|
|
406
|
+
if (!this.agent) {
|
|
407
|
+
const Agent = await getAgentClass();
|
|
408
|
+
this.agent = new Agent({
|
|
409
|
+
name: this.config.name || 'TaskAgent',
|
|
410
|
+
instructions: 'You are a task management assistant.',
|
|
411
|
+
llm: this.config.llm,
|
|
412
|
+
verbose: this.config.verbose ?? false
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
return this.agent;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Add a task
|
|
419
|
+
*/
|
|
420
|
+
addTask(content, priority = 'medium') {
|
|
421
|
+
const item = new TodoItem({ content, priority });
|
|
422
|
+
this.todos.add(item);
|
|
423
|
+
return item;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Complete a task by content (partial match)
|
|
427
|
+
*/
|
|
428
|
+
completeTask(contentMatch) {
|
|
429
|
+
const item = this.todos.items.find(t => t.content.toLowerCase().includes(contentMatch.toLowerCase()) && t.status !== 'completed');
|
|
430
|
+
if (item) {
|
|
431
|
+
item.complete();
|
|
432
|
+
return true;
|
|
433
|
+
}
|
|
434
|
+
return false;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Get pending tasks
|
|
438
|
+
*/
|
|
439
|
+
getPendingTasks() {
|
|
440
|
+
return this.todos.getPending();
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Get all tasks
|
|
444
|
+
*/
|
|
445
|
+
getAllTasks() {
|
|
446
|
+
return [...this.todos.items];
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Get progress
|
|
450
|
+
*/
|
|
451
|
+
getProgress() {
|
|
452
|
+
return this.todos.getProgress();
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Clear all tasks
|
|
456
|
+
*/
|
|
457
|
+
clearTasks() {
|
|
458
|
+
this.todos.clear();
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Chat with AI about tasks
|
|
462
|
+
*/
|
|
463
|
+
async chat(message) {
|
|
464
|
+
const agent = await this.getAgent();
|
|
465
|
+
const context = `Current tasks:\n${this.todos.items.map(t => `- [${t.status}] ${t.content} (${t.priority})`).join('\n') || 'No tasks'}`;
|
|
466
|
+
return agent.chat(`${context}\n\nUser: ${message}`);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
exports.TaskAgent = TaskAgent;
|
|
470
|
+
/**
|
|
471
|
+
* Create a task agent
|
|
472
|
+
*/
|
|
473
|
+
function createTaskAgent(config) {
|
|
474
|
+
return new TaskAgent(config);
|
|
475
|
+
}
|
|
@@ -100,3 +100,76 @@ export declare function disableTelemetry(): void;
|
|
|
100
100
|
* Cleanup telemetry resources
|
|
101
101
|
*/
|
|
102
102
|
export declare function cleanupTelemetry(): void;
|
|
103
|
+
/**
|
|
104
|
+
* AgentTelemetry - Agent-focused telemetry wrapper
|
|
105
|
+
*
|
|
106
|
+
* @example Simple usage (3 lines)
|
|
107
|
+
* ```typescript
|
|
108
|
+
* import { Agent } from 'praisonai';
|
|
109
|
+
*
|
|
110
|
+
* // Enable telemetry on agent
|
|
111
|
+
* const agent = new Agent({
|
|
112
|
+
* instructions: 'You are helpful',
|
|
113
|
+
* telemetry: true // Opt-in telemetry
|
|
114
|
+
* });
|
|
115
|
+
* await agent.chat('Hello!'); // Automatically tracked
|
|
116
|
+
* ```
|
|
117
|
+
*
|
|
118
|
+
* @example Manual tracking
|
|
119
|
+
* ```typescript
|
|
120
|
+
* import { AgentTelemetry } from 'praisonai';
|
|
121
|
+
*
|
|
122
|
+
* const telemetry = new AgentTelemetry('MyAgent');
|
|
123
|
+
* const result = await telemetry.trackChat(async () => {
|
|
124
|
+
* return await agent.chat('Hello!');
|
|
125
|
+
* });
|
|
126
|
+
* console.log(telemetry.getStats());
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
export interface AgentStats {
|
|
130
|
+
totalChats: number;
|
|
131
|
+
successfulChats: number;
|
|
132
|
+
failedChats: number;
|
|
133
|
+
totalDuration: number;
|
|
134
|
+
avgDuration: number;
|
|
135
|
+
totalTokens: number;
|
|
136
|
+
toolCalls: number;
|
|
137
|
+
}
|
|
138
|
+
export declare class AgentTelemetry {
|
|
139
|
+
private agentName;
|
|
140
|
+
private collector;
|
|
141
|
+
private stats;
|
|
142
|
+
constructor(agentName: string, config?: TelemetryConfig);
|
|
143
|
+
/**
|
|
144
|
+
* Track a chat execution
|
|
145
|
+
*/
|
|
146
|
+
trackChat<T>(fn: () => Promise<T>): Promise<T>;
|
|
147
|
+
/**
|
|
148
|
+
* Track a tool call
|
|
149
|
+
*/
|
|
150
|
+
trackToolCall(toolName: string, duration: number, success: boolean): void;
|
|
151
|
+
/**
|
|
152
|
+
* Track token usage
|
|
153
|
+
*/
|
|
154
|
+
trackTokens(tokens: number): void;
|
|
155
|
+
/**
|
|
156
|
+
* Get agent statistics
|
|
157
|
+
*/
|
|
158
|
+
getStats(): AgentStats;
|
|
159
|
+
/**
|
|
160
|
+
* Reset statistics
|
|
161
|
+
*/
|
|
162
|
+
resetStats(): void;
|
|
163
|
+
/**
|
|
164
|
+
* Get success rate
|
|
165
|
+
*/
|
|
166
|
+
getSuccessRate(): number;
|
|
167
|
+
/**
|
|
168
|
+
* Print summary
|
|
169
|
+
*/
|
|
170
|
+
printSummary(): void;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Create agent telemetry
|
|
174
|
+
*/
|
|
175
|
+
export declare function createAgentTelemetry(agentName: string, config?: TelemetryConfig): AgentTelemetry;
|
package/dist/telemetry/index.js
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
* Telemetry - Usage tracking and analytics
|
|
4
4
|
*/
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.TelemetryCollector = void 0;
|
|
6
|
+
exports.AgentTelemetry = exports.TelemetryCollector = void 0;
|
|
7
7
|
exports.getTelemetry = getTelemetry;
|
|
8
8
|
exports.enableTelemetry = enableTelemetry;
|
|
9
9
|
exports.disableTelemetry = disableTelemetry;
|
|
10
10
|
exports.cleanupTelemetry = cleanupTelemetry;
|
|
11
|
+
exports.createAgentTelemetry = createAgentTelemetry;
|
|
11
12
|
/**
|
|
12
13
|
* Telemetry collector for tracking usage
|
|
13
14
|
*/
|
|
@@ -185,3 +186,102 @@ function cleanupTelemetry() {
|
|
|
185
186
|
globalTelemetry.cleanup();
|
|
186
187
|
}
|
|
187
188
|
}
|
|
189
|
+
class AgentTelemetry {
|
|
190
|
+
constructor(agentName, config) {
|
|
191
|
+
this.stats = {
|
|
192
|
+
totalChats: 0,
|
|
193
|
+
successfulChats: 0,
|
|
194
|
+
failedChats: 0,
|
|
195
|
+
totalDuration: 0,
|
|
196
|
+
avgDuration: 0,
|
|
197
|
+
totalTokens: 0,
|
|
198
|
+
toolCalls: 0
|
|
199
|
+
};
|
|
200
|
+
this.agentName = agentName;
|
|
201
|
+
this.collector = config ? new TelemetryCollector(config) : getTelemetry();
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Track a chat execution
|
|
205
|
+
*/
|
|
206
|
+
async trackChat(fn) {
|
|
207
|
+
const startTime = Date.now();
|
|
208
|
+
this.stats.totalChats++;
|
|
209
|
+
try {
|
|
210
|
+
const result = await fn();
|
|
211
|
+
const duration = Date.now() - startTime;
|
|
212
|
+
this.stats.successfulChats++;
|
|
213
|
+
this.stats.totalDuration += duration;
|
|
214
|
+
this.stats.avgDuration = this.stats.totalDuration / this.stats.totalChats;
|
|
215
|
+
this.collector.trackAgentExecution(this.agentName, duration, true);
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
const duration = Date.now() - startTime;
|
|
220
|
+
this.stats.failedChats++;
|
|
221
|
+
this.stats.totalDuration += duration;
|
|
222
|
+
this.stats.avgDuration = this.stats.totalDuration / this.stats.totalChats;
|
|
223
|
+
this.collector.trackAgentExecution(this.agentName, duration, false);
|
|
224
|
+
this.collector.trackError(String(error), { agent: this.agentName });
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Track a tool call
|
|
230
|
+
*/
|
|
231
|
+
trackToolCall(toolName, duration, success) {
|
|
232
|
+
this.stats.toolCalls++;
|
|
233
|
+
this.collector.trackToolCall(toolName, duration, success);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Track token usage
|
|
237
|
+
*/
|
|
238
|
+
trackTokens(tokens) {
|
|
239
|
+
this.stats.totalTokens += tokens;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Get agent statistics
|
|
243
|
+
*/
|
|
244
|
+
getStats() {
|
|
245
|
+
return { ...this.stats };
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Reset statistics
|
|
249
|
+
*/
|
|
250
|
+
resetStats() {
|
|
251
|
+
this.stats = {
|
|
252
|
+
totalChats: 0,
|
|
253
|
+
successfulChats: 0,
|
|
254
|
+
failedChats: 0,
|
|
255
|
+
totalDuration: 0,
|
|
256
|
+
avgDuration: 0,
|
|
257
|
+
totalTokens: 0,
|
|
258
|
+
toolCalls: 0
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Get success rate
|
|
263
|
+
*/
|
|
264
|
+
getSuccessRate() {
|
|
265
|
+
if (this.stats.totalChats === 0)
|
|
266
|
+
return 0;
|
|
267
|
+
return (this.stats.successfulChats / this.stats.totalChats) * 100;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Print summary
|
|
271
|
+
*/
|
|
272
|
+
printSummary() {
|
|
273
|
+
console.log(`\nš Agent Telemetry: ${this.agentName}`);
|
|
274
|
+
console.log(` Total chats: ${this.stats.totalChats}`);
|
|
275
|
+
console.log(` Success rate: ${this.getSuccessRate().toFixed(1)}%`);
|
|
276
|
+
console.log(` Avg duration: ${this.stats.avgDuration.toFixed(0)}ms`);
|
|
277
|
+
console.log(` Tool calls: ${this.stats.toolCalls}`);
|
|
278
|
+
console.log(` Total tokens: ${this.stats.totalTokens}`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
exports.AgentTelemetry = AgentTelemetry;
|
|
282
|
+
/**
|
|
283
|
+
* Create agent telemetry
|
|
284
|
+
*/
|
|
285
|
+
function createAgentTelemetry(agentName, config) {
|
|
286
|
+
return new AgentTelemetry(agentName, config);
|
|
287
|
+
}
|