@promptbook/core 0.44.0-2 โ†’ 0.44.0-21

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 (28) hide show
  1. package/README.md +713 -2
  2. package/esm/index.es.js +361 -186
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/_packages/utils.index.d.ts +5 -3
  5. package/esm/typings/config.d.ts +4 -0
  6. package/esm/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.d.ts +9 -1
  7. package/esm/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.test.d.ts +1 -0
  8. package/esm/typings/execution/plugins/natural-execution-tools/mocked/faked-completion.test.d.ts +1 -0
  9. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions.d.ts +5 -1
  10. package/esm/typings/execution/plugins/script-execution-tools/javascript/utils/unknownToString.d.ts +7 -0
  11. package/esm/typings/execution/utils/checkExpectations.d.ts +25 -0
  12. package/esm/typings/execution/utils/checkExpectations.test.d.ts +1 -0
  13. package/esm/typings/types/Prompt.d.ts +5 -0
  14. package/esm/typings/types/PromptbookJson/PromptTemplateJson.d.ts +2 -0
  15. package/package.json +2 -2
  16. package/umd/index.umd.js +401 -230
  17. package/umd/index.umd.js.map +1 -1
  18. package/umd/typings/_packages/utils.index.d.ts +5 -3
  19. package/umd/typings/config.d.ts +4 -0
  20. package/umd/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.d.ts +9 -1
  21. package/umd/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.test.d.ts +1 -0
  22. package/umd/typings/execution/plugins/natural-execution-tools/mocked/faked-completion.test.d.ts +1 -0
  23. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions.d.ts +5 -1
  24. package/umd/typings/execution/plugins/script-execution-tools/javascript/utils/unknownToString.d.ts +7 -0
  25. package/umd/typings/execution/utils/checkExpectations.d.ts +25 -0
  26. package/umd/typings/execution/utils/checkExpectations.test.d.ts +1 -0
  27. package/umd/typings/types/Prompt.d.ts +5 -0
  28. package/umd/typings/types/PromptbookJson/PromptTemplateJson.d.ts +2 -0
package/umd/index.umd.js CHANGED
@@ -1,12 +1,8 @@
1
1
  (function (global, factory) {
2
2
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('moment'), require('lorem-ipsum')) :
3
3
  typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'moment', 'lorem-ipsum'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, null, null, null, global.loremIpsum));
