@promptbook/core 0.52.0-2 → 0.52.0-24

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 (50) hide show
  1. package/README.md +7 -6
  2. package/esm/index.es.js +1105 -179
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/_packages/core.index.d.ts +16 -6
  5. package/esm/typings/_packages/utils.index.d.ts +3 -8
  6. package/esm/typings/execution/ExecutionTools.d.ts +5 -3
  7. package/esm/typings/execution/plugins/llm-execution-tools/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +1 -0
  8. package/esm/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionTools.d.ts +4 -0
  9. package/esm/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionTools.d.ts +35 -0
  10. package/esm/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionToolsOptions.d.ts +23 -0
  11. package/esm/typings/execution/plugins/llm-execution-tools/multiple/playground/playground.d.ts +2 -0
  12. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.d.ts +1 -1
  13. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionTools.d.ts +4 -17
  14. package/esm/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +36 -4
  15. package/esm/typings/library/constructors/createPromptbookLibraryFromDirectory.test.d.ts +1 -0
  16. package/esm/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +2 -2
  17. package/esm/typings/library/constructors/createPromptbookLibraryFromPromise.test.d.ts +1 -0
  18. package/esm/typings/library/constructors/createPromptbookLibraryFromSources.test.d.ts +1 -0
  19. package/esm/typings/library/constructors/createPromptbookLibraryFromUrl.d.ts +21 -5
  20. package/esm/typings/library/constructors/justTestFsImport.d.ts +7 -0
  21. package/esm/typings/types/Prompt.d.ts +1 -1
  22. package/esm/typings/types/typeAliases.d.ts +2 -2
  23. package/package.json +3 -2
  24. package/umd/index.umd.js +1117 -182
  25. package/umd/index.umd.js.map +1 -1
  26. package/umd/typings/_packages/core.index.d.ts +16 -6
  27. package/umd/typings/_packages/utils.index.d.ts +3 -8
  28. package/umd/typings/execution/ExecutionTools.d.ts +5 -3
  29. package/umd/typings/execution/plugins/llm-execution-tools/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +1 -0
  30. package/umd/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionTools.d.ts +4 -0
  31. package/umd/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionTools.d.ts +35 -0
  32. package/umd/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionToolsOptions.d.ts +23 -0
  33. package/umd/typings/execution/plugins/llm-execution-tools/multiple/playground/playground.d.ts +2 -0
  34. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.d.ts +1 -1
  35. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionTools.d.ts +4 -17
  36. package/umd/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +36 -4
  37. package/umd/typings/library/constructors/createPromptbookLibraryFromDirectory.test.d.ts +1 -0
  38. package/umd/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +2 -2
  39. package/umd/typings/library/constructors/createPromptbookLibraryFromPromise.test.d.ts +1 -0
  40. package/umd/typings/library/constructors/createPromptbookLibraryFromSources.test.d.ts +1 -0
  41. package/umd/typings/library/constructors/createPromptbookLibraryFromUrl.d.ts +21 -5
  42. package/umd/typings/library/constructors/justTestFsImport.d.ts +7 -0
  43. package/umd/typings/types/Prompt.d.ts +1 -1
  44. package/umd/typings/types/typeAliases.d.ts +2 -2
  45. package/esm/typings/_packages/wizzard.index.d.ts +0 -5
  46. package/esm/typings/wizzard/Wizzard.d.ts +0 -4
  47. package/esm/typings/wizzard/sample.d.ts +0 -6
  48. package/umd/typings/_packages/wizzard.index.d.ts +0 -5
  49. package/umd/typings/wizzard/Wizzard.d.ts +0 -4
  50. package/umd/typings/wizzard/sample.d.ts +0 -6
package/umd/index.umd.js CHANGED
@@ -1,13 +1,14 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('moment')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'moment'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, global.prettier, global.parserHtml));
5
- })(this, (function (exports, spaceTrim, prettier, parserHtml) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('path'), require('moment')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'path', 'moment'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, global.prettier, global.parserHtml, global.path, global.moment));
5
+ })(this, (function (exports, spaceTrim, prettier, parserHtml, path, moment) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
9
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
10
10
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
11
+ var moment__default = /*#__PURE__*/_interopDefaultLegacy(moment);
11
12
 
12
13
  /*! *****************************************************************************
13
14
  Copyright (c) Microsoft Corporation.
@@ -453,7 +454,7 @@
453
454
  /**
454
455
  * The version of the Promptbook library
455
456
  */
456
- var PROMPTBOOK_VERSION = '0.52.0-1';
457
+ var PROMPTBOOK_VERSION = '0.52.0-23';
457
458
 
458
459
  /**
459
460
  * Parses the template and returns the list of all parameter names
@@ -575,38 +576,6 @@
575
576
  * TODO: [🔣] If script require contentLanguage
576
577
  */
577
578
 
578
- /**
579
- * Prettify the html code
580
- *
581
- * @param content raw html code
582
- * @returns formatted html code
583
- */
584
- function prettifyMarkdown(content) {
585
- try {
586
- return prettier.format(content, {
587
- parser: 'markdown',
588
- plugins: [parserHtml__default["default"]],
589
- // TODO: DRY - make some import or auto-copy of .prettierrc
590
- endOfLine: 'lf',
591
- tabWidth: 4,
592
- singleQuote: true,
593
- trailingComma: 'all',
594
- arrowParens: 'always',
595
- printWidth: 120,
596
- htmlWhitespaceSensitivity: 'ignore',
597
- jsxBracketSameLine: false,
598
- bracketSpacing: true,
599
- });
600
- }
601
- catch (error) {
602
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
603
- error: error,
604
- html: content,
605
- });
606
- return content;
607
- }
608
- }
609
-
610
579
  /**
611
580
  * Removes emojis from a string and fix whitespaces
612
581
  *
@@ -632,6 +601,64 @@
632
601
  return value;
633
602
  }
634
603
 
604
+ /**
605
+ * Creates a Mermaid graph based on the promptbook
606
+ *
607
+ * Note: The result is not wrapped in a Markdown code block
608
+ */
609
+ function renderPromptbookMermaid(promptbookJson, options) {
610
+ var _a = (options || {}).linkPromptTemplate, linkPromptTemplate = _a === void 0 ? function () { return null; } : _a;
611
+ var parameterNameToTemplateName = function (parameterName) {
612
+ var parameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
613
+ if (!parameter) {
614
+ throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
615
+ }
616
+ if (parameter.isInput) {
617
+ return 'input';
618
+ }
619
+ var template = promptbookJson.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
620
+ if (!template) {
621
+ throw new Error("Could not find template for {".concat(parameterName, "}"));
622
+ }
623
+ return normalizeTo_camelCase('template-' + titleToName(template.title));
624
+ };
625
+ var promptbookMermaid = spaceTrim.spaceTrim(function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson.promptTemplates
626
+ .flatMap(function (_a) {
627
+ var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
628
+ return __spreadArray([
629
+ "".concat(parameterNameToTemplateName(resultingParameterName), "(\"").concat(title, "\")")
630
+ ], __read(dependentParameterNames.map(function (dependentParameterName) {
631
+ return "".concat(parameterNameToTemplateName(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName(resultingParameterName));
632
+ })), false);
633
+ })
634
+ .join('\n')), "\n\n ").concat(block(promptbookJson.parameters
635
+ .filter(function (_a) {
636
+ var isOutput = _a.isOutput;
637
+ return isOutput;
638
+ })
639
+ .map(function (_a) {
640
+ var name = _a.name;
641
+ return "".concat(parameterNameToTemplateName(name), "--\"{").concat(name, "}\"-->output");
642
+ })
643
+ .join('\n')), "\n output((Output)):::output\n\n ").concat(block(promptbookJson.promptTemplates
644
+ .map(function (promptTemplate) {
645
+ var link = linkPromptTemplate(promptTemplate);
646
+ if (link === null) {
647
+ return '';
648
+ }
649
+ var href = link.href, title = link.title;
650
+ var templateName = parameterNameToTemplateName(promptTemplate.resultingParameterName);
651
+ return "click ".concat(templateName, " href \"").concat(href, "\" \"").concat(title, "\";");
652
+ })
653
+ .filter(function (line) { return line !== ''; })
654
+ .join('\n')), "\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n "); });
655
+ return promptbookMermaid;
656
+ }
657
+ /**
658
+ * TODO: Maybe use some Mermaid library instead of string templating
659
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
660
+ */
661
+
635
662
  /**
636
663
  * Function parseNumber will parse number from string
637
664
  *
@@ -714,35 +741,80 @@
714
741
  }(Error));
715
742
 
716
743
  /**
717
- * This error indicates errors during the execution of the promptbook
744
+ * This error occurs during the parameter replacement in the template
745
+ *
746
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
718
747
  */
