@promptbook/core 0.52.0-4 → 0.52.0-6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.es.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import spaceTrim$1, { spaceTrim } from 'spacetrim';
2
2
  import { format } from 'prettier';
3
3
  import parserHtml from 'prettier/parser-html';
4
- import 'moment';
4
+ import moment from 'moment';
5
5
 
6
6
  /*! *****************************************************************************
7
7
  Copyright (c) Microsoft Corporation.
@@ -447,7 +447,7 @@ function union() {
447
447
  /**
448
448
  * The version of the Promptbook library
449
449
  */
450
- var PROMPTBOOK_VERSION = '0.52.0-3';
450
+ var PROMPTBOOK_VERSION = '0.52.0-5';
451
451
 
452
452
  /**
453
453
  * Parses the template and returns the list of all parameter names
@@ -569,38 +569,6 @@ function extractParametersFromPromptTemplate(promptTemplate) {
569
569
  * TODO: [🔣] If script require contentLanguage
570
570
  */
571
571
 
572
- /**
573
- * Prettify the html code
574
- *
575
- * @param content raw html code
576
- * @returns formatted html code
577
- */
578
- function prettifyMarkdown(content) {
579
- try {
580
- return format(content, {
581
- parser: 'markdown',
582
- plugins: [parserHtml],
583
- // TODO: DRY - make some import or auto-copy of .prettierrc
584
- endOfLine: 'lf',
585
- tabWidth: 4,
586
- singleQuote: true,
587
- trailingComma: 'all',
588
- arrowParens: 'always',
589
- printWidth: 120,
590
- htmlWhitespaceSensitivity: 'ignore',
591
- jsxBracketSameLine: false,
592
- bracketSpacing: true,
593
- });
594
- }
595
- catch (error) {
596
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
597
- error: error,
598
- html: content,
599
- });
600
- return content;
601
- }
602
- }
603
-
604
572
  /**
605
573
  * Removes emojis from a string and fix whitespaces
606
574
  *
@@ -626,6 +594,64 @@ function titleToName(value) {
626
594
  return value;
627
595
  }
628
596
 
597
+ /**
598
+ * Creates a Mermaid graph based on the promptbook
599
+ *
600
+ * Note: The result is not wrapped in a Markdown code block
601
+ */
602
+ function renderPromptbookMermaid(promptbookJson, options) {
603
+ var _a = (options || {}).linkPromptTemplate, linkPromptTemplate = _a === void 0 ? function () { return null; } : _a;
604
+ var parameterNameToTemplateName = function (parameterName) {
605
+ var parameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
606
+ if (!parameter) {
607
+ throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
608
+ }
609
+ if (parameter.isInput) {
610
+ return 'input';
611
+ }
612
+ var template = promptbookJson.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
613
+ if (!template) {
614
+ throw new Error("Could not find template for {".concat(parameterName, "}"));
615
+ }
616
+ return normalizeTo_camelCase('template-' + titleToName(template.title));
617
+ };
618
+ var promptbookMermaid = 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
619
+ .flatMap(function (_a) {
620
+ var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
621
+ return __spreadArray([
622
+ "".concat(parameterNameToTemplateName(resultingParameterName), "(\"").concat(title, "\")")
623
+ ], __read(dependentParameterNames.map(function (dependentParameterName) {
624
+ return "".concat(parameterNameToTemplateName(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName(resultingParameterName));
625
+ })), false);
626
+ })
627
+ .join('\n')), "\n\n ").concat(block(promptbookJson.parameters
628
+ .filter(function (_a) {
629
+ var isOutput = _a.isOutput;
630
+ return isOutput;
631
+ })
632
+ .map(function (_a) {
633
+ var name = _a.name;
634
+ return "".concat(parameterNameToTemplateName(name), "--\"{").concat(name, "}\"-->output");
635
+ })
636
+ .join('\n')), "\n output((Output)):::output\n\n ").concat(block(promptbookJson.promptTemplates
637
+ .map(function (promptTemplate) {
638
+ var link = linkPromptTemplate(promptTemplate);
639
+ if (link === null) {
640
+ return '';
641
+ }
642
+ var href = link.href, title = link.title;
643
+ var templateName = parameterNameToTemplateName(promptTemplate.resultingParameterName);
644
+ return "click ".concat(templateName, " href \"").concat(href, "\" \"").concat(title, "\";");
645
+ })
646
+ .filter(function (line) { return line !== ''; })
647
+ .join('\n')), "\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n "); });
648
+ return promptbookMermaid;
649
+ }
650
+ /**
651
+ * TODO: Maybe use some Mermaid library instead of string templating
652
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
653
+ */
654
+
629
655
  /**
630
656
  * Function parseNumber will parse number from string
631
657
  *
@@ -708,35 +734,80 @@ var PromptbookLogicError = /** @class */ (function (_super) {
708
734
  }(Error));
709
735
 
710
736
  /**
711
- * This error indicates errors during the execution of the promptbook
737
+ * This error occurs during the parameter replacement in the template
738
+ *
739
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
712
740
  */
713
- var PromptbookExecutionError = /** @class */ (function (_super) {
714
- __extends(PromptbookExecutionError, _super);
715
- function PromptbookExecutionError(message) {
741
+ var TemplateError = /** @class */ (function (_super) {
742
+ __extends(TemplateError, _super);
743
+ function TemplateError(message) {
716
744
  var _this = _super.call(this, message) || this;
717
- _this.name = 'PromptbookExecutionError';
718
- Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
745
+ _this.name = 'TemplateError';
746
+ Object.setPrototypeOf(_this, TemplateError.prototype);
719
747
  return _this;
720
748
  }
721
- return PromptbookExecutionError;
749
+ return TemplateError;
722
750
  }(Error));
723
751
 
724
752
  /**
725
- * This error occurs when some expectation is not met in the execution of the pipeline
753
+ * Replaces parameters in template with values from parameters object
726
754
  *
727
- * @private Always catched and rethrown as `PromptbookExecutionError`
728
- * Note: This is a kindof subtype of PromptbookExecutionError
755
+ * @param template the template with parameters in {curly} braces
756
+ * @param parameters the object with parameters
757
+ * @returns the template with replaced parameters
758
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
759
+ *
760
+ * @private within the createPromptbookExecutor
729
761
  */
730
- var ExpectError = /** @class */ (function (_super) {
731
- __extends(ExpectError, _super);
732
- function ExpectError(message) {
733
- var _this = _super.call(this, message) || this;
734
- _this.name = 'ExpectError';
735
- Object.setPrototypeOf(_this, ExpectError.prototype);
736
- return _this;
762
+ function replaceParameters(template, parameters) {
763
+ var replacedTemplate = template;
764
+ var match;
765
+ var loopLimit = LOOP_LIMIT;
766
+ var _loop_1 = function () {
767
+ if (loopLimit-- < 0) {
768
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
769
+ }
770
+ var precol = match.groups.precol;
771
+ var parameterName = match.groups.parameterName;
772
+ if (parameterName === '') {
773
+ return "continue";
774
+ }
775
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
776
+ throw new TemplateError('Parameter is already opened or not closed');
777
+ }
778
+ if (parameters[parameterName] === undefined) {
779
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
780
+ }
781
+ var parameterValue = parameters[parameterName];
782
+ if (parameterValue === undefined) {
783
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
784
+ }
785
+ parameterValue = parameterValue.toString();
786
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
787
+ parameterValue = parameterValue
788
+ .split('\n')
789
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
790
+ .join('\n');
791
+ }
792
+ replacedTemplate =
793
+ replacedTemplate.substring(0, match.index + precol.length) +
794
+ parameterValue +
795
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
796
+ };
797
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
798
+ .exec(replacedTemplate))) {
799
+ _loop_1();
737
800
  }
738
- return ExpectError;
739
- }(Error));
801
+ // [💫] Check if there are parameters that are not closed properly
802
+ if (/{\w+$/.test(replacedTemplate)) {
803
+ throw new TemplateError('Parameter is not closed');
804
+ }
805
+ // [💫] Check if there are parameters that are not opened properly
806
+ if (/^\w+}/.test(replacedTemplate)) {
807
+ throw new TemplateError('Parameter is not opened');
808
+ }
809
+ return replacedTemplate;
810
+ }
740
811
 
