@promptbook/core 0.72.0-0 → 0.72.0-2

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 +2204 -1360
  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 +17 -12
  59. package/umd/index.umd.js +2211 -1363
  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('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('moment')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'crypto-js/enc-hex', 'crypto-js/sha256', 'moment'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.hexEncoder, global.sha256, global.moment));
5
- })(this, (function (exports, spaceTrim, prettier, parserHtml, waitasecond, hexEncoder, sha256, moment) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('moment')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'moment'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.hexEncoder, global.sha256, global.moment));
5
+ })(this, (function (exports, spaceTrim, prettier, parserHtml, waitasecond, papaparse, hexEncoder, sha256, moment) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -16,7 +16,7 @@
16
16
  /**
17
17
  * The version of the Promptbook library
18
18
  */
19
- var PROMPTBOOK_VERSION = '0.68.5';
19
+ var PROMPTBOOK_VERSION = '0.72.0-1';
20
20
  // TODO:[main] !!!! List here all the versions and annotate + put into script
21
21
 
22
22
  /*! *****************************************************************************
@@ -658,13 +658,13 @@
658
658
  *
659
659
  * @public exported from `@promptbook/core`
660
660
  */
661
- var MAX_PARALLEL_COUNT = 5;
661
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
662
662
  /**
663
663
  * The maximum number of attempts to execute LLM task before giving up
664
664
  *
665
665
  * @public exported from `@promptbook/core`
666
666
  */
667
- var MAX_EXECUTION_ATTEMPTS = 3;
667
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
668
668
  /**
669
669
  * The maximum length of the (generated) filename
670
670
  *
@@ -715,6 +715,7 @@
715
715
  'samples',
716
716
  'modelName',
717
717
  'currentDate',
718
+ // <- TODO: !!!!! list here all command names
718
719
  // <- TODO: Add more like 'date', 'modelName',...
719
720
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
720
721
  ]);
@@ -752,12 +753,32 @@
752
753
  */
753
754
  var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
754
755
  // <- TODO: [🧜‍♂️]
756
+ /**
757
+ * @@@
758
+ *
759
+ * @public exported from `@promptbook/core`
760
+ */
761
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
762
+ delimiter: ',',
763
+ quoteChar: '"',
764
+ newline: '\n',
765
+ skipEmptyLines: true,
766
+ });
755
767
  /**
756
768
  * @@@
757
769
  *
758
770
  * @public exported from `@promptbook/core`
759
771
  */
760
772
  var IS_VERBOSE = false;
773
+ /**
774
+ * @@@
775
+ *
776
+ * @private within the repository
777
+ */
778
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
779
+ /**/
780
+ // Note: In normal situations, we check the pipeline logic:
781
+ true);
761
782
  /**
762
783
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
763
784
  */
@@ -967,6 +988,26 @@
967
988
  * @public exported from `@promptbook/core`
968
989
  */
969
990
  function validatePipeline(pipeline) {
991
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
992
+ validatePipelineCore(pipeline);
993
+ }
994
+ else {
995
+ try {
996
+ validatePipelineCore(pipeline);
997
+ }
998
+ catch (error) {
999
+ if (!(error instanceof PipelineLogicError)) {
1000
+ throw error;
1001
+ }
1002
+ 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 "); }));
1003
+ }
1004
+ }
1005
+ return pipeline;
1006
+ }
1007
+ /**
1008
+ * @private internal function for `validatePipeline`
1009
+ */
1010
+ function validatePipelineCore(pipeline) {
970
1011
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
971
1012
  var e_1, _a, e_2, _b, e_3, _c;
972
1013
  var pipelineIdentification = (function () {
@@ -991,12 +1032,12 @@
991
1032
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
992
1033
  if (!Array.isArray(pipeline.parameters)) {
993
1034
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
994
- 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 "); }));
1035
+ 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 "); }));
995
1036
  }
996
1037
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
997
1038
  if (!Array.isArray(pipeline.templates)) {
998
1039
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
999
- 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 "); }));
1040
+ 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 "); }));
1000
1041
  }
1001
1042
  var _loop_1 = function (parameter) {
1002
1043
  if (parameter.isInput && parameter.isOutput) {
@@ -1165,9 +1206,9 @@
1165
1206
  while (unresovedTemplates.length > 0) {
1166
1207
  _loop_3();
1167
1208
  }
1168
- return pipeline;
1169
1209
  }
1170
1210
  /**
1211
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1171
1212
  * TODO: [🧠] Work with promptbookVersion
1172
1213
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1173
1214
  * > /**
@@ -2255,113 +2296,35 @@
2255
2296
  */
2256
2297
 
2257
2298
  /**
2258
- * Parses the given script and returns the list of all used variables that are not defined in the script
2259
- *
2260
- * @param script from which to extract the variables
2261
- * @returns the list of variable names
2262
- * @throws {ParseError} if the script is invalid
2263
- * @public exported from `@promptbook/utils`
2264
- */
2265
- function extractVariables(script) {
2266
- var variables = new Set();
2267
- script = "(()=>{".concat(script, "})()");
2268
- try {
2269
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2270
- try {
2271
- eval(script);
2272
- }
2273
- catch (error) {
2274
- if (!(error instanceof ReferenceError)) {
2275
- throw error;
2276
- }
2277
- var undefinedName = error.message.split(' ')[0];
2278
- /*
2279
- Note: Parsing the error
2280
- [PipelineUrlError: thing is not defined]
2281
- */
2282
- if (!undefinedName) {
2283
- throw error;
2284
- }
2285
- if (script.includes(undefinedName + '(')) {
2286
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2287
- }
2288
- else {
2289
- variables.add(undefinedName);
2290
- script = "const ".concat(undefinedName, " = '';") + script;
2291
- }
2292
- }
2293
- }
2294
- catch (error) {
2295
- if (!(error instanceof Error)) {
2296
- throw error;
2297
- }
2298
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2299
- }
2300
- return variables;
2301
- }
2302
- /**
2303
- * TODO: [🔣] Support for multiple languages - python, java,...
2304
- */
2305
-
2306
- /**
2307
- * Parses the template and returns the set of all used parameters
2299
+ * Determine if the pipeline is fully prepared
2308
2300
  *
2309
- * @param template the template with used parameters
2310
- * @returns the set of parameter names
2311
- * @throws {ParseError} if the script is invalid
2312
- * @public exported from `@promptbook/utils`
2301
+ * @public exported from `@promptbook/core`
2313
2302
  */
2314
- function extractParameterNamesFromTemplate(template) {
2315
- var e_1, _a, e_2, _b, e_3, _c;
2316
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2317
- var parameterNames = new Set();
2318
- try {
2319
- 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()) {
2320
- var parameterName = _e.value;
2321
- parameterNames.add(parameterName);
2322
- }
2323
- }
2324
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2325
- finally {
2326
- try {
2327
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2328
- }
2329
- finally { if (e_1) throw e_1.error; }
2330
- }
2331
- if (templateType === 'SCRIPT_TEMPLATE') {
2332
- try {
2333
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2334
- var parameterName = _g.value;
2335
- parameterNames.add(parameterName);
2336
- }
2337
- }
2338
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2339
- finally {
2340
- try {
2341
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2342
- }
2343
- finally { if (e_2) throw e_2.error; }
2344
- }
2345
- }
2346
- try {
2347
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2348
- var jokerName = _j.value;
2349
- parameterNames.add(jokerName);
2350
- }
2303
+ function isPipelinePrepared(pipeline) {
2304
+ // Note: Ignoring `pipeline.preparations` @@@
2305
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2306
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2307
+ return false;
2351
2308
  }
2352
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2353
- finally {
2354
- try {
2355
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2356
- }
2357
- finally { if (e_3) throw e_3.error; }
2309
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2310
+ return false;
2358
2311
  }
2359
- parameterNames.delete('content');
2360
- // <- Note {websiteContent} is used in `preparedContent`
2361
- return parameterNames;
2312
+ /*
2313
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2314
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2315
+ > return false;
2316
+ > }
2317
+ */
2318
+ return true;
2362
2319
  }
2363
2320
  /**
2364
- * TODO: [🔣] If script require contentLanguage
2321
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2322
+ * TODO: [🐠] Maybe base this on `makeValidator`
2323
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2324
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2325
+ * - [🏍] ? Is context in each template
2326
+ * - [♨] Are samples prepared
2327
+ * - [♨] Are templates prepared
2365
2328
  */
2366
2329
 
2367
2330
  /**
@@ -2381,27 +2344,6 @@
2381
2344
  };
2382
2345
  }
2383
2346
 
2384
- /**
2385
- * Function isValidJsonString will tell you if the string is valid JSON or not
2386
- *
2387
- * @public exported from `@promptbook/utils`
2388
- */
2389
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2390
- try {
2391
- JSON.parse(value);
2392
- return true;
2393
- }
2394
- catch (error) {
2395
- if (!(error instanceof Error)) {
2396
- throw error;
2397
- }
2398
- if (error.message.includes('Unexpected token')) {
2399
- return false;
2400
- }
2401
- return false;
2402
- }
2403
- }
2404
-
2405
2347
  /**
2406
2348
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2407
2349
  *
@@ -2428,9 +2370,10 @@
2428
2370
  });
2429
2371
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2430
2372
  get: function () {
2431
- return this.llmExecutionTools
2432
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2433
- .join('\n');
2373
+ return this.llmExecutionTools.map(function (_a, index) {
2374
+ var title = _a.title;
2375
+ return "".concat(index + 1, ") `").concat(title, "`");
2376
+ }).join('\n');
2434
2377
  },
2435
2378
  enumerable: false,
2436
2379
  configurable: true
@@ -2628,9 +2571,7 @@
2628
2571
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2629
2572
  }
2630
2573
  else {
2631
- 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
2632
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2633
- .join('\n')), "\n\n "); }));
2574
+ 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 "); }));
2634
2575
  }
2635
2576
  }
2636
2577
  });
@@ -2696,288 +2637,248 @@
2696
2637
  */
2697
2638
 
2698
2639
  /**
2699
- * Extracts all code blocks from markdown.
2640
+ * Takes an item or an array of items and returns an array of items
2700
2641
  *
2701
- * Note: There are multiple simmilar function:
2702
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2703
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2704
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2705
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2642
+ * 1) Any item except array and undefined returns array with that one item (also null)
2643
+ * 2) Undefined returns empty array
2644
+ * 3) Array returns itself
2706
2645
  *
2707
- * @param markdown any valid markdown
2708
- * @returns code blocks with language and content
2709
- * @throws {ParseError} if block is not closed properly
2710
- * @public exported from `@promptbook/markdown-utils`
2646
+ * @private internal utility
2711
2647
  */
2712
- function extractAllBlocksFromMarkdown(markdown) {
2713
- var e_1, _a;
2714
- var codeBlocks = [];
2715
- var lines = markdown.split('\n');
2716
- // Note: [0] Ensure that the last block notated by gt > will be closed
2717
- lines.push('');
2718
- var currentCodeBlock = null;
2719
- try {
2720
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2721
- var line = lines_1_1.value;
2722
- if (line.startsWith('> ') || line === '>') {
2723
- if (currentCodeBlock === null) {
2724
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2725
- } /* not else */
2726
- if (currentCodeBlock.blockNotation === '>') {
2727
- if (currentCodeBlock.content !== '') {
2728
- currentCodeBlock.content += '\n';
2729
- }
2730
- currentCodeBlock.content += line.slice(2);
2731
- }
2732
- }
2733
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2734
- codeBlocks.push(currentCodeBlock);
2735
- currentCodeBlock = null;
2736
- }
2737
- /* not else */
2738
- if (line.startsWith('```')) {
2739
- var language = line.slice(3).trim() || null;
2740
- if (currentCodeBlock === null) {
2741
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2742
- }
2743
- else {
2744
- if (language !== null) {
2745
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2746
- }
2747
- codeBlocks.push(currentCodeBlock);
2748
- currentCodeBlock = null;
2749
- }
2750
- }
2751
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2752
- if (currentCodeBlock.content !== '') {
2753
- currentCodeBlock.content += '\n';
2754
- }
2755
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2756
- }
2757
- }
2758
- }
2759
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2760
- finally {
2761
- try {
2762
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2763
- }
2764
- finally { if (e_1) throw e_1.error; }
2648
+ function arrayableToArray(input) {
2649
+ if (input === undefined) {
2650
+ return [];
2765
2651
  }
2766
- if (currentCodeBlock !== null) {
2767
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2652
+ if (input instanceof Array) {
2653
+ return input;
2768
2654
  }
2769
- return codeBlocks;
2655
+ return [input];
2770
2656
  }
2771
- /**
2772
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2773
- */
2774
2657
 
2775
2658
  /**
2776
- * Extracts extracts exactly one valid JSON code block
2777
- *
2778
- * - When given string is a valid JSON as it is, it just returns it
2779
- * - When there is no JSON code block the function throws a `ParseError`
2780
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2659
+ * @@@
2781
2660
  *
2782
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2783
- * Note: There are multiple simmilar function:
2784
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2785
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2786
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2787
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2788
- *
2789
- * @public exported from `@promptbook/markdown-utils`
2790
- * @throws {ParseError} if there is no valid JSON block in the markdown
2791
- */
2792
- function extractJsonBlock(markdown) {
2793
- if (isValidJsonString(markdown)) {
2794
- return markdown;
2795
- }
2796
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2797
- var jsonBlocks = codeBlocks.filter(function (_a) {
2798
- var content = _a.content;
2799
- return isValidJsonString(content);
2800
- });
2801
- if (jsonBlocks.length === 0) {
2802
- throw new Error('There is no valid JSON block in the markdown');
2803
- }
2804
- if (jsonBlocks.length > 1) {
2805
- throw new Error('There are multiple JSON code blocks in the markdown');
2806
- }
2807
- return jsonBlocks[0].content;
2808
- }
2809
- /**
2810
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2811
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2812
- */
2813
-
2814
- /**
2815
- * Determine if the pipeline is fully prepared
2816
- *
2817
- * @public exported from `@promptbook/core`
2661
+ * @public exported from `@promptbook/utils`
2818
2662
  */
2819
- function isPipelinePrepared(pipeline) {
2820
- // Note: Ignoring `pipeline.preparations` @@@
2821
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2822
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2823
- return false;
2824
- }
2825
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2826
- return false;
2827
- }
2663
+ function deepClone(objectValue) {
2664
+ return JSON.parse(JSON.stringify(objectValue));
2828
2665
  /*
2829
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2830
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2831
- > return false;
2666
+ TODO: [🧠] Is there a better implementation?
2667
+ > const propertyNames = Object.getOwnPropertyNames(objectValue);
2668
+ > for (const propertyName of propertyNames) {
2669
+ > const value = (objectValue as really_any)[propertyName];
2670
+ > if (value && typeof value === 'object') {
2671
+ > deepClone(value);
2672
+ > }
2832
2673
  > }
2674
+ > return Object.assign({}, objectValue);
2833
2675
  */
2834
- return true;
2835
2676
  }
2836
2677
  /**
2837
- * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2838
- * TODO: [🐠] Maybe base this on `makeValidator`
2839
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2840
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2841
- * - [🏍] ? Is context in each template
2842
- * - [♨] Are samples prepared
2843
- * - [♨] Are templates prepared
2678
+ * TODO: [🧠] Is there a way how to meaningfully test this utility
2844
2679
  */
2845
2680
 
2846
2681
  /**
2847
- * Takes an item or an array of items and returns an array of items
2682
+ * Function `addUsage` will add multiple usages into one
2848
2683
  *
2849
- * 1) Any item except array and undefined returns array with that one item (also null)
2850
- * 2) Undefined returns empty array
2851
- * 3) Array returns itself
2684
+ * Note: If you provide 0 values, it returns ZERO_USAGE
2852
2685
  *
2853
- * @private internal utility
2686
+ * @public exported from `@promptbook/core`
2854
2687
  */
2855
- function arrayableToArray(input) {
2856
- if (input === undefined) {
2857
- return [];
2858
- }
2859
- if (input instanceof Array) {
2860
- return input;
2688
+ function addUsage() {
2689
+ var usageItems = [];
2690
+ for (var _i = 0; _i < arguments.length; _i++) {
2691
+ usageItems[_i] = arguments[_i];
2861
2692
  }
2862
- return [input];
2693
+ return usageItems.reduce(function (acc, item) {
2694
+ var e_1, _a, e_2, _b;
2695
+ var _c;
2696
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
2697
+ try {
2698
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
2699
+ var key = _e.value;
2700
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2701
+ //@ts-ignore
2702
+ if (item.input[key]) {
2703
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2704
+ //@ts-ignore
2705
+ acc.input[key].value += item.input[key].value || 0;
2706
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2707
+ //@ts-ignore
2708
+ if (item.input[key].isUncertain) {
2709
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2710
+ //@ts-ignore
2711
+ acc.input[key].isUncertain = true;
2712
+ }
2713
+ }
2714
+ }
2715
+ }
2716
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2717
+ finally {
2718
+ try {
2719
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2720
+ }
2721
+ finally { if (e_1) throw e_1.error; }
2722
+ }
2723
+ try {
2724
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
2725
+ var key = _g.value;
2726
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2727
+ //@ts-ignore
2728
+ if (item.output[key]) {
2729
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2730
+ //@ts-ignore
2731
+ acc.output[key].value += item.output[key].value || 0;
2732
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2733
+ //@ts-ignore
2734
+ if (item.output[key].isUncertain) {
2735
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2736
+ //@ts-ignore
2737
+ acc.output[key].isUncertain = true;
2738
+ }
2739
+ }
2740
+ }
2741
+ }
2742
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2743
+ finally {
2744
+ try {
2745
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2746
+ }
2747
+ finally { if (e_2) throw e_2.error; }
2748
+ }
2749
+ return acc;
2750
+ }, deepClone(ZERO_USAGE));
2863
2751
  }
2864
2752
 
2865
2753
  /**
2866
- * Just says that the variable is not used but should be kept
2867
- * No side effects.
2868
- *
2869
- * Note: It can be usefull for:
2870
- *
2871
- * 1) Suppressing eager optimization of unused imports
2872
- * 2) Suppressing eslint errors of unused variables in the tests
2873
- * 3) Keeping the type of the variable for type testing
2754
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2874
2755
  *
2875
- * @param value any values
2876
- * @returns void
2877
- * @private within the repository
2756
+ * @param script from which to extract the variables
2757
+ * @returns the list of variable names
2758
+ * @throws {ParseError} if the script is invalid
2759
+ * @public exported from `@promptbook/utils`
2878
2760
  */
2879
- function keepUnused() {
2880
- var valuesToKeep = [];
2881
- for (var _i = 0; _i < arguments.length; _i++) {
2882
- valuesToKeep[_i] = arguments[_i];
2761
+ function extractVariables(script) {
2762
+ var variables = new Set();
2763
+ script = "(()=>{".concat(script, "})()");
2764
+ try {
2765
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2766
+ try {
2767
+ eval(script);
2768
+ }
2769
+ catch (error) {
2770
+ if (!(error instanceof ReferenceError)) {
2771
+ throw error;
2772
+ }
2773
+ var undefinedName = error.message.split(' ')[0];
2774
+ /*
2775
+ Note: Parsing the error
2776
+ [PipelineUrlError: thing is not defined]
2777
+ */
2778
+ if (!undefinedName) {
2779
+ throw error;
2780
+ }
2781
+ if (script.includes(undefinedName + '(')) {
2782
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2783
+ }
2784
+ else {
2785
+ variables.add(undefinedName);
2786
+ script = "const ".concat(undefinedName, " = '';") + script;
2787
+ }
2788
+ }
2789
+ }
2790
+ catch (error) {
2791
+ if (!(error instanceof Error)) {
2792
+ throw error;
2793
+ }
2794
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2883
2795
  }
2796
+ return variables;
2884
2797
  }
2885
-
2886
2798
  /**
2887
- * Just marks a place of place where should be something implemented
2888
- * No side effects.
2889
- *
2890
- * Note: It can be usefull suppressing eslint errors of unused variables
2891
- *
2892
- * @param value any values
2893
- * @returns void
2894
- * @private within the repository
2799
+ * TODO: [🔣] Support for multiple languages - python, java,...
2895
2800
  */
2896
- function TODO_USE() {
2897
- var value = [];
2898
- for (var _i = 0; _i < arguments.length; _i++) {
2899
- value[_i] = arguments[_i];
2900
- }
2901
- }
2902
2801
 
2903
2802
  /**
2904
- * Replaces parameters in template with values from parameters object
2803
+ * Parses the template and returns the set of all used parameters
2905
2804
  *
2906
- * @param template the template with parameters in {curly} braces
2907
- * @param parameters the object with parameters
2908
- * @returns the template with replaced parameters
2909
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2805
+ * @param template the template with used parameters
2806
+ * @returns the set of parameter names
2807
+ * @throws {ParseError} if the script is invalid
2910
2808
  * @public exported from `@promptbook/utils`
2911
2809
  */
2912
- function replaceParameters(template, parameters) {
2913
- var e_1, _a;
2810
+ function extractParameterNamesFromTemplate(template) {
2811
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2812
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2813
+ var parameterNames = new Set();
2914
2814
  try {
2915
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2916
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2917
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2918
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2919
- }
2920
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2921
- // TODO: [🍵]
2922
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2923
- }
2815
+ 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()) {
2816
+ var parameterName = _f.value;
2817
+ parameterNames.add(parameterName);
2924
2818
  }
2925
2819
  }
2926
2820
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2927
2821
  finally {
2928
2822
  try {
2929
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2823
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2930
2824
  }
2931
2825
  finally { if (e_1) throw e_1.error; }
2932
2826
  }
2933
- var replacedTemplate = template;
2934
- var match;
2935
- var loopLimit = LOOP_LIMIT;
2936
- var _loop_1 = function () {
2937
- if (loopLimit-- < 0) {
2938
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2939
- }
2940
- var precol = match.groups.precol;
2941
- var parameterName = match.groups.parameterName;
2942
- if (parameterName === '') {
2943
- return "continue";
2827
+ if (templateType === 'SCRIPT_TEMPLATE') {
2828
+ try {
2829
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2830
+ var parameterName = _h.value;
2831
+ parameterNames.add(parameterName);
2832
+ }
2944
2833
  }
2945
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2946
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2834
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2835
+ finally {
2836
+ try {
2837
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2838
+ }
2839
+ finally { if (e_2) throw e_2.error; }
2947
2840
  }
2948
- if (parameters[parameterName] === undefined) {
2949
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2950
- }
2951
- var parameterValue = parameters[parameterName];
2952
- if (parameterValue === undefined) {
2953
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2954
- }
2955
- parameterValue = parameterValue.toString();
2956
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2957
- parameterValue = parameterValue
2958
- .split('\n')
2959
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2960
- .join('\n');
2841
+ }
2842
+ try {
2843
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2844
+ var jokerName = _k.value;
2845
+ parameterNames.add(jokerName);
2961
2846
  }
2962
- replacedTemplate =
2963
- replacedTemplate.substring(0, match.index + precol.length) +
2964
- parameterValue +
2965
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2966
- };
2967
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2968
- .exec(replacedTemplate))) {
2969
- _loop_1();
2970
2847
  }
