@promptbook/node 0.72.0-0 → 0.72.0-1

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 (65) hide show
  1. package/README.md +5 -6
  2. package/esm/index.es.js +2083 -1234
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/cli.index.d.ts +4 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +11 -1
  6. package/esm/typings/src/_packages/openai.index.d.ts +4 -0
  7. package/esm/typings/src/_packages/types.index.d.ts +12 -0
  8. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  9. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +3 -2
  10. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +23 -0
  11. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -1
  12. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +16 -1
  13. package/esm/typings/src/config.d.ts +14 -1
  14. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  15. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  16. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +5 -0
  17. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +9 -8
  18. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +45 -0
  19. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  20. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +40 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +19 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  30. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  31. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  32. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  33. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  34. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  35. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  36. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  37. package/esm/typings/src/formats/index.d.ts +1 -1
  38. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  39. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  40. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  41. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +1 -1
  42. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionToolsOptions.d.ts +1 -1
  43. package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +9 -0
  44. package/esm/typings/src/llm-providers/openai/createOpenAiAssistantExecutionTools.d.ts +15 -0
  45. package/esm/typings/src/llm-providers/openai/register-configuration.d.ts +9 -0
  46. package/esm/typings/src/llm-providers/openai/register-constructor.d.ts +9 -0
  47. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  48. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  49. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  50. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  51. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  52. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  53. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  54. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  55. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  56. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  57. package/esm/typings/src/utils/validators/parameterName/validateParameterName.test.d.ts +1 -0
  58. package/package.json +18 -13
  59. package/umd/index.umd.js +2086 -1238
  60. package/umd/index.umd.js.map +1 -1
  61. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  62. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  63. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  64. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  65. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
package/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.hexEncoder, global.sha256, global.posix, global.dotenv));
5
- })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, hexEncoder, sha256, posix, dotenv) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.hexEncoder, global.sha256, global.posix, global.dotenv));
5
+ })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, papaparse, hexEncoder, sha256, posix, dotenv) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -35,7 +35,7 @@
35
35
  /**
36
36
  * The version of the Promptbook library
37
37
  */
38
- var PROMPTBOOK_VERSION = '0.68.5';
38
+ var PROMPTBOOK_VERSION = '0.72.0-0';
39
39
  // TODO:[main] !!!! List here all the versions and annotate + put into script
40
40
 
41
41
  /*! *****************************************************************************
@@ -388,13 +388,13 @@
388
388
  *
389
389
  * @public exported from `@promptbook/core`
390
390
  */
391
- var MAX_PARALLEL_COUNT = 5;
391
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
392
392
  /**
393
393
  * The maximum number of attempts to execute LLM task before giving up
394
394
  *
395
395
  * @public exported from `@promptbook/core`
396
396
  */
397
- var MAX_EXECUTION_ATTEMPTS = 3;
397
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
398
398
  /**
399
399
  * The maximum length of the (generated) filename
400
400
  *
@@ -425,6 +425,7 @@
425
425
  'samples',
426
426
  'modelName',
427
427
  'currentDate',
428
+ // <- TODO: !!!!! list here all command names
428
429
  // <- TODO: Add more like 'date', 'modelName',...
429
430
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
430
431
  ]);
@@ -441,12 +442,32 @@
441
442
  */
442
443
  var RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
443
444
  // <- TODO: [🧜‍♂️]
445
+ /**
446
+ * @@@
447
+ *
448
+ * @public exported from `@promptbook/core`
449
+ */
450
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
451
+ delimiter: ',',
452
+ quoteChar: '"',
453
+ newline: '\n',
454
+ skipEmptyLines: true,
455
+ });
444
456
  /**
445
457
  * @@@
446
458
  *
447
459
  * @public exported from `@promptbook/core`
448
460
  */
449
461
  var IS_VERBOSE = false;
462
+ /**
463
+ * @@@
464
+ *
465
+ * @private within the repository
466
+ */
467
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
468
+ /**/
469
+ // Note: In normal situations, we check the pipeline logic:
470
+ true);
450
471
  /**
451
472
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
452
473
  */
@@ -1034,6 +1055,26 @@
1034
1055
  * @public exported from `@promptbook/core`
1035
1056
  */
1036
1057
  function validatePipeline(pipeline) {
1058
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1059
+ validatePipelineCore(pipeline);
1060
+ }
1061
+ else {
1062
+ try {
1063
+ validatePipelineCore(pipeline);
1064
+ }
1065
+ catch (error) {
1066
+ if (!(error instanceof PipelineLogicError)) {
1067
+ throw error;
1068
+ }
1069
+ console.error(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1070
+ }
1071
+ }
1072
+ return pipeline;
1073
+ }
1074
+ /**
1075
+ * @private internal function for `validatePipeline`
1076
+ */
1077
+ function validatePipelineCore(pipeline) {
1037
1078
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1038
1079
  var e_1, _a, e_2, _b, e_3, _c;
1039
1080
  var pipelineIdentification = (function () {
@@ -1058,12 +1099,12 @@
1058
1099
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1059
1100
  if (!Array.isArray(pipeline.parameters)) {
1060
1101
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1061
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1102
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1062
1103
  }
1063
1104
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1064
1105
  if (!Array.isArray(pipeline.templates)) {
1065
1106
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1066
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1107
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1067
1108
  }
1068
1109
  var _loop_1 = function (parameter) {
1069
1110
  if (parameter.isInput && parameter.isOutput) {
@@ -1232,9 +1273,9 @@
1232
1273
  while (unresovedTemplates.length > 0) {
1233
1274
  _loop_3();
1234
1275
  }
1235
- return pipeline;
1236
1276
  }
1237
1277
  /**
1278
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1238
1279
  * TODO: [🧠] Work with promptbookVersion
1239
1280
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1240
1281
  * > /**
@@ -1972,113 +2013,35 @@
1972
2013
  */
1973
2014
 
1974
2015
  /**
1975
- * Parses the given script and returns the list of all used variables that are not defined in the script
1976
- *
1977
- * @param script from which to extract the variables
1978
- * @returns the list of variable names
1979
- * @throws {ParseError} if the script is invalid
1980
- * @public exported from `@promptbook/utils`
1981
- */
1982
- function extractVariables(script) {
1983
- var variables = new Set();
1984
- script = "(()=>{".concat(script, "})()");
1985
- try {
1986
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
1987
- try {
1988
- eval(script);
1989
- }
1990
- catch (error) {
1991
- if (!(error instanceof ReferenceError)) {
1992
- throw error;
1993
- }
1994
- var undefinedName = error.message.split(' ')[0];
1995
- /*
1996
- Note: Parsing the error
1997
- [PipelineUrlError: thing is not defined]
1998
- */
1999
- if (!undefinedName) {
2000
- throw error;
2001
- }
2002
- if (script.includes(undefinedName + '(')) {
2003
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2004
- }
2005
- else {
2006
- variables.add(undefinedName);
2007
- script = "const ".concat(undefinedName, " = '';") + script;
2008
- }
2009
- }
2010
- }
2011
- catch (error) {
2012
- if (!(error instanceof Error)) {
2013
- throw error;
2014
- }
2015
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2016
- }
2017
- return variables;
2018
- }
2019
- /**
2020
- * TODO: [🔣] Support for multiple languages - python, java,...
2021
- */
2022
-
2023
- /**
2024
- * Parses the template and returns the set of all used parameters
2016
+ * Determine if the pipeline is fully prepared
2025
2017
  *
2026
- * @param template the template with used parameters
2027
- * @returns the set of parameter names
2028
- * @throws {ParseError} if the script is invalid
2029
- * @public exported from `@promptbook/utils`
2018
+ * @public exported from `@promptbook/core`
2030
2019
  */
2031
- function extractParameterNamesFromTemplate(template) {
2032
- var e_1, _a, e_2, _b, e_3, _c;
2033
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2034
- var parameterNames = new Set();
2035
- try {
2036
- for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2037
- var parameterName = _e.value;
2038
- parameterNames.add(parameterName);
2039
- }
2040
- }
2041
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2042
- finally {
2043
- try {
2044
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2045
- }
2046
- finally { if (e_1) throw e_1.error; }
2047
- }
2048
- if (templateType === 'SCRIPT_TEMPLATE') {
2049
- try {
2050
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2051
- var parameterName = _g.value;
2052
- parameterNames.add(parameterName);
2053
- }
2054
- }
2055
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2056
- finally {
2057
- try {
2058
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2059
- }
2060
- finally { if (e_2) throw e_2.error; }
2061
- }
2062
- }
2063
- try {
2064
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2065
- var jokerName = _j.value;
2066
- parameterNames.add(jokerName);
2067
- }
2020
+ function isPipelinePrepared(pipeline) {
2021
+ // Note: Ignoring `pipeline.preparations` @@@
2022
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2023
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2024
+ return false;
2068
2025
  }
2069
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2070
- finally {
2071
- try {
2072
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2073
- }
2074
- finally { if (e_3) throw e_3.error; }
2026
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2027
+ return false;
2075
2028
  }
2076
- parameterNames.delete('content');
2077
- // <- Note {websiteContent} is used in `preparedContent`
2078
- return parameterNames;
2029
+ /*
2030
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2031
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2032
+ > return false;
2033
+ > }
2034
+ */
2035
+ return true;
2079
2036
  }
2080
2037
  /**
2081
- * TODO: [🔣] If script require contentLanguage
2038
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2039
+ * TODO: [🐠] Maybe base this on `makeValidator`
2040
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2041
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2042
+ * - [🏍] ? Is context in each template
2043
+ * - [♨] Are samples prepared
2044
+ * - [♨] Are templates prepared
2082
2045
  */
2083
2046
 
2084
2047
  /**
@@ -2098,27 +2061,6 @@
2098
2061
  };
2099
2062
  }
2100
2063
 
2101
- /**
2102
- * Function isValidJsonString will tell you if the string is valid JSON or not
2103
- *
2104
- * @public exported from `@promptbook/utils`
2105
- */
2106
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2107
- try {
2108
- JSON.parse(value);
2109
- return true;
2110
- }
2111
- catch (error) {
2112
- if (!(error instanceof Error)) {
2113
- throw error;
2114
- }
2115
- if (error.message.includes('Unexpected token')) {
2116
- return false;
2117
- }
2118
- return false;
2119
- }
2120
- }
2121
-
2122
2064
  /**
2123
2065
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2124
2066
  *
@@ -2145,9 +2087,10 @@
2145
2087
  });
2146
2088
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2147
2089
  get: function () {
2148
- return this.llmExecutionTools
2149
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2150
- .join('\n');
2090
+ return this.llmExecutionTools.map(function (_a, index) {
2091
+ var title = _a.title;
2092
+ return "".concat(index + 1, ") `").concat(title, "`");
2093
+ }).join('\n');
2151
2094
  },
2152
2095
  enumerable: false,
2153
2096
  configurable: true
@@ -2345,9 +2288,7 @@
2345
2288
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2346
2289
  }
2347
2290
  else {
2348
- throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.llmExecutionTools
2349
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2350
- .join('\n')), "\n\n "); }));
2291
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\"\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.description), "\n\n "); }));
2351
2292
  }
2352
2293
  }
2353
2294
  });
@@ -2413,171 +2354,820 @@
2413
2354
  */
2414
2355
 
2415
2356
  /**
2416
- * Extracts all code blocks from markdown.
2357
+ * Takes an item or an array of items and returns an array of items
2417
2358
  *
2418
- * Note: There are multiple simmilar function:
2419
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2420
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2421
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2422
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2359
+ * 1) Any item except array and undefined returns array with that one item (also null)
2360
+ * 2) Undefined returns empty array
2361
+ * 3) Array returns itself
2423
2362
  *
2424
- * @param markdown any valid markdown
2425
- * @returns code blocks with language and content
2426
- * @throws {ParseError} if block is not closed properly
2427
- * @public exported from `@promptbook/markdown-utils`
2363
+ * @private internal utility
2428
2364
  */
2429
- function extractAllBlocksFromMarkdown(markdown) {
2430
- var e_1, _a;
2431
- var codeBlocks = [];
2432
- var lines = markdown.split('\n');
2433
- // Note: [0] Ensure that the last block notated by gt > will be closed
2434
- lines.push('');
2435
- var currentCodeBlock = null;
2436
- try {
2437
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2438
- var line = lines_1_1.value;
2439
- if (line.startsWith('> ') || line === '>') {
2440
- if (currentCodeBlock === null) {
2441
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2442
- } /* not else */
2443
- if (currentCodeBlock.blockNotation === '>') {
2444
- if (currentCodeBlock.content !== '') {
2445
- currentCodeBlock.content += '\n';
2446
- }
2447
- currentCodeBlock.content += line.slice(2);
2448
- }
2449
- }
2450
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2451
- codeBlocks.push(currentCodeBlock);
2452
- currentCodeBlock = null;
2453
- }
2454
- /* not else */
2455
- if (line.startsWith('```')) {
2456
- var language = line.slice(3).trim() || null;
2457
- if (currentCodeBlock === null) {
2458
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2459
- }
2460
- else {
2461
- if (language !== null) {
2462
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2463
- }
2464
- codeBlocks.push(currentCodeBlock);
2465
- currentCodeBlock = null;
2466
- }
2467
- }
2468
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2469
- if (currentCodeBlock.content !== '') {
2470
- currentCodeBlock.content += '\n';
2471
- }
2472
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2473
- }
2474
- }
2475
- }
2476
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2477
- finally {
2478
- try {
2479
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2480
- }
2481
- finally { if (e_1) throw e_1.error; }
2365
+ function arrayableToArray(input) {
2366
+ if (input === undefined) {
2367
+ return [];
2482
2368
  }
2483
- if (currentCodeBlock !== null) {
2484
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2369
+ if (input instanceof Array) {
2370
+ return input;
2485
2371
  }
2486
- return codeBlocks;
2372
+ return [input];
2487
2373
  }
2488
- /**
2489
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2490
- */
2491
2374
 
2492
2375
  /**
2493
- * Extracts extracts exactly one valid JSON code block
2494
- *
2495
- * - When given string is a valid JSON as it is, it just returns it
2496
- * - When there is no JSON code block the function throws a `ParseError`
2497
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2376
+ * @@@
2498
2377
  *
2499
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2500
- * Note: There are multiple simmilar function:
2501
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2502
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2503
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2504
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2378
+ * @public exported from `@promptbook/utils`
2379
+ */
2380
+ function deepClone(objectValue) {
2381
+ return JSON.parse(JSON.stringify(objectValue));
2382
+ /*
2383
+ TODO: [🧠] Is there a better implementation?
2384
+ > const propertyNames = Object.getOwnPropertyNames(objectValue);
2385
+ > for (const propertyName of propertyNames) {
2386
+ > const value = (objectValue as really_any)[propertyName];
2387
+ > if (value && typeof value === 'object') {
2388
+ > deepClone(value);
2389
+ > }
2390
+ > }
2391
+ > return Object.assign({}, objectValue);
2392
+ */
2393
+ }
2394
+ /**
2395
+ * TODO: [🧠] Is there a way how to meaningfully test this utility
2396
+ */
2397
+
2398
+ /**
2399
+ * Function `addUsage` will add multiple usages into one
2505
2400
  *
2506
- * @public exported from `@promptbook/markdown-utils`
2507
- * @throws {ParseError} if there is no valid JSON block in the markdown
2401
+ * Note: If you provide 0 values, it returns ZERO_USAGE
2402
+ *
2403
+ * @public exported from `@promptbook/core`
2508
2404
  */
2509
- function extractJsonBlock(markdown) {
2510
- if (isValidJsonString(markdown)) {
2511
- return markdown;
2405
+ function addUsage() {
2406
+ var usageItems = [];
2407
+ for (var _i = 0; _i < arguments.length; _i++) {
2408
+ usageItems[_i] = arguments[_i];
2512
2409
  }
2513
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2514
- var jsonBlocks = codeBlocks.filter(function (_a) {
2515
- var content = _a.content;
2516
- return isValidJsonString(content);
2517
- });
2518
- if (jsonBlocks.length === 0) {
2519
- throw new Error('There is no valid JSON block in the markdown');
2410
+ return usageItems.reduce(function (acc, item) {
2411
+ var e_1, _a, e_2, _b;
2412
+ var _c;
2413
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
2414
+ try {
2415
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
2416
+ var key = _e.value;
2417
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2418
+ //@ts-ignore
2419
+ if (item.input[key]) {
2420
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2421
+ //@ts-ignore
2422
+ acc.input[key].value += item.input[key].value || 0;
2423
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2424
+ //@ts-ignore
2425
+ if (item.input[key].isUncertain) {
2426
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2427
+ //@ts-ignore
2428
+ acc.input[key].isUncertain = true;
2429
+ }
2430
+ }
2431
+ }
2432
+ }
2433
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2434
+ finally {
2435
+ try {
2436
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2437
+ }
2438
+ finally { if (e_1) throw e_1.error; }
2439
+ }
2440
+ try {
2441
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
2442
+ var key = _g.value;
2443
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2444
+ //@ts-ignore
2445
+ if (item.output[key]) {
2446
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2447
+ //@ts-ignore
2448
+ acc.output[key].value += item.output[key].value || 0;
2449
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2450
+ //@ts-ignore
2451
+ if (item.output[key].isUncertain) {
2452
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2453
+ //@ts-ignore
2454
+ acc.output[key].isUncertain = true;
2455
+ }
2456
+ }
2457
+ }
2458
+ }
2459
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2460
+ finally {
2461
+ try {
2462
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2463
+ }
2464
+ finally { if (e_2) throw e_2.error; }
2465
+ }
2466
+ return acc;
2467
+ }, deepClone(ZERO_USAGE));
2468
+ }
2469
+
2470
+ /**
2471
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2472
+ *
2473
+ * @param script from which to extract the variables
2474
+ * @returns the list of variable names
2475
+ * @throws {ParseError} if the script is invalid
2476
+ * @public exported from `@promptbook/utils`
2477
+ */
2478
+ function extractVariables(script) {
2479
+ var variables = new Set();
2480
+ script = "(()=>{".concat(script, "})()");
2481
+ try {
2482
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2483
+ try {
2484
+ eval(script);
2485
+ }
2486
+ catch (error) {
2487
+ if (!(error instanceof ReferenceError)) {
2488
+ throw error;
2489
+ }
2490
+ var undefinedName = error.message.split(' ')[0];
2491
+ /*
2492
+ Note: Parsing the error
2493
+ [PipelineUrlError: thing is not defined]
2494
+ */
2495
+ if (!undefinedName) {
2496
+ throw error;
2497
+ }
2498
+ if (script.includes(undefinedName + '(')) {
2499
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2500
+ }
2501
+ else {
2502
+ variables.add(undefinedName);
2503
+ script = "const ".concat(undefinedName, " = '';") + script;
2504
+ }
2505
+ }
2520
2506
  }
2521
- if (jsonBlocks.length > 1) {
2522
- throw new Error('There are multiple JSON code blocks in the markdown');
2507
+ catch (error) {
2508
+ if (!(error instanceof Error)) {
2509
+ throw error;
2510
+ }
2511
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2523
2512
  }
2524
- return jsonBlocks[0].content;
2513
+ return variables;
2525
2514
  }
2526
2515
  /**
2527
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2528
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2516
+ * TODO: [🔣] Support for multiple languages - python, java,...
2529
2517
  */
2530
2518
 
2531
2519
  /**
2532
- * Determine if the pipeline is fully prepared
2520
+ * Parses the template and returns the set of all used parameters
2521
+ *
2522
+ * @param template the template with used parameters
2523
+ * @returns the set of parameter names
2524
+ * @throws {ParseError} if the script is invalid
2525
+ * @public exported from `@promptbook/utils`
2526
+ */
2527
+ function extractParameterNamesFromTemplate(template) {
2528
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2529
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2530
+ var parameterNames = new Set();
2531
+ try {
2532
+ for (var _e = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _f = _e.next(); !_f.done; _f = _e.next()) {
2533
+ var parameterName = _f.value;
2534
+ parameterNames.add(parameterName);
2535
+ }
2536
+ }
2537
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2538
+ finally {
2539
+ try {
2540
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2541
+ }
2542
+ finally { if (e_1) throw e_1.error; }
2543
+ }
2544
+ if (templateType === 'SCRIPT_TEMPLATE') {
2545
+ try {
2546
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2547
+ var parameterName = _h.value;
2548
+ parameterNames.add(parameterName);
2549
+ }
2550
+ }
2551
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2552
+ finally {
2553
+ try {
2554
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2555
+ }
2556
+ finally { if (e_2) throw e_2.error; }
2557
+ }
2558
+ }
2559
+ try {
2560
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2561
+ var jokerName = _k.value;
2562
+ parameterNames.add(jokerName);
2563
+ }
2564
+ }
2565
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2566
+ finally {
2567
+ try {
2568
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2569
+ }
2570
+ finally { if (e_3) throw e_3.error; }
2571
+ }
2572
+ parameterNames.delete('content');
2573
+ // <- Note {websiteContent} is used in `preparedContent`
2574
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2575
+ if (foreach !== undefined) {
2576
+ try {
2577
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2578
+ var subparameterName = _m.value;
2579
+ if (parameterNames.has(subparameterName)) {
2580
+ parameterNames.delete(subparameterName);
2581
+ parameterNames.add(foreach.parameterName);
2582
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2583
+ }
2584
+ }
2585
+ }
2586
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2587
+ finally {
2588
+ try {
2589
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2590
+ }
2591
+ finally { if (e_4) throw e_4.error; }
2592
+ }
2593
+ }
2594
+ return parameterNames;
2595
+ }
2596
+ /**
2597
+ * TODO: [🔣] If script require contentLanguage
2598
+ */
2599
+
2600
+ /**
2601
+ * Create difference set of two sets.
2602
+ *
2603
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2604
+ * @public exported from `@promptbook/utils`
2605
+ */
2606
+ function difference(a, b, isEqual) {
2607
+ var e_1, _a;
2608
+ if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2609
+ var diff = new Set();
2610
+ var _loop_1 = function (itemA) {
2611
+ if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2612
+ diff.add(itemA);
2613
+ }
2614
+ };
2615
+ try {
2616
+ for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2617
+ var itemA = _c.value;
2618
+ _loop_1(itemA);
2619
+ }
2620
+ }
2621
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2622
+ finally {
2623
+ try {
2624
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2625
+ }
2626
+ finally { if (e_1) throw e_1.error; }
2627
+ }
2628
+ return diff;
2629
+ }
2630
+ /**
2631
+ * TODO: [🧠][💯] Maybe also implement symmetricDifference
2632
+ */
2633
+
2634
+ /**
2635
+ * Creates a new set with all elements that are present in either set
2636
+ *
2637
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2638
+ * @public exported from `@promptbook/utils`
2639
+ */
2640
+ function union() {
2641
+ var e_1, _a, e_2, _b;
2642
+ var sets = [];
2643
+ for (var _i = 0; _i < arguments.length; _i++) {
2644
+ sets[_i] = arguments[_i];
2645
+ }
2646
+ var union = new Set();
2647
+ try {
2648
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2649
+ var set = sets_1_1.value;
2650
+ try {
2651
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2652
+ var item = _d.value;
2653
+ union.add(item);
2654
+ }
2655
+ }
2656
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2657
+ finally {
2658
+ try {
2659
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2660
+ }
2661
+ finally { if (e_2) throw e_2.error; }
2662
+ }
2663
+ }
2664
+ }
2665
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2666
+ finally {
2667
+ try {
2668
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2669
+ }
2670
+ finally { if (e_1) throw e_1.error; }
2671
+ }
2672
+ return union;
2673
+ }
2674
+
2675
+ /**
2676
+ * Just marks a place of place where should be something implemented
2677
+ * No side effects.
2678
+ *
2679
+ * Note: It can be usefull suppressing eslint errors of unused variables
2680
+ *
2681
+ * @param value any values
2682
+ * @returns void
2683
+ * @private within the repository
2684
+ */
2685
+ function TODO_USE() {
2686
+ var value = [];
2687
+ for (var _i = 0; _i < arguments.length; _i++) {
2688
+ value[_i] = arguments[_i];
2689
+ }
2690
+ }
2691
+
2692
+ /**
2693
+ * @@@
2533
2694
  *
2534
2695
  * @public exported from `@promptbook/core`
2535
2696
  */