741
812
  /**
742
813
  * Counts number of characters in the text
@@ -1064,118 +1135,6 @@ var CountUtils = {
1064
1135
  PAGES: countPages,
1065
1136
  };
1066
1137
 
1067
- /**
1068
- * Function checkExpectations will check if the expectations on given value are met
1069
- *
1070
- * Note: There are two simmilar functions:
1071
- * - `checkExpectations` which throws an error if the expectations are not met
1072
- * - `isPassingExpectations` which returns a boolean
1073
- *
1074
- * @throws {ExpectError} if the expectations are not met
1075
- * @returns {void} Nothing
1076
- */
1077
- function checkExpectations(expectations, value) {
1078
- var e_1, _a;
1079
- try {
1080
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
1081
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
1082
- var amount = CountUtils[unit.toUpperCase()](value);
1083
- if (min && amount < min) {
1084
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
1085
- } /* not else */
1086
- if (max && amount > max) {
1087
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1088
- }
1089
- }
1090
- }
1091
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1092
- finally {
1093
- try {
1094
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1095
- }
1096
- finally { if (e_1) throw e_1.error; }
1097
- }
1098
- }
1099
- /**
1100
- * TODO: [💝] Unite object for expecting amount and format
1101
- */
1102
-
1103
- /**
1104
- * This error occurs during the parameter replacement in the template
1105
- *
1106
- * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
1107
- */
1108
- var TemplateError = /** @class */ (function (_super) {
1109
- __extends(TemplateError, _super);
1110
- function TemplateError(message) {
1111
- var _this = _super.call(this, message) || this;
1112
- _this.name = 'TemplateError';
1113
- Object.setPrototypeOf(_this, TemplateError.prototype);
1114
- return _this;
1115
- }
1116
- return TemplateError;
1117
- }(Error));
1118
-
1119
- /**
1120
- * Replaces parameters in template with values from parameters object
1121
- *
1122
- * @param template the template with parameters in {curly} braces
1123
- * @param parameters the object with parameters
1124
- * @returns the template with replaced parameters
1125
- * @throws {TemplateError} if parameter is not defined, not closed, or not opened
1126
- *
1127
- * @private within the createPromptbookExecutor
1128
- */
1129
- function replaceParameters(template, parameters) {
1130
- var replacedTemplate = template;
1131
- var match;
1132
- var loopLimit = LOOP_LIMIT;
1133
- var _loop_1 = function () {
1134
- if (loopLimit-- < 0) {
1135
- throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
1136
- }
1137
- var precol = match.groups.precol;
1138
- var parameterName = match.groups.parameterName;
1139
- if (parameterName === '') {
1140
- return "continue";
1141
- }
1142
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
1143
- throw new TemplateError('Parameter is already opened or not closed');
1144
- }
1145
- if (parameters[parameterName] === undefined) {
1146
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
1147
- }
1148
- var parameterValue = parameters[parameterName];
1149
- if (parameterValue === undefined) {
1150
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
1151
- }
1152
- parameterValue = parameterValue.toString();
1153
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
1154
- parameterValue = parameterValue
1155
- .split('\n')
1156
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
1157
- .join('\n');
1158
- }
1159
- replacedTemplate =
1160
- replacedTemplate.substring(0, match.index + precol.length) +
1161
- parameterValue +
1162
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
1163
- };
1164
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
1165
- .exec(replacedTemplate))) {
1166
- _loop_1();
1167
- }
1168
- // [💫] Check if there are parameters that are not closed properly
1169
- if (/{\w+$/.test(replacedTemplate)) {
1170
- throw new TemplateError('Parameter is not closed');
1171
- }
1172
- // [💫] Check if there are parameters that are not opened properly
1173
- if (/^\w+}/.test(replacedTemplate)) {
1174
- throw new TemplateError('Parameter is not opened');
1175
- }
1176
- return replacedTemplate;
1177
- }
1178
-
1179
1138
  /**
1180
1139
  * Function isValidJsonString will tell you if the string is valid JSON or not
1181
1140
  */
@@ -1330,16 +1289,71 @@ function normalizeToKebabCase(sentence) {
1330
1289
  return normalizedName;
1331
1290
  }
1332
1291
 