2971
- // [💫] Check if there are parameters that are not closed properly
2972
- if (/{\w+$/.test(replacedTemplate)) {
2973
- throw new PipelineExecutionError('Parameter is not closed');
2848
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2849
+ finally {
2850
+ try {
2851
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2852
+ }
2853
+ finally { if (e_3) throw e_3.error; }
2974
2854
  }
2975
- // [💫] Check if there are parameters that are not opened properly
2976
- if (/^\w+}/.test(replacedTemplate)) {
2977
- throw new PipelineExecutionError('Parameter is not opened');
2855
+ parameterNames.delete('content');
2856
+ // <- Note {websiteContent} is used in `preparedContent`
2857
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2858
+ if (foreach !== undefined) {
2859
+ try {
2860
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2861
+ var subparameterName = _m.value;
2862
+ if (parameterNames.has(subparameterName)) {
2863
+ parameterNames.delete(subparameterName);
2864
+ parameterNames.add(foreach.parameterName);
2865
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2866
+ }
2867
+ }
2868
+ }
2869
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2870
+ finally {
2871
+ try {
2872
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2873
+ }
2874
+ finally { if (e_4) throw e_4.error; }
2875
+ }
2978
2876
  }
2979
- return replacedTemplate;
2877
+ return parameterNames;
2980
2878
  }
2879
+ /**
2880
+ * TODO: [🔣] If script require contentLanguage
2881
+ */
2981
2882
 
2982
2883
  /**
2983
2884
  * Create difference set of two sets.
@@ -3055,212 +2956,351 @@
3055
2956
  }
3056
2957
 
3057
2958
  /**
3058
- * @@@
2959
+ * Just marks a place of place where should be something implemented
2960
+ * No side effects.
3059
2961
  *
3060
- * @public exported from `@promptbook/utils`
2962
+ * Note: It can be usefull suppressing eslint errors of unused variables
2963
+ *
2964
+ * @param value any values
2965
+ * @returns void
2966
+ * @private within the repository
3061
2967
  */
3062
- function deepClone(objectValue) {
3063
- return JSON.parse(JSON.stringify(objectValue));
3064
- /*
3065
- TODO: [🧠] Is there a better implementation?
3066
- > const propertyNames = Object.getOwnPropertyNames(objectValue);
3067
- > for (const propertyName of propertyNames) {
3068
- > const value = (objectValue as really_any)[propertyName];
3069
- > if (value && typeof value === 'object') {
3070
- > deepClone(value);
3071
- > }
3072
- > }
3073
- > return Object.assign({}, objectValue);
3074
- */
2968
+ function TODO_USE() {
2969
+ var value = [];
2970
+ for (var _i = 0; _i < arguments.length; _i++) {
2971
+ value[_i] = arguments[_i];
2972
+ }
3075
2973
  }
3076
- /**
3077
- * TODO: [🧠] Is there a way how to meaningfully test this utility
3078
- */
3079
2974
 
3080
2975
  /**
3081
- * Function `addUsage` will add multiple usages into one
3082
- *
3083
- * Note: If you provide 0 values, it returns ZERO_USAGE
2976
+ * @@@
3084
2977
  *
3085
2978
  * @public exported from `@promptbook/core`
3086
2979
  */
3087
- function addUsage() {
3088
- var usageItems = [];
3089
- for (var _i = 0; _i < arguments.length; _i++) {
3090
- usageItems[_i] = arguments[_i];
3091
- }
3092
- return usageItems.reduce(function (acc, item) {
3093
- var e_1, _a, e_2, _b;
3094
- var _c;
3095
- acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
3096
- try {
3097
- for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
3098
- var key = _e.value;
3099
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3100
- //@ts-ignore
3101
- if (item.input[key]) {
3102
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3103
- //@ts-ignore
3104
- acc.input[key].value += item.input[key].value || 0;
3105
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3106
- //@ts-ignore
3107
- if (item.input[key].isUncertain) {
3108
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3109
- //@ts-ignore
3110
- acc.input[key].isUncertain = true;
3111
- }
3112
- }
3113
- }
3114
- }
3115
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
3116
- finally {
3117
- try {
3118
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
3119
- }
3120
- finally { if (e_1) throw e_1.error; }
3121
- }
3122
- try {
3123
- for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
3124
- var key = _g.value;
3125
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3126
- //@ts-ignore
3127
- if (item.output[key]) {
3128
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3129
- //@ts-ignore
3130
- acc.output[key].value += item.output[key].value || 0;
3131
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3132
- //@ts-ignore
3133
- if (item.output[key].isUncertain) {
3134
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3135
- //@ts-ignore
3136
- acc.output[key].isUncertain = true;
3137
- }
3138
- }
3139
- }
3140
- }
3141
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
3142
- finally {
3143
- try {
3144
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
3145
- }
3146
- finally { if (e_2) throw e_2.error; }
3147
- }
3148
- return acc;
3149
- }, deepClone(ZERO_USAGE));
3150
- }
2980
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2981
+ header: true,
2982
+ // encoding: 'utf8',
2983
+ });
3151
2984
 
3152
2985
  /**
3153
- * Counts number of characters in the text
2986
+ * Definition for CSV spreadsheet
3154
2987
  *
3155
- * @public exported from `@promptbook/utils`
2988
+ * @public exported from `@promptbook/core`
2989
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2990
+ */
2991
+ var CsvFormatDefinition = {
2992
+ formatName: 'CSV',
2993
+ aliases: ['SPREADSHEET', 'TABLE'],
2994
+ isValid: function (value, settings, schema) {
2995
+ // TODO: !!!!!! Implement CSV validation
2996
+ TODO_USE(value /* <- TODO: Use value here */);
2997
+ TODO_USE(settings /* <- TODO: Use settings here */);
2998
+ TODO_USE(schema /* <- TODO: Use schema here */);
2999
+ return true;
3000
+ },
3001
+ canBeValid: function (partialValue, settings, schema) {
3002
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3003
+ TODO_USE(settings /* <- TODO: Use settings here */);
3004
+ TODO_USE(schema /* <- TODO: Use schema here */);
3005
+ return true;
3006
+ },
3007
+ heal: function (value, settings, schema) {
3008
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3009
+ TODO_USE(settings /* <- TODO: Use settings here */);
3010
+ TODO_USE(schema /* <- TODO: Use schema here */);
3011
+ throw new Error('Not implemented');
3012
+ },
3013
+ subvalueDefinitions: [
3014
+ {
3015
+ subvalueName: 'ROW',
3016
+ mapValues: function (value, settings, mapCallback) {
3017
+ return __awaiter(this, void 0, void 0, function () {
3018
+ var csv, mappedData;
3019
+ var _this = this;
3020
+ return __generator(this, function (_a) {
3021
+ switch (_a.label) {
3022
+ case 0:
3023
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
3024
+ if (csv.errors.length !== 0) {
3025
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3026
+ 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 "); }));
3027
+ }
3028
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
3029
+ var _a;
3030
+ var _b;
3031
+ return __generator(this, function (_c) {
3032
+ switch (_c.label) {
3033
+ case 0:
3034
+ _a = [__assign({}, row)];
3035
+ _b = {};
3036
+ // <- TODO: !!!!!! Dynamic new column name and position
3037
+ // <- TODO: !!!!!! Check name collisions
3038
+ return [4 /*yield*/, mapCallback(row, index)];
3039
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
3040
+ // <- TODO: !!!!!! Dynamic new column name and position
3041
+ // <- TODO: !!!!!! Check name collisions
3042
+ _c.sent(), _b)])))];
3043
+ }
3044
+ });
3045
+ }); }))];
3046
+ case 1:
3047
+ mappedData = _a.sent();
3048
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3049
+ }
3050
+ });
3051
+ });
3052
+ },
3053
+ },
3054
+ {
3055
+ subvalueName: 'CELL',
3056
+ mapValues: function (value, settings, mapCallback) {
3057
+ return __awaiter(this, void 0, void 0, function () {
3058
+ var csv, mappedData;
3059
+ var _this = this;
3060
+ return __generator(this, function (_a) {
3061
+ switch (_a.label) {
3062
+ case 0:
3063
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
3064
+ if (csv.errors.length !== 0) {
3065
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3066
+ 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 "); }));
3067
+ }
3068
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3069
+ var _this = this;
3070
+ return __generator(this, function (_a) {
3071
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
3072
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
3073
+ return __awaiter(_this, void 0, void 0, function () {
3074
+ var index;
3075
+ var _c;
3076
+ return __generator(this, function (_d) {
3077
+ index = rowIndex * Object.keys(row).length + columnIndex;
3078
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
3079
+ });
3080
+ });
3081
+ }))];
3082
+ });
3083
+ }); }))];
3084
+ case 1:
3085
+ mappedData = _a.sent();
3086
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3087
+ }
3088
+ });
3089
+ });
3090
+ },
3091
+ },
3092
+ ],
3093
+ };
3094
+ /**
3095
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
3096
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
3097
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
3098
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
3099
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3156
3100
  */
3157
- function countCharacters(text) {
3158
- // Remove null characters
3159
- text = text.replace(/\0/g, '');
3160
- // Replace emojis (and also ZWJ sequence) with hyphens
3161
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3162
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3163
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3164
- return text.length;
3165
- }
3166
3101
 
3167
3102
  /**
3168
- * Counts number of lines in the text
3103
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3169
3104
  *
3170
3105
  * @public exported from `@promptbook/utils`
3171
3106
  */
