@promptbook/core 0.29.0 → 0.30.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/esm/index.es.js +506 -505
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/_packages/core.index.d.ts +1 -2
  4. package/esm/typings/classes/PromptTemplatePipelineLibrary.d.ts +2 -3
  5. package/esm/typings/conversion/validatePromptTemplatePipelineJson.d.ts +1 -1
  6. package/esm/typings/execution/createPtpExecutor.d.ts +2 -2
  7. package/esm/typings/types/PromptTemplatePipelineJson/PromptTemplateJson.d.ts +7 -1
  8. package/esm/typings/types/PromptTemplatePipelineJson/PromptTemplatePipelineJson.d.ts +0 -1
  9. package/esm/typings/types/PromptTemplatePipelineString.d.ts +0 -1
  10. package/esm/typings/utils/extractParameters.d.ts +8 -0
  11. package/esm/typings/utils/extractParameters.test.d.ts +1 -0
  12. package/package.json +1 -1
  13. package/umd/index.umd.js +505 -505
  14. package/umd/index.umd.js.map +1 -1
  15. package/umd/typings/_packages/core.index.d.ts +1 -2
  16. package/umd/typings/classes/PromptTemplatePipelineLibrary.d.ts +2 -3
  17. package/umd/typings/conversion/validatePromptTemplatePipelineJson.d.ts +1 -1
  18. package/umd/typings/execution/createPtpExecutor.d.ts +2 -2
  19. package/umd/typings/types/PromptTemplatePipelineJson/PromptTemplateJson.d.ts +7 -1
  20. package/umd/typings/types/PromptTemplatePipelineJson/PromptTemplatePipelineJson.d.ts +0 -1
  21. package/umd/typings/types/PromptTemplatePipelineString.d.ts +0 -1
  22. package/umd/typings/utils/extractParameters.d.ts +8 -0
  23. package/umd/typings/utils/extractParameters.test.d.ts +1 -0
  24. package/esm/typings/classes/PromptTemplatePipeline.d.ts +0 -71
  25. package/umd/typings/classes/PromptTemplatePipeline.d.ts +0 -71
package/esm/index.es.js CHANGED
@@ -108,6 +108,16 @@ function __read(o, n) {
108
108
  finally { if (e) throw e.error; }
109
109
  }
110
110
  return ar;
111
+ }
112
+
113
+ function __spreadArray(to, from, pack) {
114
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
115
+ if (ar || !(i in from)) {
116
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
117
+ ar[i] = from[i];
118
+ }
119
+ }
120
+ return to.concat(ar || Array.prototype.slice.call(from));
111
121
  }
112
122
 
113
123
  /**
@@ -134,6 +144,35 @@ var DEFAULT_MODEL_REQUIREMENTS = {
134
144
  */
135
145
  var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
136
146
 
147
+ /**
148
+ * Parses the template and returns the list of all parameter names
149
+ *
150
+ * @param template the template with parameters in {curly} braces
151
+ * @returns the list of parameter names
152
+ */
153
+ function extractParameters(template) {
154
+ var e_1, _a;
155
+ var matches = template.matchAll(/{\w+}/g);
156
+ var parameterNames = [];
157
+ try {
158
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
159
+ var match = matches_1_1.value;
160
+ var parameterName = match[0].slice(1, -1);
161
+ if (!parameterNames.includes(parameterName)) {
162
+ parameterNames.push(parameterName);
163
+ }
164
+ }
165
+ }
166
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
167
+ finally {
168
+ try {
169
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
170
+ }
171
+ finally { if (e_1) throw e_1.error; }
172
+ }
173
+ return parameterNames;
174
+ }
175
+
137
176
  /**
138
177
  * Computes the deepness of the markdown structure.
139
178
  *
@@ -768,10 +807,11 @@ function promptTemplatePipelineStringToJson(promptTemplatePipelineString) {
768
807
  finally { if (e_1) throw e_1.error; }
769
808
  }
770
809
  var _loop_1 = function (section) {
771
- var e_3, _e;
810
+ var e_3, _e, e_4, _f;
772
811
  // TODO: Parse prompt template description (the content out of the codeblock and lists)
773
812
  var templateModelRequirements = __assign({}, defaultModelRequirements);
774
813
  var listItems_3 = extractAllListItemsFromMarkdown(section.content);
814
+ var dependentParameterNames = [];
775
815
  var executionType = 'PROMPT_TEMPLATE';
776
816
  var jokers = [];
777
817
  var postprocessing = [];
@@ -785,6 +825,7 @@ function promptTemplatePipelineStringToJson(promptTemplatePipelineString) {
785
825
  switch (command.type) {
786
826
  case 'JOKER':
787
827
  jokers.push(command.parameterName);
828
+ dependentParameterNames.push(command.parameterName);
788
829
  break;
789
830
  case 'EXECUTE':
790
831
  if (isExecutionTypeChanged) {
@@ -798,6 +839,7 @@ function promptTemplatePipelineStringToJson(promptTemplatePipelineString) {
798
839
  templateModelRequirements[command.key] = command.value;
799
840
  break;
800
841
  case 'PARAMETER':
842
+ // Note: This is just for detecting resulitng parameter name
801
843
  addParam(command);
802
844
  break;
803
845
  case 'POSTPROCESS':
@@ -838,7 +880,7 @@ function promptTemplatePipelineStringToJson(promptTemplatePipelineString) {
838
880
  }
839
881
  finally { if (e_3) throw e_3.error; }
840
882
  }
841
- var _f = extractOneBlockFromMarkdown(section.content), language = _f.language, content = _f.content;
883
+ var _g = extractOneBlockFromMarkdown(section.content), language = _g.language, content = _g.content;
842
884
  if (executionType === 'SCRIPT') {
843
885
  if (!language) {
844
886
  throw new Error('You must specify the language of the script in the prompt template');
@@ -877,10 +919,24 @@ function promptTemplatePipelineStringToJson(promptTemplatePipelineString) {
877
919
  if (Object.keys(postprocessing).length === 0) {
878
920
  postprocessing = undefined;
879
921
  }
922
+ try {
923
+ for (var _h = (e_4 = void 0, __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(section.title)), false), __read(extractParameters(description_1 || '')), false), __read(extractParameters(content)), false))), _j = _h.next(); !_j.done; _j = _h.next()) {
924
+ var parameterName = _j.value;
925
+ dependentParameterNames.push(parameterName);
926
+ }
927
+ }
928
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
929
+ finally {
930
+ try {
931
+ if (_j && !_j.done && (_f = _h.return)) _f.call(_h);
932
+ }
933
+ finally { if (e_4) throw e_4.error; }
934
+ }
880
935
  ptbJson.promptTemplates.push({
881
936
  name: normalizeTo_PascalCase(section.title),
882
937
  title: section.title,
883
938
  description: description_1,
939
+ dependentParameterNames: dependentParameterNames,
884
940
  executionType: executionType,
885
941
  jokers: jokers,
886
942
  postprocessing: postprocessing,
@@ -928,7 +984,7 @@ function promptTemplatePipelineStringToJson(promptTemplatePipelineString) {
928
984
  * @throws {Error} if invalid
929
985
  */