2536
- function isPipelinePrepared(pipeline) {
2537
- // Note: Ignoring `pipeline.preparations` @@@
2538
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2539
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2540
- return false;
2697
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2698
+ header: true,
2699
+ // encoding: 'utf8',
2700
+ });
2701
+
2702
+ /**
2703
+ * Definition for CSV spreadsheet
2704
+ *
2705
+ * @public exported from `@promptbook/core`
2706
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2707
+ */
2708
+ var CsvFormatDefinition = {
2709
+ formatName: 'CSV',
2710
+ aliases: ['SPREADSHEET', 'TABLE'],
2711
+ isValid: function (value, settings, schema) {
2712
+ // TODO: !!!!!! Implement CSV validation
2713
+ TODO_USE(value /* <- TODO: Use value here */);
2714
+ TODO_USE(settings /* <- TODO: Use settings here */);
2715
+ TODO_USE(schema /* <- TODO: Use schema here */);
2716
+ return true;
2717
+ },
2718
+ canBeValid: function (partialValue, settings, schema) {
2719
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2720
+ TODO_USE(settings /* <- TODO: Use settings here */);
2721
+ TODO_USE(schema /* <- TODO: Use schema here */);
2722
+ return true;
2723
+ },
2724
+ heal: function (value, settings, schema) {
2725
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2726
+ TODO_USE(settings /* <- TODO: Use settings here */);
2727
+ TODO_USE(schema /* <- TODO: Use schema here */);
2728
+ throw new Error('Not implemented');
2729
+ },
2730
+ subvalueDefinitions: [
2731
+ {
2732
+ subvalueName: 'ROW',
2733
+ mapValues: function (value, settings, mapCallback) {
2734
+ return __awaiter(this, void 0, void 0, function () {
2735
+ var csv, mappedData;
2736
+ var _this = this;
2737
+ return __generator(this, function (_a) {
2738
+ switch (_a.label) {
2739
+ case 0:
2740
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2741
+ if (csv.errors.length !== 0) {
2742
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2743
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2744
+ }
2745
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2746
+ var _a;
2747
+ var _b;
2748
+ return __generator(this, function (_c) {
2749
+ switch (_c.label) {
2750
+ case 0:
2751
+ _a = [__assign({}, row)];
2752
+ _b = {};
2753
+ // <- TODO: !!!!!! Dynamic new column name and position
2754
+ // <- TODO: !!!!!! Check name collisions
2755
+ return [4 /*yield*/, mapCallback(row, index)];
2756
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2757
+ // <- TODO: !!!!!! Dynamic new column name and position
2758
+ // <- TODO: !!!!!! Check name collisions
2759
+ _c.sent(), _b)])))];
2760
+ }
2761
+ });
2762
+ }); }))];
2763
+ case 1:
2764
+ mappedData = _a.sent();
2765
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2766
+ }
2767
+ });
2768
+ });
2769
+ },
2770
+ },
2771
+ {
2772
+ subvalueName: 'CELL',
2773
+ mapValues: function (value, settings, mapCallback) {
2774
+ return __awaiter(this, void 0, void 0, function () {
2775
+ var csv, mappedData;
2776
+ var _this = this;
2777
+ return __generator(this, function (_a) {
2778
+ switch (_a.label) {
2779
+ case 0:
2780
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2781
+ if (csv.errors.length !== 0) {
2782
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2783
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2784
+ }
2785
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2786
+ var _this = this;
2787
+ return __generator(this, function (_a) {
2788
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2789
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2790
+ return __awaiter(_this, void 0, void 0, function () {
2791
+ var index;
2792
+ var _c;
2793
+ return __generator(this, function (_d) {
2794
+ index = rowIndex * Object.keys(row).length + columnIndex;
2795
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2796
+ });
2797
+ });
2798
+ }))];
2799
+ });
2800
+ }); }))];
2801
+ case 1:
2802
+ mappedData = _a.sent();
2803
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2804
+ }
2805
+ });
2806
+ });
2807
+ },
2808
+ },
2809
+ ],
2810
+ };
2811
+ /**
2812
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2813
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2814
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2815
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2816
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2817
+ */
2818
+
2819
+ /**
2820
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2821
+ *
2822
+ * @public exported from `@promptbook/utils`
2823
+ */
2824
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2825
+ try {
2826
+ JSON.parse(value);
2827
+ return true;
2541
2828
  }
2542
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2829
+ catch (error) {
2830
+ if (!(error instanceof Error)) {
2831
+ throw error;
2832
+ }
2833
+ if (error.message.includes('Unexpected token')) {
2834
+ return false;
2835
+ }
2543
2836
  return false;
2544
2837
  }
2545
- /*
2546
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2547
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2548
- > return false;
2549
- > }
2550
- */
2551
- return true;
2552
2838
  }