3172
- function countLines(text) {
3173
- if (text === '') {
3174
- return 0;
3107
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
3108
+ try {
3109
+ JSON.parse(value);
3110
+ return true;
3111
+ }
3112
+ catch (error) {
3113
+ if (!(error instanceof Error)) {
3114
+ throw error;
3115
+ }
3116
+ if (error.message.includes('Unexpected token')) {
3117
+ return false;
3118
+ }
3119
+ return false;
3175
3120
  }
3176
- return text.split('\n').length;
3177
3121
  }
3178
3122
 
3179
3123
  /**
3180
- * Counts number of pages in the text
3124
+ * Definition for JSON format
3181
3125
  *
3182
- * @public exported from `@promptbook/utils`
3126
+ * @private still in development [🏢]
3183
3127
  */
3184
- function countPages(text) {
3185
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
3186
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3187
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3188
- return pageCount;
3189
- }
3190
-
3128
+ var JsonFormatDefinition = {
3129
+ formatName: 'JSON',
3130
+ mimeType: 'application/json',
3131
+ isValid: function (value, settings, schema) {
3132
+ TODO_USE(schema /* <- TODO: Use schema here */);
3133
+ TODO_USE(settings /* <- TODO: Use settings here */);
3134
+ return isValidJsonString(value);
3135
+ },
3136
+ canBeValid: function (partialValue, settings, schema) {
3137
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3138
+ TODO_USE(settings /* <- TODO: Use settings here */);
3139
+ TODO_USE(schema /* <- TODO: Use schema here */);
3140
+ return true;
3141
+ },
3142
+ heal: function (value, settings, schema) {
3143
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3144
+ TODO_USE(settings /* <- TODO: Use settings here */);
3145
+ TODO_USE(schema /* <- TODO: Use schema here */);
3146
+ throw new Error('Not implemented');
3147
+ },
3148
+ subvalueDefinitions: [],
3149
+ };
3191
3150
  /**
3192
- * Counts number of paragraphs in the text
3193
- *
3194
- * @public exported from `@promptbook/utils`
3151
+ * TODO: [🧠] Maybe propper instance of object
3152
+ * TODO: [0] Make string_serialized_json
3153
+ * TODO: [1] Make type for JSON Settings and Schema
3154
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3155
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3156
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3157
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3158
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3159
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3195
3160
  */
3196
- function countParagraphs(text) {
3197
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3198
- }
3199
3161
 
3200
3162
  /**
3201
- * Split text into sentences
3163
+ * Definition for any text - this will be always valid
3202
3164
  *
3203
- * @public exported from `@promptbook/utils`
3165
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3166
+ *
3167
+ * @public exported from `@promptbook/core`
3204
3168
  */
3205
- function splitIntoSentences(text) {
3206
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3207
- }
3169
+ var TextFormatDefinition = {
3170
+ formatName: 'TEXT',
3171
+ isValid: function (value) {
3172
+ return typeof value === 'string';
3173
+ },
3174
+ canBeValid: function (partialValue) {
3175
+ return typeof partialValue === 'string';
3176
+ },
3177
+ heal: function () {
3178
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3179
+ },
3180
+ subvalueDefinitions: [
3181
+ {
3182
+ subvalueName: 'LINE',
3183
+ mapValues: function (value, settings, mapCallback) {
3184
+ return __awaiter(this, void 0, void 0, function () {
3185
+ var lines, mappedLines;
3186
+ return __generator(this, function (_a) {
3187
+ switch (_a.label) {
3188
+ case 0:
3189
+ lines = value.split('\n');
3190
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3191
+ // TODO: [🧠] Maybe option to skip empty line
3192
+ /* not await */ return mapCallback({
3193
+ lineContent: lineContent,
3194
+ // TODO: [🧠] Maybe also put here `lineNumber`
3195
+ }, lineNumber);
3196
+ }))];
3197
+ case 1:
3198
+ mappedLines = _a.sent();
3199
+ return [2 /*return*/, mappedLines.join('\n')];
3200
+ }
3201
+ });
3202
+ });
3203
+ },
3204
+ },
3205
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3206
+ ],
3207
+ };
3208
3208
  /**
3209
- * Counts number of sentences in the text
3210
- *
3211
- * @public exported from `@promptbook/utils`
3209
+ * TODO: [1] Make type for XML Text and Schema
3210
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3211
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3212
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3213
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3214
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3215
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3212
3216
  */
3213
- function countSentences(text) {
3214
- return splitIntoSentences(text).length;
3215
- }
3216
3217
 
3217
3218
  /**
3218
- * Counts number of words in the text
3219
+ * Definition for XML format
3219
3220
  *
3220
- * @public exported from `@promptbook/utils`
3221
+ * @private still in development [🏢]
3222
+ */
3223
+ var XmlFormatDefinition = {
3224
+ formatName: 'XML',
3225
+ mimeType: 'application/xml',
3226
+ isValid: function (value, settings, schema) {
3227
+ TODO_USE(value /* <- TODO: Use value here */);
3228
+ TODO_USE(settings /* <- TODO: Use settings here */);
3229
+ TODO_USE(schema /* <- TODO: Use schema here */);
3230
+ return true;
3231
+ },
3232
+ canBeValid: function (partialValue, settings, schema) {
3233
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3234
+ TODO_USE(settings /* <- TODO: Use settings here */);
3235
+ TODO_USE(schema /* <- TODO: Use schema here */);
3236
+ return true;
3237
+ },
3238
+ heal: function (value, settings, schema) {
3239
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3240
+ TODO_USE(settings /* <- TODO: Use settings here */);
3241
+ TODO_USE(schema /* <- TODO: Use schema here */);
3242
+ throw new Error('Not implemented');
3243
+ },
3244
+ subvalueDefinitions: [],
3245
+ };
3246
+ /**
3247
+ * TODO: [🧠] Maybe propper instance of object
3248
+ * TODO: [0] Make string_serialized_xml
3249
+ * TODO: [1] Make type for XML Settings and Schema
3250
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3251
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3252
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3253
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3254
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3255
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3221
3256
  */
3222
- function countWords(text) {
3223
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3224
- text = removeDiacritics(text);
3225
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3226
- }
3227
3257
 
3228
3258
  /**
3229
- * Index of all counter functions
3259
+ * Definitions for all formats supported by Promptbook
3230
3260
  *
3231
- * @public exported from `@promptbook/utils`
3261
+ * @private internal index of `...` <- TODO [🏢]
3232
3262
  */
3233
- var CountUtils = {
3234
- CHARACTERS: countCharacters,
3235
- WORDS: countWords,
3236
- SENTENCES: countSentences,
3237
- PARAGRAPHS: countParagraphs,
3238
- LINES: countLines,
3239
- PAGES: countPages,
3240
- };
3263
+ var FORMAT_DEFINITIONS = [
3264
+ JsonFormatDefinition,
3265
+ XmlFormatDefinition,
3266
+ TextFormatDefinition,
3267
+ CsvFormatDefinition,
3268
+ ];
3241
3269
 
3242
3270
  /**
3243
- * Function checkExpectations will check if the expectations on given value are met
3271
+ * Maps available parameters to expected parameters
3244
3272
  *
3245
- * Note: There are two simmilar functions:
3246
- * - `checkExpectations` which throws an error if the expectations are not met
3247
- * - `isPassingExpectations` which returns a boolean
3273
+ * The strategy is:
3274
+ * 1) @@@
3275
+ * 2) @@@
3248
3276
  *
3249
- * @throws {ExpectError} if the expectations are not met
3250
- * @returns {void} Nothing
3251
- * @private internal function of `createPipelineExecutor`
3277
+ * @throws {PipelineExecutionError} @@@
3278
+ * @private within the repository used in `createPipelineExecutor`
3252
3279
  */
3253
- function checkExpectations(expectations, value) {
3280
+ function mapAvailableToExpectedParameters(options) {
3254
3281
  var e_1, _a;
3282
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3283
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3284
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3285
+ var mappedParameters = {};
3255
3286
  try {
3256
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3257
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3258
- var amount = CountUtils[unit.toUpperCase()](value);
3259
- if (min && amount < min) {
3260
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3261
- } /* not else */
3262
- if (max && amount > max) {
3263
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3287
+ // Phase 1️⃣: Matching mapping
3288
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3289
+ var parameterName = _c.value;
3290
+ // Situation: Parameter is available and expected
3291
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3292
+ mappedParameters[parameterName] = availableParameters[parameterName];
3293
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3294
+ availableParametersNames.delete(parameterName);
3295
+ expectedParameterNames.delete(parameterName);
3296
+ }
3297
+ // Situation: Parameter is available but NOT expected
3298
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3299
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3300
+ }
3301
+ // Situation: Parameter is NOT available BUT expected
3302
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3303
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3264
3304
  }
3265
3305
  }
3266
3306
  }
@@ -3271,622 +3311,1139 @@
3271
3311
  }
3272
3312
  finally { if (e_1) throw e_1.error; }
3273
3313
  }
3314
+ if (expectedParameterNames.size === 0) {
3315
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3316
+ Object.freeze(mappedParameters);
3317
+ return mappedParameters;
3318
+ }
3319
+ // Phase 2️⃣: Non-matching mapping
3320
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3321
+ 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)
3322
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3323
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3324
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3325
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3326
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3327
+ .join('\n')), "\n\n "); }));
3328
+ }
3329
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3330
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3331
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3332
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3333
+ }
3334
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3335
+ Object.freeze(mappedParameters);
3336
+ return mappedParameters;
3274
3337
  }
3338
+
3275
3339
  /**
3276
- * Function checkExpectations will check if the expectations on given value are met
3340
+ * Extracts all code blocks from markdown.
3277
3341
  *
3278
- * Note: There are two simmilar functions:
3279
- * - `checkExpectations` which throws an error if the expectations are not met
3280
- * - `isPassingExpectations` which returns a boolean
3342
+ * Note: There are multiple simmilar function:
3343
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3344
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3345
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3346
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3281
3347
  *
3282
- * @returns {boolean} True if the expectations are met
3283
- * @public exported from `@promptbook/core`
3348
+ * @param markdown any valid markdown
3349
+ * @returns code blocks with language and content
3350
+ * @throws {ParseError} if block is not closed properly
3351
+ * @public exported from `@promptbook/markdown-utils`
3284
3352
  */
3285
- function isPassingExpectations(expectations, value) {
3353
+ function extractAllBlocksFromMarkdown(markdown) {
3354
+ var e_1, _a;
3355
+ var codeBlocks = [];
3356
+ var lines = markdown.split('\n');
3357
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3358
+ lines.push('');
3359
+ var currentCodeBlock = null;
3286
3360
  try {
3287
- checkExpectations(expectations, value);
3288
- return true;
3361
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3362
+ var line = lines_1_1.value;
3363
+ if (line.startsWith('> ') || line === '>') {
3364
+ if (currentCodeBlock === null) {
3365
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3366
+ } /* not else */
3367
+ if (currentCodeBlock.blockNotation === '>') {
3368
+ if (currentCodeBlock.content !== '') {
3369
+ currentCodeBlock.content += '\n';
3370
+ }
3371
+ currentCodeBlock.content += line.slice(2);
3372
+ }
3373
+ }
3374
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3375
+ codeBlocks.push(currentCodeBlock);
3376
+ currentCodeBlock = null;
3377
+ }
3378
+ /* not else */
3379
+ if (line.startsWith('```')) {
3380
+ var language = line.slice(3).trim() || null;
3381
+ if (currentCodeBlock === null) {
3382
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3383
+ }
3384
+ else {
3385
+ if (language !== null) {
3386
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3387
+ }
3388
+ codeBlocks.push(currentCodeBlock);
3389
+ currentCodeBlock = null;
3390
+ }
3391
+ }
3392
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3393
+ if (currentCodeBlock.content !== '') {
3394
+ currentCodeBlock.content += '\n';
3395
+ }
3396
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3397
+ }
3398
+ }
3289
3399
  }