719
- var PromptbookExecutionError = /** @class */ (function (_super) {
720
- __extends(PromptbookExecutionError, _super);
721
- function PromptbookExecutionError(message) {
748
+ var TemplateError = /** @class */ (function (_super) {
749
+ __extends(TemplateError, _super);
750
+ function TemplateError(message) {
722
751
  var _this = _super.call(this, message) || this;
723
- _this.name = 'PromptbookExecutionError';
724
- Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
752
+ _this.name = 'TemplateError';
753
+ Object.setPrototypeOf(_this, TemplateError.prototype);
725
754
  return _this;
726
755
  }
727
- return PromptbookExecutionError;
756
+ return TemplateError;
728
757
  }(Error));
729
758
 
730
759
  /**
731
- * This error occurs when some expectation is not met in the execution of the pipeline
760
+ * Replaces parameters in template with values from parameters object
732
761
  *
733
- * @private Always catched and rethrown as `PromptbookExecutionError`
734
- * Note: This is a kindof subtype of PromptbookExecutionError
762
+ * @param template the template with parameters in {curly} braces
763
+ * @param parameters the object with parameters
764
+ * @returns the template with replaced parameters
765
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
766
+ *
767
+ * @private within the createPromptbookExecutor
735
768
  */
736
- var ExpectError = /** @class */ (function (_super) {
737
- __extends(ExpectError, _super);
738
- function ExpectError(message) {
739
- var _this = _super.call(this, message) || this;
740
- _this.name = 'ExpectError';
741
- Object.setPrototypeOf(_this, ExpectError.prototype);
742
- return _this;
769
+ function replaceParameters(template, parameters) {
770
+ var replacedTemplate = template;
771
+ var match;
772
+ var loopLimit = LOOP_LIMIT;
773
+ var _loop_1 = function () {
774
+ if (loopLimit-- < 0) {
775
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
776
+ }
777
+ var precol = match.groups.precol;
778
+ var parameterName = match.groups.parameterName;
779
+ if (parameterName === '') {
780
+ return "continue";
781
+ }
782
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
783
+ throw new TemplateError('Parameter is already opened or not closed');
784
+ }
785
+ if (parameters[parameterName] === undefined) {
786
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
787
+ }
788
+ var parameterValue = parameters[parameterName];
789
+ if (parameterValue === undefined) {
790
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
791
+ }
792
+ parameterValue = parameterValue.toString();
793
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
794
+ parameterValue = parameterValue
795
+ .split('\n')
796
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
797
+ .join('\n');
798
+ }
799
+ replacedTemplate =
800
+ replacedTemplate.substring(0, match.index + precol.length) +
801
+ parameterValue +
802
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
803
+ };
804
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
805
+ .exec(replacedTemplate))) {
806
+ _loop_1();
743
807
  }
744
- return ExpectError;
745
- }(Error));
808
+ // [💫] Check if there are parameters that are not closed properly
809
+ if (/{\w+$/.test(replacedTemplate)) {
810
+ throw new TemplateError('Parameter is not closed');
811
+ }
812
+ // [💫] Check if there are parameters that are not opened properly
813
+ if (/^\w+}/.test(replacedTemplate)) {
814
+ throw new TemplateError('Parameter is not opened');
815
+ }
816
+ return replacedTemplate;
817
+ }
746
818
 
747
819
  /**
748
820
  * Counts number of characters in the text
@@ -1070,118 +1142,6 @@
1070
1142
  PAGES: countPages,
1071
1143
  };
1072
1144
 
1073
- /**
1074
- * Function checkExpectations will check if the expectations on given value are met
1075
- *
1076
- * Note: There are two simmilar functions:
1077
- * - `checkExpectations` which throws an error if the expectations are not met
1078
- * - `isPassingExpectations` which returns a boolean
1079
- *
1080
- * @throws {ExpectError} if the expectations are not met
1081
- * @returns {void} Nothing
1082
- */
1083
- function checkExpectations(expectations, value) {
1084
- var e_1, _a;
1085
- try {
1086
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
1087
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
1088
- var amount = CountUtils[unit.toUpperCase()](value);
1089
- if (min && amount < min) {
1090
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
1091
- } /* not else */
1092
- if (max && amount > max) {
1093
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1094
- }
1095
- }
1096
- }
1097
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1098
- finally {
1099
- try {
1100
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1101
- }
1102
- finally { if (e_1) throw e_1.error; }
1103
- }
1104
- }
1105
- /**
1106
- * TODO: [💝] Unite object for expecting amount and format
1107
- */
1108
-
1109
- /**
1110
- * This error occurs during the parameter replacement in the template
1111
- *
1112
- * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
1113
- */
1114
- var TemplateError = /** @class */ (function (_super) {
1115
- __extends(TemplateError, _super);
1116
- function TemplateError(message) {
1117
- var _this = _super.call(this, message) || this;
1118
- _this.name = 'TemplateError';
1119
- Object.setPrototypeOf(_this, TemplateError.prototype);
1120
- return _this;
1121
- }
1122
- return TemplateError;
1123
- }(Error));
1124
-
1125
- /**
1126
- * Replaces parameters in template with values from parameters object
1127
- *
1128
- * @param template the template with parameters in {curly} braces
1129
- * @param parameters the object with parameters
1130
- * @returns the template with replaced parameters
1131
- * @throws {TemplateError} if parameter is not defined, not closed, or not opened
1132
- *
1133
- * @private within the createPromptbookExecutor
1134
- */
1135
- function replaceParameters(template, parameters) {
1136
- var replacedTemplate = template;
1137
- var match;
1138
- var loopLimit = LOOP_LIMIT;
1139
- var _loop_1 = function () {
1140
- if (loopLimit-- < 0) {
1141
- throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
1142
- }
1143
- var precol = match.groups.precol;
1144
- var parameterName = match.groups.parameterName;
1145
- if (parameterName === '') {
1146
- return "continue";
1147
- }
1148
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
1149
- throw new TemplateError('Parameter is already opened or not closed');
1150
- }
1151
- if (parameters[parameterName] === undefined) {
1152
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
1153
- }
1154
- var parameterValue = parameters[parameterName];
1155
- if (parameterValue === undefined) {
1156
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
1157
- }
1158
- parameterValue = parameterValue.toString();
1159
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
1160
- parameterValue = parameterValue
1161
- .split('\n')
1162
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
1163
- .join('\n');
1164
- }
1165
- replacedTemplate =
1166
- replacedTemplate.substring(0, match.index + precol.length) +
1167
- parameterValue +
1168
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
1169
- };
1170
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
1171
- .exec(replacedTemplate))) {
1172
- _loop_1();
1173
- }
1174
- // [💫] Check if there are parameters that are not closed properly
1175
- if (/{\w+$/.test(replacedTemplate)) {
1176
- throw new TemplateError('Parameter is not closed');
1177
- }
1178
- // [💫] Check if there are parameters that are not opened properly
1179
- if (/^\w+}/.test(replacedTemplate)) {
1180
- throw new TemplateError('Parameter is not opened');
1181
- }
1182
- return replacedTemplate;
1183
- }
1184
-
1185
1145
  /**
1186
1146
  * Function isValidJsonString will tell you if the string is valid JSON or not
1187
1147
  */
@@ -1336,6 +1296,61 @@
1336
1296
  return normalizedName;
1337
1297
  }
1338
1298
 