2839
+
2553
2840
  /**
2554
- * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2555
- * TODO: [🐠] Maybe base this on `makeValidator`
2556
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2557
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2558
- * - [🏍] ? Is context in each template
2559
- * - [♨] Are samples prepared
2560
- * - [♨] Are templates prepared
2841
+ * Definition for JSON format
2842
+ *
2843
+ * @private still in development [🏢]
2844
+ */
2845
+ var JsonFormatDefinition = {
2846
+ formatName: 'JSON',
2847
+ mimeType: 'application/json',
2848
+ isValid: function (value, settings, schema) {
2849
+ TODO_USE(schema /* <- TODO: Use schema here */);
2850
+ TODO_USE(settings /* <- TODO: Use settings here */);
2851
+ return isValidJsonString(value);
2852
+ },
2853
+ canBeValid: function (partialValue, settings, schema) {
2854
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2855
+ TODO_USE(settings /* <- TODO: Use settings here */);
2856
+ TODO_USE(schema /* <- TODO: Use schema here */);
2857
+ return true;
2858
+ },
2859
+ heal: function (value, settings, schema) {
2860
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2861
+ TODO_USE(settings /* <- TODO: Use settings here */);
2862
+ TODO_USE(schema /* <- TODO: Use schema here */);
2863
+ throw new Error('Not implemented');
2864
+ },
2865
+ subvalueDefinitions: [],
2866
+ };
2867
+ /**
2868
+ * TODO: [🧠] Maybe propper instance of object
2869
+ * TODO: [0] Make string_serialized_json
2870
+ * TODO: [1] Make type for JSON Settings and Schema
2871
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2872
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2873
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2874
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2875
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2876
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2877
+ */
2878
+
2879
+ /**
2880
+ * Definition for any text - this will be always valid
2881
+ *
2882
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
2883
+ *
2884
+ * @public exported from `@promptbook/core`
2885
+ */
2886
+ var TextFormatDefinition = {
2887
+ formatName: 'TEXT',
2888
+ isValid: function (value) {
2889
+ return typeof value === 'string';
2890
+ },
2891
+ canBeValid: function (partialValue) {
2892
+ return typeof partialValue === 'string';
2893
+ },
2894
+ heal: function () {
2895
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
2896
+ },
2897
+ subvalueDefinitions: [
2898
+ {
2899
+ subvalueName: 'LINE',
2900
+ mapValues: function (value, settings, mapCallback) {
2901
+ return __awaiter(this, void 0, void 0, function () {
2902
+ var lines, mappedLines;
2903
+ return __generator(this, function (_a) {
2904
+ switch (_a.label) {
2905
+ case 0:
2906
+ lines = value.split('\n');
2907
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
2908
+ // TODO: [🧠] Maybe option to skip empty line
2909
+ /* not await */ return mapCallback({
2910
+ lineContent: lineContent,
2911
+ // TODO: [🧠] Maybe also put here `lineNumber`
2912
+ }, lineNumber);
2913
+ }))];
2914
+ case 1:
2915
+ mappedLines = _a.sent();
2916
+ return [2 /*return*/, mappedLines.join('\n')];
2917
+ }
2918
+ });
2919
+ });
2920
+ },
2921
+ },
2922
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2923
+ ],
2924
+ };
2925
+ /**
2926
+ * TODO: [1] Make type for XML Text and Schema
2927
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2928
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
2929
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
2930
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
2931
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
2932
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
2933
+ */
2934
+
2935
+ /**
2936
+ * Definition for XML format
2937
+ *
2938
+ * @private still in development [🏢]
2939
+ */
2940
+ var XmlFormatDefinition = {
2941
+ formatName: 'XML',
2942
+ mimeType: 'application/xml',
2943
+ isValid: function (value, settings, schema) {
2944
+ TODO_USE(value /* <- TODO: Use value here */);
2945
+ TODO_USE(settings /* <- TODO: Use settings here */);
2946
+ TODO_USE(schema /* <- TODO: Use schema here */);
2947
+ return true;
2948
+ },
2949
+ canBeValid: function (partialValue, settings, schema) {
2950
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2951
+ TODO_USE(settings /* <- TODO: Use settings here */);
2952
+ TODO_USE(schema /* <- TODO: Use schema here */);
2953
+ return true;
2954
+ },
2955
+ heal: function (value, settings, schema) {
2956
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2957
+ TODO_USE(settings /* <- TODO: Use settings here */);
2958
+ TODO_USE(schema /* <- TODO: Use schema here */);
2959
+ throw new Error('Not implemented');
2960
+ },
2961
+ subvalueDefinitions: [],
2962
+ };
2963
+ /**
2964
+ * TODO: [🧠] Maybe propper instance of object
2965
+ * TODO: [0] Make string_serialized_xml
2966
+ * TODO: [1] Make type for XML Settings and Schema
2967
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
2968
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
2969
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
2970
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
2971
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
2972
+ * TODO: [🏢] Allow to expect something inside XML and other formats
2973
+ */
2974
+
2975
+ /**
2976
+ * Definitions for all formats supported by Promptbook
2977
+ *
2978
+ * @private internal index of `...` <- TODO [🏢]
2979
+ */
2980
+ var FORMAT_DEFINITIONS = [
2981
+ JsonFormatDefinition,
2982
+ XmlFormatDefinition,
2983
+ TextFormatDefinition,
2984
+ CsvFormatDefinition,
2985
+ ];
2986
+
2987
+ /**
2988
+ * Maps available parameters to expected parameters
2989
+ *
2990
+ * The strategy is:
2991
+ * 1) @@@
2992
+ * 2) @@@
2993
+ *
2994
+ * @throws {PipelineExecutionError} @@@
2995
+ * @private within the repository used in `createPipelineExecutor`
2996
+ */
2997
+ function mapAvailableToExpectedParameters(options) {
2998
+ var e_1, _a;
2999
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3000
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3001
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3002
+ var mappedParameters = {};
3003
+ try {
3004
+ // Phase 1️⃣: Matching mapping
3005
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3006
+ var parameterName = _c.value;
3007
+ // Situation: Parameter is available and expected
3008
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3009
+ mappedParameters[parameterName] = availableParameters[parameterName];
3010
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3011
+ availableParametersNames.delete(parameterName);
3012
+ expectedParameterNames.delete(parameterName);
3013
+ }
3014
+ // Situation: Parameter is available but NOT expected
3015
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3016
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3017
+ }
3018
+ // Situation: Parameter is NOT available BUT expected
3019
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3020
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3021
+ }
3022
+ }
3023
+ }
3024
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3025
+ finally {
3026
+ try {
3027
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3028
+ }
3029
+ finally { if (e_1) throw e_1.error; }
3030
+ }
3031
+ if (expectedParameterNames.size === 0) {
3032
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3033
+ Object.freeze(mappedParameters);
3034
+ return mappedParameters;
3035
+ }
3036
+ // Phase 2️⃣: Non-matching mapping
3037
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3038
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3039
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3040
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3041
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3042
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3043
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3044
+ .join('\n')), "\n\n "); }));
3045
+ }
3046
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3047
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3048
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3049
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3050
+ }
3051
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3052
+ Object.freeze(mappedParameters);
3053
+ return mappedParameters;
3054
+ }
3055
+
3056
+ /**
3057
+ * Extracts all code blocks from markdown.
3058
+ *
3059
+ * Note: There are multiple simmilar function:
3060
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3061
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3062
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3063
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3064
+ *
3065
+ * @param markdown any valid markdown
3066
+ * @returns code blocks with language and content
3067
+ * @throws {ParseError} if block is not closed properly
3068
+ * @public exported from `@promptbook/markdown-utils`
3069
+ */
3070
+ function extractAllBlocksFromMarkdown(markdown) {
3071
+ var e_1, _a;
3072
+ var codeBlocks = [];
3073
+ var lines = markdown.split('\n');
3074
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3075
+ lines.push('');
3076
+ var currentCodeBlock = null;
3077
+ try {
3078
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3079
+ var line = lines_1_1.value;
3080
+ if (line.startsWith('> ') || line === '>') {
3081
+ if (currentCodeBlock === null) {
3082
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3083
+ } /* not else */
3084
+ if (currentCodeBlock.blockNotation === '>') {
3085
+ if (currentCodeBlock.content !== '') {
3086
+ currentCodeBlock.content += '\n';
3087
+ }
3088
+ currentCodeBlock.content += line.slice(2);
3089
+ }
3090
+ }
3091
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3092
+ codeBlocks.push(currentCodeBlock);
3093
+ currentCodeBlock = null;
3094
+ }
3095
+ /* not else */
3096
+ if (line.startsWith('```')) {
3097
+ var language = line.slice(3).trim() || null;
3098
+ if (currentCodeBlock === null) {
3099
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3100
+ }
3101
+ else {
3102
+ if (language !== null) {
3103
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3104
+ }
3105
+ codeBlocks.push(currentCodeBlock);
3106
+ currentCodeBlock = null;
3107
+ }
3108
+ }
3109
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3110
+ if (currentCodeBlock.content !== '') {
3111
+ currentCodeBlock.content += '\n';
3112
+ }
3113
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3114
+ }
3115
+ }
3116
+ }
3117
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3118
+ finally {
3119
+ try {
3120
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3121
+ }
3122
+ finally { if (e_1) throw e_1.error; }
3123
+ }
3124
+ if (currentCodeBlock !== null) {
3125
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3126
+ }
3127
+ return codeBlocks;
3128
+ }
3129
+ /**
3130
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2561
3131
  */
2562
3132
 
2563
3133
  /**
2564
- * Takes an item or an array of items and returns an array of items
3134
+ * Extracts extracts exactly one valid JSON code block
2565
3135
  *
2566
- * 1) Any item except array and undefined returns array with that one item (also null)
2567
- * 2) Undefined returns empty array
2568
- * 3) Array returns itself
3136
+ * - When given string is a valid JSON as it is, it just returns it
3137
+ * - When there is no JSON code block the function throws a `ParseError`
3138
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
2569
3139
  *
2570
- * @private internal utility
3140
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3141
+ * Note: There are multiple simmilar function:
3142
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3143
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3144
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3145
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3146
+ *
3147
+ * @public exported from `@promptbook/markdown-utils`
3148
+ * @throws {ParseError} if there is no valid JSON block in the markdown
2571
3149
  */
2572
- function arrayableToArray(input) {
2573
- if (input === undefined) {
2574
- return [];
3150
+ function extractJsonBlock(markdown) {
3151
+ if (isValidJsonString(markdown)) {
3152
+ return markdown;
2575
3153
  }
2576
- if (input instanceof Array) {
2577
- return input;
3154
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3155
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3156
+ var content = _a.content;
3157
+ return isValidJsonString(content);
3158
+ });
3159
+ if (jsonBlocks.length === 0) {
3160
+ throw new Error('There is no valid JSON block in the markdown');
2578
3161
  }
2579
- return [input];
3162
+ if (jsonBlocks.length > 1) {
3163
+ throw new Error('There are multiple JSON code blocks in the markdown');
3164
+ }
3165
+ return jsonBlocks[0].content;
2580
3166
  }
3167
+ /**
3168
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3169
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3170
+ */
2581
3171
 
2582
3172
  /**
2583
3173
  * Just says that the variable is not used but should be kept
@@ -2600,23 +3190,6 @@
2600
3190
  }
2601
3191
  }
2602
3192
 
2603
- /**
2604
- * Just marks a place of place where should be something implemented
2605
- * No side effects.
2606
- *
2607
- * Note: It can be usefull suppressing eslint errors of unused variables
2608
- *
2609
- * @param value any values
2610
- * @returns void
2611
- * @private within the repository
2612
- */
2613
- function TODO_USE() {
2614
- var value = [];
2615
- for (var _i = 0; _i < arguments.length; _i++) {
2616
- value[_i] = arguments[_i];
2617
- }
2618
- }
2619
-
2620
3193
  /**
2621
3194
  * Replaces parameters in template with values from parameters object
2622
3195
  *
@@ -2663,207 +3236,37 @@
2663
3236
  throw new PipelineExecutionError('Parameter is already opened or not closed');
2664
3237
  }
2665
3238
  if (parameters[parameterName] === undefined) {
2666
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2667
- }
2668
- var parameterValue = parameters[parameterName];
2669
- if (parameterValue === undefined) {
2670
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2671
- }
2672
- parameterValue = parameterValue.toString();
2673
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2674
- parameterValue = parameterValue
2675
- .split('\n')
2676
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2677
- .join('\n');
2678
- }
2679
- replacedTemplate =
2680
- replacedTemplate.substring(0, match.index + precol.length) +
2681
- parameterValue +
2682
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2683
- };
2684
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2685
- .exec(replacedTemplate))) {
2686
- _loop_1();
2687
- }
2688
- // [💫] Check if there are parameters that are not closed properly
2689
- if (/{\w+$/.test(replacedTemplate)) {
2690
- throw new PipelineExecutionError('Parameter is not closed');
2691
- }
2692
- // [💫] Check if there are parameters that are not opened properly
2693
- if (/^\w+}/.test(replacedTemplate)) {
2694
- throw new PipelineExecutionError('Parameter is not opened');
2695
- }
2696
- return replacedTemplate;
2697
- }
2698
-
2699
- /**
2700
- * Create difference set of two sets.
2701
- *
2702
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2703
- * @public exported from `@promptbook/utils`
2704
- */
2705
- function difference(a, b, isEqual) {
2706
- var e_1, _a;
2707
- if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2708
- var diff = new Set();
2709
- var _loop_1 = function (itemA) {
2710
- if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2711
- diff.add(itemA);
2712
- }
2713
- };
2714
- try {
2715
- for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2716
- var itemA = _c.value;
2717
- _loop_1(itemA);
2718
- }
2719
- }
2720
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2721
- finally {
2722
- try {
2723
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2724
- }
2725
- finally { if (e_1) throw e_1.error; }
2726
- }
2727
- return diff;
2728
- }
2729
- /**
2730
- * TODO: [🧠][💯] Maybe also implement symmetricDifference
2731
- */
2732
-
2733
- /**
2734
- * Creates a new set with all elements that are present in either set
2735
- *
2736
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2737
- * @public exported from `@promptbook/utils`
2738
- */
2739
- function union() {
2740
- var e_1, _a, e_2, _b;
2741
- var sets = [];
2742
- for (var _i = 0; _i < arguments.length; _i++) {
2743
- sets[_i] = arguments[_i];
2744
- }
2745
- var union = new Set();
2746
- try {
2747
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2748
- var set = sets_1_1.value;
2749
- try {
2750
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2751
- var item = _d.value;
2752
- union.add(item);
2753
- }
2754
- }
2755
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2756
- finally {
2757
- try {
2758
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2759
- }
2760
- finally { if (e_2) throw e_2.error; }
2761
- }
2762
- }
2763
- }
2764
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2765
- finally {
2766
- try {
2767
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2768
- }
2769
- finally { if (e_1) throw e_1.error; }
2770
- }
2771
- return union;
2772
- }
2773
-
2774
- /**
2775
- * @@@
2776
- *
2777
- * @public exported from `@promptbook/utils`
2778
- */
2779
- function deepClone(objectValue) {
2780
- return JSON.parse(JSON.stringify(objectValue));
2781
- /*
2782
- TODO: [🧠] Is there a better implementation?
2783
- > const propertyNames = Object.getOwnPropertyNames(objectValue);
2784
- > for (const propertyName of propertyNames) {
2785
- > const value = (objectValue as really_any)[propertyName];
2786
- > if (value && typeof value === 'object') {
2787
- > deepClone(value);
2788
- > }
2789
- > }
2790
- > return Object.assign({}, objectValue);
2791
- */
2792
- }
2793
- /**
2794
- * TODO: [🧠] Is there a way how to meaningfully test this utility
2795
- */
2796
-
2797
- /**
2798
- * Function `addUsage` will add multiple usages into one
2799
- *
2800
- * Note: If you provide 0 values, it returns ZERO_USAGE
2801
- *
2802
- * @public exported from `@promptbook/core`
2803
- */
2804
- function addUsage() {
2805
- var usageItems = [];
2806
- for (var _i = 0; _i < arguments.length; _i++) {
2807
- usageItems[_i] = arguments[_i];
2808
- }
2809
- return usageItems.reduce(function (acc, item) {
2810
- var e_1, _a, e_2, _b;
2811
- var _c;
2812
- acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
2813
- try {
2814
- for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
2815
- var key = _e.value;
2816
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2817
- //@ts-ignore
2818
- if (item.input[key]) {
2819
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2820
- //@ts-ignore
2821
- acc.input[key].value += item.input[key].value || 0;
2822
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2823
- //@ts-ignore
2824
- if (item.input[key].isUncertain) {
2825
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2826
- //@ts-ignore
2827
- acc.input[key].isUncertain = true;
2828
- }
2829
- }
2830
- }
2831
- }
2832
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2833
- finally {
2834
- try {
2835
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2836
- }
2837
- finally { if (e_1) throw e_1.error; }
2838
- }
2839
- try {
2840
- for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
2841
- var key = _g.value;
2842
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2843
- //@ts-ignore
2844
- if (item.output[key]) {
2845
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2846
- //@ts-ignore
2847
- acc.output[key].value += item.output[key].value || 0;
2848
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2849
- //@ts-ignore
2850
- if (item.output[key].isUncertain) {
2851
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2852
- //@ts-ignore
2853
- acc.output[key].isUncertain = true;
2854
- }
2855
- }
2856
- }
3239
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2857
3240
  }
2858
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2859
- finally {
2860
- try {
2861
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2862
- }
2863
- finally { if (e_2) throw e_2.error; }
3241
+ var parameterValue = parameters[parameterName];
3242
+ if (parameterValue === undefined) {
3243
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2864
3244
  }
2865
- return acc;
2866
- }, deepClone(ZERO_USAGE));
3245
+ parameterValue = parameterValue.toString();
3246
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3247
+ parameterValue = parameterValue
3248
+ .split('\n')
3249
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3250
+ .join('\n');
3251
+ }
3252
+ replacedTemplate =
3253
+ replacedTemplate.substring(0, match.index + precol.length) +
3254
+ parameterValue +
3255
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3256
+ };
3257
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3258
+ .exec(replacedTemplate))) {
3259
+ _loop_1();
3260
+ }
3261
+ // [💫] Check if there are parameters that are not closed properly
3262
+ if (/{\w+$/.test(replacedTemplate)) {
3263
+ throw new PipelineExecutionError('Parameter is not closed');
3264
+ }
3265
+ // [💫] Check if there are parameters that are not opened properly
3266
+ if (/^\w+}/.test(replacedTemplate)) {
3267
+ throw new PipelineExecutionError('Parameter is not opened');
3268
+ }
3269
+ return replacedTemplate;
2867
3270
  }