5
- })(this, (function (exports, spaceTrim, prettier, parserHtml, moment, loremIpsum) { 'use strict';
6
-
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
-
9
- var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spacetrim, null, null, null, global.loremIpsum));
5
+ })(this, (function (exports, spacetrim, prettier, parserHtml, moment, loremIpsum) { 'use strict';
10
6
 
11
7
  /*! *****************************************************************************
12
8
  Copyright (c) Microsoft Corporation.
@@ -133,7 +129,7 @@
133
129
  var UnexpectedError = /** @class */ (function (_super) {
134
130
  __extends(UnexpectedError, _super);
135
131
  function UnexpectedError(message) {
136
- var _this = _super.call(this, spaceTrim__default["default"](function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
132
+ var _this = _super.call(this, spacetrim.spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
137
133
  _this.name = 'UnexpectedError';
138
134
  Object.setPrototypeOf(_this, UnexpectedError.prototype);
139
135
  return _this;
@@ -148,7 +144,7 @@
148
144
  * @returns {string} The input string with all comments removed.
149
145
  */
150
146
  function removeContentComments(content) {
151
- return spaceTrim__default["default"](content.replace(/<!--(.*?)-->/gs, ''));
147
+ return spacetrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
152
148
  }
153
149
 
154
150
  /**
@@ -247,86 +243,22 @@
247
243
  }(Error));
248
244
 
249
245
  /**
250
- * The maximum number of iterations for a loops
251
- */
252
- var LOOP_LIMIT = 1000;
253
-
254
- /**
255
- * This error occurs during the parameter replacement in the template
246
+ * This error occurs when some expectation is not met in the execution of the pipeline
256
247
  *
257
- * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
248
+ * @private Always catched and rethrown as `PromptbookExecutionError`
249
+ * Note: This is a kindof subtype of PromptbookExecutionError
258
250
  */
259
- var TemplateError = /** @class */ (function (_super) {
260
- __extends(TemplateError, _super);
261
- function TemplateError(message) {
251
+ var ExpectError = /** @class */ (function (_super) {
252
+ __extends(ExpectError, _super);
253
+ function ExpectError(message) {
262
254
  var _this = _super.call(this, message) || this;
263
- _this.name = 'TemplateError';
264
- Object.setPrototypeOf(_this, TemplateError.prototype);
255
+ _this.name = 'ExpectError';
256
+ Object.setPrototypeOf(_this, ExpectError.prototype);
265
257
  return _this;
266
258
  }
267
- return TemplateError;
259
+ return ExpectError;
268
260
  }(Error));
269
261
 
270
- /**
271
- * Replaces parameters in template with values from parameters object
272
- *
273
- * @param template the template with parameters in {curly} braces
274
- * @param parameters the object with parameters
275
- * @returns the template with replaced parameters
276
- * @throws {TemplateError} if parameter is not defined, not closed, or not opened
277
- *
278
- * @private within the createPromptbookExecutor
279
- */
280
- function replaceParameters(template, parameters) {
281
- var replacedTemplate = template;
282
- var match;
283
- var loopLimit = LOOP_LIMIT;
284
- var _loop_1 = function () {
285
- if (loopLimit-- < 0) {
286
- throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
287
- }
288
- var precol = match.groups.precol;
289
- var parameterName = match.groups.parameterName;
290
- if (parameterName === '') {
291
- return "continue";
292
- }
293
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
294
- throw new TemplateError('Parameter is already opened or not closed');
295
- }
296
- if (parameters[parameterName] === undefined) {
297
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
298
- }
299
- var parameterValue = parameters[parameterName];
300
- if (parameterValue === undefined) {
301
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
302
- }
303
- parameterValue = parameterValue.toString();
304
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
305
- parameterValue = parameterValue
306
- .split('\n')
307
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
308
- .join('\n');
309
- }
310
- replacedTemplate =
311
- replacedTemplate.substring(0, match.index + precol.length) +
312
- parameterValue +
313
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
314
- };
315
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
316
- .exec(replacedTemplate))) {
317
- _loop_1();
318
- }
319
- // [๐Ÿ’ซ] Check if there are parameters that are not closed properly
320
- if (/{\w+$/.test(replacedTemplate)) {
321
- throw new TemplateError('Parameter is not closed');
322
- }
323
- // [๐Ÿ’ซ] Check if there are parameters that are not opened properly
324
- if (/^\w+}/.test(replacedTemplate)) {
325
- throw new TemplateError('Parameter is not opened');
326
- }
327
- return replacedTemplate;
328
- }
329
-
330
262
  /**
331
263
  * Counts number of characters in the text
332
264
  */
@@ -654,6 +586,148 @@
654
586
  PAGES: countPages,
655
587
  };
656
588
 
589
+ /**
590
+ * Function checkExpectations will check if the expectations on given value are met
591
+ *
592
+ * Note: There are two simmilar functions:
593
+ * - `checkExpectations` which throws an error if the expectations are not met
594
+ * - `isPassingExpectations` which returns a boolean
595
+ *
596
+ * @throws {ExpectError} if the expectations are not met
597
+ * @returns {void} Nothing
598
+ */
599
+ function checkExpectations(expectations, value) {
600
+ var e_1, _a;
601
+ try {
602
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
603
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
604
+ var amount = CountUtils[unit.toUpperCase()](value);
605
+ if (min && amount < min) {
606
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
607
+ } /* not else */
608
+ if (max && amount > max) {
609
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
610
+ }
611
+ }
612
+ }
613
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
614
+ finally {
615
+ try {
616
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
617
+ }
618
+ finally { if (e_1) throw e_1.error; }
619
+ }
620
+ }
621
+ /**
622
+ * Function checkExpectations will check if the expectations on given value are met
623
+ *
624
+ * Note: There are two simmilar functions:
625
+ * - `checkExpectations` which throws an error if the expectations are not met
626
+ * - `isPassingExpectations` which returns a boolean
627
+ *
628
+ * @returns {boolean} True if the expectations are met
629
+ */
630
+ function isPassingExpectations(expectations, value) {
631
+ try {
632
+ checkExpectations(expectations, value);
633
+ return true;
634
+ }
635
+ catch (error) {
636
+ if (!(error instanceof ExpectError)) {
637
+ throw error;
638
+ }
639
+ return false;
640
+ }
641
+ }
642
+ /**
643
+ * TODO: [๐Ÿ’] Unite object for expecting amount and format
644
+ */
645
+
646
+ /**
647
+ * The maximum number of iterations for a loops
648
+ */
649
+ var LOOP_LIMIT = 1000;
650
+ /**
651
+ * The maximum number of iterations for a loops which adds characters one by one
652
+ */
653
+ var CHARACTER_LOOP_LIMIT = 100000;
654
+
655
+ /**
656
+ * This error occurs during the parameter replacement in the template
657
+ *
658
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
659
+ */
660
+ var TemplateError = /** @class */ (function (_super) {
661
+ __extends(TemplateError, _super);
662
+ function TemplateError(message) {
663
+ var _this = _super.call(this, message) || this;
664
+ _this.name = 'TemplateError';
665
+ Object.setPrototypeOf(_this, TemplateError.prototype);
666
+ return _this;
667
+ }
668
+ return TemplateError;
669
+ }(Error));
670
+
671
+ /**
672
+ * Replaces parameters in template with values from parameters object
673
+ *
674
+ * @param template the template with parameters in {curly} braces
675
+ * @param parameters the object with parameters
676
+ * @returns the template with replaced parameters
677
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
678
+ *
679
+ * @private within the createPromptbookExecutor
680
+ */
681
+ function replaceParameters(template, parameters) {
682
+ var replacedTemplate = template;
683
+ var match;
684
+ var loopLimit = LOOP_LIMIT;
685
+ var _loop_1 = function () {
686
+ if (loopLimit-- < 0) {
687
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
688
+ }
689
+ var precol = match.groups.precol;
690
+ var parameterName = match.groups.parameterName;
691
+ if (parameterName === '') {
692
+ return "continue";
693
+ }
694
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
695
+ throw new TemplateError('Parameter is already opened or not closed');
696
+ }
697
+ if (parameters[parameterName] === undefined) {
698
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
699
+ }
700
+ var parameterValue = parameters[parameterName];
701
+ if (parameterValue === undefined) {
702
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
703
+ }
704
+ parameterValue = parameterValue.toString();
705
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
706
+ parameterValue = parameterValue
707
+ .split('\n')
708
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
709
+ .join('\n');
710
+ }
711
+ replacedTemplate =
712
+ replacedTemplate.substring(0, match.index + precol.length) +
713
+ parameterValue +
714
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
715
+ };
716
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
717
+ .exec(replacedTemplate))) {
718
+ _loop_1();
719
+ }
720
+ // [๐Ÿ’ซ] Check if there are parameters that are not closed properly
721
+ if (/{\w+$/.test(replacedTemplate)) {
722
+ throw new TemplateError('Parameter is not closed');
723
+ }
724
+ // [๐Ÿ’ซ] Check if there are parameters that are not opened properly
725
+ if (/^\w+}/.test(replacedTemplate)) {
726
+ throw new TemplateError('Parameter is not opened');
727
+ }
728
+ return replacedTemplate;
729
+ }
730
+
657
731
  /**
658
732
  * Function isValidJsonString will tell you if the string is valid JSON or not
659
733
  */
@@ -1045,7 +1119,7 @@
1045
1119
  }
1046
1120
  if (parent_1.parent === null /* <- Note: We are in root */) {
1047
1121
  // [๐ŸŒป]
1048
- throw new Error(spaceTrim__default["default"]("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
1122
+ throw new Error(spacetrim.spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
1049
1123
  }
1050
1124
  parent_1 = parent_1.parent;
1051
1125
  }
@@ -1079,7 +1153,7 @@
1079
1153
  return {
1080
1154
  level: level,
1081
1155
  title: title,
1082
- content: spaceTrim__default["default"](contentLines.join('\n')),
1156
+ content: spacetrim.spaceTrim(contentLines.join('\n')),
1083
1157
  sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
1084
1158
  };
1085
1159
  }
@@ -1087,7 +1161,7 @@
1087
1161
  /**
1088
1162
  * The version of the Promptbook library
1089
1163
  */
1090
- var PROMPTBOOK_VERSION = '0.44.0-1';
1164
+ var PROMPTBOOK_VERSION = '0.44.0-20';
1091
1165
 
1092
1166
  /**
1093
1167
  * Parses the given script and returns the list of all used variables that are not defined in the script
@@ -1132,7 +1206,7 @@
1132
1206
  if (!(error instanceof Error)) {
1133
1207
  throw error;
1134
1208
  }
1135
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
1209
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
1136
1210
  }
1137
1211
  return variables;
1138
1212
  }
@@ -1155,6 +1229,7 @@
1155
1229
  */
1156
1230
  var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
1157
1231
  /**
1232
+ * TODO: [๐Ÿ’] Unite object for expecting amount and format - remove expectFormat
1158
1233
  * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
1159
1234
  */
1160
1235
 
@@ -1196,15 +1271,15 @@
1196
1271
  type.startsWith('PROMPTBOOKURL') ||
1197
1272
  type.startsWith('HTTPS')) {
1198
1273
  if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
1199
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
1274
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
1200
1275
  }
1201
1276
  var promptbookUrlString = listItemParts.pop();
1202
1277
  var promptbookUrl = new URL(promptbookUrlString);
1203
1278
  if (promptbookUrl.protocol !== 'https:') {
1204
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
1279
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
1205
1280
  }
1206
1281
  if (promptbookUrl.hash !== '') {
1207
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
1282
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
1208
1283
  }
1209
1284
  return {
1210
1285
  type: 'PROMPTBOOK_URL',
@@ -1213,7 +1288,7 @@
1213
1288
  }
1214
1289
  else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
1215
1290
  if (listItemParts.length !== 2) {
1216
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
1291
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
1217
1292
  }
1218
1293
  var promptbookVersion = listItemParts.pop();
1219
1294
  // TODO: Validate version
@@ -1228,7 +1303,7 @@
1228
1303
  type.startsWith('SIMPLE_TEMPLATE')) {
1229
1304
  var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
1230
1305
  if (executionTypes.length !== 1) {
1231
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
1306
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
1232
1307
  }
1233
1308
  return {
1234
1309
  type: 'EXECUTE',
@@ -1253,7 +1328,7 @@
1253
1328
  };
1254
1329
  }