3290
- catch (error) {
3291
- if (!(error instanceof ExpectError)) {
3292
- throw error;
3400
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3401
+ finally {
3402
+ try {
3403
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3293
3404
  }
3294
- return false;
3405
+ finally { if (e_1) throw e_1.error; }
3406
+ }
3407
+ if (currentCodeBlock !== null) {
3408
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3295
3409
  }
3410
+ return codeBlocks;
3296
3411
  }
3297
3412
  /**
3298
- * TODO: [💝] Unite object for expecting amount and format
3413
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3299
3414
  */
3300
3415
 
3301
3416
  /**
3302
- * Creates executor function from pipeline and execution tools.
3417
+ * Extracts extracts exactly one valid JSON code block
3303
3418
  *
3304
- * @returns The executor function
3305
- * @throws {PipelineLogicError} on logical error in the pipeline
3306
- * @public exported from `@promptbook/core`
3419
+ * - When given string is a valid JSON as it is, it just returns it
3420
+ * - When there is no JSON code block the function throws a `ParseError`
3421
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3422
+ *
3423
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3424
+ * Note: There are multiple simmilar function:
3425
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3426
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3427
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3428
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3429
+ *
3430
+ * @public exported from `@promptbook/markdown-utils`
3431
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3307
3432
  */
3308
- function createPipelineExecutor(options) {
3309
- var _this = this;
3310
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3311
- 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;
3312
- validatePipeline(pipeline);
3313
- var pipelineIdentification = (function () {
3314
- // Note: This is a 😐 implementation of [🚞]
3315
- var _ = [];
3316
- if (pipeline.sourceFile !== undefined) {
3317
- _.push("File: ".concat(pipeline.sourceFile));
3318
- }
3319
- if (pipeline.pipelineUrl !== undefined) {
3320
- _.push("Url: ".concat(pipeline.pipelineUrl));
3321
- }
3322
- return _.join('\n');
3323
- })();
3324
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3325
- var preparedPipeline;
3326
- if (isPipelinePrepared(pipeline)) {
3327
- preparedPipeline = pipeline;
3433
+ function extractJsonBlock(markdown) {
3434
+ if (isValidJsonString(markdown)) {
3435
+ return markdown;
3328
3436
  }
3329
- else if (isNotPreparedWarningSupressed !== true) {
3330
- 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 "); }));
3437
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3438
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3439
+ var content = _a.content;
3440
+ return isValidJsonString(content);
3441
+ });
3442
+ if (jsonBlocks.length === 0) {
3443
+ throw new Error('There is no valid JSON block in the markdown');
3331
3444
  }
3332
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3333
- // TODO:[main] !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3334
- function getContextForTemplate(template) {
3335
- return __awaiter(this, void 0, void 0, function () {
3336
- return __generator(this, function (_a) {
3337
- TODO_USE(template);
3338
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3339
- });
3340
- });
3445
+ if (jsonBlocks.length > 1) {
3446
+ throw new Error('There are multiple JSON code blocks in the markdown');
3447
+ }
3448
+ return jsonBlocks[0].content;
3449
+ }
3450
+ /**
3451
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3452
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3453
+ */
3454
+
3455
+ /**
3456
+ * Just says that the variable is not used but should be kept
3457
+ * No side effects.
3458
+ *
3459
+ * Note: It can be usefull for:
3460
+ *
3461
+ * 1) Suppressing eager optimization of unused imports
3462
+ * 2) Suppressing eslint errors of unused variables in the tests
3463
+ * 3) Keeping the type of the variable for type testing
3464
+ *
3465
+ * @param value any values
3466
+ * @returns void
3467
+ * @private within the repository
3468
+ */
3469
+ function keepUnused() {
3470
+ var valuesToKeep = [];
3471
+ for (var _i = 0; _i < arguments.length; _i++) {
3472
+ valuesToKeep[_i] = arguments[_i];
3473
+ }
3474
+ }
3475
+
3476
+ /**
3477
+ * Replaces parameters in template with values from parameters object
3478
+ *
3479
+ * @param template the template with parameters in {curly} braces
3480
+ * @param parameters the object with parameters
3481
+ * @returns the template with replaced parameters
3482
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3483
+ * @public exported from `@promptbook/utils`
3484
+ */
3485
+ function replaceParameters(template, parameters) {
3486
+ var e_1, _a;
3487
+ try {
3488
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3489
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3490
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3491
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3492
+ }
3493
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3494
+ // TODO: [🍵]
3495
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3496
+ }
3341
3497
  }
3342
- function getKnowledgeForTemplate(template) {
3343
- return __awaiter(this, void 0, void 0, function () {
3344
- return __generator(this, function (_a) {
3345
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3346
- TODO_USE(template);
3347
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3348
- var content = _a.content;
3349
- return "- ".concat(content);
3350
- }).join('\n')];
3351
- });
3352
- });
3498
+ }
3499
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3500
+ finally {
3501
+ try {
3502
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3353
3503
  }
3354
- function getSamplesForTemplate(template) {
3355
- return __awaiter(this, void 0, void 0, function () {
3356
- return __generator(this, function (_a) {
3357
- // TODO: [♨] Implement Better - use real index and keyword search
3358
- TODO_USE(template);
3359
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3360
- });
3361
- });
3504
+ finally { if (e_1) throw e_1.error; }
3505
+ }
3506
+ var replacedTemplate = template;
3507
+ var match;
3508
+ var loopLimit = LOOP_LIMIT;
3509
+ var _loop_1 = function () {
3510
+ if (loopLimit-- < 0) {
3511
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3362
3512
  }
3363
- function getReservedParametersForTemplate(template) {
3364
- return __awaiter(this, void 0, void 0, function () {
3365
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3366
- var e_3, _a;
3367
- return __generator(this, function (_b) {
3368
- switch (_b.label) {
3369
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3370
- case 1:
3371
- context = _b.sent();
3372
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3373
- case 2:
3374
- knowledge = _b.sent();
3375
- return [4 /*yield*/, getSamplesForTemplate(template)];
3376
- case 3:
3377
- samples = _b.sent();
3378
- currentDate = new Date().toISOString();
3379
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3380
- reservedParameters = {
3381
- content: RESERVED_PARAMETER_RESTRICTED,
3382
- context: context,
3383
- knowledge: knowledge,
3384
- samples: samples,
3385
- currentDate: currentDate,
3386
- modelName: modelName,
3387
- };
3388
- _loop_3 = function (parameterName) {
3389
- if (reservedParameters[parameterName] === undefined) {
3390
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3391
- }
3392
- };
3393
- try {
3394
- // Note: Doublecheck that ALL reserved parameters are defined:
3395
- 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()) {
3396
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3397
- _loop_3(parameterName);
3398
- }
3399
- }
3400
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3401
- finally {
3402
- try {
3403
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3404
- }
3405
- finally { if (e_3) throw e_3.error; }
3406
- }
3407
- return [2 /*return*/, reservedParameters];
3408
- }
3409
- });
3410
- });
3513
+ var precol = match.groups.precol;
3514
+ var parameterName = match.groups.parameterName;
3515
+ if (parameterName === '') {
3516
+ return "continue";
3411
3517
  }
3412
- function executeSingleTemplate(currentTemplate) {
3413
- return __awaiter(this, void 0, void 0, function () {
3414
- 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;
3415
- var e_4, _f, _g;
3416
- return __generator(this, function (_h) {
3417
- switch (_h.label) {
3418
- case 0:
3419
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3420
- title = currentTemplate.title;
3421
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3422
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3423
- progress_1 = {
3424
- name: name,
3425
- title: title,
3426
- isStarted: false,
3427
- isDone: false,
3428
- templateType: currentTemplate.templateType,
3429
- parameterName: currentTemplate.resultingParameterName,
3430
- parameterValue: null,
3431
- // <- [3]
3432
- };
3433
- if (isReturned) {
3434
- 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)
3435
- .split('\n')
3436
- .map(function (line) { return "> ".concat(line); })
3437
- .join('\n')), "\n "); }));
3438
- }
3439
- return [4 /*yield*/, onProgress(progress_1)];
3440
- case 1:
3441
- _h.sent();
3442
- _h.label = 2;
3443
- case 2:
3444
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3445
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3446
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3447
- 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)
3448
- .map(function (name) { return "{".concat(name, "}"); })
3449
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3450
- .map(function (name) { return "{".concat(name, "}"); })
3451
- .join(', '), "\n\n "); }));
3452
- }
3453
- _b = (_a = Object).freeze;
3454
- _c = [{}];
3455
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3456
- case 3:
3457
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3458
- definedParameterNames = new Set(Object.keys(definedParameters));
3459
- parameters = {};
3460
- _loop_4 = function (parameterName) {
3461
- // Situation: Parameter is defined and used
3462
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3463
- parameters[parameterName] = definedParameters[parameterName];
3464
- }
3465
- // Situation: Parameter is defined but NOT used
3466
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3467
- // Situation: Parameter is NOT defined BUT used
3468
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3469
- // Houston, we have a problem
3470
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3471
- 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 "); }));
3472
- }
3473
- };
3474
- try {
3475
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3476
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3477
- parameterName = _e.value;
3478
- _loop_4(parameterName);
3479
- }
3480
- }
3481
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3482
- finally {
3483
- try {
3484
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3485
- }
3486
- finally { if (e_4) throw e_4.error; }
3487
- }
3488
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3489
- Object.freeze(parameters);
3490
- result = null;
3491
- resultString = null;
3492
- expectError = null;
3493
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3494
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3495
- preparedContent = (currentTemplate.preparedContent || '{content}')
3496
- .split('{content}')
3497
- .join(currentTemplate.content);
3498
- _loop_5 = function (attempt) {
3499
- 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;
3500
- var e_5, _s, e_7, _t, e_6, _u;
3501
- return __generator(this, function (_v) {
3502
- switch (_v.label) {
3503
- case 0:
3504
- isJokerAttempt = attempt < 0;
3505
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3506
- if (isJokerAttempt && !jokerParameterName) {
3507
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3508
- }
3509
- result = null;
3510
- resultString = null;
3511
- expectError = null;
3512
- if (isJokerAttempt) {
3513
- if (parameters[jokerParameterName] === undefined) {
3514
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3515
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3516
- }
3517
- else {
3518
- resultString = parameters[jokerParameterName];
3519
- }
3520
- }
3521
- _v.label = 1;
3522
- case 1:
3523
- _v.trys.push([1, 44, 45, 46]);
3524
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3525
- _j = currentTemplate.templateType;
3526
- switch (_j) {
3527
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3528
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3529
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3530
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3531
- }
3532
- return [3 /*break*/, 25];
3533
- case 2:
3534
- resultString = replaceParameters(preparedContent, parameters);
3535
- return [3 /*break*/, 26];
3536
- case 3:
3537
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3538
- prompt = {
3539
- title: currentTemplate.title,
3540
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3541
- ? preparedPipeline.pipelineUrl
3542
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3543
- parameters: parameters,
3544
- content: preparedContent,
3545
- modelRequirements: modelRequirements,
3546
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3547
- var name = _a.name;
3548
- return name === currentTemplate.personaName;
3549
- }) || {})), currentTemplate.expectations),
3550
- format: currentTemplate.format,
3551
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3552
- }; // <- TODO: Not very good type guard
3553
- _k = modelRequirements.modelVariant;
3554
- switch (_k) {
3555
- case 'CHAT': return [3 /*break*/, 4];
3556
- case 'COMPLETION': return [3 /*break*/, 6];
3557
- case 'EMBEDDING': return [3 /*break*/, 8];
3558
- }
3559
- return [3 /*break*/, 10];
3560
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3561
- case 5:
3562
- chatResult = _v.sent();
3563
- // TODO: [🍬] Destroy chatThread
3564
- result = chatResult;
3565
- resultString = chatResult.content;
3566
- return [3 /*break*/, 11];
3567
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3568
- case 7:
3569
- completionResult = _v.sent();
3570
- result = completionResult;
3571
- resultString = completionResult.content;
3572
- return [3 /*break*/, 11];
3573
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3574
- case 9:
3575
- embeddingResult = _v.sent();
3576
- result = embeddingResult;
3577
- resultString = embeddingResult.content.join(',');
3578
- return [3 /*break*/, 11];
3579
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3580
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3581
- case 11: return [3 /*break*/, 26];
3582
- case 12:
3583
- if (arrayableToArray(tools.script).length === 0) {
3584
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3585
- }
3586
- if (!currentTemplate.contentLanguage) {
3587
- 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 "); }));
3588
- }
3589
- // TODO: DRY [1]
3590
- scriptPipelineExecutionErrors = [];
3591
- _v.label = 13;
3592
- case 13:
3593
- _v.trys.push([13, 20, 21, 22]);
3594
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3595
- _v.label = 14;
3596
- case 14:
3597
- if (!!_m.done) return [3 /*break*/, 19];
3598
- scriptTools = _m.value;
3599
- _v.label = 15;
3600
- case 15:
3601
- _v.trys.push([15, 17, , 18]);
3602
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3603
- scriptLanguage: currentTemplate.contentLanguage,
3604
- script: preparedContent,
3605
- parameters: parameters,
3606
- }))];
3607
- case 16:
3608
- resultString = _v.sent();
3609
- return [3 /*break*/, 19];
3610
- case 17:
3611
- error_2 = _v.sent();
3612
- if (!(error_2 instanceof Error)) {
3613
- throw error_2;
3614
- }
3615
- if (error_2 instanceof UnexpectedError) {
3616
- throw error_2;
3617
- }
3618
- scriptPipelineExecutionErrors.push(error_2);
3619
- return [3 /*break*/, 18];
3620
- case 18:
3621
- _m = _l.next();
3622
- return [3 /*break*/, 14];
3623
- case 19: return [3 /*break*/, 22];
3624
- case 20:
3625
- e_5_1 = _v.sent();
3626
- e_5 = { error: e_5_1 };
3627
- return [3 /*break*/, 22];
3628
- case 21:
3629
- try {
3630
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3631
- }
3632
- finally { if (e_5) throw e_5.error; }
3633
- return [7 /*endfinally*/];
3634
- case 22:
3635
- if (resultString !== null) {
3636
- return [3 /*break*/, 26];
3637
- }
3638
- if (scriptPipelineExecutionErrors.length === 1) {
3639
- throw scriptPipelineExecutionErrors[0];
3640
- }
3641
- else {
3642
- 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
3643
- .map(function (error) { return '- ' + error.message; })
3644
- .join('\n\n')), "\n "); }));
3645
- }
3646
- case 23:
3647
- if (tools.userInterface === undefined) {
3648
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3649
- }
3650
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3651
- promptTitle: currentTemplate.title,
3652
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3653
- defaultValue: replaceParameters(preparedContent, parameters),
3654
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3655
- placeholder: undefined,
3656
- priority: priority,
3657
- }))];
3658
- case 24:
3659
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3660
- resultString = _v.sent();
3661
- return [3 /*break*/, 26];
3662
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3663
- case 26:
3664
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3665
- _v.label = 27;
3666
- case 27:
3667
- _v.trys.push([27, 41, 42, 43]);
3668
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3669
- _v.label = 28;
3670
- case 28:
3671
- if (!!_p.done) return [3 /*break*/, 40];
3672
- functionName = _p.value;
3673
- // TODO: DRY [1]
3674
- scriptPipelineExecutionErrors = [];
3675
- postprocessingError = null;
3676
- _v.label = 29;
3677
- case 29:
3678
- _v.trys.push([29, 36, 37, 38]);
3679
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3680
- _v.label = 30;
3681
- case 30:
3682
- if (!!_r.done) return [3 /*break*/, 35];
3683
- scriptTools = _r.value;
3684
- _v.label = 31;
3685
- case 31:
3686
- _v.trys.push([31, 33, , 34]);
3687
- return [4 /*yield*/, scriptTools.execute({
3688
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3689
- script: "".concat(functionName, "(resultString)"),
3690
- parameters: {
3691
- resultString: resultString || '',
3692
- // Note: No ...parametersForTemplate, because working with result only
3693
- },
3694
- })];
3695
- case 32:
3696
- resultString = _v.sent();
3697
- postprocessingError = null;
3698
- return [3 /*break*/, 35];
3699
- case 33:
3700
- error_3 = _v.sent();
3701
- if (!(error_3 instanceof Error)) {
3702
- throw error_3;
3703
- }
3704
- if (error_3 instanceof UnexpectedError) {
3705
- throw error_3;
3706
- }
3707
- postprocessingError = error_3;
3708
- scriptPipelineExecutionErrors.push(error_3);
3709
- return [3 /*break*/, 34];
3710
- case 34:
3711
- _r = _q.next();
3712
- return [3 /*break*/, 30];
3713
- case 35: return [3 /*break*/, 38];
3714
- case 36:
3715
- e_6_1 = _v.sent();
3716
- e_6 = { error: e_6_1 };
3717
- return [3 /*break*/, 38];
3718
- case 37:
3719
- try {
3720
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3721
- }
3722
- finally { if (e_6) throw e_6.error; }
3723
- return [7 /*endfinally*/];
3724
- case 38:
3725
- if (postprocessingError) {
3726
- throw postprocessingError;
3727
- }
3728
- _v.label = 39;
3729
- case 39:
3730
- _p = _o.next();
3731
- return [3 /*break*/, 28];
3732
- case 40: return [3 /*break*/, 43];
3733
- case 41:
3734
- e_7_1 = _v.sent();
3735
- e_7 = { error: e_7_1 };
3736
- return [3 /*break*/, 43];
3737
- case 42:
3738
- try {
3739
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3740
- }
3741
- finally { if (e_7) throw e_7.error; }
3742
- return [7 /*endfinally*/];
3743
- case 43:
3744
- // TODO: [💝] Unite object for expecting amount and format
3745
- if (currentTemplate.format) {
3746
- if (currentTemplate.format === 'JSON') {
3747
- if (!isValidJsonString(resultString || '')) {
3748
- // TODO: [🏢] Do more universally via `FormatDefinition`
3749
- try {
3750
- resultString = extractJsonBlock(resultString || '');
3751
- }
3752
- catch (error) {
3753
- keepUnused(error);
3754
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3755
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3756
- }
3757
- }
3518
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3519
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3520
+ }
3521
+ if (parameters[parameterName] === undefined) {
3522
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3523
+ }
3524
+ var parameterValue = parameters[parameterName];
3525
+ if (parameterValue === undefined) {
3526
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3527
+ }
3528
+ parameterValue = parameterValue.toString();
3529
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3530
+ parameterValue = parameterValue
3531
+ .split('\n')
3532
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3533
+ .join('\n');
3534
+ }
3535
+ replacedTemplate =
3536
+ replacedTemplate.substring(0, match.index + precol.length) +
3537
+ parameterValue +
3538
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3539
+ };
3540
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3541
+ .exec(replacedTemplate))) {
3542
+ _loop_1();
3543
+ }
3544
+ // [💫] Check if there are parameters that are not closed properly
3545
+ if (/{\w+$/.test(replacedTemplate)) {
3546
+ throw new PipelineExecutionError('Parameter is not closed');
3547
+ }
3548
+ // [💫] Check if there are parameters that are not opened properly
3549
+ if (/^\w+}/.test(replacedTemplate)) {
3550
+ throw new PipelineExecutionError('Parameter is not opened');
3551
+ }
3552
+ return replacedTemplate;
3553
+ }
3554
+
3555
+ /**
3556
+ * Counts number of characters in the text
3557
+ *
3558
+ * @public exported from `@promptbook/utils`
3559
+ */
3560
+ function countCharacters(text) {
3561
+ // Remove null characters
3562
+ text = text.replace(/\0/g, '');
3563
+ // Replace emojis (and also ZWJ sequence) with hyphens
3564
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3565
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3566
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3567
+ return text.length;
3568
+ }
3569
+
3570
+ /**
3571
+ * Counts number of lines in the text
3572
+ *
3573
+ * @public exported from `@promptbook/utils`
3574
+ */
3575
+ function countLines(text) {
3576
+ if (text === '') {
3577
+ return 0;
3578
+ }
3579
+ return text.split('\n').length;
3580
+ }
3581
+
3582
+ /**
3583
+ * Counts number of pages in the text
3584
+ *
3585
+ * @public exported from `@promptbook/utils`
3586
+ */
3587
+ function countPages(text) {
3588
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3589
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3590
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3591
+ return pageCount;
3592
+ }
3593
+
3594
+ /**
3595
+ * Counts number of paragraphs in the text
3596
+ *
3597
+ * @public exported from `@promptbook/utils`
3598
+ */
3599
+ function countParagraphs(text) {
3600
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3601
+ }
3602
+
3603
+ /**
3604
+ * Split text into sentences
3605
+ *
3606
+ * @public exported from `@promptbook/utils`
3607
+ */
3608
+ function splitIntoSentences(text) {
3609
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3610
+ }
3611
+ /**
3612
+ * Counts number of sentences in the text
3613
+ *
3614
+ * @public exported from `@promptbook/utils`
3615
+ */
3616
+ function countSentences(text) {
3617
+ return splitIntoSentences(text).length;
3618
+ }
3619
+
3620
+ /**
3621
+ * Counts number of words in the text
3622
+ *
3623
+ * @public exported from `@promptbook/utils`
3624
+ */
3625
+ function countWords(text) {
3626
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3627
+ text = removeDiacritics(text);
3628
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3629
+ }
3630
+
3631
+ /**
3632
+ * Index of all counter functions
3633
+ *
3634
+ * @public exported from `@promptbook/utils`
3635
+ */
3636
+ var CountUtils = {
3637
+ CHARACTERS: countCharacters,
3638
+ WORDS: countWords,
3639
+ SENTENCES: countSentences,
3640
+ PARAGRAPHS: countParagraphs,
3641
+ LINES: countLines,
3642
+ PAGES: countPages,
3643
+ };
3644
+ /**
3645
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3646
+ */
3647
+
3648
+ /**
3649
+ * Function checkExpectations will check if the expectations on given value are met
3650
+ *
3651
+ * Note: There are two simmilar functions:
3652
+ * - `checkExpectations` which throws an error if the expectations are not met
3653
+ * - `isPassingExpectations` which returns a boolean
3654
+ *
3655
+ * @throws {ExpectError} if the expectations are not met
3656
+ * @returns {void} Nothing
3657
+ * @private internal function of `createPipelineExecutor`
3658
+ */
3659
+ function checkExpectations(expectations, value) {
3660
+ var e_1, _a;
3661
+ try {
3662
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3663
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3664
+ var amount = CountUtils[unit.toUpperCase()](value);
3665
+ if (min && amount < min) {
3666
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3667
+ } /* not else */
3668
+ if (max && amount > max) {
3669
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3670
+ }
3671
+ }
3672
+ }
3673
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3674
+ finally {
3675
+ try {
3676
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3677
+ }
3678
+ finally { if (e_1) throw e_1.error; }
3679
+ }
3680
+ }
3681
+ /**
3682
+ * Function checkExpectations will check if the expectations on given value are met
3683
+ *
3684
+ * Note: There are two simmilar functions:
3685
+ * - `checkExpectations` which throws an error if the expectations are not met
3686
+ * - `isPassingExpectations` which returns a boolean
3687
+ *
3688
+ * @returns {boolean} True if the expectations are met
3689
+ * @public exported from `@promptbook/core`
3690
+ */
3691
+ function isPassingExpectations(expectations, value) {
3692
+ try {
3693
+ checkExpectations(expectations, value);
3694
+ return true;
3695
+ }
3696
+ catch (error) {
3697
+ if (!(error instanceof ExpectError)) {
3698
+ throw error;
3699
+ }
3700
+ return false;
3701
+ }
3702
+ }
3703
+ /**
3704
+ * TODO: [💝] Unite object for expecting amount and format
3705
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3706
+ * Note: [💝] and [🤠] are interconnected together
3707
+ */
3708
+
3709
+ /**
3710
+ * @@@
3711
+ *
3712
+ * @private internal utility of `createPipelineExecutor`
3713
+ */
3714
+ function executeAttempts(options) {
3715
+ return __awaiter(this, void 0, void 0, function () {
3716
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3717
+ return __generator(this, function (_a) {
3718
+ switch (_a.label) {
3719
+ case 0:
3720
+ 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;
3721
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3722
+ $ongoingTemplateResult = {
3723
+ $result: null,
3724
+ $resultString: null,
3725
+ $expectError: null,
3726
+ $scriptPipelineExecutionErrors: [],
3727
+ };
3728
+ _loop_1 = function (attempt) {
3729
+ 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;
3730
+ var e_1, _q, e_3, _r, e_2, _s;
3731
+ return __generator(this, function (_t) {
3732
+ switch (_t.label) {
3733
+ case 0:
3734
+ isJokerAttempt = attempt < 0;
3735
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3736
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3737
+ if (isJokerAttempt && !jokerParameterName) {
3738
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3739
+ }
3740
+ $ongoingTemplateResult.$result = null;
3741
+ $ongoingTemplateResult.$resultString = null;
3742
+ $ongoingTemplateResult.$expectError = null;
3743
+ if (isJokerAttempt) {
3744
+ if (parameters[jokerParameterName] === undefined) {
3745
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3746
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3747
+ }
3748
+ else {
3749
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3750
+ }
3751
+ }
3752
+ _t.label = 1;
3753
+ case 1:
3754
+ _t.trys.push([1, 43, 44, 45]);
3755
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3756
+ _b = template.templateType;
3757
+ switch (_b) {
3758
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3759
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3760
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3761
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3762
+ }
3763
+ return [3 /*break*/, 24];
3764
+ case 2:
3765
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3766
+ return [3 /*break*/, 25];
3767
+ case 3:
3768
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3769
+ $ongoingTemplateResult.$prompt = {
3770
+ title: template.title,
3771
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3772
+ ? preparedPipeline.pipelineUrl
3773
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3774
+ parameters: parameters,
3775
+ content: preparedContent,
3776
+ modelRequirements: modelRequirements,
3777
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3778
+ var name = _a.name;
3779
+ return name === template.personaName;
3780
+ }) ||
3781
+ {})), template.expectations),
3782
+ format: template.format,
3783
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3784
+ }; // <- TODO: Not very good type guard
3785
+ _c = modelRequirements.modelVariant;
3786
+ switch (_c) {
3787
+ case 'CHAT': return [3 /*break*/, 4];
3788
+ case 'COMPLETION': return [3 /*break*/, 6];
3789
+ case 'EMBEDDING': return [3 /*break*/, 8];
3790
+ }
3791
+ return [3 /*break*/, 9];
3792
+ case 4:
3793
+ _d = $ongoingTemplateResult;
3794
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3795
+ case 5:
3796
+ _d.$chatResult = _t.sent();
3797
+ // TODO: [🍬] Destroy chatThread
3798
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3799
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3800
+ return [3 /*break*/, 10];
3801
+ case 6:
3802
+ _e = $ongoingTemplateResult;
3803
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3804
+ case 7:
3805
+ _e.$completionResult = _t.sent();
3806
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3807
+ $ongoingTemplateResult.$resultString =
3808
+ $ongoingTemplateResult.$completionResult.content;
3809
+ return [3 /*break*/, 10];
3810
+ 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 "); }));
3811
+ 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 "); }));
3812
+ case 10: return [3 /*break*/, 25];
3813
+ case 11:
3814
+ if (arrayableToArray(tools.script).length === 0) {
3815
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3816
+ }
3817
+ if (!template.contentLanguage) {
3818
+ 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 "); }));
3819
+ }
3820
+ _t.label = 12;
3821
+ case 12:
3822
+ _t.trys.push([12, 19, 20, 21]);
3823
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3824
+ _t.label = 13;
3825
+ case 13:
3826
+ if (!!_g.done) return [3 /*break*/, 18];
3827
+ scriptTools = _g.value;
3828
+ _t.label = 14;
3829
+ case 14:
3830
+ _t.trys.push([14, 16, , 17]);
3831
+ _h = $ongoingTemplateResult;
3832
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3833
+ scriptLanguage: template.contentLanguage,
3834
+ script: preparedContent,
3835
+ parameters: parameters,
3836
+ }))];
3837
+ case 15:
3838
+ _h.$resultString = _t.sent();
3839
+ return [3 /*break*/, 18];
3840
+ case 16:
3841
+ error_1 = _t.sent();
3842
+ if (!(error_1 instanceof Error)) {
3843
+ throw error_1;
3844
+ }
3845
+ if (error_1 instanceof UnexpectedError) {
3846
+ throw error_1;
3847
+ }
3848
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3849
+ return [3 /*break*/, 17];
3850
+ case 17:
3851
+ _g = _f.next();
3852
+ return [3 /*break*/, 13];
3853
+ case 18: return [3 /*break*/, 21];
3854
+ case 19:
3855
+ e_1_1 = _t.sent();
3856
+ e_1 = { error: e_1_1 };
3857
+ return [3 /*break*/, 21];
3858
+ case 20:
3859
+ try {
3860
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3861
+ }
3862
+ finally { if (e_1) throw e_1.error; }
3863
+ return [7 /*endfinally*/];
3864
+ case 21:
3865
+ if ($ongoingTemplateResult.$resultString !== null) {
3866
+ return [3 /*break*/, 25];
3867
+ }
3868
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3869
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3870
+ }
3871
+ else {
3872
+ 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
3873
+ .map(function (error) { return '- ' + error.message; })
3874
+ .join('\n\n')), "\n "); }));
3875
+ }
3876
+ case 22:
3877
+ if (tools.userInterface === undefined) {
3878
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3879
+ }
3880
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3881
+ _j = $ongoingTemplateResult;
3882
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3883
+ promptTitle: template.title,
3884
+ promptMessage: replaceParameters(template.description || '', parameters),
3885
+ defaultValue: replaceParameters(preparedContent, parameters),
3886
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3887
+ placeholder: undefined,
3888
+ priority: priority,
3889
+ }))];
3890
+ case 23:
3891
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3892
+ _j.$resultString = _t.sent();
3893
+ return [3 /*break*/, 25];
3894
+ case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3895
+ case 25:
3896
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3897
+ _t.label = 26;
3898
+ case 26:
3899
+ _t.trys.push([26, 40, 41, 42]);
3900
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3901
+ _t.label = 27;
3902
+ case 27:
3903
+ if (!!_l.done) return [3 /*break*/, 39];
3904
+ functionName = _l.value;
3905
+ postprocessingError = null;
3906
+ _t.label = 28;
3907
+ case 28:
3908
+ _t.trys.push([28, 35, 36, 37]);
3909
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3910
+ _t.label = 29;
3911
+ case 29:
3912
+ if (!!_o.done) return [3 /*break*/, 34];
3913
+ scriptTools = _o.value;
3914
+ _t.label = 30;
3915
+ case 30:
3916
+ _t.trys.push([30, 32, , 33]);
3917
+ _p = $ongoingTemplateResult;
3918
+ return [4 /*yield*/, scriptTools.execute({
3919
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3920
+ script: "".concat(functionName, "(resultString)"),
3921
+ parameters: {
3922
+ resultString: $ongoingTemplateResult.$resultString || '',
3923
+ // Note: No ...parametersForTemplate, because working with result only
3924
+ },
3925
+ })];
3926
+ case 31:
3927
+ _p.$resultString = _t.sent();
3928
+ postprocessingError = null;
3929
+ return [3 /*break*/, 34];
3930
+ case 32:
3931
+ error_2 = _t.sent();
3932
+ if (!(error_2 instanceof Error)) {
3933
+ throw error_2;
3934
+ }
3935
+ if (error_2 instanceof UnexpectedError) {
3936
+ throw error_2;
3937
+ }
3938
+ postprocessingError = error_2;
3939
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3940
+ return [3 /*break*/, 33];
3941
+ case 33:
3942
+ _o = _m.next();
3943
+ return [3 /*break*/, 29];
3944
+ case 34: return [3 /*break*/, 37];
3945
+ case 35:
3946
+ e_2_1 = _t.sent();
3947
+ e_2 = { error: e_2_1 };
3948
+ return [3 /*break*/, 37];
3949
+ case 36:
3950
+ try {
3951
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3952
+ }
3953
+ finally { if (e_2) throw e_2.error; }
3954
+ return [7 /*endfinally*/];
3955
+ case 37:
3956
+ if (postprocessingError) {
3957
+ throw postprocessingError;
3958
+ }
3959
+ _t.label = 38;
3960
+ case 38:
3961
+ _l = _k.next();
3962
+ return [3 /*break*/, 27];
3963
+ case 39: return [3 /*break*/, 42];
3964
+ case 40:
3965
+ e_3_1 = _t.sent();
3966
+ e_3 = { error: e_3_1 };
3967
+ return [3 /*break*/, 42];
3968
+ case 41:
3969
+ try {
3970
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3971
+ }
3972
+ finally { if (e_3) throw e_3.error; }
3973
+ return [7 /*endfinally*/];
3974
+ case 42:
3975
+ // TODO: [💝] Unite object for expecting amount and format
3976
+ if (template.format) {
3977
+ if (template.format === 'JSON') {
3978
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3979
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3980
+ try {
3981
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3758
3982
  }
3759
- else {
3760
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3983
+ catch (error) {
3984
+ keepUnused(error);
3985
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3986
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3761
3987
  }
3762
3988
  }
3763
- // TODO: [💝] Unite object for expecting amount and format
3764
- if (currentTemplate.expectations) {
3765
- checkExpectations(currentTemplate.expectations, resultString || '');
3766
- }
3767
- return [2 /*return*/, "break-attempts"];
3768
- case 44:
3769
- error_4 = _v.sent();
3770
- if (!(error_4 instanceof ExpectError)) {
3771
- throw error_4;
3772
- }
3773
- expectError = error_4;
3774
- return [3 /*break*/, 46];
3775
- case 45:
3776
- if (!isJokerAttempt &&
3777
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3778
- prompt
3779
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3780
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3781
- ) {
3782
- // TODO: [🧠] Maybe put other templateTypes into report
3783
- executionReport.promptExecutions.push({
3784
- prompt: __assign({}, prompt),
3785
- result: result || undefined,
3786
- error: expectError === null ? undefined : serializeError(expectError),
3787
- });
3788
- }
3789
- return [7 /*endfinally*/];
3790
- case 46:
3791
- if (expectError !== null && attempt === maxAttempts - 1) {
3792
- 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
3793
- .split('\n')
3794
- .map(function (line) { return "> ".concat(line); })
3795
- .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) || '')
3989
+ }
3990
+ else {
3991
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3992
+ }
3993
+ }
3994
+ // TODO: [💝] Unite object for expecting amount and format
3995
+ if (template.expectations) {
3996
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3997
+ }
3998
+ return [2 /*return*/, "break-attempts"];
3999
+ case 43:
4000
+ error_3 = _t.sent();
4001
+ if (!(error_3 instanceof ExpectError)) {
4002
+ throw error_3;
4003
+ }
4004
+ $ongoingTemplateResult.$expectError = error_3;
4005
+ return [3 /*break*/, 45];
4006
+ case 44:
4007
+ if (!isJokerAttempt &&
4008
+ template.templateType === 'PROMPT_TEMPLATE' &&
4009
+ $ongoingTemplateResult.$prompt
4010
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
4011
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
4012
+ ) {
4013
+ // TODO: [🧠] Maybe put other templateTypes into report
4014
+ $executionReport.promptExecutions.push({
4015
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
4016
+ result: $ongoingTemplateResult.$result || undefined,
4017
+ error: $ongoingTemplateResult.$expectError === null
4018
+ ? undefined
4019
+ : serializeError($ongoingTemplateResult.$expectError),
4020
+ });
4021
+ }
4022
+ return [7 /*endfinally*/];
4023
+ case 45:
4024
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
4025
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
4026
+ var _a, _b, _c;
4027
+ 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) || '')
4028
+ .split('\n')
4029
+ .map(function (line) { return "> ".concat(line); })
4030
+ .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) || '')
4031
+ .split('\n')
4032
+ .map(function (line) { return "> ".concat(line); })
4033
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
4034
+ ? 'null'
4035
+ : $ongoingTemplateResult.$resultString
3796
4036
  .split('\n')