1333
- /**
1334
- * Execution type describes the way how the block is executed
1335
- *
1336
- * @see https://github.com/webgptorg/promptbook#execution-type
1337
- */
1338
- var ExecutionTypes = [
1339
- 'PROMPT_TEMPLATE',
1340
- 'SIMPLE_TEMPLATE',
1341
- 'SCRIPT',
1342
- 'PROMPT_DIALOG',
1292
+ /* tslint:disable */
1293
+ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1294
+ var e_1, _a;
1295
+ if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1296
+ var charType;
1297
+ var lastCharType = null;
1298
+ var normalizedName = '';
1299
+ try {
1300
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1301
+ var char = sentence_1_1.value;
1302
+ var normalizedChar = void 0;
1303
+ if (/^[a-z]$/.test(char)) {
1304
+ charType = 'LOWERCASE';
1305
+ normalizedChar = char;
1306
+ }
1307
+ else if (/^[A-Z]$/.test(char)) {
1308
+ charType = 'UPPERCASE';
1309
+ normalizedChar = char.toLowerCase();
1310
+ }
1311
+ else if (/^[0-9]$/.test(char)) {
1312
+ charType = 'NUMBER';
1313
+ normalizedChar = char;
1314
+ }
1315
+ else {
1316
+ charType = 'OTHER';
1317
+ normalizedChar = '';
1318
+ }
1319
+ if (!lastCharType) {
1320
+ if (__firstLetterCapital) {
1321
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1322
+ }
1323
+ }
1324
+ else if (charType !== lastCharType &&
1325
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1326
+ !(lastCharType === 'NUMBER') &&
1327
+ !(charType === 'NUMBER')) {
1328
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1329
+ }
1330
+ normalizedName += normalizedChar;
1331
+ lastCharType = charType;
1332
+ }
1333
+ }
1334
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1335
+ finally {
1336
+ try {
1337
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1338
+ }
1339
+ finally { if (e_1) throw e_1.error; }
1340
+ }
1341
+ return normalizedName;
1342
+ }
1343
+ /**
1344
+ * TODO: [🌺] Use some intermediate util splitWords
1345
+ */
1346
+
1347
+ /**
1348
+ * Execution type describes the way how the block is executed
1349
+ *
1350
+ * @see https://github.com/webgptorg/promptbook#execution-type
1351
+ */
1352
+ var ExecutionTypes = [
1353
+ 'PROMPT_TEMPLATE',
1354
+ 'SIMPLE_TEMPLATE',
1355
+ 'SCRIPT',
1356
+ 'PROMPT_DIALOG',
1343
1357
  // <- [🥻] Insert here when making new command
1344
1358
  ];
1345
1359
 