1299
+ /* tslint:disable */
1300
+ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1301
+ var e_1, _a;
1302
+ if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1303
+ var charType;
1304
+ var lastCharType = null;
1305
+ var normalizedName = '';
1306
+ try {
1307
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1308
+ var char = sentence_1_1.value;
1309
+ var normalizedChar = void 0;
1310
+ if (/^[a-z]$/.test(char)) {
1311
+ charType = 'LOWERCASE';
1312
+ normalizedChar = char;
1313
+ }
1314
+ else if (/^[A-Z]$/.test(char)) {
1315
+ charType = 'UPPERCASE';
1316
+ normalizedChar = char.toLowerCase();
1317
+ }
1318
+ else if (/^[0-9]$/.test(char)) {
1319
+ charType = 'NUMBER';
1320
+ normalizedChar = char;
1321
+ }
1322
+ else {
1323
+ charType = 'OTHER';
1324
+ normalizedChar = '';
1325
+ }
1326
+ if (!lastCharType) {
1327
+ if (__firstLetterCapital) {
1328
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1329
+ }
1330
+ }
1331
+ else if (charType !== lastCharType &&
1332
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1333
+ !(lastCharType === 'NUMBER') &&
1334
+ !(charType === 'NUMBER')) {
1335
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1336
+ }
1337
+ normalizedName += normalizedChar;
1338
+ lastCharType = charType;
1339
+ }
1340
+ }
1341
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1342
+ finally {
1343
+ try {
1344
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1345
+ }
1346
+ finally { if (e_1) throw e_1.error; }
1347
+ }
1348
+ return normalizedName;
1349
+ }
1350
+ /**
1351
+ * TODO: [🌺] Use some intermediate util splitWords
1352
+ */
1353
+
1339
1354
  /**
1340
1355
  * Execution type describes the way how the block is executed
1341
1356
  *
@@ -1854,6 +1869,87 @@
1854
1869
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1855
1870
  */
1856
1871
 
1872
+ /**
1873
+ * Add or modify an auto-generated section in a markdown file
1874
+ *
1875
+ * @private within the library
1876
+ */
1877
+ function addAutoGeneratedSection(content, options) {
1878
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
1879
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1880
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1881
+ var sectionMatch = content.match(sectionRegex);
1882
+ if (sectionMatch) {
1883
+ return content.replace(sectionRegex, spaceTrim.spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1884
+ }
1885
+ var placeForSection = removeContentComments(content).match(/^##.*$/im);
1886
+ if (!placeForSection) {
1887
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1888
+ }
1889
+ var _a = __read(placeForSection, 1), heading = _a[0];
1890
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1891
+ }
1892
+
1893
+ /**
1894
+ * Prettify the html code
1895
+ *
1896
+ * @param content raw html code
1897
+ * @returns formatted html code
1898
+ */
1899
+ function prettifyMarkdown(content) {
1900
+ try {
1901
+ return prettier.format(content, {
1902
+ parser: 'markdown',
1903
+ plugins: [parserHtml__default["default"]],
1904
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1905
+ endOfLine: 'lf',
1906
+ tabWidth: 4,
1907
+ singleQuote: true,
1908
+ trailingComma: 'all',
1909
+ arrowParens: 'always',
1910
+ printWidth: 120,
1911
+ htmlWhitespaceSensitivity: 'ignore',
1912
+ jsxBracketSameLine: false,
1913
+ bracketSpacing: true,
1914
+ });
1915
+ }
1916
+ catch (error) {
1917
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1918
+ error: error,
1919
+ html: content,
1920
+ });
1921
+ return content;
1922
+ }
1923
+ }
1924
+
1925
+ /**
1926
+ * Prettyfies Promptbook string and adds Mermaid graph
1927
+ */
1928
+ function prettifyPromptbookString(promptbookString, options) {
1929
+ var isGraphAdded = options.isGraphAdded, isPrettifyed = options.isPrettifyed;
1930
+ if (isGraphAdded) {
1931
+ var promptbookJson = promptbookStringToJson(promptbookString);
1932
+ var promptbookMermaid_1 = renderPromptbookMermaid(promptbookJson, {
1933
+ linkPromptTemplate: function (promptTemplate) {
1934
+ return { href: "#".concat(promptTemplate.name), title: promptTemplate.title };
1935
+ },
1936
+ });
1937
+ var promptbookMermaidBlock = spaceTrim.spaceTrim(function (block) { return "\n ```mermaid\n ".concat(block(promptbookMermaid_1), "\n ```\n "); });
1938
+ promptbookString = addAutoGeneratedSection(promptbookString, {
1939
+ sectionName: 'Graph',
1940
+ sectionContent: promptbookMermaidBlock,
1941
+ });
1942
+ }
1943
+ if (isPrettifyed) {
1944
+ promptbookString = prettifyMarkdown(promptbookString);
1945
+ }
1946
+ return promptbookString;
1947
+ }
1948
+ /**
1949
+ * TODO: Maybe use some Mermaid library instead of string templating
1950
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
1951
+ */
1952
+
1857
1953
  /**
1858
1954
  * Converts promptbook in JSON format to string format
1859
1955
  *
@@ -2228,18 +2324,131 @@
2228
2324
  while (unresovedTemplates.length > 0) {
2229
2325
  _loop_2();
2230
2326
  }
2231
- return promptbook;
2327
+ return promptbook;
2328
+ }
2329
+ /**
2330
+ * TODO: [🧠] Work with promptbookVersion
2331
+ * TODO: Use here some json-schema, Zod or something similar and change it to:
2332
+ * > /**
2333
+ * > * Validates PromptbookJson if it is logically valid.
2334
+ * > *
2335
+ * > * It checks:
2336
+ * > * - it has a valid structure
2337
+ * > * - ...
2338
+ * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
2339
+ */
2340
+
2341
+ /**
2342
+ * This error indicates errors during the execution of the promptbook
2343
+ */
2344
+ var PromptbookExecutionError = /** @class */ (function (_super) {
2345
+ __extends(PromptbookExecutionError, _super);
2346
+ function PromptbookExecutionError(message) {
2347
+ var _this = _super.call(this, message) || this;
2348
+ _this.name = 'PromptbookExecutionError';
2349
+ Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
2350
+ return _this;
2351
+ }
2352
+ return PromptbookExecutionError;
2353
+ }(Error));
2354
+
2355
+ /**
2356
+ * Asserts that the execution of a promptnook is successful
2357
+ *
2358
+ * @param executionResult - The partial result of the promptnook execution
2359
+ * @throws {PromptbookExecutionError} If the execution is not successful or if multiple errors occurred
2360
+ */
2361
+ function assertsExecutionSuccessful(executionResult) {
2362
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2363
+ if (isSuccessful === true) {
2364
+ return;
2365
+ }
2366
+ if (errors.length === 0) {
2367
+ throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
2368
+ }
2369
+ else if (errors.length === 1) {
2370
+ throw errors[0];
2371
+ }
2372
+ else {
2373
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Multiple errors occurred during promptnook execution\n\n ".concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n')), "\n "); }));
2374
+ }
2375
+ }
2376
+ /**
2377
+ * TODO: [🧠] Can this return type be better typed than void
2378
+ */
2379
+
2380
+ /**
2381
+ * This error occurs when some expectation is not met in the execution of the pipeline
2382
+ *
2383
+ * @private Always catched and rethrown as `PromptbookExecutionError`
2384
+ * Note: This is a kindof subtype of PromptbookExecutionError
2385
+ */
2386
+ var ExpectError = /** @class */ (function (_super) {
2387
+ __extends(ExpectError, _super);
2388
+ function ExpectError(message) {
2389
+ var _this = _super.call(this, message) || this;
2390
+ _this.name = 'ExpectError';
2391
+ Object.setPrototypeOf(_this, ExpectError.prototype);
2392
+ return _this;
2393
+ }
2394
+ return ExpectError;
2395
+ }(Error));
2396
+
2397
+ /**
2398
+ * Function checkExpectations will check if the expectations on given value are met
2399
+ *
2400
+ * Note: There are two simmilar functions:
2401
+ * - `checkExpectations` which throws an error if the expectations are not met
2402
+ * - `isPassingExpectations` which returns a boolean
2403
+ *
2404
+ * @throws {ExpectError} if the expectations are not met
2405
+ * @returns {void} Nothing
2406
+ */
2407
+ function checkExpectations(expectations, value) {
2408
+ var e_1, _a;
2409
+ try {
2410
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
2411
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
2412
+ var amount = CountUtils[unit.toUpperCase()](value);
2413
+ if (min && amount < min) {
2414
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2415
+ } /* not else */
2416
+ if (max && amount > max) {
2417
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2418
+ }
2419
+ }
2420
+ }
2421
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2422
+ finally {
2423
+ try {
2424
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2425
+ }
2426
+ finally { if (e_1) throw e_1.error; }
2427
+ }
2428
+ }
2429
+ /**
2430
+ * Function checkExpectations will check if the expectations on given value are met
2431
+ *
2432
+ * Note: There are two simmilar functions:
2433
+ * - `checkExpectations` which throws an error if the expectations are not met
2434
+ * - `isPassingExpectations` which returns a boolean
2435
+ *
2436
+ * @returns {boolean} True if the expectations are met
2437
+ */
2438
+ function isPassingExpectations(expectations, value) {
2439
+ try {
2440
+ checkExpectations(expectations, value);
2441
+ return true;
2442
+ }
2443
+ catch (error) {
2444
+ if (!(error instanceof ExpectError)) {
2445
+ throw error;
2446
+ }
2447
+ return false;
2448
+ }
2232
2449
  }