3797
4037
  .map(function (line) { return "> ".concat(line); })
3798
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3799
- ? 'null'
3800
- : resultString
3801
- .split('\n')
3802
- .map(function (line) { return "> ".concat(line); })
3803
- .join('\n')), "\n ---\n "); }));
3804
- }
3805
- return [2 /*return*/];
4038
+ .join('\n')), "\n ---\n ");
4039
+ }));
3806
4040
  }
3807
- });
3808
- };
3809
- attempt = -jokerParameterNames.length;
3810
- _h.label = 4;
3811
- case 4:
3812
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3813
- return [5 /*yield**/, _loop_5(attempt)];
3814
- case 5:
3815
- state_2 = _h.sent();
3816
- switch (state_2) {
3817
- case "break-attempts": return [3 /*break*/, 7];
3818
- }
3819
- _h.label = 6;
3820
- case 6:
3821
- attempt++;
3822
- return [3 /*break*/, 4];
3823
- case 7:
3824
- if (resultString === null) {
3825
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4041
+ return [2 /*return*/];
3826
4042
  }
3827
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3828
- progress_2 = {
3829
- name: name,
3830
- title: title,
3831
- isStarted: true,
3832
- isDone: true,
3833
- templateType: currentTemplate.templateType,
3834
- parameterName: currentTemplate.resultingParameterName,
3835
- parameterValue: resultString,
3836
- // <- [3]
3837
- };
3838
- if (isReturned) {
3839
- 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)
3840
- .split('\n')
3841
- .map(function (line) { return "> ".concat(line); })
3842
- .join('\n')), "\n\n "); }));
3843
- }
3844
- return [4 /*yield*/, onProgress(progress_2)];
3845
- case 8:
3846
- _h.sent();
3847
- _h.label = 9;
3848
- case 9:
3849
- 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)));
3850
- return [2 /*return*/];
4043
+ });
4044
+ };
4045
+ attempt = -jokerParameterNames.length;
4046
+ _a.label = 1;
4047
+ case 1:
4048
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
4049
+ return [5 /*yield**/, _loop_1(attempt)];
4050
+ case 2:
4051
+ state_1 = _a.sent();
4052
+ switch (state_1) {
4053
+ case "break-attempts": return [3 /*break*/, 4];
3851
4054
  }
3852
- });
3853
- });
3854
- }
3855
- function filterJustOutputParameters() {
3856
- var e_8, _a;
3857
- var outputParameters = {};
3858
- var _loop_6 = function (parameter) {
3859
- if (parametersToPass[parameter.name] === undefined) {
3860
- // [4]
3861
- 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 "); })));
3862
- return "continue";
3863
- }
3864
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3865
- };
3866
- try {
3867
- // Note: Filter ONLY output parameters
3868
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3869
- var isOutput = _a.isOutput;
3870
- return isOutput;
3871
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3872
- var parameter = _c.value;
3873
- _loop_6(parameter);
3874
- }
4055
+ _a.label = 3;
4056
+ case 3:
4057
+ attempt++;
4058
+ return [3 /*break*/, 1];
4059
+ case 4:
4060
+ if ($ongoingTemplateResult.$resultString === null) {
4061
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4062
+ }
4063
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3875
4064
  }
