graphai 1.0.10 → 1.0.12

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/lib/bundle.esm.js CHANGED
@@ -12,6 +12,55 @@ var NodeState;
12
12
  NodeState["Skipped"] = "skipped";
13
13
  })(NodeState || (NodeState = {}));
14
14
 
15
+ const enabledLevels = {
16
+ debug: true,
17
+ info: true,
18
+ log: true,
19
+ warn: true,
20
+ error: true,
21
+ };
22
+ let customLogger = null;
23
+ function setLevelEnabled(level, enabled) {
24
+ enabledLevels[level] = enabled;
25
+ }
26
+ function setLogger(logger) {
27
+ customLogger = logger;
28
+ }
29
+ function output(level, ...args) {
30
+ if (!enabledLevels[level])
31
+ return;
32
+ if (customLogger) {
33
+ customLogger(level, ...args);
34
+ }
35
+ else {
36
+ (console[level] || console.log)(...args);
37
+ }
38
+ }
39
+ function debug(...args) {
40
+ output("debug", ...args);
41
+ }
42
+ function info(...args) {
43
+ output("info", ...args);
44
+ }
45
+ function log(...args) {
46
+ output("log", ...args);
47
+ }
48
+ function warn(...args) {
49
+ output("warn", ...args);
50
+ }
51
+ function error(...args) {
52
+ output("error", ...args);
53
+ }
54
+ const GraphAILogger = {
55
+ setLevelEnabled,
56
+ setLogger,
57
+ debug,
58
+ info,
59
+ log,
60
+ warn,
61
+ error,
62
+ };
63
+
15
64
  const sleep = async (milliseconds) => {
16
65
  return await new Promise((resolve) => setTimeout(resolve, milliseconds));
17
66
  };
@@ -42,7 +91,7 @@ function assert(condition, message, isWarn = false) {
42
91
  if (!isWarn) {
43
92
  throw new Error(message);
44
93
  }
45
- console.warn("warn: " + message);
94
+ GraphAILogger.warn("warn: " + message);
46
95
  }
47
96
  }