1255
1330
  else {
1256
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
1331
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
1257
1332
  }
1258
1333
  }
1259
1334
  if (type.startsWith('MODEL_NAME')) {
@@ -1264,7 +1339,7 @@
1264
1339
  };
1265
1340
  }
1266
1341
  else {
1267
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
1342
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
1268
1343
  }
1269
1344
  }
1270
1345
  else if (type.startsWith('PARAM') ||
@@ -1274,12 +1349,12 @@
1274
1349
  listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
1275
1350
  var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
1276
1351
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1277
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1352
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1278
1353
  }
1279
1354
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1280
1355
  var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
1281
1356
  if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
1282
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
1357
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
1283
1358
  }
1284
1359
  var isInput = type.startsWith('INPUT');
1285
1360
  var isOutput = type.startsWith('OUTPUT');
@@ -1297,11 +1372,11 @@
1297
1372
  }
1298
1373
  else if (type.startsWith('JOKER')) {
1299
1374
  if (listItemParts.length !== 2) {
1300
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
1375
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
1301
1376
  }
1302
1377
  var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
1303
1378
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1304
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1379
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1305
1380
  }
1306
1381
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1307
1382
  var parameterName = parametersMatch.groups.parameterName;
@@ -1312,7 +1387,7 @@
1312
1387
  }
1313
1388
  else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
1314
1389
  if (listItemParts.length !== 2) {
1315
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
1390
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
1316
1391
  }
1317
1392
  var functionName = listItemParts.pop();
1318
1393
  return {
@@ -1392,7 +1467,7 @@
1392
1467
  if (!(error instanceof Error)) {
1393
1468
  throw error;
1394
1469
  }
1395
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1470
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1396
1471
  }
1397
1472
  /*
1398
1473
  } else if (type.startsWith('__________________')) {
@@ -1400,7 +1475,7 @@
1400
1475
  */
1401
1476
  }
1402
1477
  else {
1403
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
1478
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
1404
1479
  }
1405
1480
  }
1406
1481
 
@@ -1436,7 +1511,7 @@
1436
1511
  existingParameter.description &&
1437
1512
  existingParameter.description !== parameterDescription &&
1438
1513
  parameterDescription) {
1439
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
1514
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
1440
1515
  }
1441
1516
  if (existingParameter) {
1442
1517
  if (parameterDescription) {
@@ -1457,7 +1532,7 @@
1457
1532
  var markdownStructure = markdownToMarkdownStructure(promptbookString);
1458
1533
  var markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
1459
1534
  if (markdownStructureDeepness !== 2) {
1460
- throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
1535
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
1461
1536
  }
1462
1537
  promptbookJson.title = markdownStructure.title;
1463
1538
  // TODO: [1] DRY description
@@ -1466,7 +1541,7 @@
1466
1541
  description = description.split(/^```.*^```/gms).join('');
1467
1542
  //Note: Remove lists and return statement
1468
1543
  description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1469
- description = spaceTrim__default["default"](description);
1544
+ description = spacetrim.spaceTrim(description);
1470
1545
  if (description === '') {
1471
1546
  description = undefined;
1472
1547
  }
@@ -1581,13 +1656,13 @@
1581
1656
  throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
1582
1657
  }
1583
1658
  else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
1584
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
1659
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
1585
1660
  }
1586
1661
  }
1587
1662
  var lastLine = section.content.split('\n').pop();
1588
1663
  var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1589
1664
  if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1590
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1665
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1591
1666
  // TODO: Show code of invalid sections each time + DRY