930
986
  function validatePromptTemplatePipelineJson(ptp) {
931
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
987
+ var e_1, _a, e_2, _b, e_3, _c;
932
988
  var definedParameters = new Set(ptp.parameters.filter(function (_a) {
933
989
  var isInput = _a.isInput;
934
990
  return isInput;
@@ -937,52 +993,37 @@ function validatePromptTemplatePipelineJson(ptp) {
937
993
  return name;
938
994
  }));
939
995
  try {
940
- for (var _e = __values(ptp.promptTemplates), _f = _e.next(); !_f.done; _f = _e.next()) {
941
- var template = _f.value;
942
- try {
943
- for (var _g = (e_2 = void 0, __values(Array.from(template.content.matchAll(/\{(?<parameterName>[a-z0-9_]+)\}/gi)))), _h = _g.next(); !_h.done; _h = _g.next()) {
944
- var match = _h.value;
945
- var parameterName = match.groups.parameterName;
946
- if (!definedParameters.has(parameterName)) {
947
- throw new Error("Parameter {".concat(parameterName, "} used before defined"));
948
- }
949
- }
950
- }
951
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
952
- finally {
953
- try {
954
- if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
955
- }
956
- finally { if (e_2) throw e_2.error; }
957
- }
996
+ // Note: Check each template individually
997
+ for (var _d = __values(ptp.promptTemplates), _e = _d.next(); !_e.done; _e = _d.next()) {
998
+ var template = _e.value;
958
999
  if (definedParameters.has(template.resultingParameterName)) {
959
1000
  throw new Error("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
960
1001
  }
961
1002
  if (template.jokers && template.jokers.length > 0) {
1003
+ if (!template.expectFormat &&
1004
+ !template.expectAmount /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1005
+ throw new Error("Joker parameters are used but no expectations are defined");
1006
+ }
962
1007
  try {
963
- for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
964
- var joker = _k.value;
965
- if (!definedParameters.has(joker)) {
966
- throw new Error("Joker parameter {".concat(joker, "} used before defined"));
1008
+ for (var _f = (e_2 = void 0, __values(template.jokers)), _g = _f.next(); !_g.done; _g = _f.next()) {
1009
+ var joker = _g.value;
1010
+ if (!template.dependentParameterNames.includes(joker)) {
1011
+ throw new Error("Parameter {".concat(joker, "} is used as joker but not in dependentParameterNames"));
967
1012
  }
968
1013
  }
969
1014
  }
970
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
1015
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
971
1016
  finally {
972
1017
  try {
973
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
1018
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
974
1019
  }
975
- finally { if (e_3) throw e_3.error; }
976
- }
977
- if (!template.expectFormat &&
978
- !template.expectAmount /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
979
- throw new Error("Joker parameters are used but no expectations are defined");
1020
+ finally { if (e_2) throw e_2.error; }
980
1021
  }
981
1022
  }
982
1023
  if (template.expectAmount) {
983
1024
  try {
984
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectAmount))), _m = _l.next(); !_m.done; _m = _l.next()) {
985
- var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1025
+ for (var _h = (e_3 = void 0, __values(Object.entries(template.expectAmount))), _j = _h.next(); !_j.done; _j = _h.next()) {
1026
+ var _k = __read(_j.value, 2), unit = _k[0], _l = _k[1], min = _l.min, max = _l.max;
986
1027
  if (min !== undefined && max !== undefined && min > max) {
987
1028
  throw new Error("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
988
1029
  }
@@ -994,12 +1035,12 @@ function validatePromptTemplatePipelineJson(ptp) {
994
1035
  }
995
1036
  }
996
1037
  }
997
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
1038
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
998
1039
  finally {
999
1040
  try {
1000
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
1041
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
1001
1042
  }
1002
- finally { if (e_4) throw e_4.error; }
1043
+ finally { if (e_3) throw e_3.error; }
1003
1044
  }
1004
1045
  }
1005
1046
  definedParameters.add(template.resultingParameterName);
@@ -1008,10 +1049,42 @@ function validatePromptTemplatePipelineJson(ptp) {
1008
1049
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1009
1050
  finally {
1010
1051
  try {
1011
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
1052
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
1012
1053
  }
1013
1054
  finally { if (e_1) throw e_1.error; }
1014
1055
  }
1056
+ // Note: Detect circular dependencies
1057
+ var resovedParameters = ptp.parameters.filter(function (_a) {
1058
+ var isInput = _a.isInput;
1059
+ return isInput;
1060
+ }).map(function (_a) {
1061
+ var name = _a.name;
1062
+ return name;
1063
+ });
1064
+ var unresovedTemplates = __spreadArray([], __read(ptp.promptTemplates), false);
1065
+ var _loop_1 = function () {
1066
+ var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
1067
+ return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
1068
+ });
1069
+ if (currentlyResovedTemplates.length === 0) {
1070
+ throw new Error(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
1071
+ .map(function (_a) {
1072
+ var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
1073
+ return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
1074
+ .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
1075
+ .join(', '));
1076
+ })
1077
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
1078
+ }
1079
+ resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
1080
+ var resultingParameterName = _a.resultingParameterName;
1081
+ return resultingParameterName;
1082
+ })), false);
1083
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
1084
+ };
1085
+ while (unresovedTemplates.length > 0) {
1086
+ _loop_1();
1087
+ }
1015
1088
  }
1016
1089
  /**
1017
1090
  * TODO: [🧠] Work with ptbkVersion
@@ -1025,124 +1098,6 @@ function validatePromptTemplatePipelineJson(ptp) {
1025
1098
  * > ex port function validatePromptTemplatePipelineJson(ptp: unknown): asserts ptp is PromptTemplatePipelineJson {
1026
1099
  */
1027
1100
 