2868
3271
 
2869
3272
  /**
@@ -2932,53 +3335,780 @@
2932
3335
  }
2933
3336
 
2934
3337
  /**
2935
- * Counts number of words in the text
3338
+ * Counts number of words in the text
3339
+ *
3340
+ * @public exported from `@promptbook/utils`
3341
+ */
3342
+ function countWords(text) {
3343
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3344
+ text = removeDiacritics(text);
3345
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3346
+ }
3347
+
3348
+ /**
3349
+ * Index of all counter functions
3350
+ *
3351
+ * @public exported from `@promptbook/utils`
3352
+ */
3353
+ var CountUtils = {
3354
+ CHARACTERS: countCharacters,
3355
+ WORDS: countWords,
3356
+ SENTENCES: countSentences,
3357
+ PARAGRAPHS: countParagraphs,
3358
+ LINES: countLines,
3359
+ PAGES: countPages,
3360
+ };
3361
+ /**
3362
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3363
+ */
3364
+
3365
+ /**
3366
+ * Function checkExpectations will check if the expectations on given value are met
3367
+ *
3368
+ * Note: There are two simmilar functions:
3369
+ * - `checkExpectations` which throws an error if the expectations are not met
3370
+ * - `isPassingExpectations` which returns a boolean
3371
+ *
3372
+ * @throws {ExpectError} if the expectations are not met
3373
+ * @returns {void} Nothing
3374
+ * @private internal function of `createPipelineExecutor`
3375
+ */
3376
+ function checkExpectations(expectations, value) {
3377
+ var e_1, _a;
3378
+ try {
3379
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3380
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3381
+ var amount = CountUtils[unit.toUpperCase()](value);
3382
+ if (min && amount < min) {
3383
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3384
+ } /* not else */
3385
+ if (max && amount > max) {
3386
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3387
+ }
3388
+ }
3389
+ }
3390
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3391
+ finally {
3392
+ try {
3393
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3394
+ }
3395
+ finally { if (e_1) throw e_1.error; }
3396
+ }
3397
+ }
3398
+ /**
3399
+ * TODO: [💝] Unite object for expecting amount and format
3400
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3401
+ * Note: [💝] and [🤠] are interconnected together
3402
+ */
3403
+
3404
+ /**
3405
+ * @@@
3406
+ *
3407
+ * @private internal utility of `createPipelineExecutor`
3408
+ */
3409
+ function executeAttempts(options) {
3410
+ return __awaiter(this, void 0, void 0, function () {
3411
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3412
+ return __generator(this, function (_a) {
3413
+ switch (_a.label) {
3414
+ case 0:
3415
+ jokerParameterNames = options.jokerParameterNames, priority = options.priority, maxAttempts = options.maxAttempts, preparedContent = options.preparedContent, parameters = options.parameters, template = options.template, preparedPipeline = options.preparedPipeline, tools = options.tools, llmTools = options.llmTools, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3416
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3417
+ $ongoingTemplateResult = {
3418
+ $result: null,
3419
+ $resultString: null,
3420
+ $expectError: null,
3421
+ $scriptPipelineExecutionErrors: [],
3422
+ };
3423
+ _loop_1 = function (attempt) {
3424
+ var isJokerAttempt, jokerParameterName, _b, modelRequirements, _c, _d, _e, _f, _g, scriptTools, _h, error_1, e_1_1, _j, _k, _l, functionName, postprocessingError, _m, _o, scriptTools, _p, error_2, e_2_1, e_3_1, error_3;
3425
+ var e_1, _q, e_3, _r, e_2, _s;
3426
+ return __generator(this, function (_t) {
3427
+ switch (_t.label) {
3428
+ case 0:
3429
+ isJokerAttempt = attempt < 0;
3430
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3431
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3432
+ if (isJokerAttempt && !jokerParameterName) {
3433
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3434
+ }
3435
+ $ongoingTemplateResult.$result = null;
3436
+ $ongoingTemplateResult.$resultString = null;
3437
+ $ongoingTemplateResult.$expectError = null;
3438
+ if (isJokerAttempt) {
3439
+ if (parameters[jokerParameterName] === undefined) {
3440
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3441
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3442
+ }
3443
+ else {
3444
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3445
+ }
3446
+ }
3447
+ _t.label = 1;
3448
+ case 1:
3449
+ _t.trys.push([1, 43, 44, 45]);
3450
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3451
+ _b = template.templateType;
3452
+ switch (_b) {
3453
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3454
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3455
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3456
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3457
+ }
3458
+ return [3 /*break*/, 24];
3459
+ case 2:
3460
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3461
+ return [3 /*break*/, 25];
3462
+ case 3:
3463
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3464
+ $ongoingTemplateResult.$prompt = {
3465
+ title: template.title,
3466
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3467
+ ? preparedPipeline.pipelineUrl
3468
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3469
+ parameters: parameters,
3470
+ content: preparedContent,
3471
+ modelRequirements: modelRequirements,
3472
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3473
+ var name = _a.name;
3474
+ return name === template.personaName;
3475
+ }) ||
3476
+ {})), template.expectations),
3477
+ format: template.format,
3478
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3479
+ }; // <- TODO: Not very good type guard
3480
+ _c = modelRequirements.modelVariant;
3481
+ switch (_c) {
3482
+ case 'CHAT': return [3 /*break*/, 4];
3483
+ case 'COMPLETION': return [3 /*break*/, 6];
3484
+ case 'EMBEDDING': return [3 /*break*/, 8];
3485
+ }
3486
+ return [3 /*break*/, 9];
3487
+ case 4:
3488
+ _d = $ongoingTemplateResult;
3489
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3490
+ case 5:
3491
+ _d.$chatResult = _t.sent();
3492
+ // TODO: [🍬] Destroy chatThread
3493
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3494
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3495
+ return [3 /*break*/, 10];
3496
+ case 6:
3497
+ _e = $ongoingTemplateResult;
3498
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3499
+ case 7:
3500
+ _e.$completionResult = _t.sent();
3501
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3502
+ $ongoingTemplateResult.$resultString =
3503
+ $ongoingTemplateResult.$completionResult.content;
3504
+ return [3 /*break*/, 10];
3505
+ case 8: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Embedding model can not be used in pipeline\n\n This should be catched during parsing\n\n ".concat(block(pipelineIdentification), "\n\n "); }));
3506
+ case 9: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3507
+ case 10: return [3 /*break*/, 25];
3508
+ case 11:
3509
+ if (arrayableToArray(tools.script).length === 0) {
3510
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3511
+ }
3512
+ if (!template.contentLanguage) {
3513
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3514
+ }
3515
+ _t.label = 12;
3516
+ case 12:
3517
+ _t.trys.push([12, 19, 20, 21]);
3518
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3519
+ _t.label = 13;
3520
+ case 13:
3521
+ if (!!_g.done) return [3 /*break*/, 18];
3522
+ scriptTools = _g.value;
3523
+ _t.label = 14;
3524
+ case 14:
3525
+ _t.trys.push([14, 16, , 17]);
3526
+ _h = $ongoingTemplateResult;
3527
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3528
+ scriptLanguage: template.contentLanguage,
3529
+ script: preparedContent,
3530
+ parameters: parameters,
3531
+ }))];
3532
+ case 15:
3533
+ _h.$resultString = _t.sent();
3534
+ return [3 /*break*/, 18];
3535
+ case 16:
3536
+ error_1 = _t.sent();
3537
+ if (!(error_1 instanceof Error)) {
3538
+ throw error_1;
3539
+ }
3540
+ if (error_1 instanceof UnexpectedError) {
3541
+ throw error_1;
3542
+ }
3543
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3544
+ return [3 /*break*/, 17];
3545
+ case 17:
3546
+ _g = _f.next();
3547
+ return [3 /*break*/, 13];
3548
+ case 18: return [3 /*break*/, 21];
3549
+ case 19:
3550
+ e_1_1 = _t.sent();
3551
+ e_1 = { error: e_1_1 };
3552
+ return [3 /*break*/, 21];
3553
+ case 20:
3554
+ try {
3555
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3556
+ }
3557
+ finally { if (e_1) throw e_1.error; }
3558
+ return [7 /*endfinally*/];
3559
+ case 21:
3560
+ if ($ongoingTemplateResult.$resultString !== null) {
3561
+ return [3 /*break*/, 25];
3562
+ }
3563
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3564
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3565
+ }
3566
+ else {
3567
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3568
+ .map(function (error) { return '- ' + error.message; })
3569
+ .join('\n\n')), "\n "); }));
3570
+ }
3571
+ case 22:
3572
+ if (tools.userInterface === undefined) {
3573
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3574
+ }
3575
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3576
+ _j = $ongoingTemplateResult;
3577
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3578
+ promptTitle: template.title,
3579
+ promptMessage: replaceParameters(template.description || '', parameters),
3580
+ defaultValue: replaceParameters(preparedContent, parameters),
3581
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3582
+ placeholder: undefined,
3583
+ priority: priority,
3584
+ }))];
3585
+ case 23:
3586
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3587
+ _j.$resultString = _t.sent();
3588
+ return [3 /*break*/, 25];
3589
+ case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3590
+ case 25:
3591
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3592
+ _t.label = 26;
3593
+ case 26:
3594
+ _t.trys.push([26, 40, 41, 42]);
3595
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3596
+ _t.label = 27;
3597
+ case 27:
3598
+ if (!!_l.done) return [3 /*break*/, 39];
3599
+ functionName = _l.value;
3600
+ postprocessingError = null;
3601
+ _t.label = 28;
3602
+ case 28:
3603
+ _t.trys.push([28, 35, 36, 37]);
3604
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3605
+ _t.label = 29;
3606
+ case 29:
3607
+ if (!!_o.done) return [3 /*break*/, 34];
3608
+ scriptTools = _o.value;
3609
+ _t.label = 30;
3610
+ case 30:
3611
+ _t.trys.push([30, 32, , 33]);
3612
+ _p = $ongoingTemplateResult;
3613
+ return [4 /*yield*/, scriptTools.execute({
3614
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3615
+ script: "".concat(functionName, "(resultString)"),
3616
+ parameters: {
3617
+ resultString: $ongoingTemplateResult.$resultString || '',
3618
+ // Note: No ...parametersForTemplate, because working with result only
3619
+ },
3620
+ })];
3621
+ case 31:
3622
+ _p.$resultString = _t.sent();
3623
+ postprocessingError = null;
3624
+ return [3 /*break*/, 34];
3625
+ case 32:
3626
+ error_2 = _t.sent();
3627
+ if (!(error_2 instanceof Error)) {
3628
+ throw error_2;
3629
+ }
3630
+ if (error_2 instanceof UnexpectedError) {
3631
+ throw error_2;
3632
+ }
3633
+ postprocessingError = error_2;
3634
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3635
+ return [3 /*break*/, 33];
3636
+ case 33:
3637
+ _o = _m.next();
3638
+ return [3 /*break*/, 29];
3639
+ case 34: return [3 /*break*/, 37];
3640
+ case 35:
3641
+ e_2_1 = _t.sent();
3642
+ e_2 = { error: e_2_1 };
3643
+ return [3 /*break*/, 37];
3644
+ case 36:
3645
+ try {
3646
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3647
+ }
3648
+ finally { if (e_2) throw e_2.error; }
3649
+ return [7 /*endfinally*/];
3650
+ case 37:
3651
+ if (postprocessingError) {
3652
+ throw postprocessingError;
3653
+ }
3654
+ _t.label = 38;
3655
+ case 38:
3656
+ _l = _k.next();
3657
+ return [3 /*break*/, 27];
3658
+ case 39: return [3 /*break*/, 42];
3659
+ case 40:
3660
+ e_3_1 = _t.sent();
3661
+ e_3 = { error: e_3_1 };
3662
+ return [3 /*break*/, 42];
3663
+ case 41:
3664
+ try {
3665
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3666
+ }
3667
+ finally { if (e_3) throw e_3.error; }
3668
+ return [7 /*endfinally*/];
3669
+ case 42:
3670
+ // TODO: [💝] Unite object for expecting amount and format
3671
+ if (template.format) {
3672
+ if (template.format === 'JSON') {
3673
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3674
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3675
+ try {
3676
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3677
+ }
3678
+ catch (error) {
3679
+ keepUnused(error);
3680
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3681
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3682
+ }
3683
+ }
3684
+ }
3685
+ else {
3686
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3687
+ }
3688
+ }
3689
+ // TODO: [💝] Unite object for expecting amount and format
3690
+ if (template.expectations) {
3691
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3692
+ }
3693
+ return [2 /*return*/, "break-attempts"];
3694
+ case 43:
3695
+ error_3 = _t.sent();
3696
+ if (!(error_3 instanceof ExpectError)) {
3697
+ throw error_3;
3698
+ }
3699
+ $ongoingTemplateResult.$expectError = error_3;
3700
+ return [3 /*break*/, 45];
3701
+ case 44:
3702
+ if (!isJokerAttempt &&
3703
+ template.templateType === 'PROMPT_TEMPLATE' &&
3704
+ $ongoingTemplateResult.$prompt
3705
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3706
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3707
+ ) {
3708
+ // TODO: [🧠] Maybe put other templateTypes into report
3709
+ $executionReport.promptExecutions.push({
3710
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3711
+ result: $ongoingTemplateResult.$result || undefined,
3712
+ error: $ongoingTemplateResult.$expectError === null
3713
+ ? undefined
3714
+ : serializeError($ongoingTemplateResult.$expectError),
3715
+ });
3716
+ }
3717
+ return [7 /*endfinally*/];
3718
+ case 45:
3719
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3720
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3721
+ var _a, _b, _c;
3722
+ return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block((((_a = $ongoingTemplateResult.$prompt) === null || _a === void 0 ? void 0 : _a.content) || '')
3723
+ .split('\n')
3724
+ .map(function (line) { return "> ".concat(line); })
3725
+ .join('\n')), "\n\n Last error ").concat(((_b = $ongoingTemplateResult.$expectError) === null || _b === void 0 ? void 0 : _b.name) || '', ":\n ").concat(block((((_c = $ongoingTemplateResult.$expectError) === null || _c === void 0 ? void 0 : _c.message) || '')
3726
+ .split('\n')
3727
+ .map(function (line) { return "> ".concat(line); })
3728
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3729
+ ? 'null'
3730
+ : $ongoingTemplateResult.$resultString
3731
+ .split('\n')
3732
+ .map(function (line) { return "> ".concat(line); })
3733
+ .join('\n')), "\n ---\n ");
3734
+ }));
3735
+ }
3736
+ return [2 /*return*/];
3737
+ }
3738
+ });
3739
+ };
3740
+ attempt = -jokerParameterNames.length;
3741
+ _a.label = 1;
3742
+ case 1:
3743
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3744
+ return [5 /*yield**/, _loop_1(attempt)];
3745
+ case 2:
3746
+ state_1 = _a.sent();
3747
+ switch (state_1) {
3748
+ case "break-attempts": return [3 /*break*/, 4];
3749
+ }
3750
+ _a.label = 3;
3751
+ case 3:
3752
+ attempt++;
3753
+ return [3 /*break*/, 1];
3754
+ case 4:
3755
+ if ($ongoingTemplateResult.$resultString === null) {
3756
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3757
+ }
3758
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3759
+ }
3760
+ });
3761
+ });
3762
+ }
3763
+ /**
3764
+ * TODO: Break into smaller functions
3765
+ */
3766
+
3767
+ /**
3768
+ * @@@
3769
+ *
3770
+ * @private internal utility of `createPipelineExecutor`
3771
+ */
3772
+ function executeFormatCells(options) {
3773
+ return __awaiter(this, void 0, void 0, function () {
3774
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
3775
+ var _this = this;
3776
+ return __generator(this, function (_a) {
3777
+ switch (_a.label) {
3778
+ case 0:
3779
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3780
+ if (template.foreach === undefined) {
3781
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3782
+ }
3783
+ if (jokerParameterNames.length !== 0) {
3784
+ throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n JOKER parameters are not supported together with FOREACH command\n\n [\uD83E\uDDDE\u200D\u2640\uFE0F] This should be prevented in `validatePipeline`\n\n ".concat(block(pipelineIdentification), "\n "); }));
3785
+ }
3786
+ parameterValue = parameters[template.foreach.parameterName] || '';
3787
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3788
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3789
+ });
3790
+ if (formatDefinition === undefined) {
3791
+ throw new UnexpectedError(
3792
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3793
+ spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(template.foreach.formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
3794
+ .map(function (formatName) { return "- ".concat(formatName); })
3795
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3796
+ }
3797
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3798
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
3799
+ });
3800
+ if (subvalueDefinition === undefined) {
3801
+ throw new UnexpectedError(
3802
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3803
+ spaceTrim__default["default"](function (block) { return "\n Unsupported subformat name \"".concat(template.foreach.subformatName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
3804
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3805
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3806
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3807
+ }
3808
+ if (formatDefinition.formatName === 'CSV') {
3809
+ formatSettings = settings.csvSettings;
3810
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
3811
+ }
3812
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3813
+ var mappedParameters, allSubparameters, subresultString;
3814
+ return __generator(this, function (_a) {
3815
+ switch (_a.label) {
3816
+ case 0:
3817
+ // TODO: !!!!!!! Limit to N concurrent executions
3818
+ // TODO: !!!!!!! Report progress
3819
+ try {
3820
+ mappedParameters = mapAvailableToExpectedParameters({
3821
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3822
+ availableParameters: subparameters,
3823
+ });
3824
+ }
3825
+ catch (error) {
3826
+ if (!(error instanceof PipelineExecutionError)) {
3827
+ throw error;
3828
+ }
3829
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n ".concat(error.message, "\n\n This is error in FOREACH command\n You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command\n\n ").concat(block(pipelineIdentification), "\n Subparameter index: ").concat(index, "\n "); }));
3830
+ }
3831
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3832
+ // Note: [👨‍👨‍👧] Now we can freeze `subparameters` because we are sure that all and only used parameters are defined and are not going to be changed
3833
+ Object.freeze(allSubparameters);
3834
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: spaceTrim__default["default"](function (block) { return "\n ".concat(block(pipelineIdentification), "\n Subparameter index: ").concat(index, "\n "); }) }))];
3835
+ case 1:
3836
+ subresultString = _a.sent();
3837
+ return [2 /*return*/, subresultString];
3838
+ }
3839
+ });
3840
+ }); })];
3841
+ case 1:
3842
+ resultString = _a.sent();
3843
+ return [2 /*return*/, resultString];
3844
+ }
3845
+ });
3846
+ });
3847
+ }
3848
+ /**
3849
+ * TODO: !!!!!! Make pipelineIdentification more precise
3850
+ * TODO: !!!!!! How FOREACH execution looks in the report
3851
+ */
3852
+
3853
+ /**
3854
+ * @@@
3855
+ *
3856
+ * @private internal utility of `createPipelineExecutor`
3857
+ */
3858
+ function getContextForTemplate(template) {
3859
+ return __awaiter(this, void 0, void 0, function () {
3860
+ return __generator(this, function (_a) {
3861
+ TODO_USE(template);
3862
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3863
+ });
3864
+ });
3865
+ }
3866
+
3867
+ /**
3868
+ * @@@
3869
+ *
3870
+ * @private internal utility of `createPipelineExecutor`
3871
+ */
3872
+ function getKnowledgeForTemplate(options) {
3873
+ return __awaiter(this, void 0, void 0, function () {
3874
+ var preparedPipeline, template;
3875
+ return __generator(this, function (_a) {
3876
+ preparedPipeline = options.preparedPipeline, template = options.template;
3877
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3878
+ TODO_USE(template);
3879
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3880
+ var content = _a.content;
3881
+ return "- ".concat(content);
3882
+ }).join('\n')];
3883
+ });
3884
+ });
3885
+ }
3886
+
3887
+ /**
3888
+ * @@@
3889
+ *
3890
+ * @private internal utility of `createPipelineExecutor`
3891
+ */
3892
+ function getSamplesForTemplate(template) {
3893
+ return __awaiter(this, void 0, void 0, function () {
3894
+ return __generator(this, function (_a) {
3895
+ // TODO: [♨] Implement Better - use real index and keyword search
3896
+ TODO_USE(template);
3897
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3898
+ });
3899
+ });
3900
+ }
3901
+
3902
+ /**
3903
+ * @@@
3904
+ *
3905
+ * @private internal utility of `createPipelineExecutor`
3906
+ */
3907
+ function getReservedParametersForTemplate(options) {
3908
+ return __awaiter(this, void 0, void 0, function () {
3909
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3910
+ var e_1, _a;
3911
+ return __generator(this, function (_b) {
3912
+ switch (_b.label) {
3913
+ case 0:
3914
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
3915
+ return [4 /*yield*/, getContextForTemplate(template)];
3916
+ case 1:
3917
+ context = _b.sent();
3918
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
3919
+ case 2:
3920
+ knowledge = _b.sent();
3921
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3922
+ case 3:
3923
+ samples = _b.sent();
3924
+ currentDate = new Date().toISOString();
3925
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3926
+ reservedParameters = {
3927
+ content: RESERVED_PARAMETER_RESTRICTED,
3928
+ context: context,
3929
+ knowledge: knowledge,
3930
+ samples: samples,
3931
+ currentDate: currentDate,
3932
+ modelName: modelName,
3933
+ };
3934
+ _loop_1 = function (parameterName) {
3935
+ if (reservedParameters[parameterName] === undefined) {
3936
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3937
+ }
3938
+ };
3939
+ try {
3940
+ // Note: Doublecheck that ALL reserved parameters are defined:
3941
+ for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3942
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3943
+ _loop_1(parameterName);
3944
+ }
3945
+ }
3946
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3947
+ finally {
3948
+ try {
3949
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3950
+ }
3951
+ finally { if (e_1) throw e_1.error; }
3952
+ }
3953
+ return [2 /*return*/, reservedParameters];
3954
+ }
3955
+ });
3956
+ });
3957
+ }
3958
+
3959
+ /**
3960
+ * @@@
2936
3961
  *
2937
- * @public exported from `@promptbook/utils`
3962
+ * @private internal utility of `createPipelineExecutor`
2938
3963
  */