3876
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3877
- finally {
3878
- try {
3879
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3880
- }
3881
- finally { if (e_8) throw e_8.error; }
4065
+ });
4066
+ });
4067
+ }
4068
+ /**
4069
+ * TODO: Break into smaller functions
4070
+ */
4071
+
4072
+ /**
4073
+ * @@@
4074
+ *
4075
+ * @private internal utility of `createPipelineExecutor`
4076
+ */
4077
+ function executeFormatCells(options) {
4078
+ return __awaiter(this, void 0, void 0, function () {
4079
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
4080
+ var _this = this;
4081
+ return __generator(this, function (_a) {
4082
+ switch (_a.label) {
4083
+ case 0:
4084
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4085
+ if (template.foreach === undefined) {
4086
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
4087
+ }
4088
+ if (jokerParameterNames.length !== 0) {
4089
+ 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 "); }));
4090
+ }
4091
+ parameterValue = parameters[template.foreach.parameterName] || '';
4092
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
4093
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
4094
+ });
4095
+ if (formatDefinition === undefined) {
4096
+ throw new UnexpectedError(
4097
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4098
+ 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; })
4099
+ .map(function (formatName) { return "- ".concat(formatName); })
4100
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4101
+ }
4102
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
4103
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
4104
+ });
4105
+ if (subvalueDefinition === undefined) {
4106
+ throw new UnexpectedError(
4107
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4108
+ 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
4109
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
4110
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
4111
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4112
+ }
4113
+ if (formatDefinition.formatName === 'CSV') {
4114
+ formatSettings = settings.csvSettings;
4115
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
4116
+ }
4117
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4118
+ var mappedParameters, allSubparameters, subresultString;
4119
+ return __generator(this, function (_a) {
4120
+ switch (_a.label) {
4121
+ case 0:
4122
+ // TODO: !!!!!!! Limit to N concurrent executions
4123
+ // TODO: !!!!!!! Report progress
4124
+ try {
4125
+ mappedParameters = mapAvailableToExpectedParameters({
4126
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4127
+ availableParameters: subparameters,
4128
+ });
4129
+ }
4130
+ catch (error) {
4131
+ if (!(error instanceof PipelineExecutionError)) {
4132
+ throw error;
4133
+ }
4134
+ 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 "); }));
4135
+ }
4136
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4137
+ // 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
4138
+ Object.freeze(allSubparameters);
4139
+ 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 "); }) }))];
4140
+ case 1:
4141
+ subresultString = _a.sent();
4142
+ return [2 /*return*/, subresultString];
4143
+ }
4144
+ });
4145
+ }); })];
4146
+ case 1:
4147
+ resultString = _a.sent();
4148
+ return [2 /*return*/, resultString];
3882
4149
  }
3883
- return outputParameters;
4150
+ });
4151
+ });
4152
+ }
4153
+ /**
4154
+ * TODO: !!!!!! Make pipelineIdentification more precise
4155
+ * TODO: !!!!!! How FOREACH execution looks in the report
4156
+ */
4157
+
4158
+ /**
4159
+ * @@@
4160
+ *
4161
+ * @private internal utility of `createPipelineExecutor`
4162
+ */
4163
+ function getContextForTemplate(template) {
4164
+ return __awaiter(this, void 0, void 0, function () {
4165
+ return __generator(this, function (_a) {
4166
+ TODO_USE(template);
4167
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
4168
+ });
4169
+ });
4170
+ }
4171
+
4172
+ /**
4173
+ * @@@
4174
+ *
4175
+ * @private internal utility of `createPipelineExecutor`
4176
+ */
4177
+ function getKnowledgeForTemplate(options) {
4178
+ return __awaiter(this, void 0, void 0, function () {
4179
+ var preparedPipeline, template;
4180
+ return __generator(this, function (_a) {
4181
+ preparedPipeline = options.preparedPipeline, template = options.template;
4182
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4183
+ TODO_USE(template);
4184
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4185
+ var content = _a.content;
4186
+ return "- ".concat(content);
4187
+ }).join('\n')];
4188
+ });
4189
+ });
4190
+ }
4191
+
4192
+ /**
4193
+ * @@@
4194
+ *
4195
+ * @private internal utility of `createPipelineExecutor`
4196
+ */
4197
+ function getSamplesForTemplate(template) {
4198
+ return __awaiter(this, void 0, void 0, function () {
4199
+ return __generator(this, function (_a) {
4200
+ // TODO: [♨] Implement Better - use real index and keyword search
4201
+ TODO_USE(template);
4202
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4203
+ });
4204
+ });
4205
+ }
4206
+
4207
+ /**
4208
+ * @@@
4209
+ *
4210
+ * @private internal utility of `createPipelineExecutor`
4211
+ */
4212
+ function getReservedParametersForTemplate(options) {
4213
+ return __awaiter(this, void 0, void 0, function () {
4214
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4215
+ var e_1, _a;
4216
+ return __generator(this, function (_b) {
4217
+ switch (_b.label) {
4218
+ case 0:
4219
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4220
+ return [4 /*yield*/, getContextForTemplate(template)];
4221
+ case 1:
4222
+ context = _b.sent();
4223
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4224
+ case 2:
4225
+ knowledge = _b.sent();
4226
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4227
+ case 3:
4228
+ samples = _b.sent();
4229
+ currentDate = new Date().toISOString();
4230
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4231
+ reservedParameters = {
4232
+ content: RESERVED_PARAMETER_RESTRICTED,
4233
+ context: context,
4234
+ knowledge: knowledge,
4235
+ samples: samples,
4236
+ currentDate: currentDate,
4237
+ modelName: modelName,
4238
+ };
4239
+ _loop_1 = function (parameterName) {
4240
+ if (reservedParameters[parameterName] === undefined) {
4241
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4242
+ }
4243
+ };
4244
+ try {
4245
+ // Note: Doublecheck that ALL reserved parameters are defined:
4246
+ 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()) {
4247
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4248
+ _loop_1(parameterName);
4249
+ }
4250
+ }
4251
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4252
+ finally {
4253
+ try {
4254
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4255
+ }
4256
+ finally { if (e_1) throw e_1.error; }
4257
+ }
4258
+ return [2 /*return*/, reservedParameters];
4259
+ }
4260
+ });
4261
+ });
4262
+ }
4263
+
4264
+ /**
4265
+ * @@@
4266
+ *
4267
+ * @private internal utility of `createPipelineExecutor`
4268
+ */
4269
+ function executeTemplate(options) {
4270
+ return __awaiter(this, void 0, void 0, function () {
4271
+ 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;
4272
+ var e_1, _f, _g;
4273
+ return __generator(this, function (_h) {
4274
+ switch (_h.label) {
4275
+ case 0:
4276
+ 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;
4277
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4278
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4279
+ title = currentTemplate.title;
4280
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4281
+ return [4 /*yield*/, onProgress({
4282
+ name: name,
4283
+ title: title,
4284
+ isStarted: false,
4285
+ isDone: false,
4286
+ templateType: currentTemplate.templateType,
4287
+ parameterName: currentTemplate.resultingParameterName,
4288
+ parameterValue: null,
4289
+ // <- [🍸]
4290
+ })];
4291
+ case 1:
4292
+ _h.sent();
4293
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4294
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4295
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4296
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4297
+ 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)
4298
+ .map(function (name) { return "{".concat(name, "}"); })
4299
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4300
+ .map(function (name) { return "{".concat(name, "}"); })
4301
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4302
+ }
4303
+ _b = (_a = Object).freeze;
4304
+ _c = [{}];
4305
+ return [4 /*yield*/, getReservedParametersForTemplate({
4306
+ preparedPipeline: preparedPipeline,
4307
+ template: currentTemplate,
4308
+ pipelineIdentification: pipelineIdentification,
4309
+ })];
4310
+ case 2:
4311
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4312
+ definedParameterNames = new Set(Object.keys(definedParameters));
4313
+ parameters = {};
4314
+ _loop_1 = function (parameterName) {
4315
+ // Situation: Parameter is defined and used
4316
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4317
+ parameters[parameterName] = definedParameters[parameterName];
4318
+ }
4319
+ // Situation: Parameter is defined but NOT used
4320
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4321
+ // Situation: Parameter is NOT defined BUT used
4322
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4323
+ // Houston, we have a problem
4324
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4325
+ 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 "); }));
4326
+ }
4327
+ };
4328
+ try {
4329
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4330
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4331
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4332
+ parameterName = _e.value;
4333
+ _loop_1(parameterName);
4334
+ }
4335
+ }
4336
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4337
+ finally {
4338
+ try {
4339
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4340
+ }
4341
+ finally { if (e_1) throw e_1.error; }
4342
+ }
4343
+ // 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
4344
+ Object.freeze(parameters);
4345
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4346
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4347
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4348
+ .split('{content}')
4349
+ .join(currentTemplate.content);
4350
+ return [4 /*yield*/, executeFormatCells({
4351
+ jokerParameterNames: jokerParameterNames,
4352
+ priority: priority,
4353
+ maxAttempts: maxAttempts,
4354
+ preparedContent: preparedContent,
4355
+ parameters: parameters,
4356
+ template: currentTemplate,
4357
+ preparedPipeline: preparedPipeline,
4358
+ tools: tools,
4359
+ llmTools: llmTools,
4360
+ settings: settings,
4361
+ $executionReport: $executionReport,
4362
+ pipelineIdentification: pipelineIdentification,
4363
+ })];
4364
+ case 3:
4365
+ resultString = _h.sent();
4366
+ return [4 /*yield*/, onProgress({
4367
+ name: name,
4368
+ title: title,
4369
+ isStarted: true,
4370
+ isDone: true,
4371
+ templateType: currentTemplate.templateType,
4372
+ parameterName: currentTemplate.resultingParameterName,
4373
+ parameterValue: resultString,
4374
+ // <- [🍸]
4375
+ })];
4376
+ case 4:
4377
+ _h.sent();
4378
+ return [2 /*return*/, Object.freeze((_g = {},
4379
+ _g[currentTemplate.resultingParameterName] =
4380
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4381
+ resultString,
4382
+ _g))];
4383
+ }
4384
+ });
4385
+ });
4386
+ }
4387
+ /**
4388
+ * TODO: [🤹‍♂️]
4389
+ */
4390
+
4391
+ /**
4392
+ * @@@
4393
+ *
4394
+ * @private internal utility of `createPipelineExecutor`
4395
+ */
4396
+ function filterJustOutputParameters(options) {
4397
+ var e_1, _a;
4398
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4399
+ var outputParameters = {};
4400
+ var _loop_1 = function (parameter) {
4401
+ if (parametersToPass[parameter.name] === undefined) {
4402
+ // [4]
4403
+ $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 "); })));
4404
+ return "continue";
3884
4405
  }
3885
- 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;
4406
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4407
+ };
4408
+ try {
4409
+ // Note: Filter ONLY output parameters
4410
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4411
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4412
+ var isOutput = _a.isOutput;
4413
+ return isOutput;
4414
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4415
+ var parameter = _c.value;
4416
+ _loop_1(parameter);
4417
+ }
4418
+ }
4419
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4420
+ finally {
4421
+ try {
4422
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4423
+ }
4424
+ finally { if (e_1) throw e_1.error; }
4425
+ }
4426
+ return outputParameters;
4427
+ }
4428
+
4429
+ /**
4430
+ * @@@
4431
+ *
4432
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4433
+ *
4434
+ * @private internal utility of `createPipelineExecutor`
4435
+ */
4436
+ function executePipeline(options) {
4437
+ return __awaiter(this, void 0, void 0, function () {
4438
+ 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;
3886
4439
  var e_1, _e, e_2, _f;
3887
4440
  return __generator(this, function (_g) {
3888
4441
  switch (_g.label) {
3889
4442
  case 0:
4443
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4444
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4445
+ preparedPipeline = options.preparedPipeline;
4446
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3890
4447
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3891
4448
  return [4 /*yield*/, preparePipeline(pipeline, {
3892
4449
  llmTools: llmTools,
@@ -3895,6 +4452,7 @@
3895
4452
  })];
3896
4453
  case 1:
3897
4454
  preparedPipeline = _g.sent();
4455
+ setPreparedPipeline(preparedPipeline);
3898
4456
  _g.label = 2;
3899
4457
  case 2:
3900
4458
  errors = [];
@@ -3964,7 +4522,7 @@
3964
4522
  return name === parameterName;
3965
4523
  });
3966
4524
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3967
- 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 "); })));
4525
+ 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 "); })));
3968
4526
  return [3 /*break*/, 4];
3969
4527
  case 1:
3970
4528
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3976,10 +4534,10 @@
3976
4534
  // Note: Wait a short time to prevent race conditions
3977
4535
  _h.sent();
3978
4536
  _h.label = 3;
3979
- 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 "); }), {
4537
+ 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 "); }), {
3980
4538
  isSuccessful: false,
3981
4539
  errors: __spreadArray([
3982
- 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 "); }))
4540
+ 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 "); }))
3983
4541
  ], __read(errors), false).map(serializeError),
3984
4542
  warnings: warnings.map(serializeError),
3985
4543
  executionReport: executionReport,
@@ -4043,7 +4601,7 @@
4043
4601
  case 0:
4044
4602
  if (loopLimit-- < 0) {
4045
4603
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
4046
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4604
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4047
4605
  }
4048
4606
  currentTemplate = unresovedTemplates_1.find(function (template) {
4049
4607
  return template.dependentParameterNames.every(function (name) {
@@ -4053,29 +4611,52 @@
4053
4611
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4054
4612
  throw new UnexpectedError(
4055
4613
  // TODO: [🐎] DRY
4056
- 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
4614
+ 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
4057
4615
  .map(function (_a) {
4058
4616
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4059
4617
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4060
4618
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4061
4619
  .join(' and '));
4062
4620
  })
4063
- .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 "); }));
4621
+ .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 "); }));
4064
4622
  case 1:
4065
4623
  if (!!currentTemplate) return [3 /*break*/, 3];
4066
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4624
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4067
4625
  case 2:
4068
- /* [5] */ _j.sent();
4626
+ /* [🤹‍♂️] */ _j.sent();
4069
4627
  return [3 /*break*/, 4];
4070
4628
  case 3:
4071
4629
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4072
- work_1 = executeSingleTemplate(currentTemplate)
4073
- .then(function () {
4630
+ work_1 = executeTemplate({
4631
+ currentTemplate: currentTemplate,
4632
+ preparedPipeline: preparedPipeline,
4633
+ parametersToPass: parametersToPass,
4634
+ tools: tools,
4635
+ llmTools: llmTools,
4636
+ onProgress: function (progress) {
4637
+ if (isReturned) {
4638
+ 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)
4639
+ .split('\n')
4640
+ .map(function (line) { return "> ".concat(line); })
4641
+ .join('\n')), "\n "); }));
4642
+ }
4643
+ if (onProgress) {
4644
+ onProgress(progress);
4645
+ }
4646
+ },
4647
+ settings: settings,
4648
+ $executionReport: executionReport,
4649
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Template name: ").concat(currentTemplate.name, "\n Template title: ").concat(currentTemplate.title, "\n "); }),
4650
+ })
4651
+ .then(function (newParametersToPass) {
4652
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4074
4653
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4075
4654
  })
4076
4655
  .then(function () {
4077
4656
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4078
4657
  });
4658
+ // <- Note: Errors are catched here [3]
4659
+ // 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
4079
4660
  resolving_1.push(work_1);
4080
4661
  _j.label = 4;
4081
4662
  case 4: return [2 /*return*/];
@@ -4102,7 +4683,12 @@
4102
4683
  var result = _a.result;
4103
4684
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4104
4685
  })), false));
4105
- outputParameters_1 = filterJustOutputParameters();
4686
+ outputParameters_1 = filterJustOutputParameters({
4687
+ preparedPipeline: preparedPipeline,
4688
+ parametersToPass: parametersToPass,
4689
+ $warnings: warnings,
4690
+ pipelineIdentification: pipelineIdentification,
4691
+ });
4106
4692
  isReturned = true;
4107
4693
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4108
4694
  // Note: Wait a short time to prevent race conditions
@@ -4125,7 +4711,12 @@
4125
4711
  var result = _a.result;
4126
4712
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4127
4713
  })), false));
4128
- outputParameters = filterJustOutputParameters();
4714
+ outputParameters = filterJustOutputParameters({
4715
+ preparedPipeline: preparedPipeline,
4716
+ parametersToPass: parametersToPass,
4717
+ $warnings: warnings,
4718
+ pipelineIdentification: pipelineIdentification,
4719
+ });
4129
4720
  isReturned = true;
4130
4721
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4131
4722
  // Note: Wait a short time to prevent race conditions
@@ -4145,22 +4736,65 @@
4145
4736
  })];
4146
4737
  }
4147
4738
  });
4148
- }); };
4149
- return pipelineExecutor;
4739
+ });
4150
4740
  }
4741
+
4151
4742
  /**
4152
- * TODO:[main] !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4153
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4154
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4155
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4156
- * TODO: [♈] Probbably move expectations from templates to parameters
4157
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4158
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4159
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4160
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4161
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4162
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4743
+ * Creates executor function from pipeline and execution tools.
4744
+ *
4745
+ * @returns The executor function
4746
+ * @throws {PipelineLogicError} on logical error in the pipeline
4747
+ * @public exported from `@promptbook/core`
4163
4748
  */