@@ -1848,6 +1862,87 @@ function promptbookStringToJson(promptbookString) {
1848
1862
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1849
1863
  */
1850
1864
 
1865
+ /**
1866
+ * Add or modify an auto-generated section in a markdown file
1867
+ *
1868
+ * @private within the library
1869
+ */
1870
+ function addAutoGeneratedSection(content, options) {
1871
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
1872
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1873
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1874
+ var sectionMatch = content.match(sectionRegex);
1875
+ if (sectionMatch) {
1876
+ return content.replace(sectionRegex, spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1877
+ }
1878
+ var placeForSection = removeContentComments(content).match(/^##.*$/im);
1879
+ if (!placeForSection) {
1880
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1881
+ }
1882
+ var _a = __read(placeForSection, 1), heading = _a[0];
1883
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1884
+ }
1885
+
1886
+ /**
1887
+ * Prettify the html code
1888
+ *
1889
+ * @param content raw html code
1890
+ * @returns formatted html code
1891
+ */
1892
+ function prettifyMarkdown(content) {
1893
+ try {
1894
+ return format(content, {
1895
+ parser: 'markdown',
1896
+ plugins: [parserHtml],
1897
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1898
+ endOfLine: 'lf',
1899
+ tabWidth: 4,
1900
+ singleQuote: true,
1901
+ trailingComma: 'all',
1902
+ arrowParens: 'always',
1903
+ printWidth: 120,
1904
+ htmlWhitespaceSensitivity: 'ignore',
1905
+ jsxBracketSameLine: false,
1906
+ bracketSpacing: true,
1907
+ });
1908
+ }
1909
+ catch (error) {
1910
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1911
+ error: error,
1912
+ html: content,
1913
+ });
1914
+ return content;
1915
+ }
1916
+ }
1917
+
1918
+ /**
1919
+ * Prettyfies Promptbook string and adds Mermaid graph
1920
+ */
1921
+ function prettifyPromptbookString(promptbookString, options) {
1922
+ var isGraphAdded = options.isGraphAdded, isPrettifyed = options.isPrettifyed;
1923
+ if (isGraphAdded) {
1924
+ var promptbookJson = promptbookStringToJson(promptbookString);
1925
+ var promptbookMermaid_1 = renderPromptbookMermaid(promptbookJson, {
1926
+ linkPromptTemplate: function (promptTemplate) {
1927
+ return { href: "#".concat(promptTemplate.name), title: promptTemplate.title };
1928
+ },
1929
+ });
1930
+ var promptbookMermaidBlock = spaceTrim(function (block) { return "\n ```mermaid\n ".concat(block(promptbookMermaid_1), "\n ```\n "); });
1931
+ promptbookString = addAutoGeneratedSection(promptbookString, {
1932
+ sectionName: 'Graph',
1933
+ sectionContent: promptbookMermaidBlock,
1934
+ });
1935
+ }
1936
+ if (isPrettifyed) {
1937
+ promptbookString = prettifyMarkdown(promptbookString);
1938
+ }
1939
+ return promptbookString;
1940
+ }
1941
+ /**
1942
+ * TODO: Maybe use some Mermaid library instead of string templating
1943
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
1944
+ */
1945
+
1851
1946
  /**
1852
1947
  * Converts promptbook in JSON format to string format
1853
1948
  *
@@ -2236,6 +2331,119 @@ function validatePromptbookJson(promptbook) {
2236
2331
  * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
2237
2332
  */
2238
2333
 
2334
+ /**
2335
+ * This error indicates errors during the execution of the promptbook
2336
+ */
2337
+ var PromptbookExecutionError = /** @class */ (function (_super) {
2338
+ __extends(PromptbookExecutionError, _super);
2339
+ function PromptbookExecutionError(message) {
2340
+ var _this = _super.call(this, message) || this;
2341
+ _this.name = 'PromptbookExecutionError';
2342
+ Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
2343
+ return _this;
2344
+ }
2345
+ return PromptbookExecutionError;
2346
+ }(Error));
2347
+
2348
+ /**
2349
+ * Asserts that the execution of a promptnook is successful
2350
+ *
2351
+ * @param executionResult - The partial result of the promptnook execution
2352
+ * @throws {PromptbookExecutionError} If the execution is not successful or if multiple errors occurred
2353
+ */
2354
+ function assertsExecutionSuccessful(executionResult) {
2355
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2356
+ if (isSuccessful === true) {
2357
+ return;
2358
+ }
2359
+ if (errors.length === 0) {
2360
+ throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
2361
+ }
2362
+ else if (errors.length === 1) {
2363
+ throw errors[0];
2364
+ }
2365
+ else {
2366
+ throw new PromptbookExecutionError(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 "); }));
2367
+ }
2368
+ }
2369
+ /**
2370
+ * TODO: [🧠] Can this return type be better typed than void
2371
+ */
2372
+
2373
+ /**
2374
+ * This error occurs when some expectation is not met in the execution of the pipeline
2375
+ *
2376
+ * @private Always catched and rethrown as `PromptbookExecutionError`
2377
+ * Note: This is a kindof subtype of PromptbookExecutionError
2378
+ */
2379
+ var ExpectError = /** @class */ (function (_super) {
2380
+ __extends(ExpectError, _super);
2381
+ function ExpectError(message) {
2382
+ var _this = _super.call(this, message) || this;
2383
+ _this.name = 'ExpectError';
2384
+ Object.setPrototypeOf(_this, ExpectError.prototype);
2385
+ return _this;
2386
+ }
2387
+ return ExpectError;
2388
+ }(Error));
2389
+
2390
+ /**
2391
+ * Function checkExpectations will check if the expectations on given value are met
2392
+ *
2393
+ * Note: There are two simmilar functions:
2394
+ * - `checkExpectations` which throws an error if the expectations are not met
2395
+ * - `isPassingExpectations` which returns a boolean
2396
+ *
2397
+ * @throws {ExpectError} if the expectations are not met
2398
+ * @returns {void} Nothing
2399
+ */
2400
+ function checkExpectations(expectations, value) {
2401
+ var e_1, _a;
2402
+ try {
2403
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
2404
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
2405
+ var amount = CountUtils[unit.toUpperCase()](value);
2406
+ if (min && amount < min) {
2407
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2408
+ } /* not else */
2409
+ if (max && amount > max) {
2410
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2411
+ }
2412
+ }
2413
+ }
2414
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2415
+ finally {
2416
+ try {
2417
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2418
+ }
2419
+ finally { if (e_1) throw e_1.error; }
2420
+ }
2421
+ }
2422
+ /**
2423
+ * Function checkExpectations will check if the expectations on given value are met
2424
+ *
2425
+ * Note: There are two simmilar functions:
2426
+ * - `checkExpectations` which throws an error if the expectations are not met
2427
+ * - `isPassingExpectations` which returns a boolean
2428
+ *
2429
+ * @returns {boolean} True if the expectations are met
2430
+ */
2431
+ function isPassingExpectations(expectations, value) {
2432
+ try {
2433
+ checkExpectations(expectations, value);
2434
+ return true;
2435
+ }
2436
+ catch (error) {
2437
+ if (!(error instanceof ExpectError)) {
2438
+ throw error;
2439
+ }
2440
+ return false;
2441
+ }
2442
+ }
2443
+ /**
2444
+ * TODO: [💝] Unite object for expecting amount and format
2445
+ */
2446
+
2239
2447
  /**
2240
2448
  * Creates executor function from promptbook and execution tools.
2241
2449
  *
@@ -2756,50 +2964,181 @@ function createPromptbookExecutor(options) {
2756
2964
  */
2757
2965
 
2758
2966
  /**
2759
- * Delagates the user interaction to a async callback function
2760
- * You need to provide your own implementation of this callback function and its bind to UI.
2967
+ * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2968
+ *
2969
+ * @see https://github.com/webgptorg/promptbook#multiple-server
2761
2970
  */
2762
- var CallbackInterfaceTools = /** @class */ (function () {
2763
- function CallbackInterfaceTools(options) {
2764
- this.options = options;
2971
+ var MultipleLlmExecutionTools = /** @class */ (function () {
2972
+ /**
2973
+ * Gets array of execution tools in order of priority
2974
+ */
2975
+ function MultipleLlmExecutionTools() {
2976
+ var llmExecutionTools = [];
2977
+ for (var _i = 0; _i < arguments.length; _i++) {
2978
+ llmExecutionTools[_i] = arguments[_i];
2979
+ }
2980
+ this.llmExecutionTools = llmExecutionTools;
2765
2981
  }
2766
2982
  /**
2767
- * Trigger the custom callback function
2983
+ * Calls the best available chat model
2768
2984
  */
2769
- CallbackInterfaceTools.prototype.promptDialog = function (options) {
2770
- return __awaiter(this, void 0, void 0, function () {
2771
- var answer;
2772
- return __generator(this, function (_a) {
2773
- switch (_a.label) {
2774
- case 0: return [4 /*yield*/, this.options.callback(options)];
2775
- case 1:
2776
- answer = _a.sent();
2777
- if (this.options.isVerbose) {
2778
- console.info(spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
2779
- }
2780
- return [2 /*return*/, answer];
2781
- }
2782
- });
2783
- });
2985
+ MultipleLlmExecutionTools.prototype.gptChat = function (prompt) {
2986
+ return this.gptCommon(prompt);
2784
2987
  };
2785
- return CallbackInterfaceTools;
2786
- }());
2787
-
2788
- /**
2789
- * Wrapper around `window.prompt` synchronous function that interacts with the user via browser prompt
2790
- *
2791
- * Warning: It is used for testing and mocking
2792
- * **NOT intended to use in the production** due to its synchronous nature.
2793
- */
2794
- var SimplePromptInterfaceTools = /** @class */ (function () {
2795
- function SimplePromptInterfaceTools(options) {
2796
- this.options = options;
2797
- }
2798
2988
  /**
2799
- * Trigger window.PROMPT DIALOG
2989
+ * Calls the best available completion model
2800
2990
  */
2801
- SimplePromptInterfaceTools.prototype.promptDialog = function (options) {
2802
- return __awaiter(this, void 0, void 0, function () {
2991
+ MultipleLlmExecutionTools.prototype.gptComplete = function (prompt) {
2992
+ return this.gptCommon(prompt);
2993
+ };
2994
+ /**
2995
+ * Calls the best available model
2996
+ */
2997
+ MultipleLlmExecutionTools.prototype.gptCommon = function (prompt) {
2998
+ return __awaiter(this, void 0, void 0, function () {
2999
+ var errors, _a, _b, llmExecutionTools, error_1, e_1_1;
3000
+ var e_1, _c;
3001
+ return __generator(this, function (_d) {
3002
+ switch (_d.label) {
3003
+ case 0:
3004
+ errors = [];
3005
+ _d.label = 1;
3006
+ case 1:
3007
+ _d.trys.push([1, 11, 12, 13]);
3008
+ _a = __values(this.llmExecutionTools), _b = _a.next();
3009
+ _d.label = 2;
3010
+ case 2:
3011
+ if (!!_b.done) return [3 /*break*/, 10];
3012
+ llmExecutionTools = _b.value;
3013
+ _d.label = 3;
3014
+ case 3:
3015
+ _d.trys.push([3, 8, , 9]);
3016
+ if (!(prompt.modelRequirements.modelVariant === 'CHAT')) return [3 /*break*/, 5];
3017
+ return [4 /*yield*/, llmExecutionTools.gptChat(prompt)];
3018
+ case 4: return [2 /*return*/, _d.sent()];
3019
+ case 5:
3020
+ if (!(prompt.modelRequirements.modelVariant === 'COMPLETION')) return [3 /*break*/, 7];
3021
+ return [4 /*yield*/, llmExecutionTools.gptComplete(prompt)];
3022
+ case 6: return [2 /*return*/, _d.sent()];
3023
+ case 7: return [3 /*break*/, 9];
3024
+ case 8:
3025
+ error_1 = _d.sent();
3026
+ if (!(error_1 instanceof Error)) {
3027
+ throw error_1;
3028
+ }
3029
+ errors.push(error_1);
3030
+ return [3 /*break*/, 9];
3031
+ case 9:
3032
+ _b = _a.next();
3033
+ return [3 /*break*/, 2];
3034
+ case 10: return [3 /*break*/, 13];
3035
+ case 11:
3036
+ e_1_1 = _d.sent();
3037
+ e_1 = { error: e_1_1 };
3038
+ return [3 /*break*/, 13];
3039
+ case 12:
3040
+ try {
3041
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3042
+ }
3043
+ finally { if (e_1) throw e_1.error; }
3044
+ return [7 /*endfinally*/];
3045
+ case 13: throw new Error(spaceTrim$1(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 "); }));
3046
+ }
3047
+ });
3048
+ });
3049
+ };
3050
+ /**
3051
+ * List all available models that can be used
3052
+ * This liost is a combination of all available models from all execution tools
3053
+ */
3054
+ MultipleLlmExecutionTools.prototype.listModels = function () {
3055
+ return __awaiter(this, void 0, void 0, function () {
3056
+ var availableModels, _a, _b, llmExecutionTools, models, e_2_1;
3057
+ var e_2, _c;
3058
+ return __generator(this, function (_d) {
3059
+ switch (_d.label) {
3060
+ case 0:
3061
+ availableModels = [];
3062
+ _d.label = 1;
3063
+ case 1:
3064
+ _d.trys.push([1, 6, 7, 8]);
3065
+ _a = __values(this.llmExecutionTools), _b = _a.next();
3066
+ _d.label = 2;
3067
+ case 2:
3068
+ if (!!_b.done) return [3 /*break*/, 5];
3069
+ llmExecutionTools = _b.value;
3070
+ return [4 /*yield*/, llmExecutionTools.listModels()];
3071
+ case 3:
3072
+ models = _d.sent();
3073
+ availableModels.push.apply(availableModels, __spreadArray([], __read(models), false));
3074
+ _d.label = 4;
3075
+ case 4:
3076
+ _b = _a.next();
3077
+ return [3 /*break*/, 2];
3078
+ case 5: return [3 /*break*/, 8];
3079
+ case 6:
3080
+ e_2_1 = _d.sent();
3081
+ e_2 = { error: e_2_1 };
3082
+ return [3 /*break*/, 8];
3083
+ case 7:
3084
+ try {
3085
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3086
+ }
3087
+ finally { if (e_2) throw e_2.error; }
3088
+ return [7 /*endfinally*/];
3089
+ case 8: return [2 /*return*/, availableModels];
3090
+ }
3091
+ });
3092
+ });
3093
+ };
3094
+ return MultipleLlmExecutionTools;
3095
+ }());
3096
+
3097
+ /**
3098
+ * Delagates the user interaction to a async callback function
3099
+ * You need to provide your own implementation of this callback function and its bind to UI.
3100
+ */
3101
+ var CallbackInterfaceTools = /** @class */ (function () {
3102
+ function CallbackInterfaceTools(options) {
3103
+ this.options = options;
3104
+ }
3105
+ /**
3106
+ * Trigger the custom callback function
3107
+ */
3108
+ CallbackInterfaceTools.prototype.promptDialog = function (options) {
3109
+ return __awaiter(this, void 0, void 0, function () {
3110
+ var answer;
3111
+ return __generator(this, function (_a) {
3112
+ switch (_a.label) {
3113
+ case 0: return [4 /*yield*/, this.options.callback(options)];
3114
+ case 1:
3115
+ answer = _a.sent();
3116
+ if (this.options.isVerbose) {
3117
+ console.info(spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
3118
+ }
3119
+ return [2 /*return*/, answer];
3120
+ }
3121
+ });
3122
+ });
3123
+ };
3124
+ return CallbackInterfaceTools;
3125
+ }());
3126
+
3127
+ /**
3128
+ * Wrapper around `window.prompt` synchronous function that interacts with the user via browser prompt
3129
+ *
3130
+ * Warning: It is used for testing and mocking
3131
+ * **NOT intended to use in the production** due to its synchronous nature.
3132
+ */
3133
+ var SimplePromptInterfaceTools = /** @class */ (function () {
3134
+ function SimplePromptInterfaceTools(options) {
3135
+ this.options = options;
3136
+ }
3137
+ /**
3138
+ * Trigger window.PROMPT DIALOG
3139
+ */
3140
+ SimplePromptInterfaceTools.prototype.promptDialog = function (options) {
3141
+ return __awaiter(this, void 0, void 0, function () {
2803
3142
  var answer;
2804
3143
  return __generator(this, function (_a) {
2805
3144
  answer = window.prompt(spaceTrim(function (block) { return "\n ".concat(block(options.promptTitle), "\n\n ").concat(block(options.promptMessage), "\n "); }));
@@ -3127,135 +3466,321 @@ function createPromptbookSublibrary(library, predicate) {
3127
3466
  */
3128
3467
 
3129
3468
  /**
3130
- * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
3469
+ * Format either small or big number
3131
3470
  *
3132
- * @see https://github.com/webgptorg/promptbook#multiple-server
3471
+ * @private within the library
3133
3472
  */
3134
- var MultipleLlmExecutionTools = /** @class */ (function () {
3135
- /**
3136
- * Gets array of execution tools in order of priority
3137
- */
3138
- function MultipleLlmExecutionTools() {
3139
- var llmExecutionTools = [];
3140
- for (var _i = 0; _i < arguments.length; _i++) {
3141
- llmExecutionTools[_i] = arguments[_i];
3473
+ function formatNumber(value) {
3474
+ if (value === 0) {
3475
+ return '0';
3476
+ }
3477
+ for (var exponent = 0; exponent < 15; exponent++) {
3478
+ var factor = Math.pow(10, exponent);
3479
+ var valueRounded = Math.round(value * factor) / factor;
3480
+ if (Math.abs(value - valueRounded) / value <
3481
+ 0.001 /* <- TODO: Pass as option, pass to executionReportJsonToString as option */) {
3482
+ return valueRounded.toFixed(exponent);
3142
3483
  }
3143
- this.llmExecutionTools = llmExecutionTools;
3144
3484
  }
3145
- /**
3146
- * Calls the best available chat model
3147
- */
3148
- MultipleLlmExecutionTools.prototype.gptChat = function (prompt) {
3149
- return this.gptCommon(prompt);
3150
- };
3151
- /**
3152
- * Calls the best available completion model
3153
- */
3154
- MultipleLlmExecutionTools.prototype.gptComplete = function (prompt) {
3155
- return this.gptCommon(prompt);
3485
+ return value.toString();
3486
+ }
3487
+
3488
+ /**
3489
+ * Returns the same value that is passed as argument.
3490
+ * No side effects.
3491
+ *
3492
+ * Note: It can be usefull for leveling indentation
3493
+ *
3494
+ * @param value any values
3495
+ * @returns the same values
3496
+ */
3497
+ function just(value) {
3498
+ if (value === undefined) {
3499
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3500
+ return undefined;
3501
+ }
3502
+ return value;
3503
+ }
3504
+
3505
+ /**
3506
+ * Create a markdown table from a 2D array of strings
3507
+ *
3508
+ * @private within the library
3509
+ */
3510
+ function createMarkdownTable(table) {
3511
+ var columnWidths = table.reduce(function (widths, row) {
3512
+ row.forEach(function (cell, columnIndex) {
3513
+ var cellLength = cell.length;
3514
+ if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
3515
+ widths[columnIndex] = cellLength;
3516
+ }
3517
+ });
3518
+ return widths;
3519
+ }, []);
3520
+ var header = "| ".concat(table[0]
3521
+ .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
3522
+ .join(' | '), " |");
3523
+ var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
3524
+ var rows = table.slice(1).map(function (row) {
3525
+ var paddedRow = row.map(function (cell, columnIndex) {
3526
+ return cell.padEnd(columnWidths[columnIndex]);
3527
+ });
3528
+ return "| ".concat(paddedRow.join(' | '), " |");
3529
+ });
3530
+ return __spreadArray([header, separator], __read(rows), false).join('\n');
3531
+ }
3532
+
3533
+ /**
3534
+ * Function createMarkdownChart will draw a chart in markdown from ⬛+🟦 tiles
3535
+ *
3536
+ * @private within the library
3537
+ */
3538
+ function createMarkdownChart(options) {
3539
+ var e_1, _a;
3540
+ var nameHeader = options.nameHeader, valueHeader = options.valueHeader, items = options.items, width = options.width, unitName = options.unitName;
3541
+ var from = Math.min.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.from; })), false));
3542
+ var to = Math.max.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.to; })), false));
3543
+ var scale = width / (to - from);
3544
+ var table = [[nameHeader, valueHeader]];
3545
+ try {
3546
+ for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
3547
+ var item = items_1_1.value;
3548
+ var before = Math.round((item.from - from) * scale);
3549
+ var during = Math.round((item.to - item.from) * scale);
3550
+ var after = width - before - during;
3551
+ table.push([removeEmojis(item.title).trim(), '░'.repeat(before) + '█'.repeat(during) + '░'.repeat(after)]);
3552
+ }
3553
+ }
3554
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3555
+ finally {
3556
+ try {
3557
+ if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
3558
+ }
3559
+ finally { if (e_1) throw e_1.error; }
3560
+ }
3561
+ 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_");
3562
+ return createMarkdownTable(table) + '\n\n' + legend;
3563
+ }
3564
+ /**
3565
+ * TODO: Maybe use Mermain Gant Diagrams
3566
+ * @see https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/
3567
+ */
3568
+
3569
+ /**
3570
+ * Function escapeMarkdownBlock will escape markdown block if needed
3571
+ * It is useful when you want have block in block
3572
+ */
3573
+ function escapeMarkdownBlock(value) {
3574
+ return value.replace(/```/g, '\\`\\`\\`');
3575
+ }
3576
+
3577
+ /**
3578
+ * Default options for generating an execution report string
3579
+ */
3580
+ var ExecutionReportStringOptionsDefaults = {
3581
+ taxRate: 0,
3582
+ chartsWidth: 36,
3583
+ };
3584
+
3585
+ /**
3586
+ * The thresholds for the relative time in the `moment` library.
3587
+ *
3588
+ * @see https://momentjscom.readthedocs.io/en/latest/moment/07-customization/13-relative-time-threshold/
3589
+ */
3590
+ var MOMENT_ARG_THRESHOLDS = {
3591
+ 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.
3592
+ };
3593
+
3594
+ /**
3595
+ * Count the duration of working time
3596
+ *
3597
+ * @private within the library
3598
+ */
3599
+ function countWorkingDuration(items) {
3600
+ var e_1, _a;
3601
+ var steps = Array.from(new Set(items.flatMap(function (item) { return [item.from, item.to]; })));
3602
+ steps.sort(function (a, b) { return a - b; });
3603
+ var intervals = steps.map(function (step, index) { return [step, steps[index + 1] || 0]; }).slice(0, -1);
3604
+ var duration = 0;
3605
+ var _loop_1 = function (interval) {
3606
+ var _b = __read(interval, 2), from = _b[0], to = _b[1];
3607
+ if (items.some(function (item) { return item.from < to && item.to > from; })) {
3608
+ duration += to - from;
3609
+ }
3156
3610
  };
3157
- /**
3158
- * Calls the best available model
3159
- */
3160
- MultipleLlmExecutionTools.prototype.gptCommon = function (prompt) {
3161
- return __awaiter(this, void 0, void 0, function () {
3162
- var errors, _a, _b, llmExecutionTools, error_1, e_1_1;
3163
- var e_1, _c;
3164
- return __generator(this, function (_d) {
3165
- switch (_d.label) {
3166
- case 0:
3167
- errors = [];
3168
- _d.label = 1;
3169
- case 1:
3170
- _d.trys.push([1, 11, 12, 13]);
3171
- _a = __values(this.llmExecutionTools), _b = _a.next();
3172
- _d.label = 2;
3173
- case 2:
3174
- if (!!_b.done) return [3 /*break*/, 10];
3175
- llmExecutionTools = _b.value;
3176
- _d.label = 3;
3177
- case 3:
3178
- _d.trys.push([3, 8, , 9]);
3179
- if (!(prompt.modelRequirements.modelVariant === 'CHAT')) return [3 /*break*/, 5];
3180
- return [4 /*yield*/, llmExecutionTools.gptChat(prompt)];
3181
- case 4: return [2 /*return*/, _d.sent()];
3182
- case 5:
3183
- if (!(prompt.modelRequirements.modelVariant === 'COMPLETION')) return [3 /*break*/, 7];
3184
- return [4 /*yield*/, llmExecutionTools.gptComplete(prompt)];
3185
- case 6: return [2 /*return*/, _d.sent()];
3186
- case 7: return [3 /*break*/, 9];
3187
- case 8:
3188
- error_1 = _d.sent();
3189
- if (!(error_1 instanceof Error)) {
3190
- throw error_1;
3191
- }
3192
- errors.push(error_1);
3193
- return [3 /*break*/, 9];
3194
- case 9:
3195
- _b = _a.next();
3196
- return [3 /*break*/, 2];
3197
- case 10: return [3 /*break*/, 13];
3198
- case 11:
3199
- e_1_1 = _d.sent();
3200
- e_1 = { error: e_1_1 };
3201
- return [3 /*break*/, 13];
3202
- case 12:
3203
- try {
3204
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3205
- }
3206
- finally { if (e_1) throw e_1.error; }
3207
- return [7 /*endfinally*/];
3208
- case 13: throw new Error(spaceTrim$1(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 "); }));
3209
- }
3611
+ try {
3612
+ for (var intervals_1 = __values(intervals), intervals_1_1 = intervals_1.next(); !intervals_1_1.done; intervals_1_1 = intervals_1.next()) {
3613
+ var interval = intervals_1_1.value;
3614
+ _loop_1(interval);
3615
+ }
3616
+ }
3617
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3618
+ finally {
3619
+ try {
3620
+ if (intervals_1_1 && !intervals_1_1.done && (_a = intervals_1.return)) _a.call(intervals_1);
3621
+ }
3622
+ finally { if (e_1) throw e_1.error; }
3623
+ }
3624
+ return duration;
3625
+ }
3626
+
3627
+ /**
3628
+ * Converts execution report from JSON to string format
3629
+ */
3630
+ function executionReportJsonToString(executionReportJson, options) {
3631
+ var e_1, _a;
3632
+ var _b, _c, _d, _e, _f, _g;
3633
+ var _h = __assign(__assign({}, ExecutionReportStringOptionsDefaults), (options || {})), taxRate = _h.taxRate, chartsWidth = _h.chartsWidth;
3634
+ var executionReportString = spaceTrim(function (block) { return "\n # ".concat(executionReportJson.title || 'Execution report', "\n\n ").concat(block(executionReportJson.description || ''), "\n "); });
3635
+ var headerList = [];
3636
+ if (executionReportJson.promptbookUrl) {
3637
+ headerList.push("PROMPTBOOK URL ".concat(executionReportJson.promptbookUrl));
3638
+ }
3639
+ headerList.push("PROMPTBOOK VERSION ".concat(executionReportJson.promptbookUsedVersion) +
3640
+ (!executionReportJson.promptbookRequestedVersion
3641
+ ? ''
3642
+ : " *(requested ".concat(executionReportJson.promptbookRequestedVersion, ")*")));
3643
+ if (executionReportJson.promptExecutions.length !== 0) {
3644
+ // TODO: What if startedAt OR/AND completedAt is not defined?
3645
+ var startedAt = moment(Math.min.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
3646
+ .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; })
3647
+ .map(function (promptExecution) { return moment(promptExecution.result.timing.start).valueOf(); })), false)));
3648
+ var completedAt = moment(Math.max.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
3649
+ .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; })
3650
+ .map(function (promptExecution) { return moment(promptExecution.result.timing.complete).valueOf(); })), false)));
3651
+ var timingItems = executionReportJson.promptExecutions.map(function (promptExecution) {
3652
+ var _a, _b, _c, _d;
3653
+ return ({
3654
+ title: promptExecution.prompt.title,
3655
+ from: moment((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.start).valueOf() / 1000,
3656
+ to: moment((_d = (_c = promptExecution.result) === null || _c === void 0 ? void 0 : _c.timing) === null || _d === void 0 ? void 0 : _d.complete).valueOf() / 1000,
3210
3657
  });
3211
3658
  });
3212
- };
3213
- /**
3214
- * List all available models that can be used
3215
- * This liost is a combination of all available models from all execution tools
3216
- */
3217
- MultipleLlmExecutionTools.prototype.listModels = function () {
3218
- return __awaiter(this, void 0, void 0, function () {
3219
- var availableModels, _a, _b, llmExecutionTools, models, e_2_1;
3220
- var e_2, _c;
3221
- return __generator(this, function (_d) {
3222
- switch (_d.label) {
3223
- case 0:
3224
- availableModels = [];
3225
- _d.label = 1;
3226
- case 1:
3227
- _d.trys.push([1, 6, 7, 8]);
3228
- _a = __values(this.llmExecutionTools), _b = _a.next();
3229
- _d.label = 2;
3230
- case 2:
3231
- if (!!_b.done) return [3 /*break*/, 5];
3232
- llmExecutionTools = _b.value;
3233
- return [4 /*yield*/, llmExecutionTools.listModels()];
3234
- case 3:
3235
- models = _d.sent();
3236
- availableModels.push.apply(availableModels, __spreadArray([], __read(models), false));
3237
- _d.label = 4;
3238
- case 4:
3239
- _b = _a.next();
3240
- return [3 /*break*/, 2];
3241
- case 5: return [3 /*break*/, 8];
3242
- case 6:
3243
- e_2_1 = _d.sent();
3244
- e_2 = { error: e_2_1 };
3245
- return [3 /*break*/, 8];
3246
- case 7:
3247
- try {
3248
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3249
- }
3250
- finally { if (e_2) throw e_2.error; }
3251
- return [7 /*endfinally*/];
3252
- case 8: return [2 /*return*/, availableModels];
3253
- }
3659
+ var costItems = executionReportJson.promptExecutions
3660
+ .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'; })
3661
+ .map(function (promptExecution) {
3662
+ var _a, _b;
3663
+ return ({
3664
+ title: promptExecution.prompt.title,
3665
+ from: 0,
3666
+ to: ((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) * (1 + taxRate),
3254
3667
  });
3255
3668
  });
3669
+ var duration = moment.duration(completedAt.diff(startedAt));
3670
+ var llmDuration = moment.duration(countWorkingDuration(timingItems) * 1000);
3671
+ 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'; });
3672
+ var cost = executionsWithKnownCost.reduce(function (cost, promptExecution) { return cost + (promptExecution.result.usage.price || 0); }, 0);
3673
+ headerList.push("STARTED AT ".concat(moment(startedAt).format("YYYY-MM-DD HH:mm:ss")));
3674
+ headerList.push("COMPLETED AT ".concat(moment(completedAt).format("YYYY-MM-DD HH:mm:ss")));
3675
+ headerList.push("TOTAL DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
3676
+ headerList.push("TOTAL LLM DURATION ".concat(llmDuration.humanize(MOMENT_ARG_THRESHOLDS)));
3677
+ headerList.push("TOTAL COST $".concat(formatNumber(cost * (1 + taxRate))) +
3678
+ (executionsWithKnownCost.length === executionReportJson.promptExecutions.length
3679
+ ? ''
3680
+ : " *(Some cost is unknown)*") +
3681
+ (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
3682
+ executionReportString += '\n\n' + headerList.map(function (header) { return "- ".concat(header); }).join('\n');
3683
+ executionReportString +=
3684
+ '\n\n' +
3685
+ '## 🗃 Index' +
3686
+ '\n\n' +
3687
+ executionReportJson.promptExecutions
3688
+ .map(function (promptExecution) {
3689
+ // TODO: Make some better system to convert hedings to links
3690
+ var hash = normalizeToKebabCase(promptExecution.prompt.title);
3691
+ if (/^\s*\p{Extended_Pictographic}/u.test(promptExecution.prompt.title)) {
3692
+ hash = '-' + hash;
3693
+ }
3694
+ // TODO: Make working hash link for the template in md + pdf
3695
+ return "- [".concat(promptExecution.prompt.title, "](#").concat(hash, ")");
3696
+ })
3697
+ .join('\n');
3698
+ executionReportString +=
3699
+ '\n\n' +
3700
+ '## ⌚ Time chart' +
3701
+ '\n\n' +
3702
+ createMarkdownChart({
3703
+ nameHeader: 'Template',
3704
+ valueHeader: 'Timeline',
3705
+ items: timingItems,
3706
+ width: chartsWidth,
3707
+ unitName: 'seconds',
3708
+ });
3709
+ executionReportString +=
3710
+ '\n\n' +
3711
+ '## 💸 Cost chart' +
3712
+ '\n\n' +
3713
+ createMarkdownChart({
3714
+ nameHeader: 'Template',
3715
+ valueHeader: 'Cost',
3716
+ items: costItems,
3717
+ width: chartsWidth,
3718
+ unitName: 'USD',
3719
+ });
3720
+ }
3721
+ else {
3722
+ headerList.push("TOTAL COST $0 *(Nothing executed)*");
3723
+ }
3724
+ var _loop_1 = function (promptExecution) {
3725
+ executionReportString += '\n\n\n\n' + "## ".concat(promptExecution.prompt.title);
3726
+ var templateList = [];
3727
+ // TODO: What if startedAt OR/AND completedAt is not defined?
3728
+ var startedAt = moment((_c = (_b = promptExecution.result) === null || _b === void 0 ? void 0 : _b.timing) === null || _c === void 0 ? void 0 : _c.start);
3729
+ var completedAt = moment((_e = (_d = promptExecution.result) === null || _d === void 0 ? void 0 : _d.timing) === null || _e === void 0 ? void 0 : _e.complete);
3730
+ var duration = moment.duration(completedAt.diff(startedAt));
3731
+ // Not need here:
3732
+ // > templateList.push(`STARTED AT ${moment(startedAt).calendar()}`);
3733
+ templateList.push("DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
3734
+ if (typeof ((_g = (_f = promptExecution.result) === null || _f === void 0 ? void 0 : _f.usage) === null || _g === void 0 ? void 0 : _g.price) === 'number') {
3735
+ templateList.push("COST $".concat(formatNumber(promptExecution.result.usage.price * (1 + taxRate))) +
3736
+ (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
3737
+ }
3738
+ else {
3739
+ templateList.push("COST UNKNOWN");
3740
+ }
3741
+ executionReportString += '\n\n' + templateList.map(function (header) { return "- ".concat(header); }).join('\n');
3742
+ /*
3743
+ - MODEL VARIANT ${promptExecution.prompt.modelRequirements.modelVariant}
3744
+ - MODEL NAME \`${promptExecution.result?.model}\` (requested \`${
3745
+ promptExecution.prompt.modelRequirements.modelName
3746
+
3747
+ */
3748
+ if (just(true)) {
3749
+ executionReportString +=
3750
+ '\n\n\n\n' +
3751
+ spaceTrim(function (block) { return "\n\n ### Prompt\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.prompt.content)), "\n ```\n\n "); });
3752
+ }
3753
+ if (promptExecution.result && promptExecution.result.content) {
3754
+ executionReportString +=
3755
+ '\n\n\n\n' +
3756
+ spaceTrim(function (block) { return "\n\n ### Result\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.result.content)), "\n ```\n "); });
3757
+ }
3758
+ if (promptExecution.error && promptExecution.error.message) {
3759
+ executionReportString +=
3760
+ '\n\n\n\n' +
3761
+ spaceTrim(function (block) { return "\n\n ### Error\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.error.message)), "\n ```\n\n "); });
3762
+ }
3256
3763
  };
3257
- return MultipleLlmExecutionTools;
3258
- }());
3764
+ try {
3765
+ for (var _j = __values(executionReportJson.promptExecutions), _k = _j.next(); !_k.done; _k = _j.next()) {
3766
+ var promptExecution = _k.value;
3767
+ _loop_1(promptExecution);
3768
+ }
3769
+ }
3770
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3771
+ finally {
3772
+ try {
3773
+ if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
3774
+ }
3775
+ finally { if (e_1) throw e_1.error; }
3776
+ }
3777
+ executionReportString = prettifyMarkdown(executionReportString);
3778
+ return executionReportString;
3779
+ }
3780
+ /**
3781
+ * TODO: Add mermaid chart for every report
3782
+ * TODO: [🧠] Allow to filter out some parts of the report by options
3783
+ */
3259
3784
 
3260
- export { CallbackInterfaceTools, ExecutionTypes, MultipleLlmExecutionTools, PROMPTBOOK_VERSION, SimplePromptInterfaceTools, SimplePromptbookLibrary, createPromptbookExecutor, createPromptbookLibraryFromPromise, createPromptbookLibraryFromSources, createPromptbookSublibrary, promptbookJsonToString, promptbookStringToJson, validatePromptbookJson };
3785
+ export { CallbackInterfaceTools, ExecutionReportStringOptionsDefaults, ExecutionTypes, MultipleLlmExecutionTools, PROMPTBOOK_VERSION, SimplePromptInterfaceTools, SimplePromptbookLibrary, assertsExecutionSuccessful, checkExpectations, createPromptbookExecutor, createPromptbookLibraryFromPromise, createPromptbookLibraryFromSources, createPromptbookSublibrary, executionReportJsonToString, isPassingExpectations, prettifyPromptbookString, promptbookJsonToString, promptbookStringToJson, validatePromptbookJson };
3261
3786
  //# sourceMappingURL=index.es.js.map