2939
- function countWords(text) {
2940
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
2941
- text = removeDiacritics(text);
2942
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3964
+ function executeTemplate(options) {
3965
+ return __awaiter(this, void 0, void 0, function () {
3966
+ var currentTemplate, preparedPipeline, parametersToPass, tools, llmTools, onProgress, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, maxAttempts, jokerParameterNames, preparedContent, resultString;
3967
+ var e_1, _f, _g;
3968
+ return __generator(this, function (_h) {
3969
+ switch (_h.label) {
3970
+ case 0:
3971
+ currentTemplate = options.currentTemplate, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, llmTools = options.llmTools, onProgress = options.onProgress, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3972
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3973
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3974
+ title = currentTemplate.title;
3975
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3976
+ return [4 /*yield*/, onProgress({
3977
+ name: name,
3978
+ title: title,
3979
+ isStarted: false,
3980
+ isDone: false,
3981
+ templateType: currentTemplate.templateType,
3982
+ parameterName: currentTemplate.resultingParameterName,
3983
+ parameterValue: null,
3984
+ // <- [🍸]
3985
+ })];
3986
+ case 1:
3987
+ _h.sent();
3988
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3989
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3990
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
3991
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3992
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
3993
+ .map(function (name) { return "{".concat(name, "}"); })
3994
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3995
+ .map(function (name) { return "{".concat(name, "}"); })
3996
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3997
+ }
3998
+ _b = (_a = Object).freeze;
3999
+ _c = [{}];
4000
+ return [4 /*yield*/, getReservedParametersForTemplate({
4001
+ preparedPipeline: preparedPipeline,
4002
+ template: currentTemplate,
4003
+ pipelineIdentification: pipelineIdentification,
4004
+ })];
4005
+ case 2:
4006
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4007
+ definedParameterNames = new Set(Object.keys(definedParameters));
4008
+ parameters = {};
4009
+ _loop_1 = function (parameterName) {
4010
+ // Situation: Parameter is defined and used
4011
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4012
+ parameters[parameterName] = definedParameters[parameterName];
4013
+ }
4014
+ // Situation: Parameter is defined but NOT used
4015
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4016
+ // Situation: Parameter is NOT defined BUT used
4017
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4018
+ // Houston, we have a problem
4019
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4020
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4021
+ }
4022
+ };
4023
+ try {
4024
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4025
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4026
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4027
+ parameterName = _e.value;
4028
+ _loop_1(parameterName);
4029
+ }
4030
+ }
4031
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4032
+ finally {
4033
+ try {
4034
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4035
+ }
4036
+ finally { if (e_1) throw e_1.error; }
4037
+ }
4038
+ // Note: [👨‍👨‍👧] Now we can freeze `parameters` because we are sure that all and only used parameters are defined and are not going to be changed
4039
+ Object.freeze(parameters);
4040
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4041
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4042
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4043
+ .split('{content}')
4044
+ .join(currentTemplate.content);
4045
+ return [4 /*yield*/, executeFormatCells({
4046
+ jokerParameterNames: jokerParameterNames,
4047
+ priority: priority,
4048
+ maxAttempts: maxAttempts,
4049
+ preparedContent: preparedContent,
4050
+ parameters: parameters,
4051
+ template: currentTemplate,
4052
+ preparedPipeline: preparedPipeline,
4053
+ tools: tools,
4054
+ llmTools: llmTools,
4055
+ settings: settings,
4056
+ $executionReport: $executionReport,
4057
+ pipelineIdentification: pipelineIdentification,
4058
+ })];
4059
+ case 3:
4060
+ resultString = _h.sent();
4061
+ return [4 /*yield*/, onProgress({
4062
+ name: name,
4063
+ title: title,
4064
+ isStarted: true,
4065
+ isDone: true,
4066
+ templateType: currentTemplate.templateType,
4067
+ parameterName: currentTemplate.resultingParameterName,
4068
+ parameterValue: resultString,
4069
+ // <- [🍸]
4070
+ })];
4071
+ case 4:
4072
+ _h.sent();
4073
+ return [2 /*return*/, Object.freeze((_g = {},
4074
+ _g[currentTemplate.resultingParameterName] =
4075
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4076
+ resultString,
4077
+ _g))];
4078
+ }
4079
+ });
4080
+ });
2943
4081
  }
2944
-
2945
4082
  /**
2946
- * Index of all counter functions
2947
- *
2948
- * @public exported from `@promptbook/utils`
4083
+ * TODO: [🤹‍♂️]
2949
4084
  */
2950
- var CountUtils = {
2951
- CHARACTERS: countCharacters,
2952
- WORDS: countWords,
2953
- SENTENCES: countSentences,
2954
- PARAGRAPHS: countParagraphs,
2955
- LINES: countLines,
2956
- PAGES: countPages,
2957
- };
2958
4085
 
2959
4086
  /**
2960
- * Function checkExpectations will check if the expectations on given value are met
2961
- *
2962
- * Note: There are two simmilar functions:
2963
- * - `checkExpectations` which throws an error if the expectations are not met
2964
- * - `isPassingExpectations` which returns a boolean
4087
+ * @@@
2965
4088
  *
2966
- * @throws {ExpectError} if the expectations are not met
2967
- * @returns {void} Nothing
2968
- * @private internal function of `createPipelineExecutor`
4089
+ * @private internal utility of `createPipelineExecutor`
2969
4090
  */
2970
- function checkExpectations(expectations, value) {
4091
+ function filterJustOutputParameters(options) {
2971
4092
  var e_1, _a;
4093
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4094
+ var outputParameters = {};
4095
+ var _loop_1 = function (parameter) {
4096
+ if (parametersToPass[parameter.name] === undefined) {
4097
+ // [4]
4098
+ $warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
4099
+ return "continue";
4100
+ }
4101
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4102
+ };
2972
4103
  try {
2973
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
2974
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
2975
- var amount = CountUtils[unit.toUpperCase()](value);
2976
- if (min && amount < min) {
2977
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2978
- } /* not else */
2979
- if (max && amount > max) {
2980
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2981
- }
4104
+ // Note: Filter ONLY output parameters
4105
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4106
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4107
+ var isOutput = _a.isOutput;
4108
+ return isOutput;
4109
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4110
+ var parameter = _c.value;
4111
+ _loop_1(parameter);
2982
4112
  }
2983
4113
  }
2984
4114
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -2988,600 +4118,27 @@
2988
4118
  }
2989
4119
  finally { if (e_1) throw e_1.error; }
2990
4120
  }
4121
+ return outputParameters;
2991
4122
  }
2992
- /**
2993
- * TODO: [💝] Unite object for expecting amount and format
2994
- */
2995
4123
 