1028
- /**
1029
- * Prompt template pipeline is the **core concept of this library**.
1030
- * It represents a series of prompt templates chained together to form a pipeline / one big prompt template with input and result parameters.
1031
- *
1032
- * It can have 3 formats:
1033
- * - **.ptbk.md file** in custom markdown format described above
1034
- * - **JSON** format, parsed from the .ptbk.md file
1035
- * - _(this)_ **Object** which is created from JSON format and bound with tools around (but not the execution logic)
1036
- *
1037
- * @see https://github.com/webgptorg/promptbook#prompt-template-pipeline
1038
- */
1039
- var PromptTemplatePipeline = /** @class */ (function () {
1040
- function PromptTemplatePipeline(ptbkUrl, title, ptbkVersion, description, parameters, promptTemplates) {
1041
- this.ptbkUrl = ptbkUrl;
1042
- this.title = title;
1043
- this.ptbkVersion = ptbkVersion;
1044
- this.description = description;
1045
- this.parameters = parameters;
1046
- this.promptTemplates = promptTemplates;
1047
- if (promptTemplates.length === 0) {
1048
- throw new Error('Prompt template pipeline must have at least one prompt template');
1049
- }
1050
- }
1051
- /**
1052
- * Constructs PromptTemplatePipeline from any source
1053
- *
1054
- * Note: During the construction syntax and logic of source is validated
1055
- *
1056
- * @param source content of .ptbk.md or .ptbk.json file
1057
- * @returns PromptTemplatePipeline
1058
- */
1059
- PromptTemplatePipeline.fromSource = function (ptbkSource) {
1060
- if (typeof ptbkSource === 'string') {
1061
- return PromptTemplatePipeline.fromString(ptbkSource);
1062
- }
1063
- else {
1064
- return PromptTemplatePipeline.fromJson(ptbkSource);
1065
- }
1066
- };
1067
- /**
1068
- * Constructs PromptTemplatePipeline from markdown source
1069
- *
1070
- * Note: During the construction syntax and logic of source is validated
1071
- *
1072
- * @param ptbkString content of .ptbk.md file
1073
- * @returns PromptTemplatePipeline
1074
- */
1075
- PromptTemplatePipeline.fromString = function (ptbkString) {
1076
- var ptbkjson = promptTemplatePipelineStringToJson(ptbkString);
1077
- return PromptTemplatePipeline.fromJson(ptbkjson);
1078
- };
1079
- /**
1080
- * Constructs PromptTemplatePipeline from JSON source
1081
- *
1082
- * Note: During the construction the source is logic validated
1083
- *
1084
- * @param ptbkjson content of .ptbk.json file parsed into JSON
1085
- * @returns PromptTemplatePipeline
1086
- */
1087
- PromptTemplatePipeline.fromJson = function (ptbkjson) {
1088
- validatePromptTemplatePipelineJson(ptbkjson);
1089
- return new PromptTemplatePipeline(ptbkjson.ptbkUrl ? new URL(ptbkjson.ptbkUrl) : null, ptbkjson.title, ptbkjson.ptbkVersion, ptbkjson.description || null, Object.fromEntries(ptbkjson.parameters.map(function (parameter) { return [parameter.name, parameter]; })), ptbkjson.promptTemplates);
1090
- };
1091
- Object.defineProperty(PromptTemplatePipeline.prototype, "entryPromptTemplate", {
1092
- /**
1093
- * Returns the first prompt template in the pipeline
1094
- */
1095
- get: function () {
1096
- return this.promptTemplates[0];
1097
- },
1098
- enumerable: false,
1099
- configurable: true
1100
- });
1101
- /**
1102
- * Gets the parameter that is the result of given prompt template
1103
- */
1104
- PromptTemplatePipeline.prototype.getResultingParameter = function (promptTemplateName) {
1105
- var index = this.promptTemplates.findIndex(function (_a) {
1106
- var name = _a.name;
1107
- return name === promptTemplateName;
1108
- });
1109
- if (index === -1) {
1110
- throw new Error('Prompt template is not in this pipeline');
1111
- }
1112
- var resultingParameterName = this.promptTemplates[index].resultingParameterName;
1113
- var resultingParameter = this.parameters[resultingParameterName];
1114
- if (!resultingParameter) {
1115
- // <- TODO: [🥨] Make some NeverShouldHappenError
1116
- throw new Error("Resulting parameter of prompt template ".concat(promptTemplateName, " {").concat(resultingParameterName, "} is not defined"));
1117
- }
1118
- return resultingParameter;
1119
- };
1120
- /**
1121
- * Gets the following prompt template in the pipeline or null if there is no following prompt template and this is the last one
1122
- */
1123
- PromptTemplatePipeline.prototype.getFollowingPromptTemplate = function (promptTemplateName) {
1124
- var index = this.promptTemplates.findIndex(function (_a) {
1125
- var name = _a.name;
1126
- return name === promptTemplateName;
1127
- });
1128
- if (index === -1) {
1129
- throw new Error('Prompt template is not in this pipeline');
1130
- }
1131
- if (index === this.promptTemplates.length - 1) {
1132
- return null;
1133
- }
1134
- return this.promptTemplates[index + 1];
1135
- };
1136
- return PromptTemplatePipeline;
1137
- }());
1138
- /**
1139
- * TODO: !! [👐][🧠] Split of PromptTemplatePipeline,PromptTemplatePipelineLibrary between interface and class
1140
- * TODO: !! [👐] Make parameters and promptTemplates private WHEN split between interface and class
1141
- * TODO: !! Add generic type for entry and result parameters
1142
- * TODO: Can be Array elegantly typed such as it must have at least one element?
1143
- * TODO: [🧠] Each PromptTemplatePipeline should have its unique hash to be able to compare them and execute on server ONLY the desired ones
1144
- */
1145
-
1146
1101
  /**
1147
1102
  * Counts number of characters in the text
1148
1103
  */
@@ -1335,11 +1290,11 @@ function replaceParameters(template, parameters) {
1335
1290
  finally { if (e_1) throw e_1.error; }
1336
1291
  }
1337
1292
  }
1338
- // Check if there are parameters that are not closed properly
1293
+ // [💫] Check if there are parameters that are not closed properly
1339
1294
  if (/{\w+$/.test(replacedTemplate)) {
1340
1295
  throw new Error('Parameter is not closed');
1341
1296
  }
1342
- // Check if there are parameters that are not opened properly
1297
+ // [💫] Check if there are parameters that are not opened properly
1343
1298
  if (/^\w+}/.test(replacedTemplate)) {
1344
1299
  throw new Error('Parameter is not opened');
1345
1300
  }