2233
2450
  /**
2234
- * TODO: [🧠] Work with promptbookVersion
2235
- * TODO: Use here some json-schema, Zod or something similar and change it to:
2236
- * > /**
2237
- * > * Validates PromptbookJson if it is logically valid.
2238
- * > *
2239
- * > * It checks:
2240
- * > * - it has a valid structure
2241
- * > * - ...
2242
- * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
2451
+ * TODO: [💝] Unite object for expecting amount and format
2243
2452
  */
2244
2453
 
2245
2454
  /**
@@ -2323,7 +2532,7 @@
2323
2532
  title: currentTemplate.title,
2324
2533
  promptbookUrl: "".concat(promptbook.promptbookUrl
2325
2534
  ? promptbook.promptbookUrl
2326
- : 'anonymous' /* <- [🧠][🈴] How to deal with anonymous PROMPTBOOKs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
2535
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous PROMPTBOOKs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
2327
2536
  parameters: parametersToPass,
2328
2537
  content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
2329
2538
  modelRequirements: currentTemplate.modelRequirements,
@@ -2761,6 +2970,137 @@
2761
2970
  * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
2762
2971
  */
2763
2972
 
2973
+ /**
2974
+ * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2975
+ *
2976
+ * @see https://github.com/webgptorg/promptbook#multiple-server
2977
+ */
2978
+ var MultipleLlmExecutionTools = /** @class */ (function () {
2979
+ /**
2980
+ * Gets array of execution tools in order of priority
2981
+ */
2982
+ function MultipleLlmExecutionTools() {
2983
+ var llmExecutionTools = [];
2984
+ for (var _i = 0; _i < arguments.length; _i++) {
2985
+ llmExecutionTools[_i] = arguments[_i];
2986
+ }
2987
+ this.llmExecutionTools = llmExecutionTools;
2988
+ }
2989
+ /**
2990
+ * Calls the best available chat model
2991
+ */
2992
+ MultipleLlmExecutionTools.prototype.gptChat = function (prompt) {
2993
+ return this.gptCommon(prompt);
2994
+ };
2995
+ /**
2996
+ * Calls the best available completion model
2997
+ */
2998
+ MultipleLlmExecutionTools.prototype.gptComplete = function (prompt) {
2999
+ return this.gptCommon(prompt);
3000
+ };
3001
+ /**
3002
+ * Calls the best available model
3003
+ */
3004
+ MultipleLlmExecutionTools.prototype.gptCommon = function (prompt) {
3005
+ return __awaiter(this, void 0, void 0, function () {
3006
+ var errors, _a, _b, llmExecutionTools, error_1, e_1_1;
3007
+ var e_1, _c;
3008
+ return __generator(this, function (_d) {
3009
+ switch (_d.label) {
3010
+ case 0:
3011
+ errors = [];
3012
+ _d.label = 1;
3013
+ case 1:
3014
+ _d.trys.push([1, 11, 12, 13]);
3015
+ _a = __values(this.llmExecutionTools), _b = _a.next();
3016
+ _d.label = 2;
3017
+ case 2:
3018
+ if (!!_b.done) return [3 /*break*/, 10];
3019
+ llmExecutionTools = _b.value;
3020
+ _d.label = 3;
3021
+ case 3:
3022
+ _d.trys.push([3, 8, , 9]);
3023
+ if (!(prompt.modelRequirements.modelVariant === 'CHAT')) return [3 /*break*/, 5];
3024
+ return [4 /*yield*/, llmExecutionTools.gptChat(prompt)];
3025
+ case 4: return [2 /*return*/, _d.sent()];
3026
+ case 5:
3027
+ if (!(prompt.modelRequirements.modelVariant === 'COMPLETION')) return [3 /*break*/, 7];
3028
+ return [4 /*yield*/, llmExecutionTools.gptComplete(prompt)];
3029
+ case 6: return [2 /*return*/, _d.sent()];
3030
+ case 7: return [3 /*break*/, 9];
3031
+ case 8:
3032
+ error_1 = _d.sent();
3033
+ if (!(error_1 instanceof Error)) {
3034
+ throw error_1;
3035
+ }
3036
+ errors.push(error_1);
3037
+ return [3 /*break*/, 9];
3038
+ case 9:
3039
+ _b = _a.next();
3040
+ return [3 /*break*/, 2];
3041
+ case 10: return [3 /*break*/, 13];
3042
+ case 11:
3043
+ e_1_1 = _d.sent();
3044
+ e_1 = { error: e_1_1 };
3045
+ return [3 /*break*/, 13];
3046
+ case 12:
3047
+ try {
3048
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3049
+ }
3050
+ finally { if (e_1) throw e_1.error; }
3051
+ return [7 /*endfinally*/];
3052
+ case 13: throw new Error(spaceTrim__default["default"](function (block) { return "\n All execution tools failed:\n \n ".concat(block(errors.map(function (error) { return "- ".concat(error.name || 'Error', ": ").concat(error.message); }).join('\n')), "\n \n "); }));
3053
+ }
3054
+ });
3055
+ });
3056
+ };
3057
+ /**
3058
+ * List all available models that can be used
3059
+ * This liost is a combination of all available models from all execution tools
3060
+ */
3061
+ MultipleLlmExecutionTools.prototype.listModels = function () {
3062
+ return __awaiter(this, void 0, void 0, function () {
3063
+ var availableModels, _a, _b, llmExecutionTools, models, e_2_1;
3064
+ var e_2, _c;
3065
+ return __generator(this, function (_d) {
3066
+ switch (_d.label) {
3067
+ case 0:
3068
+ availableModels = [];
3069
+ _d.label = 1;
3070
+ case 1:
3071
+ _d.trys.push([1, 6, 7, 8]);
3072
+ _a = __values(this.llmExecutionTools), _b = _a.next();
3073
+ _d.label = 2;
3074
+ case 2:
3075
+ if (!!_b.done) return [3 /*break*/, 5];
3076
+ llmExecutionTools = _b.value;
3077
+ return [4 /*yield*/, llmExecutionTools.listModels()];
3078
+ case 3:
3079
+ models = _d.sent();
3080
+ availableModels.push.apply(availableModels, __spreadArray([], __read(models), false));
3081
+ _d.label = 4;
3082
+ case 4:
3083
+ _b = _a.next();
3084
+ return [3 /*break*/, 2];
3085
+ case 5: return [3 /*break*/, 8];
3086
+ case 6:
3087
+ e_2_1 = _d.sent();
3088
+ e_2 = { error: e_2_1 };
3089
+ return [3 /*break*/, 8];
3090
+ case 7:
3091
+ try {
3092
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3093
+ }
3094
+ finally { if (e_2) throw e_2.error; }
3095
+ return [7 /*endfinally*/];
3096
+ case 8: return [2 /*return*/, availableModels];
3097
+ }
3098
+ });
3099
+ });
3100
+ };
3101
+ return MultipleLlmExecutionTools;
3102
+ }());
3103
+
2764
3104
  /**
2765
3105
  * Delagates the user interaction to a async callback function
2766
3106
  * You need to provide your own implementation of this callback function and its bind to UI.
@@ -2822,6 +3162,36 @@
2822
3162
  return SimplePromptInterfaceTools;
2823
3163
  }());
2824
3164
 
3165
+ /**
3166
+ * Detects if the code is running in a browser environment in main thread (Not in a web worker)
3167
+ */
3168
+ new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
3169
+ /**
3170
+ * Detects if the code is running in a Node.js environment
3171
+ */
3172
+ var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
3173
+ /**
3174
+ * Detects if the code is running in a web worker
3175
+ */
3176
+ new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
3177
+
3178
+ /**
3179
+ * Returns the same value that is passed as argument.
3180
+ * No side effects.
3181
+ *
3182
+ * Note: It can be usefull for leveling indentation
3183
+ *
3184
+ * @param value any values
3185
+ * @returns the same values
3186
+ */
3187
+ function just(value) {
3188
+ if (value === undefined) {
3189
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3190
+ return undefined;
3191
+ }
3192
+ return value;
3193
+ }
3194
+
2825
3195
  /**
2826
3196
  * This error indicates that promptbook not found in the library
2827
3197
  */