4749
+ function createPipelineExecutor(options) {
4750
+ var _this = this;
4751
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4752
+ 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;
4753
+ validatePipeline(pipeline);
4754
+ var pipelineIdentification = (function () {
4755
+ // Note: This is a 😐 implementation of [🚞]
4756
+ var _ = [];
4757
+ if (pipeline.sourceFile !== undefined) {
4758
+ _.push("File: ".concat(pipeline.sourceFile));
4759
+ }
4760
+ if (pipeline.pipelineUrl !== undefined) {
4761
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4762
+ }
4763
+ return _.join('\n');
4764
+ })();
4765
+ var preparedPipeline;
4766
+ if (isPipelinePrepared(pipeline)) {
4767
+ preparedPipeline = pipeline;
4768
+ }
4769
+ else if (isNotPreparedWarningSupressed !== true) {
4770
+ 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 "); }));
4771
+ }
4772
+ var runCount = 0;
4773
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4774
+ return __generator(this, function (_a) {
4775
+ runCount++;
4776
+ return [2 /*return*/, /* not await */ executePipeline({
4777
+ pipeline: pipeline,
4778
+ preparedPipeline: preparedPipeline,
4779
+ setPreparedPipeline: function (newPreparedPipeline) {
4780
+ preparedPipeline = newPreparedPipeline;
4781
+ },
4782
+ inputParameters: inputParameters,
4783
+ tools: tools,
4784
+ onProgress: onProgress,
4785
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n ").concat(runCount === 1 ? '' : "Run #".concat(runCount), "\n "); }),
4786
+ settings: {
4787
+ maxExecutionAttempts: maxExecutionAttempts,
4788
+ maxParallelCount: maxParallelCount,
4789
+ csvSettings: csvSettings,
4790
+ isVerbose: isVerbose,
4791
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4792
+ },
4793
+ })];
4794
+ });
4795
+ }); };
4796
+ return pipelineExecutor;
4797
+ }
4164
4798
 
4165
4799
  /**
4166
4800
  * @@@
@@ -4270,8 +4904,13 @@
4270
4904
  case 6: return [3 /*break*/, 8];
4271
4905
  case 7:
4272
4906
  error_1 = _c.sent();
4907
+ // Note: Here is expected error:
4908
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4909
+ if (!(error_1 instanceof PipelineExecutionError)) {
4910
+ throw error_1;
4911
+ }
4273
4912
  // TODO: [🟥] Detect browser / node and make it colorfull
4274
- console.error(error_1);
4913
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4275
4914
  return [3 /*break*/, 8];
4276
4915
  case 8: return [2 /*return*/, {
4277
4916
  name: name,
@@ -5178,53 +5817,288 @@
5178
5817
  if (!(error instanceof Error)) {
5179
5818
  throw error;
5180
5819
  }
5181
- throw new ParseError(spaceTrim__default["default"](function (block) {
5182
- return "\n Invalid FORMAT command\n ".concat(block(error.message), ":\n ");
5183
- }));
5820
+ throw new ParseError(spaceTrim__default["default"](function (block) {
5821
+ return "\n Invalid FORMAT command\n ".concat(block(error.message), ":\n ");
5822
+ }));
5823
+ }
5824
+ },
5825
+ /**
5826
+ * Apply the FORMAT command to the `pipelineJson`
5827
+ *
5828
+ * Note: `$` is used to indicate that this function mutates given `templateJson`
5829
+ */
5830
+ $applyToTemplateJson: function (command, $templateJson) {
5831
+ // eslint-disable-next-line no-case-declarations
5832
+ var unit = command.unit.toLowerCase();
5833
+ $templateJson.expectations = $templateJson.expectations || {};
5834
+ $templateJson.expectations[unit] = $templateJson.expectations[unit] || {};
5835
+ if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
5836
+ if ($templateJson.expectations[unit].min !== undefined) {
5837
+ throw new ParseError("Already defined minumum ".concat($templateJson.expectations[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
5838
+ }
5839
+ $templateJson.expectations[unit].min = command.amount;
5840
+ } /* not else */
5841
+ if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
5842
+ if ($templateJson.expectations[unit].max !== undefined) {
5843
+ throw new ParseError("Already defined maximum ".concat($templateJson.expectations[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
5844
+ }
5845
+ $templateJson.expectations[unit].max = command.amount;
5846
+ }
5847
+ },
5848
+ /**
5849
+ * Converts the FORMAT command back to string
5850
+ *
5851
+ * Note: This is used in `pipelineJsonToString` utility
5852
+ */
5853
+ stringify: function (command) {
5854
+ keepUnused(command);
5855
+ return "---"; // <- TODO: [🛋] Implement
5856
+ },
5857
+ /**
5858
+ * Reads the FORMAT command from the `TemplateJson`
5859
+ *
5860
+ * Note: This is used in `pipelineJsonToString` utility
5861
+ */
5862
+ takeFromTemplateJson: function ($templateJson) {
5863
+ keepUnused($templateJson);
5864
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5865
+ },
5866
+ };
5867
+
5868
+ /**
5869
+ * @@@
5870
+ *
5871
+ * @param text @@@
5872
+ * @returns @@@
5873
+ * @example 'HELLO_WORLD'
5874
+ * @example 'I_LOVE_PROMPTBOOK'
5875
+ * @public exported from `@promptbook/utils`
5876
+ */
5877
+ function normalizeTo_SCREAMING_CASE(text) {
5878
+ var e_1, _a;
5879
+ var charType;
5880
+ var lastCharType = 'OTHER';
5881
+ var normalizedName = '';
5882
+ try {
5883
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5884
+ var char = text_1_1.value;
5885
+ var normalizedChar = void 0;
5886
+ if (/^[a-z]$/.test(char)) {
5887
+ charType = 'LOWERCASE';
5888
+ normalizedChar = char.toUpperCase();
5889
+ }
5890
+ else if (/^[A-Z]$/.test(char)) {
5891
+ charType = 'UPPERCASE';
5892
+ normalizedChar = char;
5893
+ }
5894
+ else if (/^[0-9]$/.test(char)) {
5895
+ charType = 'NUMBER';
5896
+ normalizedChar = char;
5897
+ }
5898
+ else if (/^\/$/.test(char)) {
5899
+ charType = 'SLASH';
5900
+ normalizedChar = char;
5901
+ }
5902
+ else {
5903
+ charType = 'OTHER';
5904
+ normalizedChar = '_';
5905
+ }
5906
+ if (charType !== lastCharType &&
5907
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
5908
+ !(lastCharType === 'NUMBER') &&
5909
+ !(charType === 'NUMBER')) {
5910
+ normalizedName += '_';
5911
+ }
5912
+ normalizedName += normalizedChar;
5913
+ lastCharType = charType;
5914
+ }
5915
+ }
5916
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5917
+ finally {
5918
+ try {
5919
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5920
+ }
5921
+ finally { if (e_1) throw e_1.error; }
5922
+ }
5923
+ normalizedName = normalizedName.replace(/_+/g, '_');
5924
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
5925
+ normalizedName = normalizedName.replace(/^_/, '');
5926
+ normalizedName = normalizedName.replace(/_$/, '');
5927
+ return normalizedName;
5928
+ }
5929
+ /**
5930
+ * TODO: Tests
5931
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
5932
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
5933
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
5934
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
5935
+ * TODO: [🌺] Use some intermediate util splitWords
5936
+ */
5937
+
5938
+ /**
5939
+ * @@@
5940
+ *
5941
+ * @param text @@@
5942
+ * @param _isFirstLetterCapital @@@
5943
+ * @returns @@@
5944
+ * @example 'helloWorld'
5945
+ * @example 'iLovePromptbook'
5946
+ * @public exported from `@promptbook/utils`
5947
+ */
5948
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5949
+ var e_1, _a;
5950
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5951
+ var charType;
5952
+ var lastCharType = null;
5953
+ var normalizedName = '';
5954
+ try {
5955
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5956
+ var char = text_1_1.value;
5957
+ var normalizedChar = void 0;
5958
+ if (/^[a-z]$/.test(char)) {
5959
+ charType = 'LOWERCASE';
5960
+ normalizedChar = char;
5961
+ }
5962
+ else if (/^[A-Z]$/.test(char)) {
5963
+ charType = 'UPPERCASE';
5964
+ normalizedChar = char.toLowerCase();
5965
+ }
5966
+ else if (/^[0-9]$/.test(char)) {
5967
+ charType = 'NUMBER';
5968
+ normalizedChar = char;
5969
+ }
5970
+ else {
5971
+ charType = 'OTHER';
5972
+ normalizedChar = '';
5973
+ }
5974
+ if (!lastCharType) {
5975
+ if (_isFirstLetterCapital) {
5976
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5977
+ }
5978
+ }
5979
+ else if (charType !== lastCharType &&
5980
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5981
+ !(lastCharType === 'NUMBER') &&
5982
+ !(charType === 'NUMBER')) {
5983
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5984
+ }
5985
+ normalizedName += normalizedChar;
5986
+ lastCharType = charType;
5987
+ }
5988
+ }
5989
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5990
+ finally {
5991
+ try {
5992
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5993
+ }
5994
+ finally { if (e_1) throw e_1.error; }
5995
+ }
5996
+ return normalizedName;
5997
+ }
5998
+ /**
5999
+ * TODO: [🌺] Use some intermediate util splitWords
6000
+ */
6001
+
6002
+ /**
6003
+ * Removes quotes from a string
6004
+ *
6005
+ * Tip: This is very usefull for post-processing of the result of the LLM model
6006
+ * Note: This function removes only the same quotes from the beginning and the end of the string
6007
+ * Note: There are two simmilar functions:
6008
+ * - `removeQuotes` which removes only bounding quotes
6009
+ * - `unwrapResult` which removes whole introduce sentence
6010
+ *
6011
+ * @param text optionally quoted text
6012
+ * @returns text without quotes
6013
+ * @public exported from `@promptbook/utils`
6014
+ */
6015
+ function removeQuotes(text) {
6016
+ if (text.startsWith('"') && text.endsWith('"')) {
6017
+ return text.slice(1, -1);
6018
+ }
6019
+ if (text.startsWith('\'') && text.endsWith('\'')) {
6020
+ return text.slice(1, -1);
6021
+ }
6022
+ return text;
6023
+ }
6024
+
6025
+ /**
6026
+ * Function `validateParameterName` will @@@
6027
+ *
6028
+ * @param parameterName @@@
6029
+ * @returns @@@
6030
+ * @throws {ParseError} @@@
6031
+ * @private within the repository
6032
+ */
6033
+ function validateParameterName(parameterName) {
6034
+ var e_1, _a;
6035
+ var rawParameterName = parameterName;
6036
+ try {
6037
+ for (var _b = __values([
6038
+ ['`', '`'],
6039
+ ['{', '}'],
6040
+ ['[', ']'],
6041
+ ['(', ')'],
6042
+ ['<', '>'],
6043
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
6044
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
6045
+ if (parameterName.substring(0, 1) === start &&
6046
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
6047
+ // <- TODO: More universal that 1 character
6048
+ ) {
6049
+ parameterName = parameterName.substring(1, parameterName.length - 1);
6050
+ // <- TODO: More universal that 1 character
6051
+ }
5184
6052
  }
5185
- },
5186
- /**
5187
- * Apply the FORMAT command to the `pipelineJson`
5188
- *
5189
- * Note: `$` is used to indicate that this function mutates given `templateJson`
5190
- */
5191
- $applyToTemplateJson: function (command, $templateJson) {
5192
- // eslint-disable-next-line no-case-declarations
5193
- var unit = command.unit.toLowerCase();
5194
- $templateJson.expectations = $templateJson.expectations || {};
5195
- $templateJson.expectations[unit] = $templateJson.expectations[unit] || {};
5196
- if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
5197
- if ($templateJson.expectations[unit].min !== undefined) {
5198
- throw new ParseError("Already defined minumum ".concat($templateJson.expectations[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
5199
- }
5200
- $templateJson.expectations[unit].min = command.amount;
5201
- } /* not else */
5202
- if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
5203
- if ($templateJson.expectations[unit].max !== undefined) {
5204
- throw new ParseError("Already defined maximum ".concat($templateJson.expectations[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
5205
- }
5206
- $templateJson.expectations[unit].max = command.amount;
6053
+ }
6054
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
6055
+ finally {
6056
+ try {
6057
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5207
6058
  }
5208
- },
5209
- /**
5210
- * Converts the FORMAT command back to string
5211
- *
5212
- * Note: This is used in `pipelineJsonToString` utility
5213
- */
5214
- stringify: function (command) {
5215
- keepUnused(command);
5216
- return "---"; // <- TODO: [🛋] Implement
5217
- },
5218
- /**
5219
- * Reads the FORMAT command from the `TemplateJson`
5220
- *
5221
- * Note: This is used in `pipelineJsonToString` utility
5222
- */
5223
- takeFromTemplateJson: function ($templateJson) {
5224
- keepUnused($templateJson);
5225
- throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5226
- },
5227
- };
6059
+ finally { if (e_1) throw e_1.error; }
6060
+ }
6061
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
6062
+ try {
6063
+ /*
6064
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
6065
+ if (parameterName.includes(' ')) {
6066
+ throw new ParseError(`Parameter name cannot contain spaces`);
6067
+ }
6068
+ */
6069
+ if (parameterName.includes('.')) {
6070
+ throw new ParseError("Parameter name cannot contain dots");
6071
+ }
6072
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
6073
+ throw new ParseError("Parameter name cannot contain slashes");
6074
+ }
6075
+ if (parameterName.includes('(') ||
6076
+ parameterName.includes(')') ||
6077
+ parameterName.includes('{') ||
6078
+ parameterName.includes('}') ||
6079
+ parameterName.includes('[') ||
6080
+ parameterName.includes(']')) {
6081
+ throw new ParseError("Parameter name cannot contain braces");
6082
+ }
6083
+ parameterName = removeDiacritics(parameterName);
6084
+ parameterName = removeEmojis(parameterName);
6085
+ parameterName = removeQuotes(parameterName);
6086
+ parameterName = normalizeTo_camelCase(parameterName);
6087
+ if (parameterName === '') {
6088
+ throw new ParseError("Parameter name cannot be empty");
6089
+ }
6090
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
6091
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
6092
+ }
6093
+ }
6094
+ catch (error) {
6095
+ if (!(error instanceof ParseError)) {
6096
+ throw error;
6097
+ }
6098
+ 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 "); }));
6099
+ }
6100
+ return parameterName;
6101
+ }
5228
6102
 
5229
6103
  /**
5230
6104
  * Parses the foreach command
@@ -5255,25 +6129,61 @@
5255
6129
  /**
5256
6130
  * Link to discussion
5257
6131
  */
5258
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
6132
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5259
6133
  /**
5260
6134
  * Example usages of the FOREACH command
5261
6135
  */
5262
6136
  examples: [
5263
- 'FOREACH List Line -> `{customer}`',
5264
- 'FOR List Line -> `{customer}`',
5265
- 'EACH List Line -> `{customer}`',
5266
- // <- TODO: [🍭] More
6137
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
6138
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
6139
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
5267
6140
  ],
5268
6141
  /**
5269
6142
  * Parses the FOREACH command
5270
6143
  */
5271
6144
  parse: function (input) {
5272
6145
  var args = input.args;
5273
- keepUnused(args);
5274
- // <- TODO: [🍭] Implement
6146
+ var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
6147
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
6148
+ var parameterNameArg = args[2] || '';
6149
+ var assignSign = args[3];
6150
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
6151
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
6152
+ });
6153
+ if (formatDefinition === undefined) {
6154
+ 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; })
6155
+ .map(function (formatName) { return "- ".concat(formatName); })
6156
+ .join('\n')), "\n "); }));
6157
+ // <- TODO: [🏢] List all supported format names
6158
+ }
6159
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
6160
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
6161
+ });
6162
+ if (subvalueDefinition === undefined) {
6163
+ 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
6164
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6165
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6166
+ .join('\n')), "\n "); }));
6167
+ // <- TODO: [🏢] List all supported subformat names for the format
6168
+ }
6169
+ if (assignSign !== '->') {
6170
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6171
+ }
6172
+ var parameterName = validateParameterName(parameterNameArg);
6173
+ var subparameterNames = args
6174
+ .slice(4)
6175
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6176
+ .filter(function (parameterName) { return parameterName !== ''; })
6177
+ .map(validateParameterName);
6178
+ if (subparameterNames.length === 0) {
6179
+ throw new ParseError("FOREACH command must have at least one subparameter");
6180
+ }
5275
6181
  return {
5276
6182
  type: 'FOREACH',
6183
+ formatName: formatName,
6184
+ subformatName: subformatName,
6185
+ parameterName: parameterName,
6186
+ subparameterNames: subparameterNames,
5277
6187
  };
5278
6188
  },
5279
6189
  /**
@@ -5282,8 +6192,12 @@
5282
6192
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5283
6193
  */
5284
6194
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5285
- keepUnused(command, $templateJson, $pipelineJson);
5286
- // <- TODO: [🍭] Implement
6195
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6196
+ // TODO: [🍭] Detect double use
6197
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6198
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
6199
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
6200
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5287
6201
  },
5288
6202
  /**
5289
6203
  * Converts the FOREACH command back to string
@@ -5292,8 +6206,7 @@
5292
6206
  */
5293
6207
  stringify: function (command) {
5294
6208
  keepUnused(command);
5295
- return "";
5296
- // <- TODO: [🍭] Implement
6209
+ return "---"; // <- TODO: [🛋] Implement
5297
6210
  },
5298
6211
  /**
5299
6212
  * Reads the FOREACH command from the `TemplateJson`
@@ -5302,12 +6215,11 @@
5302
6215
  */
5303
6216
  takeFromTemplateJson: function ($templateJson) {
5304
6217
  keepUnused($templateJson);
5305
- return [];
5306
- // <- TODO: [🍭] Implement
6218
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5307
6219
  },