2996
4124
  /**
2997
- * Creates executor function from pipeline and execution tools.
4125
+ * @@@
2998
4126
  *
2999
- * @returns The executor function
3000
- * @throws {PipelineLogicError} on logical error in the pipeline
3001
- * @public exported from `@promptbook/core`
4127
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4128
+ *
4129
+ * @private internal utility of `createPipelineExecutor`
3002
4130
  */
3003
- function createPipelineExecutor(options) {
3004
- var _this = this;
3005
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3006
- var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
3007
- validatePipeline(pipeline);
3008
- var pipelineIdentification = (function () {
3009
- // Note: This is a 😐 implementation of [🚞]
3010
- var _ = [];
3011
- if (pipeline.sourceFile !== undefined) {
3012
- _.push("File: ".concat(pipeline.sourceFile));
3013
- }
3014
- if (pipeline.pipelineUrl !== undefined) {
3015
- _.push("Url: ".concat(pipeline.pipelineUrl));
3016
- }
3017
- return _.join('\n');
3018
- })();
3019
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3020
- var preparedPipeline;
3021
- if (isPipelinePrepared(pipeline)) {
3022
- preparedPipeline = pipeline;
3023
- }
3024
- else if (isNotPreparedWarningSupressed !== true) {
3025
- console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3026
- }
3027
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3028
- // TODO:[main] !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3029
- function getContextForTemplate(template) {
3030
- return __awaiter(this, void 0, void 0, function () {
3031
- return __generator(this, function (_a) {
3032
- TODO_USE(template);
3033
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3034
- });
3035
- });
3036
- }
3037
- function getKnowledgeForTemplate(template) {
3038
- return __awaiter(this, void 0, void 0, function () {
3039
- return __generator(this, function (_a) {
3040
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3041
- TODO_USE(template);
3042
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3043
- var content = _a.content;
3044
- return "- ".concat(content);
3045
- }).join('\n')];
3046
- });
3047
- });
3048
- }
3049
- function getSamplesForTemplate(template) {
3050
- return __awaiter(this, void 0, void 0, function () {
3051
- return __generator(this, function (_a) {
3052
- // TODO: [♨] Implement Better - use real index and keyword search
3053
- TODO_USE(template);
3054
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3055
- });
3056
- });
3057
- }
3058
- function getReservedParametersForTemplate(template) {
3059
- return __awaiter(this, void 0, void 0, function () {
3060
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3061
- var e_3, _a;
3062
- return __generator(this, function (_b) {
3063
- switch (_b.label) {
3064
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3065
- case 1:
3066
- context = _b.sent();
3067
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3068
- case 2:
3069
- knowledge = _b.sent();
3070
- return [4 /*yield*/, getSamplesForTemplate(template)];
3071
- case 3:
3072
- samples = _b.sent();
3073
- currentDate = new Date().toISOString();
3074
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3075
- reservedParameters = {
3076
- content: RESERVED_PARAMETER_RESTRICTED,
3077
- context: context,
3078
- knowledge: knowledge,
3079
- samples: samples,
3080
- currentDate: currentDate,
3081
- modelName: modelName,
3082
- };
3083
- _loop_3 = function (parameterName) {
3084
- if (reservedParameters[parameterName] === undefined) {
3085
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3086
- }
3087
- };
3088
- try {
3089
- // Note: Doublecheck that ALL reserved parameters are defined:
3090
- for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3091
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3092
- _loop_3(parameterName);
3093
- }
3094
- }
3095
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3096
- finally {
3097
- try {
3098
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3099
- }
3100
- finally { if (e_3) throw e_3.error; }
3101
- }
3102
- return [2 /*return*/, reservedParameters];
3103
- }
3104
- });
3105
- });
3106
- }
3107
- function executeSingleTemplate(currentTemplate) {
3108
- return __awaiter(this, void 0, void 0, function () {
3109
- var name, title, priority, progress_1, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_4, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_5, attempt, state_2, progress_2;
3110
- var e_4, _f, _g;
3111
- return __generator(this, function (_h) {
3112
- switch (_h.label) {
3113
- case 0:
3114
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3115
- title = currentTemplate.title;
3116
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3117
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3118
- progress_1 = {
3119
- name: name,
3120
- title: title,
3121
- isStarted: false,
3122
- isDone: false,
3123
- templateType: currentTemplate.templateType,
3124
- parameterName: currentTemplate.resultingParameterName,
3125
- parameterValue: null,
3126
- // <- [3]
3127
- };
3128
- if (isReturned) {
3129
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3130
- .split('\n')
3131
- .map(function (line) { return "> ".concat(line); })
3132
- .join('\n')), "\n "); }));
3133
- }
3134
- return [4 /*yield*/, onProgress(progress_1)];
3135
- case 1:
3136
- _h.sent();
3137
- _h.label = 2;
3138
- case 2:
3139
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3140
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3141
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3142
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3143
- .map(function (name) { return "{".concat(name, "}"); })
3144
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3145
- .map(function (name) { return "{".concat(name, "}"); })
3146
- .join(', '), "\n\n "); }));
3147
- }
3148
- _b = (_a = Object).freeze;
3149
- _c = [{}];
3150
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3151
- case 3:
3152
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3153
- definedParameterNames = new Set(Object.keys(definedParameters));
3154
- parameters = {};
3155
- _loop_4 = function (parameterName) {
3156
- // Situation: Parameter is defined and used
3157
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3158
- parameters[parameterName] = definedParameters[parameterName];
3159
- }
3160
- // Situation: Parameter is defined but NOT used
3161
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3162
- // Situation: Parameter is NOT defined BUT used
3163
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3164
- // Houston, we have a problem
3165
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3166
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3167
- }
3168
- };
3169
- try {
3170
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3171
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3172
- parameterName = _e.value;
3173
- _loop_4(parameterName);
3174
- }
3175
- }
3176
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3177
- finally {
3178
- try {
3179
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3180
- }
3181
- finally { if (e_4) throw e_4.error; }
3182
- }
3183
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3184
- Object.freeze(parameters);
3185
- result = null;
3186
- resultString = null;
3187
- expectError = null;
3188
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3189
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3190
- preparedContent = (currentTemplate.preparedContent || '{content}')
3191
- .split('{content}')
3192
- .join(currentTemplate.content);
3193
- _loop_5 = function (attempt) {
3194
- var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_2, e_5_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_3, e_6_1, e_7_1, error_4;
3195
- var e_5, _s, e_7, _t, e_6, _u;
3196
- return __generator(this, function (_v) {
3197
- switch (_v.label) {
3198
- case 0:
3199
- isJokerAttempt = attempt < 0;
3200
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3201
- if (isJokerAttempt && !jokerParameterName) {
3202
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3203
- }
3204
- result = null;
3205
- resultString = null;
3206
- expectError = null;
3207
- if (isJokerAttempt) {
3208
- if (parameters[jokerParameterName] === undefined) {
3209
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3210
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3211
- }
3212
- else {
3213
- resultString = parameters[jokerParameterName];
3214
- }
3215
- }
3216
- _v.label = 1;
3217
- case 1:
3218
- _v.trys.push([1, 44, 45, 46]);
3219
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3220
- _j = currentTemplate.templateType;
3221
- switch (_j) {
3222
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3223
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3224
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3225
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3226
- }
3227
- return [3 /*break*/, 25];
3228
- case 2:
3229
- resultString = replaceParameters(preparedContent, parameters);
3230
- return [3 /*break*/, 26];
3231
- case 3:
3232
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3233
- prompt = {
3234
- title: currentTemplate.title,
3235
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3236
- ? preparedPipeline.pipelineUrl
3237
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3238
- parameters: parameters,
3239
- content: preparedContent,
3240
- modelRequirements: modelRequirements,
3241
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3242
- var name = _a.name;
3243
- return name === currentTemplate.personaName;
3244
- }) || {})), currentTemplate.expectations),
3245
- format: currentTemplate.format,
3246
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3247
- }; // <- TODO: Not very good type guard
3248
- _k = modelRequirements.modelVariant;
3249
- switch (_k) {
3250
- case 'CHAT': return [3 /*break*/, 4];
3251
- case 'COMPLETION': return [3 /*break*/, 6];
3252
- case 'EMBEDDING': return [3 /*break*/, 8];
3253
- }
3254
- return [3 /*break*/, 10];
3255
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3256
- case 5:
3257
- chatResult = _v.sent();
3258
- // TODO: [🍬] Destroy chatThread
3259
- result = chatResult;
3260
- resultString = chatResult.content;
3261
- return [3 /*break*/, 11];
3262
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3263
- case 7:
3264
- completionResult = _v.sent();
3265
- result = completionResult;
3266
- resultString = completionResult.content;
3267
- return [3 /*break*/, 11];
3268
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3269
- case 9:
3270
- embeddingResult = _v.sent();
3271
- result = embeddingResult;
3272
- resultString = embeddingResult.content.join(',');
3273
- return [3 /*break*/, 11];
3274
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3275
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3276
- case 11: return [3 /*break*/, 26];
3277
- case 12:
3278
- if (arrayableToArray(tools.script).length === 0) {
3279
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3280
- }
3281
- if (!currentTemplate.contentLanguage) {
3282
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3283
- }
3284
- // TODO: DRY [1]
3285
- scriptPipelineExecutionErrors = [];
3286
- _v.label = 13;
3287
- case 13:
3288
- _v.trys.push([13, 20, 21, 22]);
3289
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3290
- _v.label = 14;
3291
- case 14:
3292
- if (!!_m.done) return [3 /*break*/, 19];
3293
- scriptTools = _m.value;
3294
- _v.label = 15;
3295
- case 15:
3296
- _v.trys.push([15, 17, , 18]);
3297
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3298
- scriptLanguage: currentTemplate.contentLanguage,
3299
- script: preparedContent,
3300
- parameters: parameters,
3301
- }))];
3302
- case 16:
3303
- resultString = _v.sent();
3304
- return [3 /*break*/, 19];
3305
- case 17:
3306
- error_2 = _v.sent();
3307
- if (!(error_2 instanceof Error)) {
3308
- throw error_2;
3309
- }
3310
- if (error_2 instanceof UnexpectedError) {
3311
- throw error_2;
3312
- }
3313
- scriptPipelineExecutionErrors.push(error_2);
3314
- return [3 /*break*/, 18];
3315
- case 18:
3316
- _m = _l.next();
3317
- return [3 /*break*/, 14];
3318
- case 19: return [3 /*break*/, 22];
3319
- case 20:
3320
- e_5_1 = _v.sent();
3321
- e_5 = { error: e_5_1 };
3322
- return [3 /*break*/, 22];
3323
- case 21:
3324
- try {
3325
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3326
- }
3327
- finally { if (e_5) throw e_5.error; }
3328
- return [7 /*endfinally*/];
3329
- case 22:
3330
- if (resultString !== null) {
3331
- return [3 /*break*/, 26];
3332
- }
3333
- if (scriptPipelineExecutionErrors.length === 1) {
3334
- throw scriptPipelineExecutionErrors[0];
3335
- }
3336
- else {
3337
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3338
- .map(function (error) { return '- ' + error.message; })
3339
- .join('\n\n')), "\n "); }));
3340
- }
3341
- case 23:
3342
- if (tools.userInterface === undefined) {
3343
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3344
- }
3345
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3346
- promptTitle: currentTemplate.title,
3347
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3348
- defaultValue: replaceParameters(preparedContent, parameters),
3349
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3350
- placeholder: undefined,
3351
- priority: priority,
3352
- }))];
3353
- case 24:
3354
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3355
- resultString = _v.sent();
3356
- return [3 /*break*/, 26];
3357
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3358
- case 26:
3359
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3360
- _v.label = 27;
3361
- case 27:
3362
- _v.trys.push([27, 41, 42, 43]);
3363
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3364
- _v.label = 28;
3365
- case 28:
3366
- if (!!_p.done) return [3 /*break*/, 40];
3367
- functionName = _p.value;
3368
- // TODO: DRY [1]
3369
- scriptPipelineExecutionErrors = [];
3370
- postprocessingError = null;
3371
- _v.label = 29;
3372
- case 29:
3373
- _v.trys.push([29, 36, 37, 38]);
3374
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3375
- _v.label = 30;
3376
- case 30:
3377
- if (!!_r.done) return [3 /*break*/, 35];
3378
- scriptTools = _r.value;
3379
- _v.label = 31;
3380
- case 31:
3381
- _v.trys.push([31, 33, , 34]);
3382
- return [4 /*yield*/, scriptTools.execute({
3383
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3384
- script: "".concat(functionName, "(resultString)"),
3385
- parameters: {
3386
- resultString: resultString || '',
3387
- // Note: No ...parametersForTemplate, because working with result only
3388
- },
3389
- })];
3390
- case 32:
3391
- resultString = _v.sent();
3392
- postprocessingError = null;
3393
- return [3 /*break*/, 35];
3394
- case 33:
3395
- error_3 = _v.sent();
3396
- if (!(error_3 instanceof Error)) {
3397
- throw error_3;
3398
- }
3399
- if (error_3 instanceof UnexpectedError) {
3400
- throw error_3;
3401
- }
3402
- postprocessingError = error_3;
3403
- scriptPipelineExecutionErrors.push(error_3);
3404
- return [3 /*break*/, 34];
3405
- case 34:
3406
- _r = _q.next();
3407
- return [3 /*break*/, 30];
3408
- case 35: return [3 /*break*/, 38];
3409
- case 36:
3410
- e_6_1 = _v.sent();
3411
- e_6 = { error: e_6_1 };
3412
- return [3 /*break*/, 38];
3413
- case 37:
3414
- try {
3415
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3416
- }
3417
- finally { if (e_6) throw e_6.error; }
3418
- return [7 /*endfinally*/];
3419
- case 38:
3420
- if (postprocessingError) {
3421
- throw postprocessingError;
3422
- }
3423
- _v.label = 39;
3424
- case 39:
3425
- _p = _o.next();
3426
- return [3 /*break*/, 28];
3427
- case 40: return [3 /*break*/, 43];
3428
- case 41:
3429
- e_7_1 = _v.sent();
3430
- e_7 = { error: e_7_1 };
3431
- return [3 /*break*/, 43];
3432
- case 42:
3433
- try {
3434
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3435
- }
3436
- finally { if (e_7) throw e_7.error; }
3437
- return [7 /*endfinally*/];
3438
- case 43:
3439
- // TODO: [💝] Unite object for expecting amount and format
3440
- if (currentTemplate.format) {
3441
- if (currentTemplate.format === 'JSON') {
3442
- if (!isValidJsonString(resultString || '')) {
3443
- // TODO: [🏢] Do more universally via `FormatDefinition`
3444
- try {
3445
- resultString = extractJsonBlock(resultString || '');
3446
- }
3447
- catch (error) {
3448
- keepUnused(error);
3449
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3450
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3451
- }
3452
- }
3453
- }
3454
- else {
3455
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3456
- }
3457
- }
3458
- // TODO: [💝] Unite object for expecting amount and format
3459
- if (currentTemplate.expectations) {
3460
- checkExpectations(currentTemplate.expectations, resultString || '');
3461
- }
3462
- return [2 /*return*/, "break-attempts"];
3463
- case 44:
3464
- error_4 = _v.sent();
3465
- if (!(error_4 instanceof ExpectError)) {
3466
- throw error_4;
3467
- }
3468
- expectError = error_4;
3469
- return [3 /*break*/, 46];
3470
- case 45:
3471
- if (!isJokerAttempt &&
3472
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3473
- prompt
3474
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3475
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3476
- ) {
3477
- // TODO: [🧠] Maybe put other templateTypes into report
3478
- executionReport.promptExecutions.push({
3479
- prompt: __assign({}, prompt),
3480
- result: result || undefined,
3481
- error: expectError === null ? undefined : serializeError(expectError),
3482
- });
3483
- }
3484
- return [7 /*endfinally*/];
3485
- case 46:
3486
- if (expectError !== null && attempt === maxAttempts - 1) {
3487
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3488
- .split('\n')
3489
- .map(function (line) { return "> ".concat(line); })
3490
- .join('\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) || '')
3491
- .split('\n')
3492
- .map(function (line) { return "> ".concat(line); })
3493
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3494
- ? 'null'
3495
- : resultString
3496
- .split('\n')
3497
- .map(function (line) { return "> ".concat(line); })
3498
- .join('\n')), "\n ---\n "); }));
3499
- }
3500
- return [2 /*return*/];
3501
- }
3502
- });
3503
- };
3504
- attempt = -jokerParameterNames.length;
3505
- _h.label = 4;
3506
- case 4:
3507
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3508
- return [5 /*yield**/, _loop_5(attempt)];
3509
- case 5:
3510
- state_2 = _h.sent();
3511
- switch (state_2) {
3512
- case "break-attempts": return [3 /*break*/, 7];
3513
- }
3514
- _h.label = 6;
3515
- case 6:
3516
- attempt++;
3517
- return [3 /*break*/, 4];
3518
- case 7:
3519
- if (resultString === null) {
3520
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3521
- }
3522
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3523
- progress_2 = {
3524
- name: name,
3525
- title: title,
3526
- isStarted: true,
3527
- isDone: true,
3528
- templateType: currentTemplate.templateType,
3529
- parameterName: currentTemplate.resultingParameterName,
3530
- parameterValue: resultString,
3531
- // <- [3]
3532
- };
3533
- if (isReturned) {
3534
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3535
- .split('\n')
3536
- .map(function (line) { return "> ".concat(line); })
3537
- .join('\n')), "\n\n "); }));
3538
- }
3539
- return [4 /*yield*/, onProgress(progress_2)];
3540
- case 8:
3541
- _h.sent();
3542
- _h.label = 9;
3543
- case 9:
3544
- parametersToPass = Object.freeze(__assign(__assign({}, parametersToPass), (_g = {}, _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _g)));
3545
- return [2 /*return*/];
3546
- }
3547
- });
3548
- });
3549
- }
3550
- function filterJustOutputParameters() {
3551
- var e_8, _a;
3552
- var outputParameters = {};
3553
- var _loop_6 = function (parameter) {
3554
- if (parametersToPass[parameter.name] === undefined) {
3555
- // [4]
3556
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3557
- return "continue";
3558
- }
3559
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3560
- };
3561
- try {
3562
- // Note: Filter ONLY output parameters
3563
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3564
- var isOutput = _a.isOutput;
3565
- return isOutput;
3566
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3567
- var parameter = _c.value;
3568
- _loop_6(parameter);
3569
- }
3570
- }
3571
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3572
- finally {
3573
- try {
3574
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3575
- }
3576
- finally { if (e_8) throw e_8.error; }
3577
- }
3578
- return outputParameters;
3579
- }
3580
- var errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
4131
+ function executePipeline(options) {
4132
+ return __awaiter(this, void 0, void 0, function () {
4133
+ var inputParameters, tools, onProgress, pipeline, setPreparedPipeline, pipelineIdentification, settings, maxParallelCount, isVerbose, preparedPipeline, llmTools, errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
3581
4134
  var e_1, _e, e_2, _f;
3582
4135
  return __generator(this, function (_g) {
3583
4136
  switch (_g.label) {
3584
4137
  case 0:
4138
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4139
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4140
+ preparedPipeline = options.preparedPipeline;
4141
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3585
4142
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3586
4143
  return [4 /*yield*/, preparePipeline(pipeline, {
3587
4144
  llmTools: llmTools,
@@ -3590,6 +4147,7 @@
3590
4147
  })];
3591
4148
  case 1:
3592
4149
  preparedPipeline = _g.sent();
4150
+ setPreparedPipeline(preparedPipeline);
3593
4151
  _g.label = 2;
3594
4152
  case 2:
3595
4153
  errors = [];
@@ -3659,7 +4217,7 @@
3659
4217
  return name === parameterName;
3660
4218
  });
3661
4219
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3662
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4220
+ warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3663
4221
  return [3 /*break*/, 4];
3664
4222
  case 1:
3665
4223
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3671,10 +4229,10 @@
3671
4229
  // Note: Wait a short time to prevent race conditions
3672
4230
  _h.sent();
3673
4231
  _h.label = 3;
3674
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4232
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3675
4233
  isSuccessful: false,
3676
4234
  errors: __spreadArray([
3677
- new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4235
+ new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3678
4236
  ], __read(errors), false).map(serializeError),
3679
4237
  warnings: warnings.map(serializeError),
3680
4238
  executionReport: executionReport,
@@ -3738,7 +4296,7 @@
3738
4296
  case 0:
3739
4297
  if (loopLimit-- < 0) {
3740
4298
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3741
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4299
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3742
4300
  }
3743
4301
  currentTemplate = unresovedTemplates_1.find(function (template) {
3744
4302
  return template.dependentParameterNames.every(function (name) {
@@ -3748,29 +4306,52 @@
3748
4306
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3749
4307
  throw new UnexpectedError(
3750
4308
  // TODO: [🐎] DRY
3751
- spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4309
+ spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3752
4310
  .map(function (_a) {
3753
4311
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3754
4312
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3755
4313
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3756
4314
  .join(' and '));
3757
4315
  })
3758
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
4316
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
3759
4317
  case 1:
3760
4318
  if (!!currentTemplate) return [3 /*break*/, 3];
3761
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4319
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3762
4320
  case 2:
3763
- /* [5] */ _j.sent();
4321
+ /* [🤹‍♂️] */ _j.sent();
3764
4322
  return [3 /*break*/, 4];
3765
4323
  case 3:
3766
4324
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3767
- work_1 = executeSingleTemplate(currentTemplate)
3768
- .then(function () {
4325
+ work_1 = executeTemplate({
4326
+ currentTemplate: currentTemplate,
4327
+ preparedPipeline: preparedPipeline,
4328
+ parametersToPass: parametersToPass,
4329
+ tools: tools,
4330
+ llmTools: llmTools,
4331
+ onProgress: function (progress) {
4332
+ if (isReturned) {
4333
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4334
+ .split('\n')
4335
+ .map(function (line) { return "> ".concat(line); })
4336
+ .join('\n')), "\n "); }));
4337
+ }
4338
+ if (onProgress) {
4339
+ onProgress(progress);
4340
+ }
4341
+ },
4342
+ settings: settings,
4343
+ $executionReport: executionReport,
4344
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Template name: ").concat(currentTemplate.name, "\n Template title: ").concat(currentTemplate.title, "\n "); }),
4345
+ })
4346
+ .then(function (newParametersToPass) {
4347
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3769
4348
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3770
4349
  })
3771
4350
  .then(function () {
3772
4351
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3773
4352
  });
4353
+ // <- Note: Errors are catched here [3]
4354
+ // TODO: BUT if in multiple templates are errors, only the first one is catched so maybe we should catch errors here and save them to errors array here
3774
4355
  resolving_1.push(work_1);
3775
4356
  _j.label = 4;
3776
4357
  case 4: return [2 /*return*/];
@@ -3797,7 +4378,12 @@
3797
4378
  var result = _a.result;
3798
4379
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3799
4380
  })), false));