@@ -2879,6 +3249,12 @@
2879
3249
  throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the promptbook library\n\n ")));
2880
3250
  }
2881
3251
  validatePromptbookJson(promptbook);
3252
+ // Note: [🦄]
3253
+ if (this.library.has(promptbook.promptbookUrl) &&
3254
+ promptbookJsonToString(promptbook) !==
3255
+ promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
3256
+ throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with URL \"".concat(promptbook.promptbookUrl, "\" is already in the library\n\n Note: Promptbooks with the same URL are not allowed\n Note: Automatically check whether the promptbooks are the same BUT they are DIFFERENT\n\n ")));
3257
+ }
2882
3258
  this.library.set(promptbook.promptbookUrl, promptbook);
2883
3259
  }
2884
3260
  }
@@ -2905,6 +3281,9 @@
2905
3281
  var _this = this;
2906
3282
  var promptbook = this.library.get(url);
2907
3283
  if (!promptbook) {
3284
+ if (this.listPromptbooks().length === 0) {
3285
+ throw new PromptbookNotFoundError(spaceTrim.spaceTrim("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
3286
+ }
2908
3287
  throw new PromptbookNotFoundError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
2909
3288
  .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
2910
3289
  .join('\n')), "\n\n "); }));
@@ -2977,11 +3356,11 @@
2977
3356
  * Note: The function does NOT return promise it returns the library directly which waits for the sources to be resolved
2978
3357
  * when error occurs in given promise or factory function, it is thrown during `listPromptbooks` or `getPromptbookByUrl` call
2979
3358
  *
3359
+ * Note: Consider using `createPromptbookLibraryFromUrl` or `createPromptbookLibraryFromDirectory`
2980
3360
  *
2981
3361
  * @param promptbookSourcesPromiseOrFactory
2982
3362
  * @returns PromptbookLibrary
2983
- *
2984
- * @deprecated Consider using `createPromptbookLibraryFromUrl` or `createPromptbookLibraryFromDirectory`
3363
+ * @private Just internal tool for other constructor functions
2985
3364
  */