@@ -1372,370 +1327,408 @@ function createPtpExecutor(options) {
1372
1327
  var _this = this;
1373
1328
  var ptp = options.ptp, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
1374
1329
  var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? 3 : _b;
1330
+ validatePromptTemplatePipelineJson(ptp);
1375
1331
  var ptpExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1376
- var parametersToPass, currentTemplate, executionReport, priority, _loop_1, error_1;
1377
- var _a;
1378
- return __generator(this, function (_b) {
1379
- switch (_b.label) {
1332
+ function executeSingleTemplate(currentTemplate) {
1333
+ return __awaiter(this, void 0, void 0, function () {
1334
+ var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_1_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_2_1, e_3_1, _j, _k, _l, unit, _m, max, min, amount, error_4;
1335
+ var e_1, _o, e_3, _p, e_2, _q, e_4, _r, _s;
1336
+ return __generator(this, function (_t) {
1337
+ switch (_t.label) {
1338
+ case 0:
1339
+ console.log('!!!! executeSingleTemplate', currentTemplate.title);
1340
+ name = "ptp-executor-frame-".concat(currentTemplate.name);
1341
+ title = removeEmojis(removeMarkdownFormatting(currentTemplate.title));
1342
+ priority = ptp.promptTemplates.indexOf(currentTemplate);
1343
+ if (!onProgress) return [3 /*break*/, 2];
1344
+ return [4 /*yield*/, onProgress({
1345
+ name: name,
1346
+ title: title,
1347
+ isStarted: false,
1348
+ isDone: false,
1349
+ executionType: currentTemplate.executionType,
1350
+ parameterName: currentTemplate.resultingParameterName,
1351
+ parameterValue: null,
1352
+ })];
1353
+ case 1:
1354
+ _t.sent();
1355
+ _t.label = 2;
1356
+ case 2:
1357
+ result = null;
1358
+ resultString = null;
1359
+ expectError = null;
1360
+ maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1361
+ jokers = currentTemplate.jokers || [];
1362
+ attempt = -jokers.length;
1363
+ _t.label = 3;
1364
+ case 3:
1365
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1366
+ isJokerAttempt = attempt < 0;
1367
+ joker = jokers[jokers.length + attempt];
1368
+ if (isJokerAttempt && !joker) {
1369
+ throw new Error("Joker not found in attempt ".concat(attempt));
1370
+ // <- TODO: [🥨] Make some NeverShouldHappenError
1371
+ }
1372
+ result = null;
1373
+ resultString = null;
1374
+ expectError = null;
1375
+ if (isJokerAttempt) {
1376
+ if (typeof parametersToPass[joker] === 'undefined') {
1377
+ throw new Error("Joker parameter {".concat(joker, "} not defined"));
1378
+ }
1379
+ resultString = parametersToPass[joker];
1380
+ }
1381
+ _t.label = 4;
1382
+ case 4:
1383
+ _t.trys.push([4, 45, 46, 47]);
1384
+ if (!!isJokerAttempt) return [3 /*break*/, 27];
1385
+ _a = currentTemplate.executionType;
1386
+ switch (_a) {
1387
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 5];
1388
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 6];
1389
+ case 'SCRIPT': return [3 /*break*/, 13];
1390
+ case 'PROMPT_DIALOG': return [3 /*break*/, 24];
1391
+ }
1392
+ return [3 /*break*/, 26];
1393
+ case 5:
1394
+ resultString = replaceParameters(currentTemplate.content, parametersToPass);
1395
+ return [3 /*break*/, 27];
1396
+ case 6:
1397
+ prompt = {
1398
+ title: currentTemplate.title,
1399
+ ptbkUrl: "".concat(ptp.ptbkUrl
1400
+ ? ptp.ptbkUrl
1401
+ : 'anonymous' /* <- [🧠] !!! How to deal with anonymous PTPs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
1402
+ parameters: parametersToPass,
1403
+ content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1404
+ modelRequirements: currentTemplate.modelRequirements,
1405
+ };
1406
+ _b = currentTemplate.modelRequirements.modelVariant;
1407
+ switch (_b) {
1408
+ case 'CHAT': return [3 /*break*/, 7];
1409
+ case 'COMPLETION': return [3 /*break*/, 9];
1410
+ }
1411
+ return [3 /*break*/, 11];
1412
+ case 7: return [4 /*yield*/, tools.natural.gptChat(prompt)];
1413
+ case 8:
1414
+ chatThread = _t.sent();
1415
+ // TODO: [🍬] Destroy chatThread
1416
+ result = chatThread;
1417
+ resultString = chatThread.content;
1418
+ return [3 /*break*/, 12];
1419
+ case 9: return [4 /*yield*/, tools.natural.gptComplete(prompt)];
1420
+ case 10:
1421
+ completionResult = _t.sent();
1422
+ result = completionResult;
1423
+ resultString = completionResult.content;
1424
+ return [3 /*break*/, 12];
1425
+ case 11: throw new Error("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
1426
+ case 12: return [3 /*break*/, 27];
1427
+ case 13:
1428
+ if (tools.script.length === 0) {
1429
+ throw new Error('No script execution tools are available');
1430
+ }
1431
+ if (!currentTemplate.contentLanguage) {
1432
+ throw new Error("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
1433
+ }
1434
+ // TODO: DRY [1]
1435
+ scriptExecutionErrors = [];
1436
+ _t.label = 14;
1437
+ case 14:
1438
+ _t.trys.push([14, 21, 22, 23]);
1439
+ _c = (e_1 = void 0, __values(tools.script)), _d = _c.next();
1440
+ _t.label = 15;
1441
+ case 15:
1442
+ if (!!_d.done) return [3 /*break*/, 20];
1443
+ scriptTools = _d.value;
1444
+ _t.label = 16;
1445
+ case 16:
1446
+ _t.trys.push([16, 18, , 19]);
1447
+ return [4 /*yield*/, scriptTools.execute({
1448
+ scriptLanguage: currentTemplate.contentLanguage,
1449
+ script: currentTemplate.content,
1450
+ parameters: parametersToPass,
1451
+ })];
1452
+ case 17:
1453
+ resultString = _t.sent();
1454
+ return [3 /*break*/, 20];
1455
+ case 18:
1456
+ error_2 = _t.sent();
1457
+ if (!(error_2 instanceof Error)) {
1458
+ throw error_2;
1459
+ }
1460
+ scriptExecutionErrors.push(error_2);
1461
+ return [3 /*break*/, 19];
1462
+ case 19:
1463
+ _d = _c.next();
1464
+ return [3 /*break*/, 15];
1465
+ case 20: return [3 /*break*/, 23];
1466
+ case 21:
1467
+ e_1_1 = _t.sent();
1468
+ e_1 = { error: e_1_1 };
1469
+ return [3 /*break*/, 23];
1470
+ case 22:
1471
+ try {
1472
+ if (_d && !_d.done && (_o = _c.return)) _o.call(_c);
1473
+ }
1474
+ finally { if (e_1) throw e_1.error; }
1475
+ return [7 /*endfinally*/];
1476
+ case 23:
1477
+ if (resultString) {
1478
+ return [3 /*break*/, 27];
1479
+ }
1480
+ if (scriptExecutionErrors.length === 1) {
1481
+ throw scriptExecutionErrors[0];
1482
+ }
1483
+ else {
1484
+ throw new Error(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
1485
+ .map(function (error) { return '- ' + error.message; })
1486
+ .join('\n\n')), "\n "); }));
1487
+ }
1488
+ case 24: return [4 /*yield*/, tools.userInterface.promptDialog({
1489
+ promptTitle: currentTemplate.title,
1490
+ promptMessage: replaceParameters(currentTemplate.description || '', parametersToPass),
1491
+ defaultValue: replaceParameters(currentTemplate.content, parametersToPass),
1492
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
1493
+ placeholder: undefined,
1494
+ priority: priority /* <- TODO: !!!! Is it ending with 0 */,
1495
+ })];
1496
+ case 25:
1497
+ // TODO: !!!! When making next attempt for `PROMPT DIALOG`, preserve the previous user input
1498
+ resultString = _t.sent();
1499
+ return [3 /*break*/, 27];
1500
+ case 26: throw new Error(
1501
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1502
+ "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
1503
+ case 27:
1504
+ if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
1505
+ _t.label = 28;
1506
+ case 28:
1507
+ _t.trys.push([28, 42, 43, 44]);
1508
+ _e = (e_3 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
1509
+ _t.label = 29;
1510
+ case 29:
1511
+ if (!!_f.done) return [3 /*break*/, 41];
1512
+ functionName = _f.value;
1513
+ // TODO: DRY [1]
1514
+ scriptExecutionErrors = [];
1515
+ postprocessingError = null;
1516
+ _t.label = 30;
1517
+ case 30:
1518
+ _t.trys.push([30, 37, 38, 39]);
1519
+ _g = (e_2 = void 0, __values(tools.script)), _h = _g.next();
1520
+ _t.label = 31;
1521
+ case 31:
1522
+ if (!!_h.done) return [3 /*break*/, 36];
1523
+ scriptTools = _h.value;
1524
+ _t.label = 32;
1525
+ case 32:
1526
+ _t.trys.push([32, 34, , 35]);
1527
+ return [4 /*yield*/, scriptTools.execute({
1528
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1529
+ script: "".concat(functionName, "(resultString)"),
1530
+ parameters: __assign(__assign({}, parametersToPass), { resultString: resultString || '' }),
1531
+ })];
1532
+ case 33:
1533
+ resultString = _t.sent();
1534
+ postprocessingError = null;
1535
+ return [3 /*break*/, 36];
1536
+ case 34:
1537
+ error_3 = _t.sent();
1538
+ if (!(error_3 instanceof Error)) {
1539
+ throw error_3;
1540
+ }
1541
+ postprocessingError = error_3;
1542
+ scriptExecutionErrors.push(error_3);
1543
+ return [3 /*break*/, 35];
1544
+ case 35:
1545
+ _h = _g.next();
1546
+ return [3 /*break*/, 31];
1547
+ case 36: return [3 /*break*/, 39];
1548
+ case 37:
1549
+ e_2_1 = _t.sent();
1550
+ e_2 = { error: e_2_1 };
1551
+ return [3 /*break*/, 39];
1552
+ case 38:
1553
+ try {
1554
+ if (_h && !_h.done && (_q = _g.return)) _q.call(_g);
1555
+ }
1556
+ finally { if (e_2) throw e_2.error; }
1557
+ return [7 /*endfinally*/];
1558
+ case 39:
1559
+ if (postprocessingError) {
1560
+ throw postprocessingError;
1561
+ }
1562
+ _t.label = 40;
1563
+ case 40:
1564
+ _f = _e.next();
1565
+ return [3 /*break*/, 29];
1566
+ case 41: return [3 /*break*/, 44];
1567
+ case 42:
1568
+ e_3_1 = _t.sent();
1569
+ e_3 = { error: e_3_1 };
1570
+ return [3 /*break*/, 44];
1571
+ case 43:
1572
+ try {
1573
+ if (_f && !_f.done && (_p = _e.return)) _p.call(_e);
1574
+ }
1575
+ finally { if (e_3) throw e_3.error; }
1576
+ return [7 /*endfinally*/];
1577
+ case 44:
1578
+ if (currentTemplate.expectFormat) {
1579
+ if (currentTemplate.expectFormat === 'JSON') {
1580
+ if (!isValidJsonString(resultString || '')) {
1581
+ throw new ExpectError('Expected valid JSON string');
1582
+ }
1583
+ }
1584
+ }
1585
+ if (currentTemplate.expectAmount) {
1586
+ try {
1587
+ for (_j = (e_4 = void 0, __values(Object.entries(currentTemplate.expectAmount))), _k = _j.next(); !_k.done; _k = _j.next()) {
1588
+ _l = __read(_k.value, 2), unit = _l[0], _m = _l[1], max = _m.max, min = _m.min;
1589
+ amount = CountUtils[unit.toUpperCase()](resultString || '');
1590
+ if (min && amount < min) {
1591
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
1592
+ } /* not else */
1593
+ if (max && amount > max) {
1594
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1595
+ }
1596
+ }
1597
+ }
1598
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1599
+ finally {
1600
+ try {
1601
+ if (_k && !_k.done && (_r = _j.return)) _r.call(_j);
1602
+ }
1603
+ finally { if (e_4) throw e_4.error; }
1604
+ }
1605
+ }
1606
+ return [3 /*break*/, 49];
1607
+ case 45:
1608
+ error_4 = _t.sent();
1609
+ if (!(error_4 instanceof ExpectError)) {
1610
+ throw error_4;
1611
+ }
1612
+ expectError = error_4;
1613
+ return [3 /*break*/, 47];
1614
+ case 46:
1615
+ if (!isJokerAttempt &&
1616
+ currentTemplate.executionType === 'PROMPT_TEMPLATE' &&
1617
+ prompt
1618
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
1619
+ // In that case we don’t want to make a report about it because it’s not a natural execution error
1620
+ ) {
1621
+ // TODO: [🧠] Maybe put other executionTypes into report
1622
+ executionReport.promptExecutions.push({
1623
+ prompt: {
1624
+ title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
1625
+ content: prompt.content,
1626
+ modelRequirements: prompt.modelRequirements,
1627
+ // <- Note: Do want to pass ONLY wanted information to the report
1628
+ },
1629
+ result: result || undefined,
1630
+ error: expectError || undefined,
1631
+ });
1632
+ }
1633
+ return [7 /*endfinally*/];
1634
+ case 47:
1635
+ if (expectError !== null && attempt === maxAttempts - 1) {
1636
+ throw new Error(spaceTrim(function (block) { return "\n Natural execution failed ".concat(settings.maxExecutionAttempts, "x\n\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n "); }));
1637
+ }
1638
+ _t.label = 48;
1639
+ case 48:
1640
+ attempt++;
1641
+ return [3 /*break*/, 3];
1642
+ case 49:
1643
+ if (resultString === null) {
1644
+ // <- TODO: [🥨] Make some NeverShouldHappenError
1645
+ throw new Error('Something went wrong and prompt result is null');
1646
+ }
1647
+ if (onProgress) {
1648
+ onProgress({
1649
+ name: name,
1650
+ title: title,
1651
+ isStarted: true,
1652
+ isDone: true,
1653
+ executionType: currentTemplate.executionType,
1654
+ parameterName: currentTemplate.resultingParameterName,
1655
+ parameterValue: resultString,
1656
+ });
1657
+ }
1658
+ parametersToPass = __assign(__assign({}, parametersToPass), (_s = {}, _s[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because PromptTemplatePipeline checks logic consistency during construction */, _s));
1659
+ return [2 /*return*/];
1660
+ }
1661
+ });
1662
+ });
1663
+ }
1664
+ var parametersToPass, executionReport, resovedParameters_1, unresovedTemplates, works_1, _loop_1, error_1;
1665
+ return __generator(this, function (_a) {
1666
+ switch (_a.label) {
1380
1667
  case 0:
1381
1668
  parametersToPass = inputParameters;
1382
- currentTemplate = ptp.entryPromptTemplate;
1383
1669
  executionReport = {
1384
- ptbkUrl: ((_a = ptp.ptbkUrl) === null || _a === void 0 ? void 0 : _a.href) || undefined,
1385
- title: ptp.title || undefined,
1670
+ ptbkUrl: ptp.ptbkUrl,
1671
+ title: ptp.title,
1386
1672
  ptbkUsedVersion: PTBK_VERSION,
1387
- ptbkRequestedVersion: ptp.ptbkVersion || undefined,
1388
- description: ptp.description || undefined,
1673
+ ptbkRequestedVersion: ptp.ptbkVersion,
1674
+ description: ptp.description,
1389
1675
  promptExecutions: [],
1390
1676
  };
1391
- priority = ptp.promptTemplates.length;
1392
- _b.label = 1;
1677
+ _a.label = 1;
1393
1678
  case 1:
1394
- _b.trys.push([1, 5, , 6]);
1679
+ _a.trys.push([1, 6, , 7]);
1680
+ resovedParameters_1 = ptp.parameters
1681
+ .filter(function (_a) {
1682
+ var isInput = _a.isInput;
1683
+ return isInput;
1684
+ })
1685
+ .map(function (_a) {
1686
+ var name = _a.name;
1687
+ return name;
1688
+ });
1689
+ unresovedTemplates = __spreadArray([], __read(ptp.promptTemplates), false);
1690
+ works_1 = [];
1395
1691
  _loop_1 = function () {
1396
- var resultingParameter, name_1, title, prompt_1, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _c, _d, _e, _f, scriptTools, error_2, e_1_1, _g, _h, functionName, postprocessingError, _j, _k, scriptTools, error_3, e_2_1, e_3_1, _l, _m, _o, unit, _p, max, min, amount, error_4;
1397
- var e_1, _q, e_3, _r, e_2, _s, e_4, _t, _u;
1398
- return __generator(this, function (_v) {
1399
- switch (_v.label) {
1692
+ var currentTemplate, work_1;
1693
+ return __generator(this, function (_b) {
1694
+ switch (_b.label) {
1400
1695
  case 0:
1401
- priority--;
1402
- resultingParameter = ptp.getResultingParameter(currentTemplate.name);
1403
- name_1 = "ptp-executor-frame-".concat(currentTemplate.name);
1404
- title = removeEmojis(removeMarkdownFormatting(currentTemplate.title));
1405
- if (!onProgress) return [3 /*break*/, 2];
1406
- return [4 /*yield*/, onProgress({
1407
- name: name_1,
1408
- title: title,
1409
- isStarted: false,
1410
- isDone: false,
1411
- executionType: currentTemplate.executionType,
1412
- parameterName: resultingParameter.name,
1413
- parameterValue: null,
1414
- })];
1696
+ currentTemplate = unresovedTemplates.find(function (template) {
1697
+ return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
1698
+ });
1699
+ if (!!currentTemplate) return [3 /*break*/, 2];
1700
+ /* [5] */ return [4 /*yield*/, Promise.race(works_1)];
1415
1701
  case 1:
1416
- _v.sent();
1417
- _v.label = 2;
1418
- case 2:
1419
- prompt_1 = void 0;
1420
- chatThread = void 0;
1421
- completionResult = void 0;
1422
- result = null;
1423
- resultString = null;
1424
- expectError = null;
1425
- maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1426
- jokers = currentTemplate.jokers || [];
1427
- attempt = -jokers.length;
1428
- _v.label = 3;
1429
- case 3:
1430
- if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1431
- isJokerAttempt = attempt < 0;
1432
- joker = jokers[jokers.length + attempt];
1433
- if (isJokerAttempt && !joker) {
1434
- throw new Error("Joker not found in attempt ".concat(attempt));
1435
- // <- TODO: [🥨] Make some NeverShouldHappenError
1436
- }
1437
- result = null;
1438
- resultString = null;
1439
- expectError = null;
1440
- if (isJokerAttempt) {
1441
- if (typeof parametersToPass[joker] === 'undefined') {
1442
- throw new Error("Joker parameter {".concat(joker, "} not defined"));
1443
- }
1444
- resultString = parametersToPass[joker];
1445
- }
1446
- _v.label = 4;
1447
- case 4:
1448
- _v.trys.push([4, 45, 46, 47]);
1449
- if (!!isJokerAttempt) return [3 /*break*/, 27];
1450
- _c = currentTemplate.executionType;
1451
- switch (_c) {
1452
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 5];
1453
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 6];
1454
- case 'SCRIPT': return [3 /*break*/, 13];
1455
- case 'PROMPT_DIALOG': return [3 /*break*/, 24];
1456
- }
1457
- return [3 /*break*/, 26];
1458
- case 5:
1459
- resultString = replaceParameters(currentTemplate.content, parametersToPass);
1460
- return [3 /*break*/, 27];
1461
- case 6:
1462
- prompt_1 = {
1463
- title: currentTemplate.title,
1464
- ptbkUrl: "".concat(ptp.ptbkUrl
1465
- ? ptp.ptbkUrl.href
1466
- : 'anonymous' /* <- [🧠] !!! How to deal with anonymous PTPs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
1467
- parameters: parametersToPass,
1468
- content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1469
- modelRequirements: currentTemplate.modelRequirements,
1470
- };
1471
- _d = currentTemplate.modelRequirements.modelVariant;
1472
- switch (_d) {
1473
- case 'CHAT': return [3 /*break*/, 7];
1474
- case 'COMPLETION': return [3 /*break*/, 9];
1475
- }
1476
- return [3 /*break*/, 11];
1477
- case 7: return [4 /*yield*/, tools.natural.gptChat(prompt_1)];
1478
- case 8:
1479
- chatThread = _v.sent();
1480
- // TODO: [🍬] Destroy chatThread
1481
- result = chatThread;
1482
- resultString = chatThread.content;
1483
- return [3 /*break*/, 12];
1484
- case 9: return [4 /*yield*/, tools.natural.gptComplete(prompt_1)];
1485
- case 10:
1486
- completionResult = _v.sent();
1487
- result = completionResult;
1488
- resultString = completionResult.content;
1489
- return [3 /*break*/, 12];
1490
- case 11: throw new Error("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
1491
- case 12: return [3 /*break*/, 27];
1492
- case 13:
1493
- if (tools.script.length === 0) {
1494
- throw new Error('No script execution tools are available');
1495
- }
1496
- if (!currentTemplate.contentLanguage) {
1497
- throw new Error("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
1498
- }
1499
- // TODO: DRY [1]
1500
- scriptExecutionErrors = [];
1501
- _v.label = 14;
1502
- case 14:
1503
- _v.trys.push([14, 21, 22, 23]);
1504
- _e = (e_1 = void 0, __values(tools.script)), _f = _e.next();
1505
- _v.label = 15;
1506
- case 15:
1507
- if (!!_f.done) return [3 /*break*/, 20];
1508
- scriptTools = _f.value;
1509
- _v.label = 16;
1510
- case 16:
1511
- _v.trys.push([16, 18, , 19]);
1512
- return [4 /*yield*/, scriptTools.execute({
1513
- scriptLanguage: currentTemplate.contentLanguage,
1514
- script: currentTemplate.content,
1515
- parameters: parametersToPass,
1516
- })];
1517
- case 17:
1518
- resultString = _v.sent();
1519
- return [3 /*break*/, 20];
1520
- case 18:
1521
- error_2 = _v.sent();
1522
- if (!(error_2 instanceof Error)) {
1523
- throw error_2;
1524
- }
1525
- scriptExecutionErrors.push(error_2);
1526
- return [3 /*break*/, 19];
1527
- case 19:
1528
- _f = _e.next();
1529
- return [3 /*break*/, 15];
1530
- case 20: return [3 /*break*/, 23];
1531
- case 21:
1532
- e_1_1 = _v.sent();
1533
- e_1 = { error: e_1_1 };
1534
- return [3 /*break*/, 23];
1535
- case 22:
1536
- try {
1537
- if (_f && !_f.done && (_q = _e.return)) _q.call(_e);
1538
- }
1539
- finally { if (e_1) throw e_1.error; }
1540
- return [7 /*endfinally*/];
1541
- case 23:
1542
- if (resultString) {
1543
- return [3 /*break*/, 27];
1544
- }
1545
- if (scriptExecutionErrors.length === 1) {
1546
- throw scriptExecutionErrors[0];
1547
- }
1548
- else {
1549
- throw new Error(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
1550
- .map(function (error) { return '- ' + error.message; })
1551
- .join('\n\n')), "\n "); }));
1552
- }
1553
- case 24: return [4 /*yield*/, tools.userInterface.promptDialog({
1554
- promptTitle: currentTemplate.title,
1555
- promptMessage: replaceParameters(currentTemplate.description || '', parametersToPass),
1556
- defaultValue: replaceParameters(currentTemplate.content, parametersToPass),
1557
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
1558
- placeholder: undefined,
1559
- priority: priority /* <- TODO: !!!! Is it ending with 0 */,
1560
- })];
1561
- case 25:
1562
- // TODO: !!!! When making next attempt for `PROMPT DIALOG`, preserve the previous user input
1563
- resultString = _v.sent();
1564
- return [3 /*break*/, 27];
1565
- case 26: throw new Error(
1566
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1567
- "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
1568
- case 27:
1569
- if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
1570
- _v.label = 28;
1571
- case 28:
1572
- _v.trys.push([28, 42, 43, 44]);
1573
- _g = (e_3 = void 0, __values(currentTemplate.postprocessing)), _h = _g.next();
1574
- _v.label = 29;
1575
- case 29:
1576
- if (!!_h.done) return [3 /*break*/, 41];
1577
- functionName = _h.value;
1578
- // TODO: DRY [1]
1579
- scriptExecutionErrors = [];
1580
- postprocessingError = null;
1581
- _v.label = 30;
1582
- case 30:
1583
- _v.trys.push([30, 37, 38, 39]);
1584
- _j = (e_2 = void 0, __values(tools.script)), _k = _j.next();
1585
- _v.label = 31;
1586
- case 31:
1587
- if (!!_k.done) return [3 /*break*/, 36];
1588
- scriptTools = _k.value;
1589
- _v.label = 32;
1590
- case 32:
1591
- _v.trys.push([32, 34, , 35]);
1592
- return [4 /*yield*/, scriptTools.execute({
1593
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1594
- script: "".concat(functionName, "(resultString)"),
1595
- parameters: __assign(__assign({}, parametersToPass), { resultString: resultString || '' }),
1596
- })];
1597
- case 33:
1598
- resultString = _v.sent();
1599
- postprocessingError = null;
1600
- return [3 /*break*/, 36];
1601
- case 34:
1602
- error_3 = _v.sent();
1603
- if (!(error_3 instanceof Error)) {
1604
- throw error_3;
1605
- }
1606
- postprocessingError = error_3;
1607
- scriptExecutionErrors.push(error_3);
1608
- return [3 /*break*/, 35];
1609
- case 35:
1610
- _k = _j.next();
1611
- return [3 /*break*/, 31];
1612
- case 36: return [3 /*break*/, 39];
1613
- case 37:
1614
- e_2_1 = _v.sent();
1615
- e_2 = { error: e_2_1 };
1616
- return [3 /*break*/, 39];
1617
- case 38:
1618
- try {
1619
- if (_k && !_k.done && (_s = _j.return)) _s.call(_j);
1620
- }
1621
- finally { if (e_2) throw e_2.error; }
1622
- return [7 /*endfinally*/];
1623
- case 39:
1624
- if (postprocessingError) {
1625
- throw postprocessingError;
1626
- }
1627
- _v.label = 40;
1628
- case 40:
1629
- _h = _g.next();
1630
- return [3 /*break*/, 29];
1631
- case 41: return [3 /*break*/, 44];
1632
- case 42:
1633
- e_3_1 = _v.sent();
1634
- e_3 = { error: e_3_1 };
1635
- return [3 /*break*/, 44];
1636
- case 43:
1637
- try {
1638
- if (_h && !_h.done && (_r = _g.return)) _r.call(_g);
1639
- }
1640
- finally { if (e_3) throw e_3.error; }
1641
- return [7 /*endfinally*/];
1642
- case 44:
1643
- if (currentTemplate.expectFormat) {
1644
- if (currentTemplate.expectFormat === 'JSON') {
1645
- if (!isValidJsonString(resultString || '')) {
1646
- throw new ExpectError('Expected valid JSON string');
1647
- }
1648
- }
1649
- }
1650
- if (currentTemplate.expectAmount) {
1651
- try {
1652
- for (_l = (e_4 = void 0, __values(Object.entries(currentTemplate.expectAmount))), _m = _l.next(); !_m.done; _m = _l.next()) {
1653
- _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], max = _p.max, min = _p.min;
1654
- amount = CountUtils[unit.toUpperCase()](resultString || '');
1655
- if (min && amount < min) {
1656
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
1657
- } /* not else */
1658
- if (max && amount > max) {
1659
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1660
- }
1661
- }
1662
- }
1663
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
1664
- finally {
1665
- try {
1666
- if (_m && !_m.done && (_t = _l.return)) _t.call(_l);
1667
- }
1668
- finally { if (e_4) throw e_4.error; }
1669
- }
1670
- }
1671
- return [3 /*break*/, 49];
1672
- case 45:
1673
- error_4 = _v.sent();
1674
- if (!(error_4 instanceof ExpectError)) {
1675
- throw error_4;
1676
- }
1677
- expectError = error_4;
1678
- return [3 /*break*/, 47];
1679
- case 46:
1680
- if (!isJokerAttempt &&
1681
- currentTemplate.executionType === 'PROMPT_TEMPLATE' &&
1682
- prompt_1
1683
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
1684
- // In that case we don’t want to make a report about it because it’s not a natural execution error
1685
- ) {
1686
- // TODO: [🧠] Maybe put other executionTypes into report
1687
- executionReport.promptExecutions.push({
1688
- prompt: {
1689
- title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
1690
- content: prompt_1.content,
1691
- modelRequirements: prompt_1.modelRequirements,
1692
- // <- Note: Do want to pass ONLY wanted information to the report
1693
- },
1694
- result: result || undefined,
1695
- error: expectError || undefined,
1696
- });
1697
- }
1698
- return [7 /*endfinally*/];
1699
- case 47:
1700
- if (expectError !== null && attempt === maxAttempts - 1) {
1701
- throw new Error(spaceTrim(function (block) { return "\n Natural execution failed ".concat(settings.maxExecutionAttempts, "x\n\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n "); }));
1702
- }
1703
- _v.label = 48;
1704
- case 48:
1705
- attempt++;
1702
+ /* [5] */ _b.sent();
1706
1703
  return [3 /*break*/, 3];
1707
- case 49:
1708
- if (resultString === null) {
1709
- // <- TODO: [🥨] Make some NeverShouldHappenError
1710
- throw new Error('Something went wrong and prompt result is null');
1711
- }
1712
- if (onProgress) {
1713
- onProgress({
1714
- name: name_1,
1715
- title: title,
1716
- isStarted: true,
1717
- isDone: true,
1718
- executionType: currentTemplate.executionType,
1719
- parameterName: resultingParameter.name,
1720
- parameterValue: resultString,
1721
- });
1722
- }
1723
- parametersToPass = __assign(__assign({}, parametersToPass), (_u = {}, _u[resultingParameter.name] = resultString /* <- Note: Not need to detect parameter collision here because PromptTemplatePipeline checks logic consistency during construction */, _u));
1724
- currentTemplate = ptp.getFollowingPromptTemplate(currentTemplate.name);
1725
- return [2 /*return*/];
1704
+ case 2:
1705
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return template !== currentTemplate; });
1706
+ work_1 = executeSingleTemplate(currentTemplate)
1707
+ .then(function () {
1708
+ resovedParameters_1 = resovedParameters_1.filter(function (name) { return !currentTemplate.dependentParameterNames.includes(name); });
1709
+ })
1710
+ .then(function () {
1711
+ works_1 = works_1.filter(function (w) { return w !== work_1; });
1712
+ });
1713
+ works_1.push(work_1);
1714
+ _b.label = 3;
1715
+ case 3: return [2 /*return*/];
1726
1716
  }
1727
1717
  });
1728
1718
  };
1729
- _b.label = 2;
1719
+ _a.label = 2;
1730
1720
  case 2:
1731
- if (!(currentTemplate !== null)) return [3 /*break*/, 4];
1721
+ if (!(unresovedTemplates.length > 0)) return [3 /*break*/, 4];
1732
1722
  return [5 /*yield**/, _loop_1()];
1733
1723
  case 3:
1734
- _b.sent();
1724
+ _a.sent();
1735
1725
  return [3 /*break*/, 2];
1736
- case 4: return [3 /*break*/, 6];
1726
+ case 4: return [4 /*yield*/, Promise.all(works_1)];
1737
1727
  case 5:
1738
- error_1 = _b.sent();
1728
+ _a.sent();
1729
+ return [3 /*break*/, 7];
1730
+ case 6:
1731
+ error_1 = _a.sent();
1739
1732
  if (!(error_1 instanceof Error)) {
1740
1733
  throw error_1;
1741
1734
  }
@@ -1745,7 +1738,7 @@ function createPtpExecutor(options) {
1745
1738
  executionReport: executionReport,
1746
1739
  outputParameters: parametersToPass,
1747
1740
  }];
1748
- case 6: return [2 /*return*/, {
1741
+ case 7: return [2 /*return*/, {
1749
1742
  isSuccessful: true,
1750
1743
  errors: [],
1751
1744
  executionReport: executionReport,
@@ -1791,7 +1784,15 @@ var PromptTemplatePipelineLibrary = /** @class */ (function () {
1791
1784
  try {
1792
1785
  for (var _b = __values(Object.entries(ptbkSources)), _c = _b.next(); !_c.done; _c = _b.next()) {
1793
1786
  var _d = __read(_c.value, 2), name_1 = _d[0], source = _d[1];
1794
- library[name_1] = PromptTemplatePipeline.fromSource(source);
1787
+ if (typeof source === 'string') {
1788
+ // Note: When directly creating from string, no need to validate the source
1789
+ // The validation is performed always before execution
1790
+ library[name_1] = promptTemplatePipelineStringToJson(source);
1791
+ }
1792
+ else {
1793
+ validatePromptTemplatePipelineJson(source);
1794
+ library[name_1] = source;
1795
+ }
1795
1796
  }
1796
1797
  }
1797
1798
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -1957,5 +1958,5 @@ var SimplePromptInterfaceTools = /** @class */ (function () {
1957
1958
  return SimplePromptInterfaceTools;
1958
1959
  }());
1959
1960
 
1960
- export { CallbackInterfaceTools, ExecutionTypes, MockedEchoNaturalExecutionTools, PTBK_VERSION, PromptTemplatePipeline, PromptTemplatePipelineLibrary, SimplePromptInterfaceTools, createPtpExecutor, promptTemplatePipelineStringToJson, validatePromptTemplatePipelineJson };
1961
+ export { CallbackInterfaceTools, ExecutionTypes, MockedEchoNaturalExecutionTools, PTBK_VERSION, PromptTemplatePipelineLibrary, SimplePromptInterfaceTools, createPtpExecutor, promptTemplatePipelineStringToJson, validatePromptTemplatePipelineJson };
1961
1962
  //# sourceMappingURL=index.es.js.map