3800
- outputParameters_1 = filterJustOutputParameters();
4381
+ outputParameters_1 = filterJustOutputParameters({
4382
+ preparedPipeline: preparedPipeline,
4383
+ parametersToPass: parametersToPass,
4384
+ $warnings: warnings,
4385
+ pipelineIdentification: pipelineIdentification,
4386
+ });
3801
4387
  isReturned = true;
3802
4388
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3803
4389
  // Note: Wait a short time to prevent race conditions
@@ -3820,7 +4406,12 @@
3820
4406
  var result = _a.result;
3821
4407
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3822
4408
  })), false));
3823
- outputParameters = filterJustOutputParameters();
4409
+ outputParameters = filterJustOutputParameters({
4410
+ preparedPipeline: preparedPipeline,
4411
+ parametersToPass: parametersToPass,
4412
+ $warnings: warnings,
4413
+ pipelineIdentification: pipelineIdentification,
4414
+ });
3824
4415
  isReturned = true;
3825
4416
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3826
4417
  // Note: Wait a short time to prevent race conditions
@@ -3840,22 +4431,65 @@
3840
4431
  })];
3841
4432
  }
3842
4433
  });
4434
+ });
4435
+ }
4436
+
4437
+ /**
4438
+ * Creates executor function from pipeline and execution tools.
4439
+ *
4440
+ * @returns The executor function
4441
+ * @throws {PipelineLogicError} on logical error in the pipeline
4442
+ * @public exported from `@promptbook/core`
4443
+ */
4444
+ function createPipelineExecutor(options) {
4445
+ var _this = this;
4446
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4447
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.csvSettings, csvSettings = _d === void 0 ? DEFAULT_CSV_SETTINGS : _d, _e = settings.isVerbose, isVerbose = _e === void 0 ? IS_VERBOSE : _e, _f = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _f === void 0 ? false : _f;
4448
+ validatePipeline(pipeline);
4449
+ var pipelineIdentification = (function () {
4450
+ // Note: This is a 😐 implementation of [🚞]
4451
+ var _ = [];
4452
+ if (pipeline.sourceFile !== undefined) {
4453
+ _.push("File: ".concat(pipeline.sourceFile));
4454
+ }
4455
+ if (pipeline.pipelineUrl !== undefined) {
4456
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4457
+ }
4458
+ return _.join('\n');
4459
+ })();
4460
+ var preparedPipeline;
4461
+ if (isPipelinePrepared(pipeline)) {
4462
+ preparedPipeline = pipeline;
4463
+ }
4464
+ else if (isNotPreparedWarningSupressed !== true) {
4465
+ console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4466
+ }
4467
+ var runCount = 0;
4468
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4469
+ return __generator(this, function (_a) {
4470
+ runCount++;
4471
+ return [2 /*return*/, /* not await */ executePipeline({
4472
+ pipeline: pipeline,
4473
+ preparedPipeline: preparedPipeline,
4474
+ setPreparedPipeline: function (newPreparedPipeline) {
4475
+ preparedPipeline = newPreparedPipeline;
4476
+ },
4477
+ inputParameters: inputParameters,
4478
+ tools: tools,
4479
+ onProgress: onProgress,
4480
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n ").concat(runCount === 1 ? '' : "Run #".concat(runCount), "\n "); }),
4481
+ settings: {
4482
+ maxExecutionAttempts: maxExecutionAttempts,
4483
+ maxParallelCount: maxParallelCount,
4484
+ csvSettings: csvSettings,
4485
+ isVerbose: isVerbose,
4486
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4487
+ },
4488
+ })];
4489
+ });
3843
4490
  }); };
3844
4491
  return pipelineExecutor;
3845
4492
  }
3846
- /**
3847
- * TODO:[main] !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3848
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3849
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3850
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3851
- * TODO: [♈] Probbably move expectations from templates to parameters
3852
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3853
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3854
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3855
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3856
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3857
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
3858
- */
3859
4493
 
3860
4494
  /**
3861
4495
  * @@@
@@ -3965,8 +4599,13 @@
3965
4599
  case 6: return [3 /*break*/, 8];
3966
4600
  case 7:
3967
4601
  error_1 = _c.sent();
4602
+ // Note: Here is expected error:
4603
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4604
+ if (!(error_1 instanceof PipelineExecutionError)) {
4605
+ throw error_1;
4606
+ }
3968
4607
  // TODO: [🟥] Detect browser / node and make it colorfull
3969
- console.error(error_1);
4608
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
3970
4609
  return [3 /*break*/, 8];
3971
4610
  case 8: return [2 /*return*/, {
3972
4611
  name: name,
@@ -4939,6 +5578,241 @@
4939
5578
  },
4940
5579
  };
4941
5580
 
