@promptbook/core 0.66.0-9 → 0.67.0-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.
Files changed (59) hide show
  1. package/esm/index.es.js +377 -237
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/src/_packages/core.index.d.ts +6 -4
  4. package/esm/typings/src/_packages/types.index.d.ts +7 -1
  5. package/esm/typings/src/_packages/utils.index.d.ts +14 -8
  6. package/esm/typings/src/commands/EXPECT/ExpectFormatCommand.d.ts +2 -0
  7. package/esm/typings/src/config.d.ts +6 -0
  8. package/esm/typings/src/errors/{ReferenceError.d.ts → PipelineUrlError.d.ts} +2 -2
  9. package/esm/typings/src/errors/index.d.ts +27 -0
  10. package/esm/typings/src/errors/utils/ErrorJson.d.ts +20 -0
  11. package/esm/typings/src/errors/utils/deserializeError.d.ts +7 -0
  12. package/esm/typings/src/errors/utils/deserializeError.test.d.ts +1 -0
  13. package/esm/typings/src/errors/utils/serializeError.d.ts +7 -0
  14. package/esm/typings/src/errors/utils/serializeError.test.d.ts +1 -0
  15. package/esm/typings/src/execution/ExecutionTools.d.ts +4 -1
  16. package/esm/typings/src/execution/PipelineExecutor.d.ts +1 -47
  17. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +49 -0
  18. package/esm/typings/src/execution/PromptResult.d.ts +5 -4
  19. package/esm/typings/src/execution/PromptResultUsage.d.ts +4 -0
  20. package/esm/typings/src/execution/UncertainNumber.d.ts +1 -0
  21. package/esm/typings/src/execution/assertsExecutionSuccessful.d.ts +2 -2
  22. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +0 -1
  23. package/esm/typings/src/llm-providers/mocked/$fakeTextToExpectations.d.ts +2 -2
  24. package/esm/typings/src/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -3
  25. package/esm/typings/src/llm-providers/remote/RemoteLlmExecutionTools.d.ts +1 -0
  26. package/esm/typings/src/llm-providers/remote/interfaces/PromptbookServer_Error.d.ts +2 -6
  27. package/esm/typings/src/llm-providers/remote/startRemoteServer.d.ts +1 -0
  28. package/esm/typings/src/scripting/javascript/JavascriptExecutionToolsOptions.d.ts +2 -2
  29. package/esm/typings/src/storage/_common/PromptbookStorage.d.ts +1 -1
  30. package/esm/typings/src/types/ModelRequirements.d.ts +5 -5
  31. package/esm/typings/src/types/PipelineJson/Expectations.d.ts +3 -1
  32. package/esm/typings/src/types/PipelineJson/KnowledgePieceJson.d.ts +2 -0
  33. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +4 -0
  34. package/esm/typings/src/types/PipelineJson/LlmTemplateJson.d.ts +2 -0
  35. package/esm/typings/src/types/PipelineJson/PersonaJson.d.ts +4 -0
  36. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +2 -0
  37. package/esm/typings/src/types/PipelineJson/PromptDialogJson.d.ts +1 -0
  38. package/esm/typings/src/types/PipelineJson/PromptTemplateJson.d.ts +2 -0
  39. package/esm/typings/src/types/PipelineJson/PromptTemplateJsonCommon.d.ts +2 -2
  40. package/esm/typings/src/types/PipelineJson/PromptTemplateParameterJson.d.ts +2 -0
  41. package/esm/typings/src/types/PipelineJson/ScriptJson.d.ts +1 -0
  42. package/esm/typings/src/types/PipelineJson/SimpleTemplateJson.d.ts +1 -0
  43. package/esm/typings/src/types/Prompt.d.ts +7 -7
  44. package/esm/typings/src/types/ScriptLanguage.d.ts +2 -0
  45. package/esm/typings/src/types/execution-report/ExecutionPromptReportJson.d.ts +24 -0
  46. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -20
  47. package/esm/typings/src/types/typeAliases.d.ts +7 -0
  48. package/esm/typings/src/utils/environment/$getGlobalScope.d.ts +1 -4
  49. package/esm/typings/src/utils/serialization/$asDeeplyFrozenSerializableJson.d.ts +17 -0
  50. package/esm/typings/src/utils/{deepFreeze.d.ts → serialization/$deepFreeze.d.ts} +0 -10
  51. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +27 -0
  52. package/esm/typings/src/utils/{clonePipeline.d.ts → serialization/clonePipeline.d.ts} +1 -1
  53. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +24 -0
  54. package/esm/typings/src/utils/serialization/isSerializableAsJson.test.d.ts +1 -0
  55. package/package.json +1 -1
  56. package/umd/index.umd.js +379 -238
  57. package/umd/index.umd.js.map +1 -1
  58. package/esm/typings/src/errors/VersionMismatchError.d.ts +0 -10
  59. /package/esm/typings/src/utils/{deepClone.d.ts → serialization/deepClone.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -9,7 +9,7 @@ import moment from 'moment';
9
9
  /**
10
10
  * The version of the Promptbook library
11
11
  */
12
- var PROMPTBOOK_VERSION = '0.66.0-8';
12
+ var PROMPTBOOK_VERSION = '0.66.0';
13
13
  // TODO: !!!! List here all the versions and annotate + put into script
14
14
 
15
15
  /*! *****************************************************************************
@@ -405,6 +405,26 @@ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
405
405
  * TODO: [🧠] Should be in generated .ptbk.md file GENERATOR_WARNING
406
406
  */
407
407
 
408
+ /**
409
+ * Returns the same value that is passed as argument.
410
+ * No side effects.
411
+ *
412
+ * Note: It can be usefull for:
413
+ *
414
+ * 1) Leveling indentation
415
+ * 2) Putting always-true or always-false conditions without getting eslint errors
416
+ *
417
+ * @param value any values
418
+ * @returns the same values
419
+ * @private within the repository
420
+ */
421
+ function just(value) {
422
+ if (value === undefined) {
423
+ return undefined;
424
+ }
425
+ return value;
426
+ }
427
+
408
428
  /**
409
429
  * @@@
410
430
  *
@@ -435,42 +455,169 @@ function $deepFreeze(objectValue) {
435
455
  }
436
456
  return Object.freeze(objectValue);
437
457
  }
458
+ /**
459
+ * TODO: [🧠] Is there a way how to meaningfully test this utility
460
+ */
461
+
462
+ /**
463
+ * This error type indicates that the error should not happen and its last check before crashing with some other error
464
+ *
465
+ * @public exported from `@promptbook/core`
466
+ */
467
+ var UnexpectedError = /** @class */ (function (_super) {
468
+ __extends(UnexpectedError, _super);
469
+ function UnexpectedError(message) {
470
+ var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the pipeline collection\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
471
+ _this.name = 'UnexpectedError';
472
+ Object.setPrototypeOf(_this, UnexpectedError.prototype);
473
+ return _this;
474
+ }
475
+ return UnexpectedError;
476
+ }(Error));
477
+
478
+ /**
479
+ * Checks if the value is [🚉] serializable as JSON
480
+ * If not, throws an UnexpectedError with a rich error message and tracking
481
+ *
482
+ * - Almost all primitives are serializable BUT:
483
+ * - `undefined` is not serializable
484
+ * - `NaN` is not serializable
485
+ * - Objects and arrays are serializable if all their properties are serializable
486
+ * - Functions are not serializable
487
+ * - Circular references are not serializable
488
+ * - `Date` objects are not serializable
489
+ * - `Map` and `Set` objects are not serializable
490
+ * - `RegExp` objects are not serializable
491
+ * - `Error` objects are not serializable
492
+ * - `Symbol` objects are not serializable
493
+ * - And much more...
494
+ *
495
+ * @throws UnexpectedError if the value is not serializable as JSON
496
+ * @public exported from `@promptbook/utils`
497
+ */
498
+ function checkSerializableAsJson(name, value) {
499
+ var e_1, _a;
500
+ if (value === undefined) {
501
+ throw new UnexpectedError("".concat(name, " is undefined"));
502
+ }
503
+ else if (value === null) {
504
+ return;
505
+ }
506
+ else if (typeof value === 'boolean') {
507
+ return;
508
+ }
509
+ else if (typeof value === 'number' && !isNaN(value)) {
510
+ return;
511
+ }
512
+ else if (typeof value === 'string') {
513
+ return;
514
+ }
515
+ else if (typeof value === 'symbol') {
516
+ throw new UnexpectedError("".concat(name, " is symbol"));
517
+ }
518
+ else if (typeof value === 'function') {
519
+ throw new UnexpectedError("".concat(name, " is function"));
520
+ }
521
+ else if (typeof value === 'object' && Array.isArray(value)) {
522
+ for (var i = 0; i < value.length; i++) {
523
+ checkSerializableAsJson("".concat(name, "[").concat(i, "]"), value[i]);
524
+ }
525
+ }
526
+ else if (typeof value === 'object') {
527
+ if (value instanceof Date) {
528
+ throw new UnexpectedError(spaceTrim("\n ".concat(name, " is Date\n\n Use `string_date_iso8601` instead\n ")));
529
+ }
530
+ else if (value instanceof Map) {
531
+ throw new UnexpectedError("".concat(name, " is Map"));
532
+ }
533
+ else if (value instanceof Set) {
534
+ throw new UnexpectedError("".concat(name, " is Set"));
535
+ }
536
+ else if (value instanceof RegExp) {
537
+ throw new UnexpectedError("".concat(name, " is RegExp"));
538
+ }
539
+ else if (value instanceof Error) {
540
+ throw new UnexpectedError(spaceTrim("\n ".concat(name, " is unserialized Error\n\n Use function `serializeError`\n ")));
541
+ }
542
+ else {
543
+ try {
544
+ for (var _b = __values(Object.entries(value)), _c = _b.next(); !_c.done; _c = _b.next()) {
545
+ var _d = __read(_c.value, 2), subName = _d[0], subValue = _d[1];
546
+ if (subValue === undefined) {
547
+ // Note: undefined in object is serializable - it is just omited
548
+ continue;
549
+ }
550
+ checkSerializableAsJson("".concat(name, ".").concat(subName), subValue);
551
+ }
552
+ }
553
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
554
+ finally {
555
+ try {
556
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
557
+ }
558
+ finally { if (e_1) throw e_1.error; }
559
+ }
560
+ try {
561
+ JSON.stringify(value); // <- TODO: [0]
562
+ }
563
+ catch (error) {
564
+ if (!(error instanceof Error)) {
565
+ throw error;
566
+ }
567
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n ".concat(name, " is not serializable\n\n ").concat(block(error.toString()), "\n "); }));
568
+ }
569
+ /*
570
+ TODO: [0] Is there some more elegant way to check circular references?
571
+ const seen = new Set();
572
+ const stack = [{ value }];
573
+ while (stack.length > 0) {
574
+ const { value } = stack.pop()!;
575
+ if (typeof value === 'object' && value !== null) {
576
+ if (seen.has(value)) {
577
+ throw new UnexpectedError(`${name} has circular reference`);
578
+ }
579
+ seen.add(value);
580
+ if (Array.isArray(value)) {
581
+ stack.push(...value.map((value) => ({ value })));
582
+ } else {
583
+ stack.push(...Object.values(value).map((value) => ({ value })));
584
+ }
585
+ }
586
+ }
587
+ */
588
+ return;
589
+ }
590
+ }
591
+ else {
592
+ throw new UnexpectedError("".concat(name, " is unknown"));
593
+ }
594
+ }
595
+ /**
596
+ * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
597
+ * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
598
+ * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
599
+ */
600
+
438
601
  /**
439
602
  * @@@
440
603
  * @@@
441
604
  *
442
605
  * Note: This function mutates the object and returns the original (but mutated-deep-freezed) object
443
606
  *
607
+ * @param name - Name of the object for debugging purposes
608
+ * @param objectValue - Object to be deeply frozen
444
609
  * @returns The same object as the input, but deeply frozen
445
610
  * @private this is in comparison to `deepFreeze` a more specific utility and maybe not very good practice to use without specific reason and considerations
446
611
  */
447
- function deepFreezeWithSameType(objectValue) {
612
+ function $asDeeplyFrozenSerializableJson(name, objectValue) {
613
+ checkSerializableAsJson(name, objectValue);
448
614
  return $deepFreeze(objectValue);
449
615
  }
450
616
  /**
617
+ * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
451
618
  * TODO: [🧠] Is there a way how to meaningfully test this utility
452
619
  */
453
620
 
454
- /**
455
- * Returns the same value that is passed as argument.
456
- * No side effects.
457
- *
458
- * Note: It can be usefull for:
459
- *
460
- * 1) Leveling indentation
461
- * 2) Putting always-true or always-false conditions without getting eslint errors
462
- *
463
- * @param value any values
464
- * @returns the same values
465
- * @private within the repository
466
- */
467
- function just(value) {
468
- if (value === undefined) {
469
- return undefined;
470
- }
471
- return value;
472
- }
473
-
474
621
  /**
475
622
  * Warning message for the generated sections and files files
476
623
  *
@@ -547,7 +694,7 @@ var REPLACING_NONCE = 'u$k42k%!V2zo34w7Fu#@QUHYPW';
547
694
  *
548
695
  * @public exported from `@promptbook/core`
549
696
  */
550
- var RESERVED_PARAMETER_NAMES = $deepFreeze([
697
+ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMETER_NAMES', [
551
698
  'content',
552
699
  'context',
553
700
  'knowledge',
@@ -590,6 +737,13 @@ var DEFAULT_REMOTE_URL = 'https://api.pavolhejny.com/';
590
737
  * @public exported from `@promptbook/core`
591
738
  */
592
739
  var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
740
+ // <- TODO: [🧜‍♂️]
741
+ /**
742
+ * @@@
743
+ *
744
+ * @public exported from `@promptbook/core`
745
+ */
746
+ var IS_VERBOSE = false;
593
747
  /**
594
748
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
595
749
  */
@@ -626,22 +780,6 @@ var PipelineLogicError = /** @class */ (function (_super) {
626
780
  return PipelineLogicError;
627
781
  }(Error));
628
782
 
629
- /**
630
- * This error type indicates that the error should not happen and its last check before crashing with some other error
631
- *
632
- * @public exported from `@promptbook/core`
633
- */
634
- var UnexpectedError = /** @class */ (function (_super) {
635
- __extends(UnexpectedError, _super);
636
- function UnexpectedError(message) {
637
- var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the pipeline collection\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
638
- _this.name = 'UnexpectedError';
639
- Object.setPrototypeOf(_this, UnexpectedError.prototype);
640
- return _this;
641
- }
642
- return UnexpectedError;
643
- }(Error));
644
-
645
783
  /**
646
784
  * Tests if given string is valid semantic version
647
785
  *
@@ -1055,15 +1193,15 @@ var NotFoundError = /** @class */ (function (_super) {
1055
1193
  *
1056
1194
  * @public exported from `@promptbook/core`
1057
1195
  */
1058
- var ReferenceError$1 = /** @class */ (function (_super) {
1059
- __extends(ReferenceError, _super);
1060
- function ReferenceError(message) {
1196
+ var PipelineUrlError = /** @class */ (function (_super) {
1197
+ __extends(PipelineUrlError, _super);
1198
+ function PipelineUrlError(message) {
1061
1199
  var _this = _super.call(this, message) || this;
1062
- _this.name = 'ReferenceError';
1063
- Object.setPrototypeOf(_this, ReferenceError.prototype);
1200
+ _this.name = 'PipelineUrlError';
1201
+ Object.setPrototypeOf(_this, PipelineUrlError.prototype);
1064
1202
  return _this;
1065
1203
  }
1066
- return ReferenceError;
1204
+ return PipelineUrlError;
1067
1205
  }(Error));
1068
1206
 
1069
1207
  /**
@@ -1111,7 +1249,7 @@ function unpreparePipeline(pipeline) {
1111
1249
  delete promptTemplateUnprepared.preparedContent;
1112
1250
  return promptTemplateUnprepared;
1113
1251
  });
1114
- return __assign(__assign({}, pipeline), { promptTemplates: promptTemplates, knowledgeSources: knowledgeSources, knowledgePieces: [], personas: personas, preparations: [] });
1252
+ return $asDeeplyFrozenSerializableJson('Unprepared PipelineJson', __assign(__assign({}, pipeline), { promptTemplates: promptTemplates, knowledgeSources: knowledgeSources, knowledgePieces: [], personas: personas, preparations: [] }));
1115
1253
  }
1116
1254
  /**
1117
1255
  * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
@@ -1147,7 +1285,7 @@ var SimplePipelineCollection = /** @class */ (function () {
1147
1285
  var pipeline = pipelines_1_1.value;
1148
1286
  // TODO: [👠] DRY
1149
1287
  if (pipeline.pipelineUrl === undefined) {
1150
- throw new ReferenceError$1(spaceTrim$1("\n Pipeline with name \"".concat(pipeline.title, "\" does not have defined URL\n\n File:\n ").concat(pipeline.sourceFile || 'Unknown', "\n\n Note: Pipelines without URLs are called anonymous pipelines\n They can be used as standalone pipelines, but they cannot be referenced by other pipelines\n And also they cannot be used in the pipeline collection\n\n ")));
1288
+ throw new PipelineUrlError(spaceTrim$1("\n Pipeline with name \"".concat(pipeline.title, "\" does not have defined URL\n\n File:\n ").concat(pipeline.sourceFile || 'Unknown', "\n\n Note: Pipelines without URLs are called anonymous pipelines\n They can be used as standalone pipelines, but they cannot be referenced by other pipelines\n And also they cannot be used in the pipeline collection\n\n ")));
1151
1289
  }
1152
1290
  // Note: [🐨]
1153
1291
  validatePipeline(pipeline);
@@ -1159,7 +1297,7 @@ var SimplePipelineCollection = /** @class */ (function () {
1159
1297
  pipelineJsonToString(unpreparePipeline(pipeline)) !==
1160
1298
  pipelineJsonToString(unpreparePipeline(this.collection.get(pipeline.pipelineUrl)))) {
1161
1299
  var existing = this.collection.get(pipeline.pipelineUrl);
1162
- throw new ReferenceError$1(spaceTrim$1("\n Pipeline with URL \"".concat(pipeline.pipelineUrl, "\" is already in the collection \uD83C\uDF4E\n\n Conflicting files:\n ").concat(existing.sourceFile || 'Unknown', "\n ").concat(pipeline.sourceFile || 'Unknown', "\n\n Note: You have probably forgotten to run \"ptbk make\" to update the collection\n Note: Pipelines with the same URL are not allowed\n Only exepction is when the pipelines are identical\n\n ")));
1300
+ throw new PipelineUrlError(spaceTrim$1("\n Pipeline with URL \"".concat(pipeline.pipelineUrl, "\" is already in the collection \uD83C\uDF4E\n\n Conflicting files:\n ").concat(existing.sourceFile || 'Unknown', "\n ").concat(pipeline.sourceFile || 'Unknown', "\n\n Note: You have probably forgotten to run \"ptbk make\" to update the collection\n Note: Pipelines with the same URL are not allowed\n Only exepction is when the pipelines are identical\n\n ")));
1163
1301
  }
1164
1302
  // Note: [🧠] Overwrite existing pipeline with the same URL
1165
1303
  this.collection.set(pipeline.pipelineUrl, pipeline);
@@ -1323,7 +1461,7 @@ function createCollectionFromUrl(url, options) {
1323
1461
  return __generator(this, function (_d) {
1324
1462
  switch (_d.label) {
1325
1463
  case 0:
1326
- _a = options || {}, _b = _a.isVerbose, isVerbose = _b === void 0 ? false : _b, _c = _a.isLazyLoaded, isLazyLoaded = _c === void 0 ? false : _c;
1464
+ _a = options || {}, _b = _a.isVerbose, isVerbose = _b === void 0 ? IS_VERBOSE : _b, _c = _a.isLazyLoaded, isLazyLoaded = _c === void 0 ? false : _c;
1327
1465
  collection = createCollectionFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
1328
1466
  return __generator(this, function (_a) {
1329
1467
  if (isVerbose) {
@@ -1640,7 +1778,7 @@ function forEachAsync(array, options, callbackfunction) {
1640
1778
  });
1641
1779
  }
1642
1780
 
1643
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.66.0-8",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",dependentParameterNames:["knowledgeContent"],resultingParameterName:"knowledgePieces"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.66.0-8",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"keywords"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.66.0-8",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"title"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.66.0-8",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",modelRequirements:{modelVariant:"CHAT",modelName:"gpt-4-turbo"},content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n### Option `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Option `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Option `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",expectFormat:"JSON",dependentParameterNames:["availableModelNames","personaDescription"],resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1781
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.66.0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",dependentParameterNames:["knowledgeContent"],resultingParameterName:"knowledgePieces"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.66.0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"keywords"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.66.0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"title"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.66.0",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",modelRequirements:{modelVariant:"CHAT",modelName:"gpt-4-turbo"},content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n### Option `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Option `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Option `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",expectFormat:"JSON",dependentParameterNames:["availableModelNames","personaDescription"],resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1644
1782
 
1645
1783
  var defaultDiacriticsRemovalMap = [
1646
1784
  {
@@ -2022,9 +2160,105 @@ var PipelineExecutionError = /** @class */ (function (_super) {
2022
2160
  }(Error));
2023
2161
 
2024
2162
  /**
2025
- * Asserts that the execution of a promptnook is successful
2163
+ * This error indicates that the pipeline collection cannot be propperly loaded
2164
+ *
2165
+ * @public exported from `@promptbook/core`
2166
+ */
2167
+ var CollectionError = /** @class */ (function (_super) {
2168
+ __extends(CollectionError, _super);
2169
+ function CollectionError(message) {
2170
+ var _this = _super.call(this, message) || this;
2171
+ _this.name = 'CollectionError';
2172
+ Object.setPrototypeOf(_this, CollectionError.prototype);
2173
+ return _this;
2174
+ }
2175
+ return CollectionError;
2176
+ }(Error));
2177
+
2178
+ /**
2179
+ * This error type indicates that you try to use a feature that is not available in the current environment
2180
+ *
2181
+ * @public exported from `@promptbook/core`
2182
+ */
2183
+ var EnvironmentMismatchError = /** @class */ (function (_super) {
2184
+ __extends(EnvironmentMismatchError, _super);
2185
+ function EnvironmentMismatchError(message) {
2186
+ var _this = _super.call(this, message) || this;
2187
+ _this.name = 'EnvironmentMismatchError';
2188
+ Object.setPrototypeOf(_this, EnvironmentMismatchError.prototype);
2189
+ return _this;
2190
+ }
2191
+ return EnvironmentMismatchError;
2192
+ }(Error));
2193
+
2194
+ /**
2195
+ * This error type indicates that some limit was reached
2196
+ *
2197
+ * @public exported from `@promptbook/core`
2198
+ */
2199
+ var LimitReachedError = /** @class */ (function (_super) {
2200
+ __extends(LimitReachedError, _super);
2201
+ function LimitReachedError(message) {
2202
+ var _this = _super.call(this, message) || this;
2203
+ _this.name = 'LimitReachedError';
2204
+ Object.setPrototypeOf(_this, LimitReachedError.prototype);
2205
+ return _this;
2206
+ }
2207
+ return LimitReachedError;
2208
+ }(Error));
2209
+
2210
+ /**
2211
+ * This error type indicates that some part of the code is not implemented yet
2212
+ *
2213
+ * @public exported from `@promptbook/core`
2214
+ */
2215
+ var NotYetImplementedError = /** @class */ (function (_super) {
2216
+ __extends(NotYetImplementedError, _super);
2217
+ function NotYetImplementedError(message) {
2218
+ var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: This feature is not implemented yet but it will be soon.\n\n If you want speed up the implementation or just read more, look here:\n https://github.com/webgptorg/promptbook\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
2219
+ _this.name = 'NotYetImplementedError';
2220
+ Object.setPrototypeOf(_this, NotYetImplementedError.prototype);
2221
+ return _this;
2222
+ }
2223
+ return NotYetImplementedError;
2224
+ }(Error));
2225
+
2226
+ /**
2227
+ * Index of all custom errors
2228
+ *
2229
+ * @public exported from `@promptbook/core`
2230
+ */
2231
+ var ERRORS = {
2232
+ CollectionError: CollectionError,
2233
+ EnvironmentMismatchError: EnvironmentMismatchError,
2234
+ LimitReachedError: LimitReachedError,
2235
+ NotFoundError: NotFoundError,
2236
+ NotYetImplementedError: NotYetImplementedError,
2237
+ ParsingError: ParsingError,
2238
+ PipelineExecutionError: PipelineExecutionError,
2239
+ PipelineLogicError: PipelineLogicError,
2240
+ PipelineUrlError: PipelineUrlError,
2241
+ UnexpectedError: UnexpectedError,
2242
+ // TODO: [🪑]> VersionMismatchError,
2243
+ };
2244
+
2245
+ /**
2246
+ * Deserializes the error object
2247
+ *
2248
+ * @public exported from `@promptbook/utils`
2249
+ */
2250
+ function deserializeError(error) {
2251
+ if (error.name === 'Error') {
2252
+ return new Error(error.message);
2253
+ }
2254
+ var CustomError = ERRORS[error.name];
2255
+ return new CustomError(error.message);
2256
+ }
2257
+
2258
+ /**
2259
+ * Asserts that the execution of a Promptbook is successful
2026
2260
  *
2027
- * @param executionResult - The partial result of the promptnook execution
2261
+ * @param executionResult - The partial result of the Promptbook execution
2028
2262
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
2029
2263
  * @public exported from `@promptbook/core`
2030
2264
  */
@@ -2034,15 +2268,16 @@ function assertsExecutionSuccessful(executionResult) {
2034
2268
  return;
2035
2269
  }
2036
2270
  if (errors.length === 0) {
2037
- throw new PipelineExecutionError("Promptnook Execution failed because of unknown reason");
2271
+ throw new PipelineExecutionError("Promptbook Execution failed because of unknown reason");
2038
2272
  }
2039
2273
  else if (errors.length === 1) {
2040
- throw errors[0];
2274
+ throw deserializeError(errors[0]);
2041
2275
  }
2042
2276
  else {
2043
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Multiple errors occurred during promptnook execution\n\n ".concat(block(errors
2044
- .map(function (error, index) {
2045
- return spaceTrim$1(function (block) { return "\n Error ".concat(index + 1, ":\n ").concat(block(error.stack || error.message), "\n "); });
2277
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Multiple errors occurred during Promptbook execution\n\n ".concat(block(errors
2278
+ .map(function (_a, index) {
2279
+ var name = _a.name, stack = _a.stack, message = _a.message;
2280
+ return spaceTrim$1(function (block) { return "\n ".concat(name, " ").concat(index + 1, ":\n ").concat(block(stack || message), "\n "); });
2046
2281
  })
2047
2282
  .join('\n')), "\n "); }));
2048
2283
  }
@@ -2074,7 +2309,7 @@ function extractVariables(script) {
2074
2309
  var undefinedName = error.message.split(' ')[0];
2075
2310
  /*
2076
2311
  Note: Parsing the error
2077
- [ReferenceError: thing is not defined]
2312
+ [PipelineUrlError: thing is not defined]
2078
2313
  */
2079
2314
  if (!undefinedName) {
2080
2315
  throw error;
@@ -2092,7 +2327,7 @@ function extractVariables(script) {
2092
2327
  if (!(error instanceof Error)) {
2093
2328
  throw error;
2094
2329
  }
2095
- throw new ParsingError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
2330
+ throw new ParsingError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2096
2331
  }
2097
2332
  return variables;
2098
2333
  }
@@ -2179,6 +2414,23 @@ var ExpectError = /** @class */ (function (_super) {
2179
2414
  return ExpectError;
2180
2415
  }(Error));
2181
2416
 
2417
+ /**
2418
+ * Serializes an error into a [🚉] JSON-serializable object
2419
+ *
2420
+ * @public exported from `@promptbook/utils`
2421
+ */
2422
+ function serializeError(error) {
2423
+ var name = error.name, message = error.message, stack = error.stack;
2424
+ if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2425
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2426
+ }
2427
+ return {
2428
+ name: name,
2429
+ message: message,
2430
+ stack: stack,
2431
+ };
2432
+ }
2433
+
2182
2434
  /**
2183
2435
  * Function isValidJsonString will tell you if the string is valid JSON or not
2184
2436
  *
@@ -2560,22 +2812,6 @@ function TODO_USE() {
2560
2812
  }
2561
2813
  }
2562
2814
 
2563
- /**
2564
- * This error type indicates that some limit was reached
2565
- *
2566
- * @public exported from `@promptbook/core`
2567
- */
2568
- var LimitReachedError = /** @class */ (function (_super) {
2569
- __extends(LimitReachedError, _super);
2570
- function LimitReachedError(message) {
2571
- var _this = _super.call(this, message) || this;
2572
- _this.name = 'LimitReachedError';
2573
- Object.setPrototypeOf(_this, LimitReachedError.prototype);
2574
- return _this;
2575
- }
2576
- return LimitReachedError;
2577
- }(Error));
2578
-
2579
2815
  /**
2580
2816
  * Replaces parameters in template with values from parameters object
2581
2817
  *
@@ -2889,7 +3125,7 @@ function isPassingExpectations(expectations, value) {
2889
3125
  function createPipelineExecutor(options) {
2890
3126
  var _this = this;
2891
3127
  var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
2892
- var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? false : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
3128
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
2893
3129
  validatePipeline(pipeline);
2894
3130
  var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
2895
3131
  var preparedPipeline;
@@ -2983,7 +3219,6 @@ function createPipelineExecutor(options) {
2983
3219
  return __awaiter(this, void 0, void 0, function () {
2984
3220
  var name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, attempt, isJokerAttempt, jokerParameterName, _f, _g, _h, _j, scriptTools, error_2, e_4_1, _k, _l, functionName, postprocessingError, _m, _o, scriptTools, error_3, e_5_1, e_6_1, error_4;
2985
3221
  var e_7, _p, e_4, _q, e_6, _r, e_5, _s, _t;
2986
- var _this = this;
2987
3222
  return __generator(this, function (_u) {
2988
3223
  switch (_u.label) {
2989
3224
  case 0:
@@ -3104,71 +3339,8 @@ function createPipelineExecutor(options) {
3104
3339
  return name === currentTemplate.personaName;
3105
3340
  }) || {})), currentTemplate.expectations),
3106
3341
  expectFormat: currentTemplate.expectFormat,
3107
- postprocessing: (currentTemplate.postprocessingFunctionNames || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
3108
- var errors, _a, _b, scriptTools, error_5, e_8_1;
3109
- var e_8, _c;
3110
- return __generator(this, function (_d) {
3111
- switch (_d.label) {
3112
- case 0:
3113
- errors = [];
3114
- _d.label = 1;
3115
- case 1:
3116
- _d.trys.push([1, 8, 9, 10]);
3117
- _a = __values(arrayableToArray(tools.script)), _b = _a.next();
3118
- _d.label = 2;
3119
- case 2:
3120
- if (!!_b.done) return [3 /*break*/, 7];
3121
- scriptTools = _b.value;
3122
- _d.label = 3;
3123
- case 3:
3124
- _d.trys.push([3, 5, , 6]);
3125
- return [4 /*yield*/, scriptTools.execute({
3126
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3127
- script: "".concat(functionName, "(result)"),
3128
- parameters: {
3129
- result: result || '',
3130
- // Note: No ...parametersForTemplate, because working with result only
3131
- },
3132
- })];
3133
- case 4: return [2 /*return*/, _d.sent()];
3134
- case 5:
3135
- error_5 = _d.sent();
3136
- if (!(error_5 instanceof Error)) {
3137
- throw error_5;
3138
- }
3139
- if (error_5 instanceof UnexpectedError) {
3140
- throw error_5;
3141
- }
3142
- errors.push(error_5);
3143
- return [3 /*break*/, 6];
3144
- case 6:
3145
- _b = _a.next();
3146
- return [3 /*break*/, 2];
3147
- case 7: return [3 /*break*/, 10];
3148
- case 8:
3149
- e_8_1 = _d.sent();
3150
- e_8 = { error: e_8_1 };
3151
- return [3 /*break*/, 10];
3152
- case 9:
3153
- try {
3154
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3155
- }
3156
- finally { if (e_8) throw e_8.error; }
3157
- return [7 /*endfinally*/];
3158
- case 10:
3159
- if (errors.length === 0) {
3160
- throw new PipelineExecutionError('Postprocessing in LlmExecutionTools failed because no ScriptExecutionTools were provided');
3161
- }
3162
- else if (errors.length === 1) {
3163
- throw errors[0];
3164
- }
3165
- else {
3166
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Postprocessing in LlmExecutionTools failed ".concat(errors.length, "x\n\n ").concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n\n')), "\n "); }));
3167
- }
3168
- }
3169
- });
3170
- }); }; }),
3171
- };
3342
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3343
+ }; // <- TODO: Not very good type guard
3172
3344
  _g = currentTemplate.modelRequirements.modelVariant;
3173
3345
  switch (_g) {
3174
3346
  case 'CHAT': return [3 /*break*/, 8];
@@ -3393,7 +3565,7 @@ function createPipelineExecutor(options) {
3393
3565
  executionReport.promptExecutions.push({
3394
3566
  prompt: __assign({}, prompt),
3395
3567
  result: result || undefined,
3396
- error: expectError || undefined,
3568
+ error: expectError === null ? undefined : serializeError(expectError),
3397
3569
  });
3398
3570
  }
3399
3571
  return [7 /*endfinally*/];
@@ -3428,7 +3600,7 @@ function createPipelineExecutor(options) {
3428
3600
  });
3429
3601
  }
3430
3602
  function filterJustOutputParameters() {
3431
- var e_9, _a;
3603
+ var e_8, _a;
3432
3604
  var outputParameters = {};
3433
3605
  try {
3434
3606
  // Note: Filter ONLY output parameters
@@ -3445,12 +3617,12 @@ function createPipelineExecutor(options) {
3445
3617
  outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3446
3618
  }
3447
3619
  }
3448
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
3620
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
3449
3621
  finally {
3450
3622
  try {
3451
3623
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3452
3624
  }
3453
- finally { if (e_9) throw e_9.error; }
3625
+ finally { if (e_8) throw e_8.error; }
3454
3626
  }
3455
3627
  return outputParameters;
3456
3628
  }
@@ -3487,11 +3659,11 @@ function createPipelineExecutor(options) {
3487
3659
  })), _b = _a.next(); !_b.done; _b = _a.next()) {
3488
3660
  parameter = _b.value;
3489
3661
  if (inputParameters[parameter.name] === undefined) {
3490
- return [2 /*return*/, deepFreezeWithSameType({
3662
+ return [2 /*return*/, $asDeeplyFrozenSerializableJson("Unuccessful PipelineExecutorResult (with missing parameter {".concat(parameter.name, "}) PipelineExecutorResult"), {
3491
3663
  isSuccessful: false,
3492
3664
  errors: __spreadArray([
3493
3665
  new PipelineExecutionError("Parameter {".concat(parameter.name, "} is required as an input parameter"))
3494
- ], __read(errors), false),
3666
+ ], __read(errors), false).map(serializeError),
3495
3667
  warnings: [],
3496
3668
  executionReport: executionReport,
3497
3669
  outputParameters: {},
@@ -3517,12 +3689,12 @@ function createPipelineExecutor(options) {
3517
3689
  warnings.push(new PipelineExecutionError("Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.")));
3518
3690
  }
3519
3691
  else if (parameter.isInput === false) {
3520
- return { value: deepFreezeWithSameType({
3692
+ return { value: $asDeeplyFrozenSerializableJson("Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult"), {
3521
3693
  isSuccessful: false,
3522
3694
  errors: __spreadArray([
3523
3695
  new PipelineExecutionError("Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input"))
3524
- ], __read(errors), false),
3525
- warnings: warnings,
3696
+ ], __read(errors), false).map(serializeError),
3697
+ warnings: warnings.map(serializeError),
3526
3698
  executionReport: executionReport,
3527
3699
  outputParameters: {},
3528
3700
  usage: ZERO_USAGE,
@@ -3629,10 +3801,10 @@ function createPipelineExecutor(options) {
3629
3801
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3630
3802
  })), false));
3631
3803
  outputParameters_1 = filterJustOutputParameters();
3632
- return [2 /*return*/, deepFreezeWithSameType({
3804
+ return [2 /*return*/, $asDeeplyFrozenSerializableJson('Unuccessful PipelineExecutorResult (with misc errors) PipelineExecutorResult', {
3633
3805
  isSuccessful: false,
3634
- errors: __spreadArray([error_1], __read(errors), false),
3635
- warnings: warnings,
3806
+ errors: __spreadArray([error_1], __read(errors), false).map(serializeError),
3807
+ warnings: warnings.map(serializeError),
3636
3808
  usage: usage_1,
3637
3809
  executionReport: executionReport,
3638
3810
  outputParameters: outputParameters_1,
@@ -3644,10 +3816,10 @@ function createPipelineExecutor(options) {
3644
3816
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3645
3817
  })), false));
3646
3818
  outputParameters = filterJustOutputParameters();
3647
- return [2 /*return*/, deepFreezeWithSameType({
3819
+ return [2 /*return*/, $asDeeplyFrozenSerializableJson('Successful PipelineExecutorResult', {
3648
3820
  isSuccessful: true,
3649
- errors: errors,
3650
- warnings: warnings,
3821
+ errors: errors.map(serializeError),
3822
+ warnings: warnings.map(serializeError),
3651
3823
  usage: usage,
3652
3824
  executionReport: executionReport,
3653
3825
  outputParameters: outputParameters,
@@ -3684,7 +3856,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
3684
3856
  return __generator(this, function (_j) {
3685
3857
  switch (_j.label) {
3686
3858
  case 0:
3687
- llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? false : _b;
3859
+ llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? IS_VERBOSE : _b;
3688
3860
  TODO_USE(maxParallelCount); // <- [🪂]
3689
3861
  collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
3690
3862
  _c = createPipelineExecutor;
@@ -3971,7 +4143,7 @@ function preparePersona(personaDescription, options) {
3971
4143
  return __generator(this, function (_d) {
3972
4144
  switch (_d.label) {
3973
4145
  case 0:
3974
- llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
4146
+ llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? IS_VERBOSE : _a;
3975
4147
  collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
3976
4148
  _b = createPipelineExecutor;
3977
4149
  _c = {};
@@ -4117,7 +4289,7 @@ function preparePipeline(pipeline, options) {
4117
4289
  return __awaiter(this, void 0, void 0, function () {
4118
4290
  var llmTools, _a, maxParallelCount, _b, isVerbose, parameters, promptTemplates,
4119
4291
  /*
4120
- <- TODO: [🧠][0] `promptbookVersion` */
4292
+ <- TODO: [🧠][🪑] `promptbookVersion` */
4121
4293
  knowledgeSources /*
4122
4294
  <- TODO: [🧊] `knowledgePieces` */, personas /*
4123
4295
  <- TODO: [🧊] `preparations` */, llmToolsWithUsage, currentPreparation, preparations, preparedPersonas, knowledgeSourcesPrepared, partialknowledgePiecesPrepared, knowledgePiecesPrepared, promptTemplatesPrepared /* TODO: parameters: parametersPrepared*/;
@@ -4128,7 +4300,7 @@ function preparePipeline(pipeline, options) {
4128
4300
  if (isPipelinePrepared(pipeline)) {
4129
4301
  return [2 /*return*/, pipeline];
4130
4302
  }
4131
- llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? false : _b;
4303
+ llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? IS_VERBOSE : _b;
4132
4304
  parameters = pipeline.parameters, promptTemplates = pipeline.promptTemplates, knowledgeSources = pipeline.knowledgeSources, personas = pipeline.personas;
4133
4305
  llmToolsWithUsage = countTotalUsage(llmTools);
4134
4306
  currentPreparation = {
@@ -4187,7 +4359,7 @@ function preparePipeline(pipeline, options) {
4187
4359
  // ----- /Templates preparation -----
4188
4360
  // Note: Count total usage
4189
4361
  currentPreparation.usage = llmToolsWithUsage.getTotalUsage();
4190
- return [2 /*return*/, __assign(__assign({}, clonePipeline(pipeline)), { promptTemplates: promptTemplatesPrepared, knowledgeSources: knowledgeSourcesPrepared, knowledgePieces: knowledgePiecesPrepared, personas: preparedPersonas, preparations: preparations })];
4362
+ return [2 /*return*/, $asDeeplyFrozenSerializableJson('Prepared PipelineJson', __assign(__assign({}, clonePipeline(pipeline)), { promptTemplates: promptTemplatesPrepared, knowledgeSources: knowledgeSourcesPrepared, knowledgePieces: knowledgePiecesPrepared, personas: preparedPersonas, preparations: preparations }))];
4191
4363
  }
4192
4364
  });
4193
4365
  });
@@ -5425,22 +5597,6 @@ function parseCommandVariant(input) {
5425
5597
  return null;
5426
5598
  }
5427
5599
 
5428
- /**
5429
- * This error type indicates that some part of the code is not implemented yet
5430
- *
5431
- * @public exported from `@promptbook/core`
5432
- */
5433
- var NotYetImplementedError = /** @class */ (function (_super) {
5434
- __extends(NotYetImplementedError, _super);
5435
- function NotYetImplementedError(message) {
5436
- var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: This feature is not implemented yet but it will be soon.\n\n If you want speed up the implementation or just read more, look here:\n https://github.com/webgptorg/promptbook\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
5437
- _this.name = 'NotYetImplementedError';
5438
- Object.setPrototypeOf(_this, NotYetImplementedError.prototype);
5439
- return _this;
5440
- }
5441
- return NotYetImplementedError;
5442
- }(Error));
5443
-
5444
5600
  /**
5445
5601
  * Supported script languages
5446
5602
  *
@@ -6132,7 +6288,7 @@ function pipelineStringToJsonSync(pipelineString) {
6132
6288
  }
6133
6289
  });
6134
6290
  // =============================================================
6135
- return pipelineJson;
6291
+ return $asDeeplyFrozenSerializableJson('pipelineJson', pipelineJson);
6136
6292
  }
6137
6293
  /**
6138
6294
  * TODO: !!!! Warn if used only sync version
@@ -6176,7 +6332,9 @@ function pipelineStringToJson(pipelineString, options) {
6176
6332
  case 1:
6177
6333
  pipelineJson = _a.sent();
6178
6334
  _a.label = 2;
6179
- case 2: return [2 /*return*/, pipelineJson];
6335
+ case 2:
6336
+ // Note: No need to use `$asDeeplyFrozenSerializableJson` because `pipelineStringToJsonSync` and `preparePipeline` already do that
6337
+ return [2 /*return*/, pipelineJson];
6180
6338
  }
6181
6339
  });
6182
6340
  });
@@ -6379,6 +6537,39 @@ function prettifyPipelineString(pipelineString, options) {
6379
6537
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
6380
6538
  */
6381
6539
 
6540
+ /**
6541
+ * Tests if the value is [🚉] serializable as JSON
6542
+ *
6543
+ * - Almost all primitives are serializable BUT:
6544
+ * - `undefined` is not serializable
6545
+ * - `NaN` is not serializable
6546
+ * - Objects and arrays are serializable if all their properties are serializable
6547
+ * - Functions are not serializable
6548
+ * - Circular references are not serializable
6549
+ * - `Date` objects are not serializable
6550
+ * - `Map` and `Set` objects are not serializable
6551
+ * - `RegExp` objects are not serializable
6552
+ * - `Error` objects are not serializable
6553
+ * - `Symbol` objects are not serializable
6554
+ * - And much more...
6555
+ *
6556
+ *
6557
+ * @public exported from `@promptbook/utils`
6558
+ */
6559
+ function isSerializableAsJson(value) {
6560
+ try {
6561
+ checkSerializableAsJson('', value);
6562
+ return true;
6563
+ }
6564
+ catch (error) {
6565
+ return false;
6566
+ }
6567
+ }
6568
+ /**
6569
+ * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
6570
+ * TODO: [🧠][💺] Can be done this on type-level?
6571
+ */
6572
+
6382
6573
  /**
6383
6574
  * Stringify the PipelineJson with proper formatting
6384
6575
  *
@@ -6388,6 +6579,9 @@ function prettifyPipelineString(pipelineString, options) {
6388
6579
  * @public exported from `@promptbook/core`
6389
6580
  */
6390
6581
  function stringifyPipelineJson(pipeline) {
6582
+ if (!isSerializableAsJson(pipeline)) {
6583
+ throw new UnexpectedError(spaceTrim("\n Cannot stringify the pipeline, because it is not serializable as JSON\n\n There can be multiple reasons:\n 1) The pipeline contains circular references\n 2) It is not a valid PipelineJson\n "));
6584
+ }
6391
6585
  var pipelineJsonStringified = JSON.stringify(pipeline, null, 4);
6392
6586
  for (var i = 0; i < LOOP_LIMIT; i++) {
6393
6587
  pipelineJsonStringified = pipelineJsonStringified.replace(/(-?0\.\d+),[\n\s]+(-?0\.\d+)/gms, "$1".concat(REPLACING_NONCE, "$2"));
@@ -6403,54 +6597,6 @@ function stringifyPipelineJson(pipeline) {
6403
6597
  * TODO: [🍙] Make some standart order of json properties
6404
6598
  */
6405
6599
 
6406
- /**
6407
- * This error indicates that the pipeline collection cannot be propperly loaded
6408
- *
6409
- * @public exported from `@promptbook/core`
6410
- */
6411
- var CollectionError = /** @class */ (function (_super) {
6412
- __extends(CollectionError, _super);
6413
- function CollectionError(message) {
6414
- var _this = _super.call(this, message) || this;
6415
- _this.name = 'CollectionError';
6416
- Object.setPrototypeOf(_this, CollectionError.prototype);
6417
- return _this;
6418
- }
6419
- return CollectionError;
6420
- }(Error));
6421
-
6422
- /**
6423
- * This error type indicates that you try to use a feature that is not available in the current environment
6424
- *
6425
- * @public exported from `@promptbook/core`
6426
- */
6427
- var EnvironmentMismatchError = /** @class */ (function (_super) {
6428
- __extends(EnvironmentMismatchError, _super);
6429
- function EnvironmentMismatchError(message) {
6430
- var _this = _super.call(this, message) || this;
6431
- _this.name = 'EnvironmentMismatchError';
6432
- Object.setPrototypeOf(_this, EnvironmentMismatchError.prototype);
6433
- return _this;
6434
- }
6435
- return EnvironmentMismatchError;
6436
- }(Error));
6437
-
6438
- /**
6439
- * This error type indicates that the version of the pipeline is not matching the expected version
6440
- *
6441
- * @public exported from `@promptbook/core`
6442
- */
6443
- var VersionMismatchError = /** @class */ (function (_super) {
6444
- __extends(VersionMismatchError, _super);
6445
- function VersionMismatchError(message, expectedVersion) {
6446
- var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n This error indicates that there is error with compatibility\n\n Expected version:\n ").concat(expectedVersion, "\n\n Current version:\n ").concat(PROMPTBOOK_VERSION, "\n\n "); })) || this;
6447
- _this.name = 'UnexpectedError';
6448
- Object.setPrototypeOf(_this, VersionMismatchError.prototype);
6449
- return _this;
6450
- }
6451
- return VersionMismatchError;
6452
- }(Error));
6453
-
6454
6600
  /**
6455
6601
  * Pretty print an embedding vector for logging
6456
6602
  *
@@ -6543,14 +6689,11 @@ var CallbackInterfaceTools = /** @class */ (function () {
6543
6689
  *
6544
6690
  * Note: `$` is used to indicate that this function is not a pure function - it access global scope
6545
6691
  *
6546
- * @public exported from `@promptbook/utils`
6692
+ * @private internal function of `$Register`
6547
6693
  */
6548
6694
  function $getGlobalScope() {
6549
6695
  return Function('return this')();
6550
6696
  }
6551
- /***
6552
- * TODO: !!!!! Make private and promptbook registry from this
6553
- */
6554
6697
 
6555
6698
  /**
6556
6699
  * Register is @@@
@@ -6581,13 +6724,10 @@ var $Register = /** @class */ (function () {
6581
6724
  var packageName = registered.packageName, className = registered.className;
6582
6725
  var existingRegistrationIndex = this.storage.findIndex(function (item) { return item.packageName === packageName && item.className === className; });
6583
6726
  var existingRegistration = this.storage[existingRegistrationIndex];
6584
- // TODO: !!!!!! Global IS_VERBOSE mode
6585
6727
  if (!existingRegistration) {
6586
- console.warn("[\uD83D\uDCE6] Registering `".concat(packageName, ".").concat(className, "` to `").concat(this.storageName, "`"));
6587
6728
  this.storage.push(registered);
6588
6729
  }
6589
6730
  else {
6590
- console.warn("[\uD83D\uDCE6] Re-registering `".concat(packageName, ".").concat(className, "` to `").concat(this.storageName, "`"));
6591
6731
  this.storage[existingRegistrationIndex] = registered;
6592
6732
  }
6593
6733
  };
@@ -6717,7 +6857,7 @@ function $registeredLlmToolsMessage() {
6717
6857
  */
6718
6858
  function createLlmToolsFromConfiguration(configuration, options) {
6719
6859
  if (options === void 0) { options = {}; }
6720
- var _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
6860
+ var _a = options.isVerbose, isVerbose = _a === void 0 ? IS_VERBOSE : _a;
6721
6861
  var llmTools = configuration.map(function (llmConfiguration) {
6722
6862
  var registeredItem = $llmToolsRegister
6723
6863
  .list()
@@ -7443,5 +7583,5 @@ function executionReportJsonToString(executionReportJson, options) {
7443
7583
  * TODO: [🧠] Should be in generated file GENERATOR_WARNING
7444
7584
  */
7445
7585
 
7446
- export { $llmToolsMetadataRegister, $llmToolsRegister, BlockTypes, CLAIM, CallbackInterfaceTools, CollectionError, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, LimitReachedError, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParsingError, PipelineExecutionError, PipelineLogicError, PrefixStorage, RESERVED_PARAMETER_NAMES, ReferenceError$1 as ReferenceError, UnexpectedError, VersionMismatchError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _OpenAiMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
7586
+ export { $llmToolsMetadataRegister, $llmToolsRegister, BlockTypes, CLAIM, CallbackInterfaceTools, CollectionError, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, ERRORS, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, IS_VERBOSE, LimitReachedError, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParsingError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, RESERVED_PARAMETER_NAMES, UnexpectedError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _OpenAiMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
7447
7587
  //# sourceMappingURL=index.es.js.map