2986
3365
  function createPromptbookLibraryFromPromise(promptbookSourcesPromiseOrFactory) {
2987
3366
  var library;
@@ -3050,6 +3429,228 @@
3050
3429
  * TODO: [🍓][🚯] !!! Add to README and samples + maybe make `@promptbook/library` package
3051
3430
  */
3052
3431
 
3432
+ /**
3433
+ * Constructs Promptbook from given directory
3434
+ *
3435
+ * Note: Works only in Node.js environment because it reads the file system
3436
+ *
3437
+ * @param path - path to the directory with promptbooks
3438
+ * @param options - Misc options for the library
3439
+ * @returns PromptbookLibrary
3440
+ */
3441
+ function createPromptbookLibraryFromDirectory(path, options) {
3442
+ return __awaiter(this, void 0, void 0, function () {
3443
+ var _a, _b, isRecursive, _c, isVerbose, _d, isLazyLoaded, library;
3444
+ var _this = this;
3445
+ return __generator(this, function (_e) {
3446
+ switch (_e.label) {
3447
+ case 0:
3448
+ if (!isRunningInNode()) {
3449
+ throw new Error('Function `createPromptbookLibraryFromDirectory` can only be run in Node.js environment because it reads the file system.');
3450
+ }
3451
+ _a = options || {}, _b = _a.isRecursive, isRecursive = _b === void 0 ? true : _b, _c = _a.isVerbose, isVerbose = _c === void 0 ? false : _c, _d = _a.isLazyLoaded, isLazyLoaded = _d === void 0 ? false : _d;
3452
+ library = createPromptbookLibraryFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
3453
+ var fsPromises, readFile, fileNames, promptbooks, fileNames_1, fileNames_1_1, fileName, promptbook, promptbookString, _a, _b, e_1_1;
3454
+ var e_1, _c;
3455
+ return __generator(this, function (_d) {
3456
+ switch (_d.label) {
3457
+ case 0:
3458
+ if (isVerbose) {
3459
+ console.info("Creating promptbook library from path ".concat(path));
3460
+ }
3461
+ fsPromises = require(just('fs/promises') /* <- Note: [1] */);
3462
+ readFile = fsPromises.readFile;
3463
+ return [4 /*yield*/, listAllFiles(path, isRecursive)];
3464
+ case 1:
3465
+ fileNames = _d.sent();
3466
+ if (isVerbose) {
3467
+ console.info('createPromptbookLibraryFromDirectory', { path: path, isRecursive: isRecursive, fileNames: fileNames });
3468
+ }
3469
+ promptbooks = [];
3470
+ _d.label = 2;
3471
+ case 2:
3472
+ _d.trys.push([2, 11, 12, 13]);
3473
+ fileNames_1 = __values(fileNames), fileNames_1_1 = fileNames_1.next();
3474
+ _d.label = 3;
3475
+ case 3:
3476
+ if (!!fileNames_1_1.done) return [3 /*break*/, 10];
3477
+ fileName = fileNames_1_1.value;
3478
+ promptbook = null;
3479
+ if (!fileName.endsWith('.ptbk.md')) return [3 /*break*/, 5];
3480
+ return [4 /*yield*/, readFile(fileName, 'utf8')];
3481
+ case 4:
3482
+ promptbookString = (_d.sent());
3483
+ promptbook = promptbookStringToJson(promptbookString);
3484
+ return [3 /*break*/, 8];
3485
+ case 5:
3486
+ if (!fileName.endsWith('.ptbk.json')) return [3 /*break*/, 7];
3487
+ if (isVerbose) {
3488
+ console.info("Loading ".concat(fileName));
3489
+ }
3490
+ _b = (_a = JSON).parse;
3491
+ return [4 /*yield*/, readFile(fileName, 'utf8')];
3492
+ case 6:
3493
+ // TODO: Handle non-valid JSON files
3494
+ promptbook = _b.apply(_a, [_d.sent()]);
3495
+ return [3 /*break*/, 8];
3496
+ case 7:
3497
+ if (isVerbose) {
3498
+ console.info("Skipping file ".concat(fileName));
3499
+ }
3500
+ _d.label = 8;
3501
+ case 8:
3502
+ // ---
3503
+ if (promptbook !== null) {
3504
+ if (!promptbook.promptbookUrl) {
3505
+ if (isVerbose) {
3506
+ console.info("Not loading ".concat(fileName, " - missing URL"));
3507
+ }
3508
+ }
3509
+ else {
3510
+ if (isVerbose) {
3511
+ console.info("Loading ".concat(fileName));
3512
+ }
3513
+ // Note: [🦄] Promptbook with same url uniqueness will be checked automatically in SimplePromptbookLibrary
3514
+ promptbooks.push(promptbook);
3515
+ }
3516
+ }
3517
+ _d.label = 9;
3518
+ case 9:
3519
+ fileNames_1_1 = fileNames_1.next();
3520
+ return [3 /*break*/, 3];
3521
+ case 10: return [3 /*break*/, 13];
3522
+ case 11:
3523
+ e_1_1 = _d.sent();
3524
+ e_1 = { error: e_1_1 };
3525
+ return [3 /*break*/, 13];
3526
+ case 12:
3527
+ try {
3528
+ if (fileNames_1_1 && !fileNames_1_1.done && (_c = fileNames_1.return)) _c.call(fileNames_1);
3529
+ }
3530
+ finally { if (e_1) throw e_1.error; }
3531
+ return [7 /*endfinally*/];
3532
+ case 13: return [2 /*return*/, promptbooks];
3533
+ }
3534
+ });
3535
+ }); });
3536
+ if (!(isLazyLoaded === false)) return [3 /*break*/, 2];
3537
+ return [4 /*yield*/, library.listPromptbooks()];
3538
+ case 1:
3539
+ _e.sent();
3540
+ _e.label = 2;
3541
+ case 2: return [2 /*return*/, library];
3542
+ }
3543
+ });
3544
+ });
3545
+ }
3546
+ /**
3547
+ * Reads all files in the directory
3548
+ *
3549
+ * @param path
3550
+ * @param isRecursive
3551
+ * @returns List of all files in the directory
3552
+ * @private internal function for `createPromptbookLibraryFromDirectory`
3553
+ */
3554
+ function listAllFiles(path$1, isRecursive) {
3555
+ return __awaiter(this, void 0, void 0, function () {
3556
+ var fsPromises, readdir, dirents, fileNames, _a, _b, dirent, subPath, _c, _d, _e, _f, e_2_1;
3557
+ var e_2, _g;
3558
+ return __generator(this, function (_h) {
3559
+ switch (_h.label) {
3560
+ case 0:
3561
+ fsPromises = require(just('fs/promises') /* <- Note: [1] */);
3562
+ readdir = fsPromises.readdir;
3563
+ return [4 /*yield*/, readdir(path$1, {
3564
+ withFileTypes: true /* Note: This is not working: recursive: isRecursive */,
3565
+ })];
3566
+ case 1:
3567
+ dirents = _h.sent();
3568
+ fileNames = dirents.filter(function (dirent) { return dirent.isFile(); }).map(function (_a) {
3569
+ var name = _a.name;
3570
+ return path.join(path$1, name);
3571
+ });
3572
+ if (!isRecursive) return [3 /*break*/, 9];
3573
+ _h.label = 2;
3574
+ case 2:
3575
+ _h.trys.push([2, 7, 8, 9]);
3576
+ _a = __values(dirents.filter(function (dirent) { return dirent.isDirectory(); })), _b = _a.next();
3577
+ _h.label = 3;
3578
+ case 3:
3579
+ if (!!_b.done) return [3 /*break*/, 6];
3580
+ dirent = _b.value;
3581
+ subPath = path.join(path$1, dirent.name);
3582
+ _d = (_c = fileNames.push).apply;
3583
+ _e = [fileNames];
3584
+ _f = [[]];
3585
+ return [4 /*yield*/, listAllFiles(subPath, isRecursive)];
3586
+ case 4:
3587
+ _d.apply(_c, _e.concat([__spreadArray.apply(void 0, _f.concat([__read.apply(void 0, [(_h.sent())]), false]))]));
3588
+ _h.label = 5;
3589
+ case 5:
3590
+ _b = _a.next();
3591
+ return [3 /*break*/, 3];
3592
+ case 6: return [3 /*break*/, 9];
3593
+ case 7:
3594
+ e_2_1 = _h.sent();
3595
+ e_2 = { error: e_2_1 };
3596
+ return [3 /*break*/, 9];
3597
+ case 8:
3598
+ try {
3599
+ if (_b && !_b.done && (_g = _a.return)) _g.call(_a);
3600
+ }
3601
+ finally { if (e_2) throw e_2.error; }
3602
+ return [7 /*endfinally*/];
3603
+ case 9: return [2 /*return*/, fileNames];
3604
+ }
3605
+ });
3606
+ });
3607
+ }
3608
+ /***
3609
+ * TODO: [🧠] Maybe do not do hacks like [1] and just create package @promptbook/node
3610
+ * [🍓][🚯] maybe make `@promptbook/library` package
3611
+ * TODO: Fix the dynamic import issue in Webpack (! Not working !)
3612
+ * > ./node_modules/@promptbook/core/esm/index.es.js
3613
+ * > Critical dependency: the request of a dependency is an expression
3614
+ *
3615
+ * Note: [1] Using require(just('fs/promises')) to allow
3616
+ * the `@promptbook/core` work for both Node.js and browser environments
3617
+ */
3618
+
3619
+ /**
3620
+ * Constructs Promptbook from remote Promptbase URL
3621
+
3622
+ * @returns PromptbookLibrary
3623
+ */
3624
+ function createPromptbookLibraryFromUrl(url, options) {
3625
+ return __awaiter(this, void 0, void 0, function () {
3626
+ var _a, _b, isVerbose, _c, isLazyLoaded, library;
3627
+ var _this = this;
3628
+ return __generator(this, function (_d) {
3629
+ switch (_d.label) {
3630
+ case 0:
3631
+ _a = options || {}, _b = _a.isVerbose, isVerbose = _b === void 0 ? false : _b, _c = _a.isLazyLoaded, isLazyLoaded = _c === void 0 ? false : _c;
3632
+ library = createPromptbookLibraryFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
3633
+ return __generator(this, function (_a) {
3634
+ if (isVerbose) {
3635
+ console.info("Creating promptbook library from url ".concat(url.toString()));
3636
+ }
3637
+ throw new Error('Not implemented yet');
3638
+ });
3639
+ }); });
3640
+ if (!(isLazyLoaded === false)) return [3 /*break*/, 2];
3641
+ return [4 /*yield*/, library.listPromptbooks()];
3642
+ case 1:
3643
+ _d.sent();
3644
+ _d.label = 2;
3645
+ case 2: return [2 /*return*/, library];
3646
+ }
3647
+ });
3648
+ });
3649
+ }
3650
+ /***
3651
+ * TODO: [🍓][🚯] !!! Add to README and samples + maybe make `@promptbook/library` package
3652
+ */
3653
+
3053
3654
  /**
3054
3655
  * Creates PromptbookLibrary as a subset of another PromptbookLibrary
3055
3656
  *
@@ -3132,15 +3733,349 @@
3132
3733
  * TODO: [🍓][🚯] !!! Add to README and samples + maybe make `@promptbook/library` package
3133
3734
  */
3134
3735
 