5581
+ /**
5582
+ * @@@
5583
+ *
5584
+ * @param text @@@
5585
+ * @returns @@@
5586
+ * @example 'HELLO_WORLD'
5587
+ * @example 'I_LOVE_PROMPTBOOK'
5588
+ * @public exported from `@promptbook/utils`
5589
+ */
5590
+ function normalizeTo_SCREAMING_CASE(text) {
5591
+ var e_1, _a;
5592
+ var charType;
5593
+ var lastCharType = 'OTHER';
5594
+ var normalizedName = '';
5595
+ try {
5596
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5597
+ var char = text_1_1.value;
5598
+ var normalizedChar = void 0;
5599
+ if (/^[a-z]$/.test(char)) {
5600
+ charType = 'LOWERCASE';
5601
+ normalizedChar = char.toUpperCase();
5602
+ }
5603
+ else if (/^[A-Z]$/.test(char)) {
5604
+ charType = 'UPPERCASE';
5605
+ normalizedChar = char;
5606
+ }
5607
+ else if (/^[0-9]$/.test(char)) {
5608
+ charType = 'NUMBER';
5609
+ normalizedChar = char;
5610
+ }
5611
+ else if (/^\/$/.test(char)) {
5612
+ charType = 'SLASH';
5613
+ normalizedChar = char;
5614
+ }
5615
+ else {
5616
+ charType = 'OTHER';
5617
+ normalizedChar = '_';
5618
+ }
5619
+ if (charType !== lastCharType &&
5620
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
5621
+ !(lastCharType === 'NUMBER') &&
5622
+ !(charType === 'NUMBER')) {
5623
+ normalizedName += '_';
5624
+ }
5625
+ normalizedName += normalizedChar;
5626
+ lastCharType = charType;
5627
+ }
5628
+ }
5629
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5630
+ finally {
5631
+ try {
5632
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5633
+ }
5634
+ finally { if (e_1) throw e_1.error; }
5635
+ }
5636
+ normalizedName = normalizedName.replace(/_+/g, '_');
5637
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
5638
+ normalizedName = normalizedName.replace(/^_/, '');
5639
+ normalizedName = normalizedName.replace(/_$/, '');
5640
+ return normalizedName;
5641
+ }
5642
+ /**
5643
+ * TODO: Tests
5644
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
5645
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
5646
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
5647
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
5648
+ * TODO: [🌺] Use some intermediate util splitWords
5649
+ */
5650
+
5651
+ /**
5652
+ * @@@
5653
+ *
5654
+ * @param text @@@
5655
+ * @param _isFirstLetterCapital @@@
5656
+ * @returns @@@
5657
+ * @example 'helloWorld'
5658
+ * @example 'iLovePromptbook'
5659
+ * @public exported from `@promptbook/utils`
5660
+ */
5661
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5662
+ var e_1, _a;
5663
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5664
+ var charType;
5665
+ var lastCharType = null;
5666
+ var normalizedName = '';
5667
+ try {
5668
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5669
+ var char = text_1_1.value;
5670
+ var normalizedChar = void 0;
5671
+ if (/^[a-z]$/.test(char)) {
5672
+ charType = 'LOWERCASE';
5673
+ normalizedChar = char;
5674
+ }
5675
+ else if (/^[A-Z]$/.test(char)) {
5676
+ charType = 'UPPERCASE';
5677
+ normalizedChar = char.toLowerCase();
5678
+ }
5679
+ else if (/^[0-9]$/.test(char)) {
5680
+ charType = 'NUMBER';
5681
+ normalizedChar = char;
5682
+ }
5683
+ else {
5684
+ charType = 'OTHER';
5685
+ normalizedChar = '';
5686
+ }
5687
+ if (!lastCharType) {
5688
+ if (_isFirstLetterCapital) {
5689
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5690
+ }
5691
+ }
5692
+ else if (charType !== lastCharType &&
5693
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5694
+ !(lastCharType === 'NUMBER') &&
5695
+ !(charType === 'NUMBER')) {
5696
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5697
+ }
5698
+ normalizedName += normalizedChar;
5699
+ lastCharType = charType;
5700
+ }
5701
+ }
5702
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5703
+ finally {
5704
+ try {
5705
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5706
+ }
5707
+ finally { if (e_1) throw e_1.error; }
5708
+ }
5709
+ return normalizedName;
5710
+ }
5711
+ /**
5712
+ * TODO: [🌺] Use some intermediate util splitWords
5713
+ */
5714
+
5715
+ /**
5716
+ * Removes quotes from a string
5717
+ *
5718
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5719
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5720
+ * Note: There are two simmilar functions:
5721
+ * - `removeQuotes` which removes only bounding quotes
5722
+ * - `unwrapResult` which removes whole introduce sentence
5723
+ *
5724
+ * @param text optionally quoted text
5725
+ * @returns text without quotes
5726
+ * @public exported from `@promptbook/utils`
5727
+ */
5728
+ function removeQuotes(text) {
5729
+ if (text.startsWith('"') && text.endsWith('"')) {
5730
+ return text.slice(1, -1);
5731
+ }
5732
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5733
+ return text.slice(1, -1);
5734
+ }
5735
+ return text;
5736
+ }
5737
+
5738
+ /**
5739
+ * Function `validateParameterName` will @@@
5740
+ *
5741
+ * @param parameterName @@@
5742
+ * @returns @@@
5743
+ * @throws {ParseError} @@@
5744
+ * @private within the repository
5745
+ */
5746
+ function validateParameterName(parameterName) {
5747
+ var e_1, _a;
5748
+ var rawParameterName = parameterName;
5749
+ try {
5750
+ for (var _b = __values([
5751
+ ['`', '`'],
5752
+ ['{', '}'],
5753
+ ['[', ']'],
5754
+ ['(', ')'],
5755
+ ['<', '>'],
5756
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5757
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5758
+ if (parameterName.substring(0, 1) === start &&
5759
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5760
+ // <- TODO: More universal that 1 character
5761
+ ) {
5762
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5763
+ // <- TODO: More universal that 1 character
5764
+ }
5765
+ }
5766
+ }
5767
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5768
+ finally {
5769
+ try {
5770
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5771
+ }
5772
+ finally { if (e_1) throw e_1.error; }
5773
+ }
5774
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5775
+ try {
5776
+ /*
5777
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5778
+ if (parameterName.includes(' ')) {
5779
+ throw new ParseError(`Parameter name cannot contain spaces`);
5780
+ }
5781
+ */
5782
+ if (parameterName.includes('.')) {
5783
+ throw new ParseError("Parameter name cannot contain dots");
5784
+ }
5785
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5786
+ throw new ParseError("Parameter name cannot contain slashes");
5787
+ }
5788
+ if (parameterName.includes('(') ||
5789
+ parameterName.includes(')') ||
5790
+ parameterName.includes('{') ||
5791
+ parameterName.includes('}') ||
5792
+ parameterName.includes('[') ||
5793
+ parameterName.includes(']')) {
5794
+ throw new ParseError("Parameter name cannot contain braces");
5795
+ }
5796
+ parameterName = removeDiacritics(parameterName);
5797
+ parameterName = removeEmojis(parameterName);
5798
+ parameterName = removeQuotes(parameterName);
5799
+ parameterName = normalizeTo_camelCase(parameterName);
5800
+ if (parameterName === '') {
5801
+ throw new ParseError("Parameter name cannot be empty");
5802
+ }
5803
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5804
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5805
+ }
5806
+ }
5807
+ catch (error) {
5808
+ if (!(error instanceof ParseError)) {
5809
+ throw error;
5810
+ }
5811
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
5812
+ }
5813
+ return parameterName;
5814
+ }
5815
+
4942
5816
  /**
4943
5817
  * Parses the foreach command
4944
5818
  *
@@ -4968,25 +5842,61 @@
4968
5842
  /**
4969
5843
  * Link to discussion
4970
5844
  */
4971
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5845
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
4972
5846
  /**
4973
5847
  * Example usages of the FOREACH command
4974
5848
  */
4975
5849
  examples: [
4976
- 'FOREACH List Line -> `{customer}`',
4977
- 'FOR List Line -> `{customer}`',
4978
- 'EACH List Line -> `{customer}`',
4979
- // <- TODO: [🍭] More
5850
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5851
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5852
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
4980
5853
  ],
4981
5854
  /**
4982
5855
  * Parses the FOREACH command
4983
5856
  */
4984
5857
  parse: function (input) {
4985
5858
  var args = input.args;
4986
- keepUnused(args);
4987
- // <- TODO: [🍭] Implement
5859
+ var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5860
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5861
+ var parameterNameArg = args[2] || '';
5862
+ var assignSign = args[3];
5863
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5864
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5865
+ });
5866
+ if (formatDefinition === undefined) {
5867
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
5868
+ .map(function (formatName) { return "- ".concat(formatName); })
5869
+ .join('\n')), "\n "); }));
5870
+ // <- TODO: [🏢] List all supported format names
5871
+ }
5872
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5873
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5874
+ });
5875
+ if (subvalueDefinition === undefined) {
5876
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported subformat name \"".concat(subformatName, "\" for format \"").concat(formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
5877
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5878
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5879
+ .join('\n')), "\n "); }));
5880
+ // <- TODO: [🏢] List all supported subformat names for the format
5881
+ }
5882
+ if (assignSign !== '->') {
5883
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5884
+ }
5885
+ var parameterName = validateParameterName(parameterNameArg);
5886
+ var subparameterNames = args
5887
+ .slice(4)
5888
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5889
+ .filter(function (parameterName) { return parameterName !== ''; })
5890
+ .map(validateParameterName);
5891
+ if (subparameterNames.length === 0) {
5892
+ throw new ParseError("FOREACH command must have at least one subparameter");
5893
+ }
4988
5894
  return {
4989
5895
  type: 'FOREACH',
5896
+ formatName: formatName,
5897
+ subformatName: subformatName,
5898
+ parameterName: parameterName,
5899
+ subparameterNames: subparameterNames,
4990
5900
  };
4991
5901
  },
4992
5902
  /**
@@ -4995,8 +5905,12 @@
4995
5905
  * Note: `$` is used to indicate that this function mutates given `templateJson`
4996
5906
  */
4997
5907
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
4998
- keepUnused(command, $templateJson, $pipelineJson);
4999
- // <- TODO: [🍭] Implement
5908
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
5909
+ // TODO: [🍭] Detect double use
5910
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
5911
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
5912
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5913
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5000
5914
  },
5001
5915
  /**
5002
5916
  * Converts the FOREACH command back to string
@@ -5005,8 +5919,7 @@
5005
5919
  */
5006
5920
  stringify: function (command) {
5007
5921
  keepUnused(command);
5008
- return "";
5009
- // <- TODO: [🍭] Implement
5922
+ return "---"; // <- TODO: [🛋] Implement
5010
5923
  },
5011
5924
  /**
5012
5925
  * Reads the FOREACH command from the `TemplateJson`
@@ -5015,12 +5928,11 @@
5015
5928
  */
5016
5929
  takeFromTemplateJson: function ($templateJson) {
5017
5930
  keepUnused($templateJson);
5018
- return [];
5019
- // <- TODO: [🍭] Implement
5931
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5020
5932
  },
5021
5933
  };
5022
5934
  /**
5023
- * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5935
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5024
5936
  */
5025
5937
 
5026
5938
  /**
@@ -5130,11 +6042,11 @@
5130
6042
  */
5131
6043
  parse: function (input) {
5132
6044
  var args = input.args;
5133
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5134
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5135
- throw new ParseError("Invalid joker");
6045
+ if (args.length !== 1) {
6046
+ throw new ParseError("JOKE command expects exactly one parameter name");
5136
6047
  }
5137
- var parameterName = parametersMatch.groups.parameterName;
6048
+ var parameterNameArg = args[0] || '';
6049
+ var parameterName = validateParameterName(parameterNameArg);
5138
6050
  return {
5139
6051
  type: 'JOKER',
5140
6052
  parameterName: parameterName,
@@ -5209,6 +6121,9 @@
5209
6121
  */
5210
6122
  parse: function (input) {
5211
6123
  var args = input.args, normalized = input.normalized;
6124
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6125
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6126
+ }).join('\n')), "\n "); });
5212
6127
  // TODO: Make this more elegant and dynamically
5213
6128
  if (normalized.startsWith('MODEL_VARIANT')) {
5214
6129
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5224,17 +6139,13 @@
5224
6139
  key: 'modelVariant',
5225
6140
  value: 'COMPLETION',
5226
6141
  };
6142
+ // <- Note: [🤖]
5227
6143
  }
5228
6144
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5229
- return {
5230
- type: 'MODEL',
5231
- key: 'modelVariant',
5232
- value: 'EMBEDDING',
5233
- };
5234
- // <- Note: [🤖]
6145
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5235
6146
  }
5236
6147
  else {
5237
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n Supported variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) { return "- ".concat(variantName); }).join('\n')), "\n "); }));
6148
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5238
6149
  }
5239
6150
  }
5240
6151
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5259,6 +6170,7 @@
5259
6170
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5260
6171
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5261
6172
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6173
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5262
6174
  }
5263
6175
  else {
5264
6176
  throw new ParseError(spaceTrim__default["default"]("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -5358,14 +6270,13 @@
5358
6270
  * Parses the PARAMETER command
5359
6271
  */
5360
6272
  parse: function (input) {
5361
- var normalized = input.normalized, raw = input.raw;
5362
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5363
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5364
- throw new ParseError("Invalid parameter");
5365
- }
5366
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5367
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5368
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6273
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6274
+ var parameterNameRaw = args.shift() || '';
6275
+ var parameterDescriptionRaw = args.join(' ');
6276
+ // <- TODO: When [🥶] fixed, change to:
6277
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6278
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6279
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Parameter {".concat(parameterNameRaw, "} can not contain another parameter in description\n\n The description:\n ").concat(block(parameterDescriptionRaw), "\n "); }));
5369
6280
  }
5370
6281
  var isInput = normalized.startsWith('INPUT');
5371
6282
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5373,10 +6284,12 @@
5373
6284
  isInput = false;
5374
6285
  isOutput = false;
5375
6286
  }
6287
+ var parameterName = validateParameterName(parameterNameRaw);
6288
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5376
6289
  return {
5377
6290
  type: 'PARAMETER',
5378
6291
  parameterName: parameterName,
5379
- parameterDescription: parameterDescription.trim() || null,
6292
+ parameterDescription: parameterDescription,
5380
6293
  isInput: isInput,
5381
6294
  isOutput: isOutput,
5382
6295
  };
@@ -6126,76 +7039,6 @@
6126
7039
  return str;
6127
7040
  }
6128
7041
 
6129
- /**
6130
- * @@@
6131
- *
6132
- * @param text @@@
6133
- * @returns @@@
6134
- * @example 'HELLO_WORLD'
6135
- * @example 'I_LOVE_PROMPTBOOK'
6136
- * @public exported from `@promptbook/utils`
6137
- */
6138
- function normalizeTo_SCREAMING_CASE(text) {
6139
- var e_1, _a;
6140
- var charType;
6141
- var lastCharType = 'OTHER';
6142
- var normalizedName = '';
6143
- try {
6144
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
6145
- var char = text_1_1.value;
6146
- var normalizedChar = void 0;
6147
- if (/^[a-z]$/.test(char)) {
6148
- charType = 'LOWERCASE';
6149
- normalizedChar = char.toUpperCase();
6150
- }
6151
- else if (/^[A-Z]$/.test(char)) {
6152
- charType = 'UPPERCASE';
6153
- normalizedChar = char;
6154
- }
6155
- else if (/^[0-9]$/.test(char)) {
6156
- charType = 'NUMBER';
6157
- normalizedChar = char;
6158
- }
6159
- else if (/^\/$/.test(char)) {
6160
- charType = 'SLASH';
6161
- normalizedChar = char;
6162
- }
6163
- else {
6164
- charType = 'OTHER';
6165
- normalizedChar = '_';
6166
- }
6167
- if (charType !== lastCharType &&
6168
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
6169
- !(lastCharType === 'NUMBER') &&
6170
- !(charType === 'NUMBER')) {
6171
- normalizedName += '_';
6172
- }
6173
- normalizedName += normalizedChar;
6174
- lastCharType = charType;
6175
- }
6176
- }
6177
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
6178
- finally {
6179
- try {
6180
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
6181
- }
6182
- finally { if (e_1) throw e_1.error; }
6183
- }
6184
- normalizedName = normalizedName.replace(/_+/g, '_');
6185
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
6186
- normalizedName = normalizedName.replace(/^_/, '');
6187
- normalizedName = normalizedName.replace(/_$/, '');
6188
- return normalizedName;
6189
- }
6190
- /**
6191
- * TODO: Tests
6192
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
6193
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
6194
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
6195
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
6196
- * TODO: [🌺] Use some intermediate util splitWords
6197
- */
6198
-
6199
7042
  /**
6200
7043
  * Parses one line of ul/ol to command
6201
7044
  *
@@ -6208,6 +7051,7 @@
6208
7051
  if (raw.includes('\n') || raw.includes('\r')) {
6209
7052
  throw new ParseError('Command can not contain new line characters' /* <- TODO: [🚞] */);
6210
7053
  }
7054
+ // TODO: Unit test all this processing and parsing
6211
7055
  var normalized = raw.trim();
6212
7056
  normalized = normalized.split('`').join('');
6213
7057
  normalized = normalized.split('"').join('');
@@ -6253,7 +7097,9 @@
6253
7097
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6254
7098
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6255
7099
  var args = items.slice(commandNameSegmentsCount + 1);
6256
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7100
+ var rawArgs = raw
7101
+ .substring(commandNameRaw.length)
7102
+ .trim();
6257
7103
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6258
7104
  if (command !== null) {
6259
7105
  return command;
@@ -6263,8 +7109,10 @@
6263
7109
  // Arg1 Arg2 Arg3 | FOO
6264
7110
  {
6265
7111
  var commandNameRaw = items.slice(-1).join('_');
6266
- var args = items.slice(0, -1);
6267
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7112
+ var args = items.slice(0, -1); // <- Note: This is probbably not correct
7113
+ var rawArgs = raw
7114
+ .substring(0, raw.length - commandNameRaw.length)
7115
+ .trim();
6268
7116
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6269
7117
  if (command !== null) {
6270
7118
  return command;
@@ -6404,7 +7252,7 @@
6404
7252
  function extractOneBlockFromMarkdown(markdown) {
6405
7253
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6406
7254
  if (codeBlocks.length !== 1) {
6407
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7255
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6408
7256
  }
6409
7257
  return codeBlocks[0];
6410
7258
  }