5308
6220
  };
5309
6221
  /**
5310
- * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6222
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5311
6223
  */
5312
6224
 
5313
6225
  /**
@@ -5417,11 +6329,11 @@
5417
6329
  */
5418
6330
  parse: function (input) {
5419
6331
  var args = input.args;
5420
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5421
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5422
- throw new ParseError("Invalid joker");
6332
+ if (args.length !== 1) {
6333
+ throw new ParseError("JOKE command expects exactly one parameter name");
5423
6334
  }
5424
- var parameterName = parametersMatch.groups.parameterName;
6335
+ var parameterNameArg = args[0] || '';
6336
+ var parameterName = validateParameterName(parameterNameArg);
5425
6337
  return {
5426
6338
  type: 'JOKER',
5427
6339
  parameterName: parameterName,
@@ -5496,6 +6408,9 @@
5496
6408
  */
5497
6409
  parse: function (input) {
5498
6410
  var args = input.args, normalized = input.normalized;
6411
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6412
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6413
+ }).join('\n')), "\n "); });
5499
6414
  // TODO: Make this more elegant and dynamically
5500
6415
  if (normalized.startsWith('MODEL_VARIANT')) {
5501
6416
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5511,17 +6426,13 @@
5511
6426
  key: 'modelVariant',
5512
6427
  value: 'COMPLETION',
5513
6428
  };
6429
+ // <- Note: [🤖]
5514
6430
  }
5515
6431
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5516
- return {
5517
- type: 'MODEL',
5518
- key: 'modelVariant',
5519
- value: 'EMBEDDING',
5520
- };
5521
- // <- Note: [🤖]
6432
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5522
6433
  }
5523
6434
  else {
5524
- 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 "); }));
6435
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5525
6436
  }
5526
6437
  }
5527
6438
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5546,6 +6457,7 @@
5546
6457
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5547
6458
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5548
6459
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6460
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5549
6461
  }
5550
6462
  else {
5551
6463
  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 ")));
@@ -5645,14 +6557,13 @@
5645
6557
  * Parses the PARAMETER command
5646
6558
  */
5647
6559
  parse: function (input) {
5648
- var normalized = input.normalized, raw = input.raw;
5649
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5650
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5651
- throw new ParseError("Invalid parameter");
5652
- }
5653
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5654
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5655
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6560
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6561
+ var parameterNameRaw = args.shift() || '';
6562
+ var parameterDescriptionRaw = args.join(' ');
6563
+ // <- TODO: When [🥶] fixed, change to:
6564
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6565
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6566
+ 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 "); }));
5656
6567
  }
5657
6568
  var isInput = normalized.startsWith('INPUT');
5658
6569
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5660,10 +6571,12 @@
5660
6571
  isInput = false;
5661
6572
  isOutput = false;
5662
6573
  }
6574
+ var parameterName = validateParameterName(parameterNameRaw);
6575
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5663
6576
  return {
5664
6577
  type: 'PARAMETER',
5665
6578
  parameterName: parameterName,
5666
- parameterDescription: parameterDescription.trim() || null,
6579
+ parameterDescription: parameterDescription,
5667
6580
  isInput: isInput,
5668
6581
  isOutput: isOutput,
5669
6582
  };
@@ -6413,76 +7326,6 @@
6413
7326
  return str;
6414
7327
  }
6415
7328
 
6416
- /**
6417
- * @@@
6418
- *
6419
- * @param text @@@
6420
- * @returns @@@
6421
- * @example 'HELLO_WORLD'
6422
- * @example 'I_LOVE_PROMPTBOOK'
6423
- * @public exported from `@promptbook/utils`
6424
- */
6425
- function normalizeTo_SCREAMING_CASE(text) {
6426
- var e_1, _a;
6427
- var charType;
6428
- var lastCharType = 'OTHER';
6429
- var normalizedName = '';
6430
- try {
6431
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
6432
- var char = text_1_1.value;
6433
- var normalizedChar = void 0;
6434
- if (/^[a-z]$/.test(char)) {
6435
- charType = 'LOWERCASE';
6436
- normalizedChar = char.toUpperCase();
6437
- }
6438
- else if (/^[A-Z]$/.test(char)) {
6439
- charType = 'UPPERCASE';
6440
- normalizedChar = char;
6441
- }
6442
- else if (/^[0-9]$/.test(char)) {
6443
- charType = 'NUMBER';
6444
- normalizedChar = char;
6445
- }
6446
- else if (/^\/$/.test(char)) {
6447
- charType = 'SLASH';
6448
- normalizedChar = char;
6449
- }
6450
- else {
6451
- charType = 'OTHER';
6452
- normalizedChar = '_';
6453
- }
6454
- if (charType !== lastCharType &&
6455
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
6456
- !(lastCharType === 'NUMBER') &&
6457
- !(charType === 'NUMBER')) {
6458
- normalizedName += '_';
6459
- }
6460
- normalizedName += normalizedChar;
6461
- lastCharType = charType;
6462
- }
6463
- }
6464
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
6465
- finally {
6466
- try {
6467
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
6468
- }
6469
- finally { if (e_1) throw e_1.error; }
6470
- }
6471
- normalizedName = normalizedName.replace(/_+/g, '_');
6472
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
6473
- normalizedName = normalizedName.replace(/^_/, '');
6474
- normalizedName = normalizedName.replace(/_$/, '');
6475
- return normalizedName;
6476
- }
6477
- /**
6478
- * TODO: Tests
6479
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
6480
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
6481
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
6482
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
6483
- * TODO: [🌺] Use some intermediate util splitWords
6484
- */
6485
-
6486
7329
  /**
6487
7330
  * Parses one line of ul/ol to command
6488
7331
  *
@@ -6495,6 +7338,7 @@
6495
7338
  if (raw.includes('\n') || raw.includes('\r')) {
6496
7339
  throw new ParseError('Command can not contain new line characters' /* <- TODO: [🚞] */);
6497
7340
  }
7341
+ // TODO: Unit test all this processing and parsing
6498
7342
  var normalized = raw.trim();
6499
7343
  normalized = normalized.split('`').join('');
6500
7344
  normalized = normalized.split('"').join('');
@@ -6540,7 +7384,9 @@
6540
7384
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6541
7385
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6542
7386
  var args = items.slice(commandNameSegmentsCount + 1);
6543
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7387
+ var rawArgs = raw
7388
+ .substring(commandNameRaw.length)
7389
+ .trim();
6544
7390
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6545
7391
  if (command !== null) {
6546
7392
  return command;
@@ -6550,8 +7396,10 @@
6550
7396
  // Arg1 Arg2 Arg3 | FOO
6551
7397
  {
6552
7398
  var commandNameRaw = items.slice(-1).join('_');
6553
- var args = items.slice(0, -1);
6554
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7399
+ var args = items.slice(0, -1); // <- Note: This is probbably not correct
7400
+ var rawArgs = raw
7401
+ .substring(0, raw.length - commandNameRaw.length)
7402
+ .trim();
6555
7403
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6556
7404
  if (command !== null) {
6557
7405
  return command;
@@ -6691,7 +7539,7 @@
6691
7539
  function extractOneBlockFromMarkdown(markdown) {
6692
7540
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6693
7541
  if (codeBlocks.length !== 1) {
6694
- 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 "); }));
7542
+ 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 "); }));
6695
7543
  }
6696
7544
  return codeBlocks[0];
6697
7545
  }
@@ -7250,70 +8098,6 @@
7250
8098
  * TODO: [🏛] This can be part of markdown builder
7251
8099
  */
7252
8100
 
7253
- /**
7254
- * @@@
7255
- *
7256
- * @param text @@@
7257
- * @param _isFirstLetterCapital @@@
7258
- * @returns @@@
7259
- * @example 'helloWorld'
7260
- * @example 'iLovePromptbook'
7261
- * @public exported from `@promptbook/utils`
7262
- */
7263
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
7264
- var e_1, _a;
7265
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
7266
- var charType;
7267
- var lastCharType = null;
7268
- var normalizedName = '';
7269
- try {
7270
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
7271
- var char = text_1_1.value;
7272
- var normalizedChar = void 0;
7273
- if (/^[a-z]$/.test(char)) {
7274
- charType = 'LOWERCASE';
7275
- normalizedChar = char;
7276
- }
7277
- else if (/^[A-Z]$/.test(char)) {
7278
- charType = 'UPPERCASE';
7279
- normalizedChar = char.toLowerCase();
7280
- }
7281
- else if (/^[0-9]$/.test(char)) {
7282
- charType = 'NUMBER';
7283
- normalizedChar = char;
7284
- }
7285
- else {
7286
- charType = 'OTHER';
7287
- normalizedChar = '';
7288
- }
7289
- if (!lastCharType) {
7290
- if (_isFirstLetterCapital) {
7291
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
7292
- }
7293
- }
7294
- else if (charType !== lastCharType &&
7295
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
7296
- !(lastCharType === 'NUMBER') &&
7297
- !(charType === 'NUMBER')) {
7298
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
7299
- }
7300
- normalizedName += normalizedChar;
7301
- lastCharType = charType;
7302
- }
7303
- }
7304
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
7305
- finally {
7306
- try {
7307
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
7308
- }
7309
- finally { if (e_1) throw e_1.error; }
7310
- }
7311
- return normalizedName;
7312
- }
7313
- /**
7314
- * TODO: [🌺] Use some intermediate util splitWords
7315
- */
7316
-
7317
8101
  /**
7318
8102
  * Creates a Mermaid graph based on the promptbook
7319
8103
  *
@@ -7370,6 +8154,9 @@
7370
8154
  return promptbookMermaid;
7371
8155
  }
7372
8156
  /**
8157
+ * TODO: !!!!! FOREACH in mermaid graph
8158
+ * TODO: !!!!! Knowledge in mermaid graph
8159
+ * TODO: !!!!! Personas in mermaid graph
7373
8160
  * TODO: Maybe use some Mermaid package instead of string templating
7374
8161
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
7375
8162
  */
@@ -7511,21 +8298,41 @@
7511
8298
  * @public exported from `@promptbook/core`
7512
8299
  */
7513
8300
  function usageToHuman(usage) {
7514
- var report = 'Usage:';
8301
+ var reportItems = [];
7515
8302
  var uncertainNumberToHuman = function (_a) {
7516
8303
  var value = _a.value, isUncertain = _a.isUncertain;
7517
8304
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7518
8305
  };
7519
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7520
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7521
- return spaceTrim__default["default"](report);
8306
+ if (usage.price.value > 0.01
8307
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8308
+ ) {
8309
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8310
+ }
8311
+ else {
8312
+ reportItems.push("Negligible cost");
8313
+ }
8314
+ var worktime = usageToWorktime(usage);
8315
+ if (worktime.value >
8316
+ 1 / 60
8317
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8318
+ ) {
8319
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8320
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8321
+ }
8322
+ if (usage.output.charactersCount.value > 0) {
8323
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8324
+ }
8325
+ if (reportItems.length === 0) {
8326
+ // Note: For negligible usage, we report at least something
8327
+ reportItems.push('Negligible');
8328
+ }
8329
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7522
8330
  }
7523
8331
  /**
7524
- * TODO: Use "$1" not "1 USD"
7525
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7526
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8332
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8333
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8334
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7527
8335
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7528
- * TODO: When negligible usage, report "Negligible" or just don't report it
7529
8336
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7530
8337
  * TODO: [🏛] Maybe make some markdown builder
7531
8338
  */
@@ -8113,6 +8920,42 @@
8113
8920
  return null;
8114
8921
  },
8115
8922
  });
8923
+ /**
8924
+ * @@@ registration1 of default configuration for Open AI
8925
+ *
8926
+ * Note: [🏐] Configurations registrations are done in @@@ BUT constructor @@@
8927
+ *
8928
+ * @public exported from `@promptbook/core`
8929
+ * @public exported from `@promptbook/cli`
8930
+ */
8931
+ var _OpenAiAssistantMetadataRegistration = $llmToolsMetadataRegister.register({
8932
+ title: 'Open AI Assistant',
8933
+ packageName: '@promptbook/openai',
8934
+ className: 'OpenAiAssistantExecutionTools',
8935
+ getBoilerplateConfiguration: function () {
8936
+ return {
8937
+ title: 'Open AI Assistant (boilerplate)',
8938
+ packageName: '@promptbook/openai',
8939
+ className: 'OpenAiAssistantExecutionTools',
8940
+ options: {
8941
+ apiKey: 'sk-',
8942
+ },
8943
+ };
8944
+ },
8945
+ createConfigurationFromEnv: function (env) {
8946
+ if (typeof env.OPENAI_API_KEY === 'string') {
8947
+ return {
8948
+ title: 'Open AI Assistant (from env)',
8949
+ packageName: '@promptbook/openai',
8950
+ className: 'OpenAiAssistantExecutionTools',
8951
+ options: {
8952
+ apiKey: process.env.OPENAI_API_KEY,
8953
+ },
8954
+ };
8955
+ }
8956
+ return null;
8957
+ },
8958
+ });
8116
8959
 
8117
8960
  /**
8118
8961
  * This class behaves like LocalStorage but separates keys by prefix
@@ -8174,8 +9017,8 @@
8174
9017
  */
8175
9018
  function createMarkdownTable(table) {
8176
9019
  var columnWidths = table.reduce(function (widths, row) {
8177
- row.forEach(function (cell, columnIndex) {
8178
- var cellLength = cell.length;
9020
+ row.forEach(function (subformat, columnIndex) {
9021
+ var cellLength = subformat.length;
8179
9022
  if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
8180
9023
  widths[columnIndex] = cellLength;
8181
9024
  }
@@ -8183,12 +9026,12 @@
8183
9026
  return widths;
8184
9027
  }, []);
8185
9028
  var header = "| ".concat(table[0]
8186
- .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
9029
+ .map(function (subformat, columnIndex) { return subformat.padEnd(columnWidths[columnIndex]); })
8187
9030
  .join(' | '), " |");
8188
9031
  var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
8189
9032
  var rows = table.slice(1).map(function (row) {
8190
- var paddedRow = row.map(function (cell, columnIndex) {
8191
- return cell.padEnd(columnWidths[columnIndex]);
9033
+ var paddedRow = row.map(function (subformat, columnIndex) {
9034
+ return subformat.padEnd(columnWidths[columnIndex]);
8192
9035
  });
8193
9036
  return "| ".concat(paddedRow.join(' | '), " |");
8194
9037
  });
@@ -8469,6 +9312,8 @@
8469
9312
  exports.CLAIM = CLAIM;
8470
9313
  exports.CallbackInterfaceTools = CallbackInterfaceTools;
8471
9314
  exports.CollectionError = CollectionError;
9315
+ exports.CsvFormatDefinition = CsvFormatDefinition;
9316
+ exports.DEFAULT_CSV_SETTINGS = DEFAULT_CSV_SETTINGS;
8472
9317
  exports.DEFAULT_REMOTE_URL = DEFAULT_REMOTE_URL;
8473
9318
  exports.DEFAULT_REMOTE_URL_PATH = DEFAULT_REMOTE_URL_PATH;
8474
9319
  exports.ERRORS = ERRORS;
@@ -8479,6 +9324,7 @@
8479
9324
  exports.ExpectError = ExpectError;
8480
9325
  exports.IS_VERBOSE = IS_VERBOSE;
8481
9326
  exports.LimitReachedError = LimitReachedError;
9327
+ exports.MANDATORY_CSV_SETTINGS = MANDATORY_CSV_SETTINGS;
8482
9328
  exports.MAX_EXECUTION_ATTEMPTS = MAX_EXECUTION_ATTEMPTS;
8483
9329
  exports.MAX_FILENAME_LENGTH = MAX_FILENAME_LENGTH;
8484
9330
  exports.MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH = MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH;
@@ -8497,11 +9343,13 @@
8497
9343
  exports.PrefixStorage = PrefixStorage;
8498
9344
  exports.RESERVED_PARAMETER_NAMES = RESERVED_PARAMETER_NAMES;
8499
9345
  exports.TemplateTypes = TemplateTypes;
9346
+ exports.TextFormatDefinition = TextFormatDefinition;
8500
9347
  exports.UNCERTAIN_USAGE = UNCERTAIN_USAGE;
8501
9348
  exports.UnexpectedError = UnexpectedError;
8502
9349
  exports.ZERO_USAGE = ZERO_USAGE;
8503
9350
  exports._AnthropicClaudeMetadataRegistration = _AnthropicClaudeMetadataRegistration;
8504
9351
  exports._AzureOpenAiMetadataRegistration = _AzureOpenAiMetadataRegistration;
9352
+ exports._OpenAiAssistantMetadataRegistration = _OpenAiAssistantMetadataRegistration;
8505
9353
  exports._OpenAiMetadataRegistration = _OpenAiMetadataRegistration;
8506
9354
  exports.addUsage = addUsage;
8507
9355
  exports.assertsExecutionSuccessful = assertsExecutionSuccessful;