3736
+ /**
3737
+ * Just testing imports and compatibility
3738
+ */
3739
+ function justTestFsImport() {
3740
+ return __awaiter(this, void 0, void 0, function () {
3741
+ var files;
3742
+ return __generator(this, function (_a) {
3743
+ switch (_a.label) {
3744
+ case 0:
3745
+ if (!isRunningInNode()) {
3746
+ throw new Error('Function `testFiles` can only be run in Node.js environment because it reads the file system.');
3747
+ }
3748
+ return [4 /*yield*/, require(just('glob-promise'))('/**/*')];
3749
+ case 1:
3750
+ files = _a.sent();
3751
+ console.info('testFiles', { files: files });
3752
+ return [2 /*return*/];
3753
+ }
3754
+ });
3755
+ });
3756
+ }
3757
+ /**
3758
+ * TODO: !!! Remove this file
3759
+ */
3760
+
3761
+ /**
3762
+ * Format either small or big number
3763
+ *
3764
+ * @private within the library
3765
+ */
3766
+ function formatNumber(value) {
3767
+ if (value === 0) {
3768
+ return '0';
3769
+ }
3770
+ for (var exponent = 0; exponent < 15; exponent++) {
3771
+ var factor = Math.pow(10, exponent);
3772
+ var valueRounded = Math.round(value * factor) / factor;
3773
+ if (Math.abs(value - valueRounded) / value <
3774
+ 0.001 /* <- TODO: Pass as option, pass to executionReportJsonToString as option */) {
3775
+ return valueRounded.toFixed(exponent);
3776
+ }
3777
+ }
3778
+ return value.toString();
3779
+ }
3780
+
3781
+ /**
3782
+ * Create a markdown table from a 2D array of strings
3783
+ *
3784
+ * @private within the library
3785
+ */
3786
+ function createMarkdownTable(table) {
3787
+ var columnWidths = table.reduce(function (widths, row) {
3788
+ row.forEach(function (cell, columnIndex) {
3789
+ var cellLength = cell.length;
3790
+ if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
3791
+ widths[columnIndex] = cellLength;
3792
+ }
3793
+ });
3794
+ return widths;
3795
+ }, []);
3796
+ var header = "| ".concat(table[0]
3797
+ .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
3798
+ .join(' | '), " |");
3799
+ var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
3800
+ var rows = table.slice(1).map(function (row) {
3801
+ var paddedRow = row.map(function (cell, columnIndex) {
3802
+ return cell.padEnd(columnWidths[columnIndex]);
3803
+ });
3804
+ return "| ".concat(paddedRow.join(' | '), " |");
3805
+ });
3806
+ return __spreadArray([header, separator], __read(rows), false).join('\n');
3807
+ }
3808
+
3809
+ /**
3810
+ * Function createMarkdownChart will draw a chart in markdown from ⬛+🟦 tiles
3811
+ *
3812
+ * @private within the library
3813
+ */
3814
+ function createMarkdownChart(options) {
3815
+ var e_1, _a;
3816
+ var nameHeader = options.nameHeader, valueHeader = options.valueHeader, items = options.items, width = options.width, unitName = options.unitName;
3817
+ var from = Math.min.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.from; })), false));
3818
+ var to = Math.max.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.to; })), false));
3819
+ var scale = width / (to - from);
3820
+ var table = [[nameHeader, valueHeader]];
3821
+ try {
3822
+ for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
3823
+ var item = items_1_1.value;
3824
+ var before = Math.round((item.from - from) * scale);
3825
+ var during = Math.round((item.to - item.from) * scale);
3826
+ var after = width - before - during;
3827
+ table.push([removeEmojis(item.title).trim(), '░'.repeat(before) + '█'.repeat(during) + '░'.repeat(after)]);
3828
+ }
3829
+ }
3830
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3831
+ finally {
3832
+ try {
3833
+ if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
3834
+ }
3835
+ finally { if (e_1) throw e_1.error; }
3836
+ }
3837
+ var legend = "_Note: Each \u2588 represents ".concat(formatNumber(1 / scale), " ").concat(unitName, ", width of ").concat(valueHeader.toLowerCase(), " is ").concat(formatNumber(to - from), " ").concat(unitName, " = ").concat(width, " squares_");
3838
+ return createMarkdownTable(table) + '\n\n' + legend;
3839
+ }
3840
+ /**
3841
+ * TODO: Maybe use Mermain Gant Diagrams
3842
+ * @see https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/
3843
+ */
3844
+
3845
+ /**
3846
+ * Function escapeMarkdownBlock will escape markdown block if needed
3847
+ * It is useful when you want have block in block
3848
+ */
3849
+ function escapeMarkdownBlock(value) {
3850
+ return value.replace(/```/g, '\\`\\`\\`');
3851
+ }
3852
+
3853
+ /**
3854
+ * Default options for generating an execution report string
3855
+ */
3856
+ var ExecutionReportStringOptionsDefaults = {
3857
+ taxRate: 0,
3858
+ chartsWidth: 36,
3859
+ };
3860
+
3861
+ /**
3862
+ * The thresholds for the relative time in the `moment` library.
3863
+ *
3864
+ * @see https://momentjscom.readthedocs.io/en/latest/moment/07-customization/13-relative-time-threshold/
3865
+ */
3866
+ var MOMENT_ARG_THRESHOLDS = {
3867
+ ss: 3, // <- least number of seconds to be counted in seconds, minus 1. Must be set after setting the `s` unit or without setting the `s` unit.
3868
+ };
3869
+
3870
+ /**
3871
+ * Count the duration of working time
3872
+ *
3873
+ * @private within the library
3874
+ */
3875
+ function countWorkingDuration(items) {
3876
+ var e_1, _a;
3877
+ var steps = Array.from(new Set(items.flatMap(function (item) { return [item.from, item.to]; })));
3878
+ steps.sort(function (a, b) { return a - b; });
3879
+ var intervals = steps.map(function (step, index) { return [step, steps[index + 1] || 0]; }).slice(0, -1);
3880
+ var duration = 0;
3881
+ var _loop_1 = function (interval) {
3882
+ var _b = __read(interval, 2), from = _b[0], to = _b[1];
3883
+ if (items.some(function (item) { return item.from < to && item.to > from; })) {
3884
+ duration += to - from;
3885
+ }
3886
+ };
3887
+ try {
3888
+ for (var intervals_1 = __values(intervals), intervals_1_1 = intervals_1.next(); !intervals_1_1.done; intervals_1_1 = intervals_1.next()) {
3889
+ var interval = intervals_1_1.value;
3890
+ _loop_1(interval);
3891
+ }
3892
+ }
3893
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3894
+ finally {
3895
+ try {
3896
+ if (intervals_1_1 && !intervals_1_1.done && (_a = intervals_1.return)) _a.call(intervals_1);
3897
+ }
3898
+ finally { if (e_1) throw e_1.error; }
3899
+ }
3900
+ return duration;
3901
+ }
3902
+
3903
+ /**
3904
+ * Converts execution report from JSON to string format
3905
+ */
3906
+ function executionReportJsonToString(executionReportJson, options) {
3907
+ var e_1, _a;
3908
+ var _b, _c, _d, _e, _f, _g;
3909
+ var _h = __assign(__assign({}, ExecutionReportStringOptionsDefaults), (options || {})), taxRate = _h.taxRate, chartsWidth = _h.chartsWidth;
3910
+ var executionReportString = spaceTrim.spaceTrim(function (block) { return "\n # ".concat(executionReportJson.title || 'Execution report', "\n\n ").concat(block(executionReportJson.description || ''), "\n "); });
3911
+ var headerList = [];
3912
+ if (executionReportJson.promptbookUrl) {
3913
+ headerList.push("PROMPTBOOK URL ".concat(executionReportJson.promptbookUrl));
3914
+ }
3915
+ headerList.push("PROMPTBOOK VERSION ".concat(executionReportJson.promptbookUsedVersion) +
3916
+ (!executionReportJson.promptbookRequestedVersion
3917
+ ? ''
3918
+ : " *(requested ".concat(executionReportJson.promptbookRequestedVersion, ")*")));
3919
+ if (executionReportJson.promptExecutions.length !== 0) {
3920
+ // TODO: What if startedAt OR/AND completedAt is not defined?
3921
+ var startedAt = moment__default["default"](Math.min.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
3922
+ .filter(function (promptExecution) { var _a, _b; return (_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.start; })
3923
+ .map(function (promptExecution) { return moment__default["default"](promptExecution.result.timing.start).valueOf(); })), false)));
3924
+ var completedAt = moment__default["default"](Math.max.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
3925
+ .filter(function (promptExecution) { var _a, _b; return (_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.complete; })
3926
+ .map(function (promptExecution) { return moment__default["default"](promptExecution.result.timing.complete).valueOf(); })), false)));
3927
+ var timingItems = executionReportJson.promptExecutions.map(function (promptExecution) {
3928
+ var _a, _b, _c, _d;
3929
+ return ({
3930
+ title: promptExecution.prompt.title,
3931
+ from: moment__default["default"]((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.start).valueOf() / 1000,
3932
+ to: moment__default["default"]((_d = (_c = promptExecution.result) === null || _c === void 0 ? void 0 : _c.timing) === null || _d === void 0 ? void 0 : _d.complete).valueOf() / 1000,
3933
+ });
3934
+ });
3935
+ var costItems = executionReportJson.promptExecutions
3936
+ .filter(function (promptExecution) { var _a, _b; return typeof ((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) === 'number'; })
3937
+ .map(function (promptExecution) {
3938
+ var _a, _b;
3939
+ return ({
3940
+ title: promptExecution.prompt.title,
3941
+ from: 0,
3942
+ to: ((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) * (1 + taxRate),
3943
+ });
3944
+ });
3945
+ var duration = moment__default["default"].duration(completedAt.diff(startedAt));
3946
+ var llmDuration = moment__default["default"].duration(countWorkingDuration(timingItems) * 1000);
3947
+ var executionsWithKnownCost = executionReportJson.promptExecutions.filter(function (promptExecution) { var _a, _b; return (((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) || 'UNKNOWN') !== 'UNKNOWN'; });
3948
+ var cost = executionsWithKnownCost.reduce(function (cost, promptExecution) { return cost + (promptExecution.result.usage.price || 0); }, 0);
3949
+ headerList.push("STARTED AT ".concat(moment__default["default"](startedAt).format("YYYY-MM-DD HH:mm:ss")));
3950
+ headerList.push("COMPLETED AT ".concat(moment__default["default"](completedAt).format("YYYY-MM-DD HH:mm:ss")));
3951
+ headerList.push("TOTAL DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
3952
+ headerList.push("TOTAL LLM DURATION ".concat(llmDuration.humanize(MOMENT_ARG_THRESHOLDS)));
3953
+ headerList.push("TOTAL COST $".concat(formatNumber(cost * (1 + taxRate))) +
3954
+ (executionsWithKnownCost.length === executionReportJson.promptExecutions.length
3955
+ ? ''
3956
+ : " *(Some cost is unknown)*") +
3957
+ (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
3958
+ executionReportString += '\n\n' + headerList.map(function (header) { return "- ".concat(header); }).join('\n');
3959
+ executionReportString +=
3960
+ '\n\n' +
3961
+ '## 🗃 Index' +
3962
+ '\n\n' +
3963
+ executionReportJson.promptExecutions
3964
+ .map(function (promptExecution) {
3965
+ // TODO: Make some better system to convert hedings to links
3966
+ var hash = normalizeToKebabCase(promptExecution.prompt.title);
3967
+ if (/^\s*\p{Extended_Pictographic}/u.test(promptExecution.prompt.title)) {
3968
+ hash = '-' + hash;
3969
+ }
3970
+ // TODO: Make working hash link for the template in md + pdf
3971
+ return "- [".concat(promptExecution.prompt.title, "](#").concat(hash, ")");
3972
+ })
3973
+ .join('\n');
3974
+ executionReportString +=
3975
+ '\n\n' +
3976
+ '## ⌚ Time chart' +
3977
+ '\n\n' +
3978
+ createMarkdownChart({
3979
+ nameHeader: 'Template',
3980
+ valueHeader: 'Timeline',
3981
+ items: timingItems,
3982
+ width: chartsWidth,
3983
+ unitName: 'seconds',
3984
+ });
3985
+ executionReportString +=
3986
+ '\n\n' +
3987
+ '## 💸 Cost chart' +
3988
+ '\n\n' +
3989
+ createMarkdownChart({
3990
+ nameHeader: 'Template',
3991
+ valueHeader: 'Cost',
3992
+ items: costItems,
3993
+ width: chartsWidth,
3994
+ unitName: 'USD',
3995
+ });
3996
+ }
3997
+ else {
3998
+ headerList.push("TOTAL COST $0 *(Nothing executed)*");
3999
+ }
4000
+ var _loop_1 = function (promptExecution) {
4001
+ executionReportString += '\n\n\n\n' + "## ".concat(promptExecution.prompt.title);
4002
+ var templateList = [];
4003
+ // TODO: What if startedAt OR/AND completedAt is not defined?
4004
+ var startedAt = moment__default["default"]((_c = (_b = promptExecution.result) === null || _b === void 0 ? void 0 : _b.timing) === null || _c === void 0 ? void 0 : _c.start);
4005
+ var completedAt = moment__default["default"]((_e = (_d = promptExecution.result) === null || _d === void 0 ? void 0 : _d.timing) === null || _e === void 0 ? void 0 : _e.complete);
4006
+ var duration = moment__default["default"].duration(completedAt.diff(startedAt));
4007
+ // Not need here:
4008
+ // > templateList.push(`STARTED AT ${moment(startedAt).calendar()}`);
4009
+ templateList.push("DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
4010
+ if (typeof ((_g = (_f = promptExecution.result) === null || _f === void 0 ? void 0 : _f.usage) === null || _g === void 0 ? void 0 : _g.price) === 'number') {
4011
+ templateList.push("COST $".concat(formatNumber(promptExecution.result.usage.price * (1 + taxRate))) +
4012
+ (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
4013
+ }
4014
+ else {
4015
+ templateList.push("COST UNKNOWN");
4016
+ }
4017
+ executionReportString += '\n\n' + templateList.map(function (header) { return "- ".concat(header); }).join('\n');
4018
+ /*
4019
+ - MODEL VARIANT ${promptExecution.prompt.modelRequirements.modelVariant}
4020
+ - MODEL NAME \`${promptExecution.result?.model}\` (requested \`${
4021
+ promptExecution.prompt.modelRequirements.modelName
4022
+
4023
+ */
4024
+ if (just(true)) {
4025
+ executionReportString +=
4026
+ '\n\n\n\n' +
4027
+ spaceTrim.spaceTrim(function (block) { return "\n\n ### Prompt\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.prompt.content)), "\n ```\n\n "); });
4028
+ }
4029
+ if (promptExecution.result && promptExecution.result.content) {
4030
+ executionReportString +=
4031
+ '\n\n\n\n' +
4032
+ spaceTrim.spaceTrim(function (block) { return "\n\n ### Result\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.result.content)), "\n ```\n "); });
4033
+ }
4034
+ if (promptExecution.error && promptExecution.error.message) {
4035
+ executionReportString +=
4036
+ '\n\n\n\n' +
4037
+ spaceTrim.spaceTrim(function (block) { return "\n\n ### Error\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.error.message)), "\n ```\n\n "); });
4038
+ }
4039
+ };
4040
+ try {
4041
+ for (var _j = __values(executionReportJson.promptExecutions), _k = _j.next(); !_k.done; _k = _j.next()) {
4042
+ var promptExecution = _k.value;
4043
+ _loop_1(promptExecution);
4044
+ }
4045
+ }
4046
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4047
+ finally {
4048
+ try {
4049
+ if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
4050
+ }
4051
+ finally { if (e_1) throw e_1.error; }
4052
+ }
4053
+ executionReportString = prettifyMarkdown(executionReportString);
4054
+ return executionReportString;
4055
+ }
4056
+ /**
4057
+ * TODO: Add mermaid chart for every report
4058
+ * TODO: [🧠] Allow to filter out some parts of the report by options
4059
+ */
4060
+
3135
4061
  exports.CallbackInterfaceTools = CallbackInterfaceTools;
4062
+ exports.ExecutionReportStringOptionsDefaults = ExecutionReportStringOptionsDefaults;
3136
4063
  exports.ExecutionTypes = ExecutionTypes;
4064
+ exports.MultipleLlmExecutionTools = MultipleLlmExecutionTools;
3137
4065
  exports.PROMPTBOOK_VERSION = PROMPTBOOK_VERSION;
3138
4066
  exports.SimplePromptInterfaceTools = SimplePromptInterfaceTools;
3139
4067
  exports.SimplePromptbookLibrary = SimplePromptbookLibrary;
4068
+ exports.assertsExecutionSuccessful = assertsExecutionSuccessful;
4069
+ exports.checkExpectations = checkExpectations;
3140
4070
  exports.createPromptbookExecutor = createPromptbookExecutor;
3141
- exports.createPromptbookLibraryFromPromise = createPromptbookLibraryFromPromise;
4071
+ exports.createPromptbookLibraryFromDirectory = createPromptbookLibraryFromDirectory;
3142
4072
  exports.createPromptbookLibraryFromSources = createPromptbookLibraryFromSources;
4073
+ exports.createPromptbookLibraryFromUrl = createPromptbookLibraryFromUrl;
3143
4074
  exports.createPromptbookSublibrary = createPromptbookSublibrary;
4075
+ exports.executionReportJsonToString = executionReportJsonToString;
4076
+ exports.isPassingExpectations = isPassingExpectations;
4077
+ exports.justTestFsImport = justTestFsImport;
4078
+ exports.prettifyPromptbookString = prettifyPromptbookString;
3144
4079
  exports.promptbookJsonToString = promptbookJsonToString;
3145
4080
  exports.promptbookStringToJson = promptbookStringToJson;
3146
4081
  exports.validatePromptbookJson = validatePromptbookJson;