48
97
  const isObject = (x) => {
@@ -138,6 +187,7 @@ const isComputedNodeData = (node) => {
138
187
  const isStaticNodeData = (node) => {
139
188
  return !("agent" in node);
140
189
  };
190
+ const loopCounterKey = "__loopIndex";
141
191
 
142
192
  // for dataSource
143
193
  const inputs2dataSources = (inputs) => {
@@ -299,7 +349,7 @@ const propStringFunction = (result, propId) => {
299
349
  if (sliceMatch[1] !== undefined) {
300
350
  return result.slice(Number(sliceMatch[1]));
301
351
  }
302
- console.log(sliceMatch);
352
+ GraphAILogger.warn("slice is not valid format: " + sliceMatch);
303
353
  }
304
354
  const splitMatch = propId.match(/^split\(([-_:;.,\s\n]+)\)$/);
305
355
  if (splitMatch) {
@@ -330,15 +380,18 @@ const propBooleanFunction = (result, propId) => {
330
380
  return undefined;
331
381
  };
332
382
  const propFunctions = [propArrayFunction, propObjectFunction, propStringFunction, propNumberFunction, propBooleanFunction];
333
- const utilsFunctions = (input) => {
383
+ const utilsFunctions = (input, nodes) => {
334
384
  if (input === "@now" || input === "@now_ms") {
335
385
  return Date.now();
336
386
  }
337
387
  if (input === "@now_s") {
338
388
  return Math.floor(Date.now() / 1000);
339
389
  }
390
+ if (input === "@loop") {
391
+ return nodes[loopCounterKey].result;
392
+ }
340
393
  // If a placeholder does not match any key, replace it with an empty string.
341
- console.warn("not match template utility function: ${" + input + "}");
394
+ GraphAILogger.warn("not match template utility function: ${" + input + "}");
342
395
  return "";
343
396
  };
344
397
 
@@ -377,7 +430,7 @@ const innerGetDataFromSource = (result, propIds, propFunctions) => {
377
430
  const propId = propIds[0];
378
431
  const ret = getNestedData(result, propId, propFunctions);
379
432
  if (ret === undefined) {
380
- console.error(`prop: ${propIds.join(".")} is not hit`);
433
+ GraphAILogger.error(`prop: ${propIds.join(".")} is not hit`);
381
434
  }
382
435
  if (propIds.length > 1) {
383
436
  return innerGetDataFromSource(ret, propIds.slice(1), propFunctions);
@@ -400,7 +453,7 @@ const replaceTemplatePlaceholders = (input, templateMatch, nodes, propFunctions,
400
453
  const utilsFuncResult = templateMatch
401
454
  .filter((text) => text.startsWith("@"))
402
455
  .reduce((tmp, key) => {
403
- tmp[key] = utilsFunctions(key);
456
+ tmp[key] = utilsFunctions(key, nodes);
404
457
  return tmp;
405
458
  }, {});
406
459
  return Array.from(templateMatch.keys()).reduce((tmp, key) => {
@@ -491,14 +544,14 @@ class Node {
491
544
  return;
492
545
  }
493
546
  else if (this.console === true || this.console.after === true) {
494
- console.log(typeof result === "string" ? result : JSON.stringify(result, null, 2));
547
+ GraphAILogger.log(typeof result === "string" ? result : JSON.stringify(result, null, 2));
495
548
  }
496
549
  else if (this.console.after) {
497
550
  if (isObject(this.console.after)) {
498
- console.log(JSON.stringify(resultsOf(this.console.after, { self: { result } }, this.graph.propFunctions, true), null, 2));
551
+ GraphAILogger.log(JSON.stringify(resultsOf(this.console.after, { self: { result } }, this.graph.propFunctions, true), null, 2));
499
552
  }
500
553
  else {
501
- console.log(this.console.after);
554
+ GraphAILogger.log(this.console.after);
502
555
  }
503
556
  }
504
557
  }
@@ -656,7 +709,7 @@ class ComputedNode extends Node {
656
709
  // and attempt to retry (if specified).
657
710
  executeTimeout(transactionId) {
658
711
  if (this.state === NodeState.Executing && this.isCurrentTransaction(transactionId)) {
659
- console.warn(`-- timeout ${this.timeout} with ${this.nodeId}`);
712
+ GraphAILogger.warn(`-- timeout ${this.timeout} with ${this.nodeId}`);
660
713
  this.retry(NodeState.TimedOut, Error("Timeout"));
661
714
  }
662
715
  }
@@ -749,7 +802,7 @@ class ComputedNode extends Node {
749
802
  if (!this.isCurrentTransaction(transactionId)) {
750
803
  // This condition happens when the agent function returns
751
804
  // after the timeout (either retried or not).
752
- console.log(`-- transactionId mismatch with ${this.nodeId} (probably timeout)`);
805
+ GraphAILogger.log(`-- transactionId mismatch with ${this.nodeId} (probably timeout)`);
753
806
  return;
754
807
  }
755
808
  // after process
@@ -787,20 +840,20 @@ class ComputedNode extends Node {
787
840
  // the retry if specified.
788
841
  errorProcess(error, transactionId, namedInputs) {
789
842
  if (error instanceof Error && error.message !== strIntentionalError) {
790
- console.error(`<-- NodeId: ${this.nodeId}, Agent: ${this.agentId}`);
791
- console.error({ namedInputs });
792
- console.error(error);
793
- console.error("-->");
843
+ GraphAILogger.error(`<-- NodeId: ${this.nodeId}, Agent: ${this.agentId}`);
844
+ GraphAILogger.error({ namedInputs });
845
+ GraphAILogger.error(error);
846
+ GraphAILogger.error("-->");
794
847
  }
795
848
  if (!this.isCurrentTransaction(transactionId)) {
796
- console.warn(`-- transactionId mismatch with ${this.nodeId} (not timeout)`);
849
+ GraphAILogger.warn(`-- transactionId mismatch with ${this.nodeId} (not timeout)`);
797
850
  return;
798
851
  }
799
852
  if (error instanceof Error) {
800
853
  this.retry(NodeState.Failed, error);
801
854
  }
802
855
  else {
803
- console.error(`-- NodeId: ${this.nodeId}: Unknown error was caught`);
856
+ GraphAILogger.error(`-- NodeId: ${this.nodeId}: Unknown error was caught`);
804
857
  this.retry(NodeState.Failed, Error("Unknown"));
805
858
  }
806
859
  }
@@ -848,10 +901,10 @@ class ComputedNode extends Node {
848
901
  return;
849
902
  }
850
903
  else if (this.console === true || this.console.before === true) {
851
- console.log(JSON.stringify(context.namedInputs, null, 2));
904
+ GraphAILogger.log(JSON.stringify(context.namedInputs, null, 2));
852
905
  }
853
906
  else if (this.console.before) {
854
- console.log(this.console.before);
907
+ GraphAILogger.log(this.console.before);
855
908
  }
856
909
  }
857
910
  }
@@ -1250,15 +1303,14 @@ class GraphAI {
1250
1303
  this.callbacks = [];
1251
1304
  this.repeatCount = 0;
1252
1305
  if (!graphData.version && !options.taskManager) {
1253
- console.warn("------------ missing version number");
1306
+ GraphAILogger.warn("------------ missing version number");
1254
1307
  }
1255
1308
  this.version = graphData.version ?? graphDataLatestVersion;
1256
1309
  if (this.version < graphDataLatestVersion) {
1257
- console.warn(`------------ upgrade to ${graphDataLatestVersion}!`);
1310
+ GraphAILogger.warn(`------------ upgrade to ${graphDataLatestVersion}!`);
1258
1311
  }
1259
1312
  this.retryLimit = graphData.retry; // optional
1260
1313
  this.graphId = `${Date.now().toString(36)}-${Math.random().toString(36).substr(2, 9)}`; // URL.createObjectURL(new Blob()).slice(-36);
1261
- this.graphData = graphData;
1262
1314
  this.agentFunctionInfoDictionary = agentFunctionInfoDictionary;
1263
1315
  this.propFunctions = propFunctions;
1264
1316
  this.taskManager = options.taskManager ?? new TaskManager(graphData.concurrency ?? defaultConcurrency);
@@ -1273,7 +1325,14 @@ class GraphAI {
1273
1325
  };
1274
1326
  validateGraphData(graphData, [...Object.keys(agentFunctionInfoDictionary), ...this.bypassAgentIds]);
1275
1327
  validateAgent(agentFunctionInfoDictionary);
1276
- this.nodes = this.createNodes(graphData);
1328
+ this.graphData = {
1329
+ ...graphData,
1330
+ nodes: {
1331
+ ...graphData.nodes,
1332
+ [loopCounterKey]: { value: 0, update: `:${loopCounterKey}.add(1)` },
1333
+ },
1334
+ };
1335
+ this.nodes = this.createNodes(this.graphData);
1277
1336
  this.initializeStaticNodes(true);
1278
1337
  }
1279
1338
  getAgentFunctionInfo(agentId) {
@@ -1301,7 +1360,7 @@ class GraphAI {
1301
1360
  // Public API
1302
1361
  results(all) {
1303
1362
  return Object.keys(this.nodes)
1304
- .filter((nodeId) => all || this.nodes[nodeId].isResult)
1363
+ .filter((nodeId) => (all && nodeId !== loopCounterKey) || this.nodes[nodeId].isResult)
1305
1364
  .reduce((results, nodeId) => {
1306
1365
  const node = this.nodes[nodeId];
1307
1366
  if (node.result !== undefined) {
@@ -1361,7 +1420,7 @@ class GraphAI {
1361
1420
  }
1362
1421
  this.pushReadyNodesIntoQueue();
1363
1422
  if (!this.isRunning()) {
1364
- console.warn("-- nothing to execute");
1423
+ GraphAILogger.warn("-- nothing to execute");
1365
1424
  return {};
1366
1425
  }
1367
1426
  return new Promise((resolve, reject) => {
@@ -1489,5 +1548,5 @@ class GraphAI {
1489
1548
  }
1490
1549
  }
1491
1550
 
1492
- export { GraphAI, NodeState, ValidationError, agentInfoWrapper, assert, debugResultKey, defaultAgentInfo, defaultConcurrency, defaultTestContext, graphDataLatestVersion, inputs2dataSources, isComputedNodeData, isObject, isStaticNodeData, parseNodeName, sleep, strIntentionalError };
1551
+ export { GraphAI, GraphAILogger, NodeState, ValidationError, agentInfoWrapper, assert, debugResultKey, defaultAgentInfo, defaultConcurrency, defaultTestContext, graphDataLatestVersion, inputs2dataSources, isComputedNodeData, isObject, isStaticNodeData, parseNodeName, sleep, strIntentionalError };
1493
1552
  //# sourceMappingURL=bundle.esm.js.map