1592
1667
  section.content
1593
1668
  .split('\n')
@@ -1601,7 +1676,7 @@
1601
1676
  description_1 = description_1.split(/^```.*^```/gms).join('');
1602
1677
  //Note: Remove lists and return statement
1603
1678
  description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1604
- description_1 = spaceTrim__default["default"](description_1);
1679
+ description_1 = spacetrim.spaceTrim(description_1);
1605
1680
  if (description_1 === '') {
1606
1681
  description_1 = undefined;
1607
1682
  }
@@ -1749,12 +1824,12 @@
1749
1824
  if (!parameter.isInput &&
1750
1825
  !parameter.isOutput &&
1751
1826
  !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
1752
- throw new PromptbookLogicError(spaceTrim__default["default"]("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
1827
+ throw new PromptbookLogicError(spacetrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
1753
1828
  }
1754
1829
  // Note: Testing that parameter is either input or result of some template
1755
1830
  if (!parameter.isInput &&
1756
1831
  !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
1757
- throw new PromptbookLogicError(spaceTrim__default["default"]("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
1832
+ throw new PromptbookLogicError(spacetrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
1758
1833
  }
1759
1834
  };
1760
1835
  try {
@@ -1789,7 +1864,7 @@
1789
1864
  if (template.executionType === 'PROMPT_TEMPLATE' &&
1790
1865
  (template.modelRequirements.modelVariant === undefined ||
1791
1866
  template.modelRequirements.modelName === undefined)) {
1792
- throw new PromptbookLogicError(spaceTrim__default["default"]("\n\n You must specify MODEL VARIANT and MODEL NAME in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
1867
+ throw new PromptbookLogicError(spacetrim.spaceTrim("\n\n You must specify MODEL VARIANT and MODEL NAME in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
1793
1868
  }
1794
1869
  if (template.jokers && template.jokers.length > 0) {
1795
1870
  if (!template.expectFormat &&
@@ -1864,7 +1939,7 @@
1864
1939
  return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
1865
1940
  });
1866
1941
  if (currentlyResovedTemplates.length === 0) {
1867
- throw new PromptbookLogicError(spaceTrim__default["default"](function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
1942
+ throw new PromptbookLogicError(spacetrim.spaceTrim(function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
1868
1943
  .map(function (_a) {
1869
1944
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
1870
1945
  return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
@@ -1895,23 +1970,6 @@
1895
1970
  * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
1896
1971
  */
1897
1972
 
1898
- /**
1899
- * This error occurs when some expectation is not met in the execution of the pipeline
1900
- *
1901
- * @private Always catched and rethrown as `PromptbookExecutionError`
1902
- * Note: This is a kindof subtype of PromptbookExecutionError
1903
- */
1904
- var ExpectError = /** @class */ (function (_super) {
1905
- __extends(ExpectError, _super);
1906
- function ExpectError(message) {
1907
- var _this = _super.call(this, message) || this;
1908
- _this.name = 'ExpectError';
1909
- Object.setPrototypeOf(_this, ExpectError.prototype);
1910
- return _this;
1911
- }
1912
- return ExpectError;
1913
- }(Error));
1914
-
1915
1973
  /**
1916
1974
  * Creates executor function from promptbook and execution tools.
1917
1975
  *
@@ -1926,10 +1984,11 @@
1926
1984
  var promptbookExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1927
1985
  function executeSingleTemplate(currentTemplate) {
1928
1986
  return __awaiter(this, void 0, void 0, function () {
1929
- var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, _j, _k, _l, unit, _m, max, min, amount, error_4;
1930
- var e_2, _o, e_4, _p, e_3, _q, e_5, _r, _s;
1931
- return __generator(this, function (_t) {
1932
- switch (_t.label) {
1987
+ var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, error_4;
1988
+ var e_2, _j, e_4, _k, e_3, _l, _m;
1989
+ var _this = this;
1990
+ return __generator(this, function (_o) {
1991
+ switch (_o.label) {
1933
1992
  case 0:
1934
1993
  name = "promptbook-executor-frame-".concat(currentTemplate.name);
1935
1994
  title = currentTemplate.title;
@@ -1946,8 +2005,8 @@
1946
2005
  // <- [3]
1947
2006
  })];
1948
2007
  case 1:
1949
- _t.sent();
1950
- _t.label = 2;
2008
+ _o.sent();
2009
+ _o.label = 2;
1951
2010
  case 2:
1952
2011
  result = null;
1953
2012
  resultString = null;
@@ -1955,7 +2014,7 @@
1955
2014
  maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1956
2015
  jokers = currentTemplate.jokers || [];
1957
2016
  attempt = -jokers.length;
1958
- _t.label = 3;
2017
+ _o.label = 3;
1959
2018
  case 3:
1960
2019
  if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1961
2020
  isJokerAttempt = attempt < 0;
@@ -1972,9 +2031,9 @@
1972
2031
  }
1973
2032
  resultString = parametersToPass[joker];
1974
2033
  }
1975
- _t.label = 4;
2034
+ _o.label = 4;
1976
2035
  case 4:
1977
- _t.trys.push([4, 45, 46, 47]);
2036
+ _o.trys.push([4, 45, 46, 47]);
1978
2037
  if (!!isJokerAttempt) return [3 /*break*/, 27];
1979
2038
  _a = currentTemplate.executionType;
1980
2039
  switch (_a) {
@@ -1997,6 +2056,67 @@
1997
2056
  content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1998
2057
  modelRequirements: currentTemplate.modelRequirements,
1999
2058
  expectations: currentTemplate.expectations,
2059
+ postprocessing: (currentTemplate.postprocessing || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
2060
+ var errors, _a, _b, scriptTools, error_5, e_5_1;
2061
+ var e_5, _c;
2062
+ return __generator(this, function (_d) {
2063
+ switch (_d.label) {
2064
+ case 0:
2065
+ errors = [];
2066
+ _d.label = 1;
2067
+ case 1:
2068
+ _d.trys.push([1, 8, 9, 10]);
2069
+ _a = __values(tools.script), _b = _a.next();
2070
+ _d.label = 2;
2071
+ case 2:
2072
+ if (!!_b.done) return [3 /*break*/, 7];
2073
+ scriptTools = _b.value;
2074
+ _d.label = 3;
2075
+ case 3:
2076
+ _d.trys.push([3, 5, , 6]);
2077
+ return [4 /*yield*/, scriptTools.execute({
2078
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
2079
+ script: "".concat(functionName, "(result)"),
2080
+ parameters: {
2081
+ result: result || '',
2082
+ // Note: No ...parametersToPass, because working with result only
2083
+ },
2084
+ })];
2085
+ case 4: return [2 /*return*/, _d.sent()];
2086
+ case 5:
2087
+ error_5 = _d.sent();
2088
+ if (!(error_5 instanceof Error)) {
2089
+ throw error_5;
2090
+ }
2091
+ errors.push(error_5);
2092
+ return [3 /*break*/, 6];
2093
+ case 6:
2094
+ _b = _a.next();
2095
+ return [3 /*break*/, 2];
2096
+ case 7: return [3 /*break*/, 10];
2097
+ case 8:
2098
+ e_5_1 = _d.sent();
2099
+ e_5 = { error: e_5_1 };
2100
+ return [3 /*break*/, 10];
2101
+ case 9:
2102
+ try {
2103
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
2104
+ }
2105
+ finally { if (e_5) throw e_5.error; }
2106
+ return [7 /*endfinally*/];
2107
+ case 10:
2108
+ if (errors.length === 0) {
2109
+ throw new PromptbookExecutionError('Postprocessing in NaturalExecutionTools failed because no ScriptExecutionTools were provided');
2110
+ }
2111
+ else if (errors.length === 1) {
2112
+ throw errors[0];
2113
+ }
2114
+ else {
2115
+ throw new PromptbookExecutionError(spacetrim.spaceTrim(function (block) { return "\n Postprocessing in NaturalExecutionTools failed ".concat(errors.length, "x\n\n ").concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n\n')), "\n "); }));
2116
+ }
2117
+ }
2118
+ });
2119
+ }); }; }),
2000
2120
  };
2001
2121
  _b = currentTemplate.modelRequirements.modelVariant;
2002
2122
  switch (_b) {
@@ -2006,14 +2126,14 @@
2006
2126
  return [3 /*break*/, 11];
2007
2127
  case 7: return [4 /*yield*/, tools.natural.gptChat(prompt)];
2008
2128
  case 8:
2009
- chatThread = _t.sent();
2129
+ chatThread = _o.sent();
2010
2130
  // TODO: [๐Ÿฌ] Destroy chatThread
2011
2131
  result = chatThread;
2012
2132
  resultString = chatThread.content;
2013
2133
  return [3 /*break*/, 12];
2014
2134
  case 9: return [4 /*yield*/, tools.natural.gptComplete(prompt)];
2015
2135
  case 10:
2016
- completionResult = _t.sent();
2136
+ completionResult = _o.sent();
2017
2137
  result = completionResult;
2018
2138
  resultString = completionResult.content;
2019
2139
  return [3 /*break*/, 12];
@@ -2028,27 +2148,27 @@
2028
2148
  }
2029
2149
  // TODO: DRY [1]
2030
2150
  scriptExecutionErrors = [];
2031
- _t.label = 14;
2151
+ _o.label = 14;
2032
2152
  case 14:
2033
- _t.trys.push([14, 21, 22, 23]);
2153
+ _o.trys.push([14, 21, 22, 23]);
2034
2154
  _c = (e_2 = void 0, __values(tools.script)), _d = _c.next();
2035
- _t.label = 15;
2155
+ _o.label = 15;
2036
2156
  case 15:
2037
2157
  if (!!_d.done) return [3 /*break*/, 20];
2038
2158
  scriptTools = _d.value;
2039
- _t.label = 16;
2159
+ _o.label = 16;
2040
2160
  case 16:
2041
- _t.trys.push([16, 18, , 19]);
2161
+ _o.trys.push([16, 18, , 19]);
2042
2162
  return [4 /*yield*/, scriptTools.execute({
2043
2163
  scriptLanguage: currentTemplate.contentLanguage,
2044
2164
  script: currentTemplate.content,
2045
2165
  parameters: parametersToPass,
2046
2166
  })];
2047
2167
  case 17:
2048
- resultString = _t.sent();
2168
+ resultString = _o.sent();
2049
2169
  return [3 /*break*/, 20];
2050
2170
  case 18:
2051
- error_2 = _t.sent();
2171
+ error_2 = _o.sent();
2052
2172
  if (!(error_2 instanceof Error)) {
2053
2173
  throw error_2;
2054
2174
  }
@@ -2059,24 +2179,24 @@
2059
2179
  return [3 /*break*/, 15];
2060
2180
  case 20: return [3 /*break*/, 23];
2061
2181
  case 21:
2062
- e_2_1 = _t.sent();
2182
+ e_2_1 = _o.sent();
2063
2183
  e_2 = { error: e_2_1 };
2064
2184
  return [3 /*break*/, 23];
2065
2185
  case 22:
2066
2186
  try {
2067
- if (_d && !_d.done && (_o = _c.return)) _o.call(_c);
2187
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
2068
2188
  }
2069
2189
  finally { if (e_2) throw e_2.error; }
2070
2190
  return [7 /*endfinally*/];
2071
2191
  case 23:
2072
- if (resultString) {
2192
+ if (resultString !== null) {
2073
2193
  return [3 /*break*/, 27];
2074
2194
  }
2075
2195
  if (scriptExecutionErrors.length === 1) {
2076
2196
  throw scriptExecutionErrors[0];
2077
2197
  }
2078
2198
  else {
2079
- throw new PromptbookExecutionError(spaceTrim__default["default"](function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
2199
+ throw new PromptbookExecutionError(spacetrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
2080
2200
  .map(function (error) { return '- ' + error.message; })
2081
2201
  .join('\n\n')), "\n "); }));
2082
2202
  }
@@ -2090,46 +2210,49 @@
2090
2210
  })];
2091
2211
  case 25:
2092
2212
  // TODO: [๐ŸŒน] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
2093
- resultString = _t.sent();
2213
+ resultString = _o.sent();
2094
2214
  return [3 /*break*/, 27];
2095
2215
  case 26: throw new PromptbookExecutionError(
2096
2216
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
2097
2217
  "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
2098
2218
  case 27:
2099
2219
  if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
2100
- _t.label = 28;
2220
+ _o.label = 28;
2101
2221
  case 28:
2102
- _t.trys.push([28, 42, 43, 44]);
2222
+ _o.trys.push([28, 42, 43, 44]);
2103
2223
  _e = (e_4 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
2104
- _t.label = 29;
2224
+ _o.label = 29;
2105
2225
  case 29:
2106
2226
  if (!!_f.done) return [3 /*break*/, 41];
2107
2227
  functionName = _f.value;
2108
2228
  // TODO: DRY [1]
2109
2229
  scriptExecutionErrors = [];
2110
2230
  postprocessingError = null;
2111
- _t.label = 30;
2231
+ _o.label = 30;
2112
2232
  case 30:
2113
- _t.trys.push([30, 37, 38, 39]);
2233
+ _o.trys.push([30, 37, 38, 39]);
2114
2234
  _g = (e_3 = void 0, __values(tools.script)), _h = _g.next();
2115
- _t.label = 31;
2235
+ _o.label = 31;
2116
2236
  case 31:
2117
2237
  if (!!_h.done) return [3 /*break*/, 36];
2118
2238
  scriptTools = _h.value;
2119
- _t.label = 32;
2239
+ _o.label = 32;
2120
2240
  case 32:
2121
- _t.trys.push([32, 34, , 35]);
2241
+ _o.trys.push([32, 34, , 35]);
2122
2242
  return [4 /*yield*/, scriptTools.execute({
2123
2243
  scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
2124
2244
  script: "".concat(functionName, "(resultString)"),
2125
- parameters: __assign(__assign({}, parametersToPass), { resultString: resultString || '' }),
2245
+ parameters: {
2246
+ resultString: resultString || '',
2247
+ // Note: No ...parametersToPass, because working with result only
2248
+ },
2126
2249
  })];
2127
2250
  case 33:
2128
- resultString = _t.sent();
2251
+ resultString = _o.sent();
2129
2252
  postprocessingError = null;
2130
2253
  return [3 /*break*/, 36];
2131
2254
  case 34:
2132
- error_3 = _t.sent();
2255
+ error_3 = _o.sent();
2133
2256
  if (!(error_3 instanceof Error)) {
2134
2257
  throw error_3;
2135
2258
  }
@@ -2141,12 +2264,12 @@
2141
2264
  return [3 /*break*/, 31];
2142
2265
  case 36: return [3 /*break*/, 39];
2143
2266
  case 37:
2144
- e_3_1 = _t.sent();
2267
+ e_3_1 = _o.sent();
2145
2268
  e_3 = { error: e_3_1 };
2146
2269
  return [3 /*break*/, 39];
2147
2270
  case 38:
2148
2271
  try {
2149
- if (_h && !_h.done && (_q = _g.return)) _q.call(_g);
2272
+ if (_h && !_h.done && (_l = _g.return)) _l.call(_g);
2150
2273
  }
2151
2274
  finally { if (e_3) throw e_3.error; }
2152
2275
  return [7 /*endfinally*/];
@@ -2154,22 +2277,23 @@
2154
2277
  if (postprocessingError) {
2155
2278
  throw postprocessingError;
2156
2279
  }
2157
- _t.label = 40;
2280
+ _o.label = 40;
2158
2281
  case 40:
2159
2282
  _f = _e.next();
2160
2283
  return [3 /*break*/, 29];
2161
2284
  case 41: return [3 /*break*/, 44];
2162
2285
  case 42:
2163
- e_4_1 = _t.sent();
2286
+ e_4_1 = _o.sent();
2164
2287
  e_4 = { error: e_4_1 };
2165
2288
  return [3 /*break*/, 44];
2166
2289
  case 43:
2167
2290
  try {
2168
- if (_f && !_f.done && (_p = _e.return)) _p.call(_e);
2291
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
2169
2292
  }
2170
2293
  finally { if (e_4) throw e_4.error; }
2171
2294
  return [7 /*endfinally*/];
2172
2295
  case 44:
2296
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
2173
2297
  if (currentTemplate.expectFormat) {
2174
2298
  if (currentTemplate.expectFormat === 'JSON') {
2175
2299
  if (!isValidJsonString(resultString || '')) {
@@ -2177,30 +2301,13 @@
2177
2301
  }
2178
2302
  }
2179
2303
  }
2304
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
2180
2305
  if (currentTemplate.expectations) {
2181
- try {
2182
- for (_j = (e_5 = void 0, __values(Object.entries(currentTemplate.expectations))), _k = _j.next(); !_k.done; _k = _j.next()) {
2183
- _l = __read(_k.value, 2), unit = _l[0], _m = _l[1], max = _m.max, min = _m.min;
2184
- amount = CountUtils[unit.toUpperCase()](resultString || '');
2185
- if (min && amount < min) {
2186
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2187
- } /* not else */
2188
- if (max && amount > max) {
2189
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2190
- }
2191
- }
2192
- }
2193
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
2194
- finally {
2195
- try {
2196
- if (_k && !_k.done && (_r = _j.return)) _r.call(_j);
2197
- }
2198
- finally { if (e_5) throw e_5.error; }
2199
- }
2306
+ checkExpectations(currentTemplate.expectations, resultString || '');
2200
2307
  }
2201
2308
  return [3 /*break*/, 49];
2202
2309
  case 45:
2203
- error_4 = _t.sent();
2310
+ error_4 = _o.sent();
2204
2311
  if (!(error_4 instanceof ExpectError)) {
2205
2312
  throw error_4;
2206
2313
  }
@@ -2229,9 +2336,9 @@
2229
2336
  return [7 /*endfinally*/];
2230
2337
  case 47:
2231
2338
  if (expectError !== null && attempt === maxAttempts - 1) {
2232
- throw new PromptbookExecutionError(spaceTrim__default["default"](function (block) { return "\n Natural execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n "); }));
2339
+ throw new PromptbookExecutionError(spacetrim.spaceTrim(function (block) { return "\n Natural execution failed ".concat(maxExecutionAttempts, "x\n\n ---\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n\n Last result:\n ").concat(resultString, "\n ---\n "); }));
2233
2340
  }
2234
- _t.label = 48;
2341
+ _o.label = 48;
2235
2342
  case 48:
2236
2343
  attempt++;
2237
2344
  return [3 /*break*/, 3];
@@ -2251,7 +2358,7 @@
2251
2358
  // <- [3]
2252
2359
  });
2253
2360
  }
2254
- parametersToPass = __assign(__assign({}, parametersToPass), (_s = {}, _s[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because Promptbook checks logic consistency during construction */, _s));
2361
+ parametersToPass = __assign(__assign({}, parametersToPass), (_m = {}, _m[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because Promptbook checks logic consistency during construction */, _m));
2255
2362
  return [2 /*return*/];
2256
2363
  }
2257
2364
  });
@@ -2298,7 +2405,7 @@
2298
2405
  return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
2299
2406
  });
2300
2407
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
2301
- throw new UnexpectedError(spaceTrim__default["default"]("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbookJson\n "));
2408
+ throw new UnexpectedError(spacetrim.spaceTrim("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbookJson\n "));
2302
2409
  case 1:
2303
2410
  if (!!currentTemplate) return [3 /*break*/, 3];
2304
2411
  /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
@@ -2404,7 +2511,7 @@
2404
2511
  console.info('๐Ÿ’ฌ Mocked gptChat call');
2405
2512
  }
2406
2513
  return [2 /*return*/, {
2407
- content: spaceTrim__default["default"](function (block) { return "\n You said:\n ".concat(block(prompt.content), "\n "); }),
2514
+ content: spacetrim.spaceTrim(function (block) { return "\n You said:\n ".concat(block(prompt.content), "\n "); }),
2408
2515
  model: 'mocked-echo',
2409
2516
  timing: {
2410
2517
  start: getCurrentIsoDate(),
@@ -2433,7 +2540,7 @@
2433
2540
  console.info('๐Ÿ–‹ Mocked gptComplete call');
2434
2541
  }
2435
2542
  return [2 /*return*/, {
2436
- content: spaceTrim__default["default"](function (block) { return "\n ".concat(block(prompt.content), "\n And so on...\n "); }),
2543
+ content: spacetrim.spaceTrim(function (block) { return "\n ".concat(block(prompt.content), "\n And so on...\n "); }),
2437
2544
  model: 'mocked-echo',
2438
2545
  timing: {
2439
2546
  start: getCurrentIsoDate(),
@@ -2461,22 +2568,75 @@
2461
2568
  /**
2462
2569
  * Gets the expectations and creates a fake text that meets the expectations
2463
2570
  *
2571
+ * Note: You can provide postprocessing functions to modify the text before checking the expectations
2572
+ * The result will be the text BEFORE the postprocessing
2573
+ *
2464
2574
  * @private internal util for MockedFackedNaturalExecutionTools
2465
2575
  */
2466
- function $fakeTextToExpectations(expectations) {
2467
- var lorem = new loremIpsum.LoremIpsum({
2468
- sentencesPerParagraph: {
2469
- max: 8,
2470
- min: 4,
2471
- },
2472
- wordsPerSentence: {
2473
- max: 16,
2474
- min: 4,
2475
- },
2576
+ function $fakeTextToExpectations(expectations, postprocessing) {
2577
+ return __awaiter(this, void 0, void 0, function () {
2578
+ var lorem, loremText, text, loopLimit, textToCheck, _a, _b, func, e_1_1;
2579
+ var e_1, _c;
2580
+ return __generator(this, function (_d) {
2581
+ switch (_d.label) {
2582
+ case 0:
2583
+ lorem = new loremIpsum.LoremIpsum({
2584
+ wordsPerSentence: { min: 5, max: 15 },
2585
+ sentencesPerParagraph: { min: 5, max: 15 },
2586
+ });
2587
+ loremText = '';
2588
+ text = '';
2589
+ loopLimit = CHARACTER_LOOP_LIMIT;
2590
+ _d.label = 1;
2591
+ case 1:
2592
+ if (!(loopLimit-- > 0)) return [3 /*break*/, 11];
2593
+ textToCheck = text;
2594
+ _d.label = 2;
2595
+ case 2:
2596
+ _d.trys.push([2, 7, 8, 9]);
2597
+ _a = (e_1 = void 0, __values(postprocessing || [])), _b = _a.next();
2598
+ _d.label = 3;
2599
+ case 3:
2600
+ if (!!_b.done) return [3 /*break*/, 6];
2601
+ func = _b.value;
2602
+ return [4 /*yield*/, func(textToCheck)];
2603
+ case 4:
2604
+ textToCheck = _d.sent();
2605
+ _d.label = 5;
2606
+ case 5:
2607
+ _b = _a.next();
2608
+ return [3 /*break*/, 3];
2609
+ case 6: return [3 /*break*/, 9];
2610
+ case 7:
2611
+ e_1_1 = _d.sent();
2612
+ e_1 = { error: e_1_1 };
2613
+ return [3 /*break*/, 9];
2614
+ case 8:
2615
+ try {
2616
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
2617
+ }
2618
+ finally { if (e_1) throw e_1.error; }
2619
+ return [7 /*endfinally*/];
2620
+ case 9:
2621
+ if (isPassingExpectations(expectations, textToCheck)) {
2622
+ return [2 /*return*/, text]; // <- Note: Returning the text because the postprocessing
2623
+ }
2624
+ if (loremText === '') {
2625
+ loremText = lorem.generateParagraphs(1) + '\n\n';
2626
+ }
2627
+ text += loremText.substring(0, 1);
2628
+ loremText = loremText.substring(1);
2629
+ _d.label = 10;
2630
+ case 10: return [3 /*break*/, 1];
2631
+ case 11: throw new Error(spacetrim.spaceTrim(function (block) { return "\n Can not generate fake text to met the expectations\n\n Loop limit reached\n The expectations:\n ".concat(block(JSON.stringify(expectations, null, 4)), "\n\n The draft text:\n ").concat(block(text), "\n\n "); }));
2632
+ }
2633
+ });
2476
2634
  });
2477
- // TODO: !!! Really use the expectations to generate the text
2478
- return lorem.generateSentences(5);
2479
2635
  }
2636
+ /**
2637
+ * TODO: Implement better - create FakeLLM from this
2638
+ * TODO: [๐Ÿ’] Unite object for expecting amount and format - use here also a format
2639
+ */
2480
2640
 
2481
2641
  /**
2482
2642
  * Mocked execution Tools for just faking expected responses for testing purposes
@@ -2490,29 +2650,40 @@
2490
2650
  */
2491
2651
  MockedFackedNaturalExecutionTools.prototype.gptChat = function (prompt) {
2492
2652
  return __awaiter(this, void 0, void 0, function () {
2653
+ var content, result;
2493
2654
  return __generator(this, function (_a) {
2494
- if (this.options.isVerbose) {
2495
- console.info('๐Ÿ’ฌ Mocked faked call');
2655
+ switch (_a.label) {
2656
+ case 0:
2657
+ if (this.options.isVerbose) {
2658
+ console.info('๐Ÿ’ฌ Mocked faked prompt', prompt);
2659
+ }
2660
+ return [4 /*yield*/, $fakeTextToExpectations(prompt.expectations || {
2661
+ sentences: { min: 1, max: 1 },
2662
+ }, prompt.postprocessing)];
2663
+ case 1:
2664
+ content = _a.sent();
2665
+ result = {
2666
+ content: content,
2667
+ model: 'mocked-facked',
2668
+ timing: {
2669
+ start: getCurrentIsoDate(),
2670
+ complete: getCurrentIsoDate(),
2671
+ },
2672
+ usage: {
2673
+ price: 0,
2674
+ inputTokens: 0,
2675
+ outputTokens: 0,
2676
+ },
2677
+ rawResponse: {
2678
+ note: 'This is mocked echo',
2679
+ },
2680
+ // <- [๐Ÿคนโ€โ™‚๏ธ]
2681
+ };
2682
+ if (this.options.isVerbose) {
2683
+ console.info('๐Ÿ’ฌ Mocked faked result', result);
2684
+ }
2685
+ return [2 /*return*/, result];
2496
2686
  }
2497
- return [2 /*return*/, {
2498
- content: $fakeTextToExpectations(prompt.expectations || {
2499
- sentences: { min: 1, max: 1 },
2500
- }),
2501
- model: 'mocked-facked',
2502
- timing: {
2503
- start: getCurrentIsoDate(),
2504
- complete: getCurrentIsoDate(),
2505
- },
2506
- usage: {
2507
- price: 0,
2508
- inputTokens: 0,
2509
- outputTokens: 0,
2510
- },
2511
- rawResponse: {
2512
- note: 'This is mocked echo',
2513
- },
2514
- // <- [๐Ÿคนโ€โ™‚๏ธ]
2515
- }];
2516
2687
  });
2517
2688
  });
2518
2689
  };
@@ -2549,7 +2720,7 @@
2549
2720
  case 1:
2550
2721
  answer = _a.sent();
2551
2722
  if (this.options.isVerbose) {
2552
- console.info(spaceTrim__default["default"](function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
2723
+ console.info(spacetrim.spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
2553
2724
  }
2554
2725
  return [2 /*return*/, answer];
2555
2726
  }
@@ -2576,9 +2747,9 @@
2576
2747
  return __awaiter(this, void 0, void 0, function () {
2577
2748
  var answer;
2578
2749
  return __generator(this, function (_a) {
2579
- answer = window.prompt(spaceTrim__default["default"](function (block) { return "\n ".concat(block(options.promptTitle), "\n\n ").concat(block(options.promptMessage), "\n "); }));
2750
+ answer = window.prompt(spacetrim.spaceTrim(function (block) { return "\n ".concat(block(options.promptTitle), "\n\n ").concat(block(options.promptMessage), "\n "); }));
2580
2751
  if (this.options.isVerbose) {
2581
- console.info(spaceTrim__default["default"](function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer || '๐Ÿšซ User cancelled prompt'), "\n "); }));
2752
+ console.info(spacetrim.spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer || '๐Ÿšซ User cancelled prompt'), "\n "); }));
2582
2753
  }
2583
2754
  if (answer === null) {
2584
2755
  throw new PromptbookExecutionError('User cancelled prompt');
@@ -2643,7 +2814,7 @@
2643
2814
  for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
2644
2815
  var promptbook = promptbooks_1_1.value;
2645
2816
  if (promptbook.promptbookUrl === undefined) {
2646
- throw new PromptbookReferenceError(spaceTrim__default["default"]("\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 ")));
2817
+ 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 ")));
2647
2818
  }
2648
2819
  validatePromptbookJson(promptbook);
2649
2820
  this.library.set(promptbook.promptbookUrl, promptbook);
@@ -2672,7 +2843,7 @@
2672
2843
  var _this = this;
2673
2844
  var promptbook = this.library.get(url);
2674
2845
  if (!promptbook) {
2675
- throw new PromptbookNotFoundError(spaceTrim__default["default"](function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
2846
+ 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()
2676
2847
  .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
2677
2848
  .join('\n')), "\n\n "); }));
2678
2849
  }
@@ -2823,7 +2994,7 @@
2823
2994
  case 0:
2824
2995
  if (!!predicate(url)) return [3 /*break*/, 2];
2825
2996
  _a = PromptbookNotFoundError.bind;
2826
- return [4 /*yield*/, spaceTrim__default["default"](function (block) { return __awaiter(_this, void 0, void 0, function () {
2997
+ return [4 /*yield*/, spacetrim.spaceTrim(function (block) { return __awaiter(_this, void 0, void 0, function () {
2827
2998
  var _a, _b, _c, _d, _e, _f;
2828
2999
  return __generator(this, function (_g) {
2829
3000
  switch (_g.label) {