@promptbook/core 0.70.0-1 → 0.71.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +22 -59
  2. package/esm/index.es.js +1997 -1235
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/promptbook-collection/index.d.ts +0 -3
  5. package/esm/typings/src/_packages/core.index.d.ts +9 -1
  6. package/esm/typings/src/_packages/types.index.d.ts +12 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  8. package/esm/typings/src/cli/cli-commands/make.d.ts +1 -1
  9. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +1 -1
  10. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +3 -7
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +23 -0
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  14. package/esm/typings/src/config.d.ts +16 -3
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +10 -5
  19. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +9 -8
  20. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +45 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +40 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +19 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  31. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  32. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  33. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  34. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  35. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  36. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  37. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  38. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  39. package/esm/typings/src/formats/index.d.ts +1 -1
  40. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  41. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  42. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  43. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  44. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  45. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  48. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  50. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  51. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  52. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  53. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +9 -2
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  57. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  58. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  59. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  60. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  61. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  62. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  63. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  64. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  65. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  67. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  68. package/package.json +17 -12
  69. package/umd/index.umd.js +2003 -1238
  70. package/umd/index.umd.js.map +1 -1
  71. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  72. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  73. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  74. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  75. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  76. /package/esm/typings/src/{personas/preparePersona.test.d.ts → utils/validators/parameterName/validateParameterName.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,8 +16,8 @@
16
16
  /**
17
17
  * The version of the Promptbook library
18
18
  */
19
- var PROMPTBOOK_VERSION = '0.70.0-0';
20
- // TODO: !!!! List here all the versions and annotate + put into script
19
+ var PROMPTBOOK_VERSION = '0.70.0-1';
20
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
21
21
 
22
22
  /*! *****************************************************************************
23
23
  Copyright (c) Microsoft Corporation.
@@ -229,7 +229,7 @@
229
229
  commands.push("PIPELINE URL ".concat(pipelineUrl));
230
230
  }
231
231
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
232
- // TODO: !!! This increase size of the bundle and is probbably not necessary
232
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
233
233
  pipelineString = prettifyMarkdown(pipelineString);
234
234
  try {
235
235
  for (var _g = __values(parameters.filter(function (_a) {
@@ -377,12 +377,12 @@
377
377
  pipelineString += '```' + contentLanguage;
378
378
  pipelineString += '\n';
379
379
  pipelineString += spaceTrim__default["default"](content);
380
- // <- TODO: !!! Escape
380
+ // <- TODO:[main] !!! Escape
381
381
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
382
382
  pipelineString += '\n';
383
383
  pipelineString += '```';
384
384
  pipelineString += '\n\n';
385
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
385
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
386
386
  }
387
387
  }
388
388
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -602,7 +602,7 @@
602
602
  }
603
603
  /**
604
604
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
605
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
605
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
606
606
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
607
607
  */
608
608
 
@@ -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
  *
@@ -673,14 +673,14 @@
673
673
  var MAX_FILENAME_LENGTH = 30;
674
674
  /**
675
675
  * @@@
676
- * TODO: [🐝] !!! Use
676
+ * TODO: [🐝][main] !!! Use
677
677
  *
678
678
  * @public exported from `@promptbook/core`
679
679
  */
680
680
  var MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH = 3;
681
681
  /**
682
682
  * @@@
683
- * TODO: [🐝] !!! Use
683
+ * TODO: [🐝][main] !!! Use
684
684
  *
685
685
  * @public exported from `@promptbook/core`
686
686
  */
@@ -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
  */
@@ -835,7 +856,7 @@
835
856
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
836
857
  return false;
837
858
  }
838
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
859
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
839
860
  return true;
840
861
  }
841
862
 
@@ -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 () {
@@ -984,19 +1025,19 @@
984
1025
  // <- Note: [🚲]
985
1026
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
986
1027
  }
987
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1028
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
988
1029
  // <- Note: [🚲]
989
1030
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
990
1031
  }
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
  * > /**
@@ -1179,11 +1220,11 @@
1179
1220
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1180
1221
  */
1181
1222
  /**
1182
- * TODO: [🐣] !!!! Validate that all samples match expectations
1183
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1184
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1185
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1186
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1223
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1224
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1225
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1226
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1227
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1187
1228
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1188
1229
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1189
1230
  */
@@ -1497,7 +1538,7 @@
1497
1538
  });
1498
1539
  }
1499
1540
  /**
1500
- * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1541
+ * TODO:[main] !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1501
1542
  */
1502
1543
 
1503
1544
  /**
@@ -1794,7 +1835,7 @@
1794
1835
  });
1795
1836
  }
1796
1837
 
1797
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1838
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1798
1839
 
1799
1840
  var defaultDiacriticsRemovalMap = [
1800
1841
  {
@@ -2323,113 +2364,35 @@
2323
2364
  */
2324
2365
 
2325
2366
  /**
2326
- * Parses the given script and returns the list of all used variables that are not defined in the script
2327
- *
2328
- * @param script from which to extract the variables
2329
- * @returns the list of variable names
2330
- * @throws {ParseError} if the script is invalid
2331
- * @public exported from `@promptbook/utils`
2332
- */
2333
- function extractVariables(script) {
2334
- var variables = new Set();
2335
- script = "(()=>{".concat(script, "})()");
2336
- try {
2337
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2338
- try {
2339
- eval(script);
2340
- }
2341
- catch (error) {
2342
- if (!(error instanceof ReferenceError)) {
2343
- throw error;
2344
- }
2345
- var undefinedName = error.message.split(' ')[0];
2346
- /*
2347
- Note: Parsing the error
2348
- [PipelineUrlError: thing is not defined]
2349
- */
2350
- if (!undefinedName) {
2351
- throw error;
2352
- }
2353
- if (script.includes(undefinedName + '(')) {
2354
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2355
- }
2356
- else {
2357
- variables.add(undefinedName);
2358
- script = "const ".concat(undefinedName, " = '';") + script;
2359
- }
2360
- }
2361
- }
2362
- catch (error) {
2363
- if (!(error instanceof Error)) {
2364
- throw error;
2365
- }
2366
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2367
- }
2368
- return variables;
2369
- }
2370
- /**
2371
- * TODO: [🔣] Support for multiple languages - python, java,...
2372
- */
2373
-
2374
- /**
2375
- * Parses the template and returns the set of all used parameters
2367
+ * Determine if the pipeline is fully prepared
2376
2368
  *
2377
- * @param template the template with used parameters
2378
- * @returns the set of parameter names
2379
- * @throws {ParseError} if the script is invalid
2380
- * @public exported from `@promptbook/utils`
2369
+ * @public exported from `@promptbook/core`
2381
2370
  */
2382
- function extractParameterNamesFromTemplate(template) {
2383
- var e_1, _a, e_2, _b, e_3, _c;
2384
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2385
- var parameterNames = new Set();
2386
- try {
2387
- 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()) {
2388
- var parameterName = _e.value;
2389
- parameterNames.add(parameterName);
2390
- }
2391
- }
2392
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2393
- finally {
2394
- try {
2395
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2396
- }
2397
- finally { if (e_1) throw e_1.error; }
2398
- }
2399
- if (templateType === 'SCRIPT_TEMPLATE') {
2400
- try {
2401
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2402
- var parameterName = _g.value;
2403
- parameterNames.add(parameterName);
2404
- }
2405
- }
2406
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2407
- finally {
2408
- try {
2409
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2410
- }
2411
- finally { if (e_2) throw e_2.error; }
2412
- }
2413
- }
2414
- try {
2415
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2416
- var jokerName = _j.value;
2417
- parameterNames.add(jokerName);
2418
- }
2371
+ function isPipelinePrepared(pipeline) {
2372
+ // Note: Ignoring `pipeline.preparations` @@@
2373
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2374
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2375
+ return false;
2419
2376
  }
2420
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2421
- finally {
2422
- try {
2423
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2424
- }
2425
- finally { if (e_3) throw e_3.error; }
2377
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2378
+ return false;
2426
2379
  }
2427
- parameterNames.delete('content');
2428
- // <- Note {websiteContent} is used in `preparedContent`
2429
- return parameterNames;
2380
+ /*
2381
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2382
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2383
+ > return false;
2384
+ > }
2385
+ */
2386
+ return true;
2430
2387
  }
2431
2388
  /**
2432
- * TODO: [🔣] If script require contentLanguage
2389
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2390
+ * TODO: [🐠] Maybe base this on `makeValidator`
2391
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2392
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2393
+ * - [🏍] ? Is context in each template
2394
+ * - [♨] Are samples prepared
2395
+ * - [♨] Are templates prepared
2433
2396
  */
2434
2397
 
2435
2398
  /**
@@ -2449,27 +2412,6 @@
2449
2412
  };
2450
2413
  }
2451
2414
 
2452
- /**
2453
- * Function isValidJsonString will tell you if the string is valid JSON or not
2454
- *
2455
- * @public exported from `@promptbook/utils`
2456
- */
2457
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2458
- try {
2459
- JSON.parse(value);
2460
- return true;
2461
- }
2462
- catch (error) {
2463
- if (!(error instanceof Error)) {
2464
- throw error;
2465
- }
2466
- if (error.message.includes('Unexpected token')) {
2467
- return false;
2468
- }
2469
- return false;
2470
- }
2471
- }
2472
-
2473
2415
  /**
2474
2416
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2475
2417
  *
@@ -2496,9 +2438,10 @@
2496
2438
  });
2497
2439
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2498
2440
  get: function () {
2499
- return this.llmExecutionTools
2500
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2501
- .join('\n');
2441
+ return this.llmExecutionTools.map(function (_a, index) {
2442
+ var title = _a.title;
2443
+ return "".concat(index + 1, ") `").concat(title, "`");
2444
+ }).join('\n');
2502
2445
  },
2503
2446
  enumerable: false,
2504
2447
  configurable: true
@@ -2696,9 +2639,7 @@
2696
2639
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2697
2640
  }
2698
2641
  else {
2699
- 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
2700
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2701
- .join('\n')), "\n\n "); }));
2642
+ 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 "); }));
2702
2643
  }
2703
2644
  }
2704
2645
  });
@@ -2764,288 +2705,153 @@
2764
2705
  */
2765
2706
 
2766
2707
  /**
2767
- * Extracts all code blocks from markdown.
2708
+ * Takes an item or an array of items and returns an array of items
2768
2709
  *
2769
- * Note: There are multiple simmilar function:
2770
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2771
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2772
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2773
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2710
+ * 1) Any item except array and undefined returns array with that one item (also null)
2711
+ * 2) Undefined returns empty array
2712
+ * 3) Array returns itself
2774
2713
  *
2775
- * @param markdown any valid markdown
2776
- * @returns code blocks with language and content
2777
- * @throws {ParseError} if block is not closed properly
2778
- * @public exported from `@promptbook/markdown-utils`
2714
+ * @private internal utility
2779
2715
  */
2780
- function extractAllBlocksFromMarkdown(markdown) {
2781
- var e_1, _a;
2782
- var codeBlocks = [];
2783
- var lines = markdown.split('\n');
2784
- // Note: [0] Ensure that the last block notated by gt > will be closed
2785
- lines.push('');
2786
- var currentCodeBlock = null;
2787
- try {
2788
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2789
- var line = lines_1_1.value;
2790
- if (line.startsWith('> ') || line === '>') {
2791
- if (currentCodeBlock === null) {
2792
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2793
- } /* not else */
2794
- if (currentCodeBlock.blockNotation === '>') {
2795
- if (currentCodeBlock.content !== '') {
2796
- currentCodeBlock.content += '\n';
2797
- }
2798
- currentCodeBlock.content += line.slice(2);
2799
- }
2800
- }
2801
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2802
- codeBlocks.push(currentCodeBlock);
2803
- currentCodeBlock = null;
2804
- }
2805
- /* not else */
2806
- if (line.startsWith('```')) {
2807
- var language = line.slice(3).trim() || null;
2808
- if (currentCodeBlock === null) {
2809
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2810
- }
2811
- else {
2812
- if (language !== null) {
2813
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2814
- }
2815
- codeBlocks.push(currentCodeBlock);
2816
- currentCodeBlock = null;
2817
- }
2818
- }
2819
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2820
- if (currentCodeBlock.content !== '') {
2821
- currentCodeBlock.content += '\n';
2822
- }
2823
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2824
- }
2825
- }
2826
- }
2827
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2828
- finally {
2829
- try {
2830
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2831
- }
2832
- finally { if (e_1) throw e_1.error; }
2716
+ function arrayableToArray(input) {
2717
+ if (input === undefined) {
2718
+ return [];
2833
2719
  }
2834
- if (currentCodeBlock !== null) {
2835
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2720
+ if (input instanceof Array) {
2721
+ return input;
2836
2722
  }
2837
- return codeBlocks;
2723
+ return [input];
2838
2724
  }
2839
- /**
2840
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2841
- */
2842
2725
 
2843
2726
  /**
2844
- * Extracts extracts exactly one valid JSON code block
2845
- *
2846
- * - When given string is a valid JSON as it is, it just returns it
2847
- * - When there is no JSON code block the function throws a `ParseError`
2848
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2849
- *
2850
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2851
- * Note: There are multiple simmilar function:
2852
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2853
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2854
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2855
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2727
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2856
2728
  *
2857
- * @public exported from `@promptbook/markdown-utils`
2858
- * @throws {ParseError} if there is no valid JSON block in the markdown
2859
- */
2860
- function extractJsonBlock(markdown) {
2861
- if (isValidJsonString(markdown)) {
2862
- return markdown;
2863
- }
2864
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2865
- var jsonBlocks = codeBlocks.filter(function (_a) {
2866
- var content = _a.content;
2867
- return isValidJsonString(content);
2868
- });
2869
- if (jsonBlocks.length === 0) {
2870
- throw new Error('There is no valid JSON block in the markdown');
2871
- }
2872
- if (jsonBlocks.length > 1) {
2873
- throw new Error('There are multiple JSON code blocks in the markdown');
2874
- }
2875
- return jsonBlocks[0].content;
2876
- }
2877
- /**
2878
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2879
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2880
- */
2881
-
2882
- /**
2883
- * Determine if the pipeline is fully prepared
2884
- *
2885
- * @public exported from `@promptbook/core`
2886
- */
2887
- function isPipelinePrepared(pipeline) {
2888
- // Note: Ignoring `pipeline.preparations` @@@
2889
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2890
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2891
- return false;
2892
- }
2893
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2894
- return false;
2895
- }
2896
- /*
2897
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2898
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2899
- > return false;
2900
- > }
2901
- */
2902
- return true;
2903
- }
2904
- /**
2905
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2906
- * TODO: [🐠] Maybe base this on `makeValidator`
2907
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2908
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2909
- * - [🏍] ? Is context in each template
2910
- * - [♨] Are samples prepared
2911
- * - [♨] Are templates prepared
2912
- */
2913
-
2914
- /**
2915
- * Takes an item or an array of items and returns an array of items
2916
- *
2917
- * 1) Any item except array and undefined returns array with that one item (also null)
2918
- * 2) Undefined returns empty array
2919
- * 3) Array returns itself
2920
- *
2921
- * @private internal utility
2729
+ * @param script from which to extract the variables
2730
+ * @returns the list of variable names
2731
+ * @throws {ParseError} if the script is invalid
2732
+ * @public exported from `@promptbook/utils`
2922
2733
  */
2923
- function arrayableToArray(input) {
2924
- if (input === undefined) {
2925
- return [];
2926
- }
2927
- if (input instanceof Array) {
2928
- return input;
2734
+ function extractVariables(script) {
2735
+ var variables = new Set();
2736
+ script = "(()=>{".concat(script, "})()");
2737
+ try {
2738
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2739
+ try {
2740
+ eval(script);
2741
+ }
2742
+ catch (error) {
2743
+ if (!(error instanceof ReferenceError)) {
2744
+ throw error;
2745
+ }
2746
+ var undefinedName = error.message.split(' ')[0];
2747
+ /*
2748
+ Note: Parsing the error
2749
+ [PipelineUrlError: thing is not defined]
2750
+ */
2751
+ if (!undefinedName) {
2752
+ throw error;
2753
+ }
2754
+ if (script.includes(undefinedName + '(')) {
2755
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2756
+ }
2757
+ else {
2758
+ variables.add(undefinedName);
2759
+ script = "const ".concat(undefinedName, " = '';") + script;
2760
+ }
2761
+ }
2929
2762
  }
2930
- return [input];
2931
- }
2932
-
2933
- /**
2934
- * Just says that the variable is not used but should be kept
2935
- * No side effects.
2936
- *
2937
- * Note: It can be usefull for:
2938
- *
2939
- * 1) Suppressing eager optimization of unused imports
2940
- * 2) Suppressing eslint errors of unused variables in the tests
2941
- * 3) Keeping the type of the variable for type testing
2942
- *
2943
- * @param value any values
2944
- * @returns void
2945
- * @private within the repository
2946
- */
2947
- function keepUnused() {
2948
- var valuesToKeep = [];
2949
- for (var _i = 0; _i < arguments.length; _i++) {
2950
- valuesToKeep[_i] = arguments[_i];
2763
+ catch (error) {
2764
+ if (!(error instanceof Error)) {
2765
+ throw error;
2766
+ }
2767
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2951
2768
  }
2769
+ return variables;
2952
2770
  }
2953
-
2954
2771
  /**
2955
- * Just marks a place of place where should be something implemented
2956
- * No side effects.
2957
- *
2958
- * Note: It can be usefull suppressing eslint errors of unused variables
2959
- *
2960
- * @param value any values
2961
- * @returns void
2962
- * @private within the repository
2772
+ * TODO: [🔣] Support for multiple languages - python, java,...
2963
2773
  */
2964
- function TODO_USE() {
2965
- var value = [];
2966
- for (var _i = 0; _i < arguments.length; _i++) {
2967
- value[_i] = arguments[_i];
2968
- }
2969
- }
2970
2774
 
2971
2775
  /**
2972
- * Replaces parameters in template with values from parameters object
2776
+ * Parses the template and returns the set of all used parameters
2973
2777
  *
2974
- * @param template the template with parameters in {curly} braces
2975
- * @param parameters the object with parameters
2976
- * @returns the template with replaced parameters
2977
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2778
+ * @param template the template with used parameters
2779
+ * @returns the set of parameter names
2780
+ * @throws {ParseError} if the script is invalid
2978
2781
  * @public exported from `@promptbook/utils`
2979
2782
  */
2980
- function replaceParameters(template, parameters) {
2981
- var e_1, _a;
2783
+ function extractParameterNamesFromTemplate(template) {
2784
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2785
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2786
+ var parameterNames = new Set();
2982
2787
  try {
2983
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2984
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2985
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2986
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2987
- }
2988
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2989
- // TODO: [🍵]
2990
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2991
- }
2788
+ 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()) {
2789
+ var parameterName = _f.value;
2790
+ parameterNames.add(parameterName);
2992
2791
  }
2993
2792
  }
2994
2793
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2995
2794
  finally {
2996
2795
  try {
2997
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2796
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2998
2797
  }
2999
2798
  finally { if (e_1) throw e_1.error; }
3000
2799
  }
3001
- var replacedTemplate = template;
3002
- var match;
3003
- var loopLimit = LOOP_LIMIT;
3004
- var _loop_1 = function () {
3005
- if (loopLimit-- < 0) {
3006
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2800
+ if (templateType === 'SCRIPT_TEMPLATE') {
2801
+ try {
2802
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2803
+ var parameterName = _h.value;
2804
+ parameterNames.add(parameterName);
2805
+ }
3007
2806
  }
3008
- var precol = match.groups.precol;
3009
- var parameterName = match.groups.parameterName;
3010
- if (parameterName === '') {
3011
- return "continue";
2807
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2808
+ finally {
2809
+ try {
2810
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2811
+ }
2812
+ finally { if (e_2) throw e_2.error; }
3012
2813
  }
3013
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3014
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2814
+ }
2815
+ try {
2816
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2817
+ var jokerName = _k.value;
2818
+ parameterNames.add(jokerName);
3015
2819
  }
3016
- if (parameters[parameterName] === undefined) {
3017
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2820
+ }
2821
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2822
+ finally {
2823
+ try {
2824
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
3018
2825
  }
3019
- var parameterValue = parameters[parameterName];
3020
- if (parameterValue === undefined) {
3021
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2826
+ finally { if (e_3) throw e_3.error; }
2827
+ }
2828
+ parameterNames.delete('content');
2829
+ // <- Note {websiteContent} is used in `preparedContent`
2830
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2831
+ if (foreach !== undefined) {
2832
+ try {
2833
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2834
+ var subparameterName = _m.value;
2835
+ if (parameterNames.has(subparameterName)) {
2836
+ parameterNames.delete(subparameterName);
2837
+ parameterNames.add(foreach.parameterName);
2838
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2839
+ }
2840
+ }
3022
2841
  }
3023
- parameterValue = parameterValue.toString();
3024
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3025
- parameterValue = parameterValue
3026
- .split('\n')
3027
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3028
- .join('\n');
2842
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2843
+ finally {
2844
+ try {
2845
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2846
+ }
2847
+ finally { if (e_4) throw e_4.error; }
3029
2848
  }
3030
- replacedTemplate =
3031
- replacedTemplate.substring(0, match.index + precol.length) +
3032
- parameterValue +
3033
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3034
- };
3035
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3036
- .exec(replacedTemplate))) {
3037
- _loop_1();
3038
- }
3039
- // [💫] Check if there are parameters that are not closed properly
3040
- if (/{\w+$/.test(replacedTemplate)) {
3041
- throw new PipelineExecutionError('Parameter is not closed');
3042
2849
  }
3043
- // [💫] Check if there are parameters that are not opened properly
3044
- if (/^\w+}/.test(replacedTemplate)) {
3045
- throw new PipelineExecutionError('Parameter is not opened');
3046
- }
3047
- return replacedTemplate;
2850
+ return parameterNames;
3048
2851
  }
2852
+ /**
2853
+ * TODO: [🔣] If script require contentLanguage
2854
+ */
3049
2855
 
3050
2856
  /**
3051
2857
  * Create difference set of two sets.
@@ -3123,117 +2929,351 @@
3123
2929
  }
3124
2930
 
3125
2931
  /**
3126
- * Counts number of characters in the text
2932
+ * Just marks a place of place where should be something implemented
2933
+ * No side effects.
3127
2934
  *
3128
- * @public exported from `@promptbook/utils`
2935
+ * Note: It can be usefull suppressing eslint errors of unused variables
2936
+ *
2937
+ * @param value any values
2938
+ * @returns void
2939
+ * @private within the repository
3129
2940
  */
3130
- function countCharacters(text) {
3131
- // Remove null characters
3132
- text = text.replace(/\0/g, '');
3133
- // Replace emojis (and also ZWJ sequence) with hyphens
3134
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3135
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3136
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3137
- return text.length;
2941
+ function TODO_USE() {
2942
+ var value = [];
2943
+ for (var _i = 0; _i < arguments.length; _i++) {
2944
+ value[_i] = arguments[_i];
2945
+ }
3138
2946
  }
3139
2947
 
3140
2948
  /**
3141
- * Counts number of lines in the text
2949
+ * @@@
3142
2950
  *
3143
- * @public exported from `@promptbook/utils`
2951
+ * @public exported from `@promptbook/core`
3144
2952
  */
3145
- function countLines(text) {
3146
- if (text === '') {
3147
- return 0;
3148
- }
3149
- return text.split('\n').length;
3150
- }
2953
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2954
+ header: true,
2955
+ // encoding: 'utf8',
2956
+ });
3151
2957
 
3152
2958
  /**
3153
- * Counts number of pages in the text
2959
+ * Definition for CSV spreadsheet
3154
2960
  *
3155
- * @public exported from `@promptbook/utils`
2961
+ * @public exported from `@promptbook/core`
2962
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2963
+ */
2964
+ var CsvFormatDefinition = {
2965
+ formatName: 'CSV',
2966
+ aliases: ['SPREADSHEET', 'TABLE'],
2967
+ isValid: function (value, settings, schema) {
2968
+ // TODO: !!!!!! Implement CSV validation
2969
+ TODO_USE(value /* <- TODO: Use value here */);
2970
+ TODO_USE(settings /* <- TODO: Use settings here */);
2971
+ TODO_USE(schema /* <- TODO: Use schema here */);
2972
+ return true;
2973
+ },
2974
+ canBeValid: function (partialValue, settings, schema) {
2975
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2976
+ TODO_USE(settings /* <- TODO: Use settings here */);
2977
+ TODO_USE(schema /* <- TODO: Use schema here */);
2978
+ return true;
2979
+ },
2980
+ heal: function (value, settings, schema) {
2981
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2982
+ TODO_USE(settings /* <- TODO: Use settings here */);
2983
+ TODO_USE(schema /* <- TODO: Use schema here */);
2984
+ throw new Error('Not implemented');
2985
+ },
2986
+ subvalueDefinitions: [
2987
+ {
2988
+ subvalueName: 'ROW',
2989
+ mapValues: function (value, settings, mapCallback) {
2990
+ return __awaiter(this, void 0, void 0, function () {
2991
+ var csv, mappedData;
2992
+ var _this = this;
2993
+ return __generator(this, function (_a) {
2994
+ switch (_a.label) {
2995
+ case 0:
2996
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2997
+ if (csv.errors.length !== 0) {
2998
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2999
+ 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 "); }));
3000
+ }
3001
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
3002
+ var _a;
3003
+ var _b;
3004
+ return __generator(this, function (_c) {
3005
+ switch (_c.label) {
3006
+ case 0:
3007
+ _a = [__assign({}, row)];
3008
+ _b = {};
3009
+ // <- TODO: !!!!!! Dynamic new column name and position
3010
+ // <- TODO: !!!!!! Check name collisions
3011
+ return [4 /*yield*/, mapCallback(row, index)];
3012
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
3013
+ // <- TODO: !!!!!! Dynamic new column name and position
3014
+ // <- TODO: !!!!!! Check name collisions
3015
+ _c.sent(), _b)])))];
3016
+ }
3017
+ });
3018
+ }); }))];
3019
+ case 1:
3020
+ mappedData = _a.sent();
3021
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3022
+ }
3023
+ });
3024
+ });
3025
+ },
3026
+ },
3027
+ {
3028
+ subvalueName: 'CELL',
3029
+ mapValues: function (value, settings, mapCallback) {
3030
+ return __awaiter(this, void 0, void 0, function () {
3031
+ var csv, mappedData;
3032
+ var _this = this;
3033
+ return __generator(this, function (_a) {
3034
+ switch (_a.label) {
3035
+ case 0:
3036
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
3037
+ if (csv.errors.length !== 0) {
3038
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3039
+ 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 "); }));
3040
+ }
3041
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3042
+ var _this = this;
3043
+ return __generator(this, function (_a) {
3044
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
3045
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
3046
+ return __awaiter(_this, void 0, void 0, function () {
3047
+ var index;
3048
+ var _c;
3049
+ return __generator(this, function (_d) {
3050
+ index = rowIndex * Object.keys(row).length + columnIndex;
3051
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
3052
+ });
3053
+ });
3054
+ }))];
3055
+ });
3056
+ }); }))];
3057
+ case 1:
3058
+ mappedData = _a.sent();
3059
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3060
+ }
3061
+ });
3062
+ });
3063
+ },
3064
+ },
3065
+ ],
3066
+ };
3067
+ /**
3068
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
3069
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
3070
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
3071
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
3072
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3156
3073
  */
3157
- function countPages(text) {
3158
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
3159
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3160
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3161
- return pageCount;
3162
- }
3163
3074
 
3164
3075
  /**
3165
- * Counts number of paragraphs in the text
3076
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3166
3077
  *
3167
3078
  * @public exported from `@promptbook/utils`
3168
3079
  */
3169
- function countParagraphs(text) {
3170
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3080
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
3081
+ try {
3082
+ JSON.parse(value);
3083
+ return true;
3084
+ }
3085
+ catch (error) {
3086
+ if (!(error instanceof Error)) {
3087
+ throw error;
3088
+ }
3089
+ if (error.message.includes('Unexpected token')) {
3090
+ return false;
3091
+ }
3092
+ return false;
3093
+ }
3171
3094
  }
3172
3095
 
3173
3096
  /**
3174
- * Split text into sentences
3097
+ * Definition for JSON format
3175
3098
  *
3176
- * @public exported from `@promptbook/utils`
3099
+ * @private still in development [🏢]
3177
3100
  */
3178
- function splitIntoSentences(text) {
3179
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3180
- }
3101
+ var JsonFormatDefinition = {
3102
+ formatName: 'JSON',
3103
+ mimeType: 'application/json',
3104
+ isValid: function (value, settings, schema) {
3105
+ TODO_USE(schema /* <- TODO: Use schema here */);
3106
+ TODO_USE(settings /* <- TODO: Use settings here */);
3107
+ return isValidJsonString(value);
3108
+ },
3109
+ canBeValid: function (partialValue, settings, schema) {
3110
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3111
+ TODO_USE(settings /* <- TODO: Use settings here */);
3112
+ TODO_USE(schema /* <- TODO: Use schema here */);
3113
+ return true;
3114
+ },
3115
+ heal: function (value, settings, schema) {
3116
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3117
+ TODO_USE(settings /* <- TODO: Use settings here */);
3118
+ TODO_USE(schema /* <- TODO: Use schema here */);
3119
+ throw new Error('Not implemented');
3120
+ },
3121
+ subvalueDefinitions: [],
3122
+ };
3181
3123
  /**
3182
- * Counts number of sentences in the text
3183
- *
3184
- * @public exported from `@promptbook/utils`
3124
+ * TODO: [🧠] Maybe propper instance of object
3125
+ * TODO: [0] Make string_serialized_json
3126
+ * TODO: [1] Make type for JSON Settings and Schema
3127
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3128
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3129
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3130
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3131
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3132
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3185
3133
  */
3186
- function countSentences(text) {
3187
- return splitIntoSentences(text).length;
3188
- }
3189
3134
 
3190
3135
  /**
3191
- * Counts number of words in the text
3136
+ * Definition for any text - this will be always valid
3192
3137
  *
3193
- * @public exported from `@promptbook/utils`
3138
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3139
+ *
3140
+ * @public exported from `@promptbook/core`
3141
+ */
3142
+ var TextFormatDefinition = {
3143
+ formatName: 'TEXT',
3144
+ isValid: function (value) {
3145
+ return typeof value === 'string';
3146
+ },
3147
+ canBeValid: function (partialValue) {
3148
+ return typeof partialValue === 'string';
3149
+ },
3150
+ heal: function () {
3151
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3152
+ },
3153
+ subvalueDefinitions: [
3154
+ {
3155
+ subvalueName: 'LINE',
3156
+ mapValues: function (value, settings, mapCallback) {
3157
+ return __awaiter(this, void 0, void 0, function () {
3158
+ var lines, mappedLines;
3159
+ return __generator(this, function (_a) {
3160
+ switch (_a.label) {
3161
+ case 0:
3162
+ lines = value.split('\n');
3163
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3164
+ // TODO: [🧠] Maybe option to skip empty line
3165
+ /* not await */ return mapCallback({
3166
+ lineContent: lineContent,
3167
+ // TODO: [🧠] Maybe also put here `lineNumber`
3168
+ }, lineNumber);
3169
+ }))];
3170
+ case 1:
3171
+ mappedLines = _a.sent();
3172
+ return [2 /*return*/, mappedLines.join('\n')];
3173
+ }
3174
+ });
3175
+ });
3176
+ },
3177
+ },
3178
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3179
+ ],
3180
+ };
3181
+ /**
3182
+ * TODO: [1] Make type for XML Text and Schema
3183
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3184
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3185
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3186
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3187
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3188
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3194
3189
  */
3195
- function countWords(text) {
3196
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3197
- text = removeDiacritics(text);
3198
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3199
- }
3200
3190
 
3201
3191
  /**
3202
- * Index of all counter functions
3192
+ * Definition for XML format
3203
3193
  *
3204
- * @public exported from `@promptbook/utils`
3194
+ * @private still in development [🏢]
3205
3195
  */
3206
- var CountUtils = {
3207
- CHARACTERS: countCharacters,
3208
- WORDS: countWords,
3209
- SENTENCES: countSentences,
3210
- PARAGRAPHS: countParagraphs,
3211
- LINES: countLines,
3212
- PAGES: countPages,
3196
+ var XmlFormatDefinition = {
3197
+ formatName: 'XML',
3198
+ mimeType: 'application/xml',
3199
+ isValid: function (value, settings, schema) {
3200
+ TODO_USE(value /* <- TODO: Use value here */);
3201
+ TODO_USE(settings /* <- TODO: Use settings here */);
3202
+ TODO_USE(schema /* <- TODO: Use schema here */);
3203
+ return true;
3204
+ },
3205
+ canBeValid: function (partialValue, settings, schema) {
3206
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3207
+ TODO_USE(settings /* <- TODO: Use settings here */);
3208
+ TODO_USE(schema /* <- TODO: Use schema here */);
3209
+ return true;
3210
+ },
3211
+ heal: function (value, settings, schema) {
3212
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3213
+ TODO_USE(settings /* <- TODO: Use settings here */);
3214
+ TODO_USE(schema /* <- TODO: Use schema here */);
3215
+ throw new Error('Not implemented');
3216
+ },
3217
+ subvalueDefinitions: [],
3213
3218
  };
3219
+ /**
3220
+ * TODO: [🧠] Maybe propper instance of object
3221
+ * TODO: [0] Make string_serialized_xml
3222
+ * TODO: [1] Make type for XML Settings and Schema
3223
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3224
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3225
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3226
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3227
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3228
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3229
+ */
3214
3230
 
3215
3231
  /**
3216
- * Function checkExpectations will check if the expectations on given value are met
3232
+ * Definitions for all formats supported by Promptbook
3217
3233
  *
3218
- * Note: There are two simmilar functions:
3219
- * - `checkExpectations` which throws an error if the expectations are not met
3220
- * - `isPassingExpectations` which returns a boolean
3234
+ * @private internal index of `...` <- TODO [🏢]
3235
+ */
3236
+ var FORMAT_DEFINITIONS = [
3237
+ JsonFormatDefinition,
3238
+ XmlFormatDefinition,
3239
+ TextFormatDefinition,
3240
+ CsvFormatDefinition,
3241
+ ];
3242
+
3243
+ /**
3244
+ * Maps available parameters to expected parameters
3221
3245
  *
3222
- * @throws {ExpectError} if the expectations are not met
3223
- * @returns {void} Nothing
3224
- * @private internal function of `createPipelineExecutor`
3246
+ * The strategy is:
3247
+ * 1) @@@
3248
+ * 2) @@@
3249
+ *
3250
+ * @throws {PipelineExecutionError} @@@
3251
+ * @private within the repository used in `createPipelineExecutor`
3225
3252
  */
3226
- function checkExpectations(expectations, value) {
3253
+ function mapAvailableToExpectedParameters(options) {
3227
3254
  var e_1, _a;
3255
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3256
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3257
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3258
+ var mappedParameters = {};
3228
3259
  try {
3229
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3230
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3231
- var amount = CountUtils[unit.toUpperCase()](value);
3232
- if (min && amount < min) {
3233
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3234
- } /* not else */
3235
- if (max && amount > max) {
3236
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3260
+ // Phase 1️⃣: Matching mapping
3261
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3262
+ var parameterName = _c.value;
3263
+ // Situation: Parameter is available and expected
3264
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3265
+ mappedParameters[parameterName] = availableParameters[parameterName];
3266
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3267
+ availableParametersNames.delete(parameterName);
3268
+ expectedParameterNames.delete(parameterName);
3269
+ }
3270
+ // Situation: Parameter is available but NOT expected
3271
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3272
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3273
+ }
3274
+ // Situation: Parameter is NOT available BUT expected
3275
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3276
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3237
3277
  }
3238
3278
  }
3239
3279
  }
@@ -3244,622 +3284,1139 @@
3244
3284
  }
3245
3285
  finally { if (e_1) throw e_1.error; }
3246
3286
  }
3287
+ if (expectedParameterNames.size === 0) {
3288
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3289
+ Object.freeze(mappedParameters);
3290
+ return mappedParameters;
3291
+ }
3292
+ // Phase 2️⃣: Non-matching mapping
3293
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3294
+ 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)
3295
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3296
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3297
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3298
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3299
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3300
+ .join('\n')), "\n\n "); }));
3301
+ }
3302
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3303
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3304
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3305
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3306
+ }
3307
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3308
+ Object.freeze(mappedParameters);
3309
+ return mappedParameters;
3247
3310
  }
3311
+
3248
3312
  /**
3249
- * Function checkExpectations will check if the expectations on given value are met
3313
+ * Extracts all code blocks from markdown.
3250
3314
  *
3251
- * Note: There are two simmilar functions:
3252
- * - `checkExpectations` which throws an error if the expectations are not met
3253
- * - `isPassingExpectations` which returns a boolean
3315
+ * Note: There are multiple simmilar function:
3316
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3317
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3318
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3319
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3254
3320
  *
3255
- * @returns {boolean} True if the expectations are met
3256
- * @public exported from `@promptbook/core`
3321
+ * @param markdown any valid markdown
3322
+ * @returns code blocks with language and content
3323
+ * @throws {ParseError} if block is not closed properly
3324
+ * @public exported from `@promptbook/markdown-utils`
3257
3325
  */
3258
- function isPassingExpectations(expectations, value) {
3326
+ function extractAllBlocksFromMarkdown(markdown) {
3327
+ var e_1, _a;
3328
+ var codeBlocks = [];
3329
+ var lines = markdown.split('\n');
3330
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3331
+ lines.push('');
3332
+ var currentCodeBlock = null;
3259
3333
  try {
3260
- checkExpectations(expectations, value);
3261
- return true;
3334
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3335
+ var line = lines_1_1.value;
3336
+ if (line.startsWith('> ') || line === '>') {
3337
+ if (currentCodeBlock === null) {
3338
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3339
+ } /* not else */
3340
+ if (currentCodeBlock.blockNotation === '>') {
3341
+ if (currentCodeBlock.content !== '') {
3342
+ currentCodeBlock.content += '\n';
3343
+ }
3344
+ currentCodeBlock.content += line.slice(2);
3345
+ }
3346
+ }
3347
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3348
+ codeBlocks.push(currentCodeBlock);
3349
+ currentCodeBlock = null;
3350
+ }
3351
+ /* not else */
3352
+ if (line.startsWith('```')) {
3353
+ var language = line.slice(3).trim() || null;
3354
+ if (currentCodeBlock === null) {
3355
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3356
+ }
3357
+ else {
3358
+ if (language !== null) {
3359
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3360
+ }
3361
+ codeBlocks.push(currentCodeBlock);
3362
+ currentCodeBlock = null;
3363
+ }
3364
+ }
3365
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3366
+ if (currentCodeBlock.content !== '') {
3367
+ currentCodeBlock.content += '\n';
3368
+ }
3369
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3370
+ }
3371
+ }
3262
3372
  }
3263
- catch (error) {
3264
- if (!(error instanceof ExpectError)) {
3265
- throw error;
3373
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3374
+ finally {
3375
+ try {
3376
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3266
3377
  }
3267
- return false;
3378
+ finally { if (e_1) throw e_1.error; }
3379
+ }
3380
+ if (currentCodeBlock !== null) {
3381
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3268
3382
  }
3383
+ return codeBlocks;
3269
3384
  }
3270
3385
  /**
3271
- * TODO: [💝] Unite object for expecting amount and format
3386
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3272
3387
  */
3273
3388
 
3274
3389
  /**
3275
- * Creates executor function from pipeline and execution tools.
3390
+ * Extracts extracts exactly one valid JSON code block
3276
3391
  *
3277
- * @returns The executor function
3278
- * @throws {PipelineLogicError} on logical error in the pipeline
3279
- * @public exported from `@promptbook/core`
3392
+ * - When given string is a valid JSON as it is, it just returns it
3393
+ * - When there is no JSON code block the function throws a `ParseError`
3394
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3395
+ *
3396
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3397
+ * Note: There are multiple simmilar function:
3398
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3399
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3400
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3401
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3402
+ *
3403
+ * @public exported from `@promptbook/markdown-utils`
3404
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3280
3405
  */
3281
- function createPipelineExecutor(options) {
3282
- var _this = this;
3283
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3284
- 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;
3285
- validatePipeline(pipeline);
3286
- var pipelineIdentification = (function () {
3287
- // Note: This is a 😐 implementation of [🚞]
3288
- var _ = [];
3289
- if (pipeline.sourceFile !== undefined) {
3290
- _.push("File: ".concat(pipeline.sourceFile));
3291
- }
3292
- if (pipeline.pipelineUrl !== undefined) {
3293
- _.push("Url: ".concat(pipeline.pipelineUrl));
3294
- }
3295
- return _.join('\n');
3296
- })();
3297
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3298
- var preparedPipeline;
3299
- if (isPipelinePrepared(pipeline)) {
3300
- preparedPipeline = pipeline;
3406
+ function extractJsonBlock(markdown) {
3407
+ if (isValidJsonString(markdown)) {
3408
+ return markdown;
3301
3409
  }
3302
- else if (isNotPreparedWarningSupressed !== true) {
3303
- 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 "); }));
3410
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3411
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3412
+ var content = _a.content;
3413
+ return isValidJsonString(content);
3414
+ });
3415
+ if (jsonBlocks.length === 0) {
3416
+ throw new Error('There is no valid JSON block in the markdown');
3304
3417
  }
3305
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3306
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3307
- function getContextForTemplate(template) {
3308
- return __awaiter(this, void 0, void 0, function () {
3309
- return __generator(this, function (_a) {
3310
- TODO_USE(template);
3311
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3312
- });
3313
- });
3418
+ if (jsonBlocks.length > 1) {
3419
+ throw new Error('There are multiple JSON code blocks in the markdown');
3420
+ }
3421
+ return jsonBlocks[0].content;
3422
+ }
3423
+ /**
3424
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3425
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3426
+ */
3427
+
3428
+ /**
3429
+ * Just says that the variable is not used but should be kept
3430
+ * No side effects.
3431
+ *
3432
+ * Note: It can be usefull for:
3433
+ *
3434
+ * 1) Suppressing eager optimization of unused imports
3435
+ * 2) Suppressing eslint errors of unused variables in the tests
3436
+ * 3) Keeping the type of the variable for type testing
3437
+ *
3438
+ * @param value any values
3439
+ * @returns void
3440
+ * @private within the repository
3441
+ */
3442
+ function keepUnused() {
3443
+ var valuesToKeep = [];
3444
+ for (var _i = 0; _i < arguments.length; _i++) {
3445
+ valuesToKeep[_i] = arguments[_i];
3446
+ }
3447
+ }
3448
+
3449
+ /**
3450
+ * Replaces parameters in template with values from parameters object
3451
+ *
3452
+ * @param template the template with parameters in {curly} braces
3453
+ * @param parameters the object with parameters
3454
+ * @returns the template with replaced parameters
3455
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3456
+ * @public exported from `@promptbook/utils`
3457
+ */
3458
+ function replaceParameters(template, parameters) {
3459
+ var e_1, _a;
3460
+ try {
3461
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3462
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3463
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3464
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3465
+ }
3466
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3467
+ // TODO: [🍵]
3468
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3469
+ }
3314
3470
  }
3315
- function getKnowledgeForTemplate(template) {
3316
- return __awaiter(this, void 0, void 0, function () {
3317
- return __generator(this, function (_a) {
3318
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3319
- TODO_USE(template);
3320
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3321
- var content = _a.content;
3322
- return "- ".concat(content);
3323
- }).join('\n')];
3324
- });
3325
- });
3471
+ }
3472
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3473
+ finally {
3474
+ try {
3475
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3326
3476
  }
3327
- function getSamplesForTemplate(template) {
3328
- return __awaiter(this, void 0, void 0, function () {
3329
- return __generator(this, function (_a) {
3330
- // TODO: [♨] Implement Better - use real index and keyword search
3331
- TODO_USE(template);
3332
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3333
- });
3334
- });
3477
+ finally { if (e_1) throw e_1.error; }
3478
+ }
3479
+ var replacedTemplate = template;
3480
+ var match;
3481
+ var loopLimit = LOOP_LIMIT;
3482
+ var _loop_1 = function () {
3483
+ if (loopLimit-- < 0) {
3484
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3335
3485
  }
3336
- function getReservedParametersForTemplate(template) {
3337
- return __awaiter(this, void 0, void 0, function () {
3338
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3339
- var e_3, _a;
3340
- return __generator(this, function (_b) {
3341
- switch (_b.label) {
3342
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3343
- case 1:
3344
- context = _b.sent();
3345
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3346
- case 2:
3347
- knowledge = _b.sent();
3348
- return [4 /*yield*/, getSamplesForTemplate(template)];
3349
- case 3:
3350
- samples = _b.sent();
3351
- currentDate = new Date().toISOString();
3352
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3353
- reservedParameters = {
3354
- content: RESERVED_PARAMETER_RESTRICTED,
3355
- context: context,
3356
- knowledge: knowledge,
3357
- samples: samples,
3358
- currentDate: currentDate,
3359
- modelName: modelName,
3360
- };
3361
- _loop_3 = function (parameterName) {
3362
- if (reservedParameters[parameterName] === undefined) {
3363
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3364
- }
3365
- };
3366
- try {
3367
- // Note: Doublecheck that ALL reserved parameters are defined:
3368
- 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()) {
3369
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3370
- _loop_3(parameterName);
3371
- }
3372
- }
3373
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3374
- finally {
3375
- try {
3376
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3377
- }
3378
- finally { if (e_3) throw e_3.error; }
3379
- }
3380
- return [2 /*return*/, reservedParameters];
3381
- }
3382
- });
3383
- });
3486
+ var precol = match.groups.precol;
3487
+ var parameterName = match.groups.parameterName;
3488
+ if (parameterName === '') {
3489
+ return "continue";
3384
3490
  }
3385
- function executeSingleTemplate(currentTemplate) {
3386
- return __awaiter(this, void 0, void 0, function () {
3387
- 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;
3388
- var e_4, _f, _g;
3389
- return __generator(this, function (_h) {
3390
- switch (_h.label) {
3391
- case 0:
3392
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3393
- title = currentTemplate.title;
3394
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3395
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3396
- progress_1 = {
3397
- name: name,
3398
- title: title,
3399
- isStarted: false,
3400
- isDone: false,
3401
- templateType: currentTemplate.templateType,
3402
- parameterName: currentTemplate.resultingParameterName,
3403
- parameterValue: null,
3404
- // <- [3]
3405
- };
3406
- if (isReturned) {
3407
- 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)
3408
- .split('\n')
3409
- .map(function (line) { return "> ".concat(line); })
3410
- .join('\n')), "\n "); }));
3411
- }
3412
- return [4 /*yield*/, onProgress(progress_1)];
3413
- case 1:
3414
- _h.sent();
3415
- _h.label = 2;
3416
- case 2:
3417
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3418
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3419
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3420
- 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)
3421
- .map(function (name) { return "{".concat(name, "}"); })
3422
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3423
- .map(function (name) { return "{".concat(name, "}"); })
3424
- .join(', '), "\n\n "); }));
3425
- }
3426
- _b = (_a = Object).freeze;
3427
- _c = [{}];
3428
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3429
- case 3:
3430
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3431
- definedParameterNames = new Set(Object.keys(definedParameters));
3432
- parameters = {};
3433
- _loop_4 = function (parameterName) {
3434
- // Situation: Parameter is defined and used
3435
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3436
- parameters[parameterName] = definedParameters[parameterName];
3437
- }
3438
- // Situation: Parameter is defined but NOT used
3439
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3440
- // Situation: Parameter is NOT defined BUT used
3441
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3442
- // Houston, we have a problem
3443
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3444
- 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 "); }));
3445
- }
3446
- };
3447
- try {
3448
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3449
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3450
- parameterName = _e.value;
3451
- _loop_4(parameterName);
3452
- }
3453
- }
3454
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3455
- finally {
3456
- try {
3457
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3458
- }
3459
- finally { if (e_4) throw e_4.error; }
3460
- }
3461
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3462
- Object.freeze(parameters);
3463
- result = null;
3464
- resultString = null;
3465
- expectError = null;
3466
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3467
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3468
- preparedContent = (currentTemplate.preparedContent || '{content}')
3469
- .split('{content}')
3470
- .join(currentTemplate.content);
3471
- _loop_5 = function (attempt) {
3472
- 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;
3473
- var e_5, _s, e_7, _t, e_6, _u;
3474
- return __generator(this, function (_v) {
3475
- switch (_v.label) {
3476
- case 0:
3477
- isJokerAttempt = attempt < 0;
3478
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3479
- if (isJokerAttempt && !jokerParameterName) {
3480
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3481
- }
3482
- result = null;
3483
- resultString = null;
3484
- expectError = null;
3485
- if (isJokerAttempt) {
3486
- if (parameters[jokerParameterName] === undefined) {
3487
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3488
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3489
- }
3490
- else {
3491
- resultString = parameters[jokerParameterName];
3492
- }
3493
- }
3494
- _v.label = 1;
3495
- case 1:
3496
- _v.trys.push([1, 44, 45, 46]);
3497
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3498
- _j = currentTemplate.templateType;
3499
- switch (_j) {
3500
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3501
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3502
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3503
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3504
- }
3505
- return [3 /*break*/, 25];
3506
- case 2:
3507
- resultString = replaceParameters(preparedContent, parameters);
3508
- return [3 /*break*/, 26];
3509
- case 3:
3510
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3511
- prompt = {
3512
- title: currentTemplate.title,
3513
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3514
- ? preparedPipeline.pipelineUrl
3515
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3516
- parameters: parameters,
3517
- content: preparedContent,
3518
- modelRequirements: modelRequirements,
3519
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3520
- var name = _a.name;
3521
- return name === currentTemplate.personaName;
3522
- }) || {})), currentTemplate.expectations),
3523
- format: currentTemplate.format,
3524
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3525
- }; // <- TODO: Not very good type guard
3526
- _k = modelRequirements.modelVariant;
3527
- switch (_k) {
3528
- case 'CHAT': return [3 /*break*/, 4];
3529
- case 'COMPLETION': return [3 /*break*/, 6];
3530
- case 'EMBEDDING': return [3 /*break*/, 8];
3531
- }
3532
- return [3 /*break*/, 10];
3533
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3534
- case 5:
3535
- chatResult = _v.sent();
3536
- // TODO: [🍬] Destroy chatThread
3537
- result = chatResult;
3538
- resultString = chatResult.content;
3539
- return [3 /*break*/, 11];
3540
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3541
- case 7:
3542
- completionResult = _v.sent();
3543
- result = completionResult;
3544
- resultString = completionResult.content;
3545
- return [3 /*break*/, 11];
3546
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3547
- case 9:
3548
- embeddingResult = _v.sent();
3549
- result = embeddingResult;
3550
- resultString = embeddingResult.content.join(',');
3551
- return [3 /*break*/, 11];
3552
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3553
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3554
- case 11: return [3 /*break*/, 26];
3555
- case 12:
3556
- if (arrayableToArray(tools.script).length === 0) {
3557
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3558
- }
3559
- if (!currentTemplate.contentLanguage) {
3560
- 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 "); }));
3561
- }
3562
- // TODO: DRY [1]
3563
- scriptPipelineExecutionErrors = [];
3564
- _v.label = 13;
3565
- case 13:
3566
- _v.trys.push([13, 20, 21, 22]);
3567
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3568
- _v.label = 14;
3569
- case 14:
3570
- if (!!_m.done) return [3 /*break*/, 19];
3571
- scriptTools = _m.value;
3572
- _v.label = 15;
3573
- case 15:
3574
- _v.trys.push([15, 17, , 18]);
3575
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3576
- scriptLanguage: currentTemplate.contentLanguage,
3577
- script: preparedContent,
3578
- parameters: parameters,
3579
- }))];
3580
- case 16:
3581
- resultString = _v.sent();
3582
- return [3 /*break*/, 19];
3583
- case 17:
3584
- error_2 = _v.sent();
3585
- if (!(error_2 instanceof Error)) {
3586
- throw error_2;
3587
- }
3588
- if (error_2 instanceof UnexpectedError) {
3589
- throw error_2;
3590
- }
3591
- scriptPipelineExecutionErrors.push(error_2);
3592
- return [3 /*break*/, 18];
3593
- case 18:
3594
- _m = _l.next();
3595
- return [3 /*break*/, 14];
3596
- case 19: return [3 /*break*/, 22];
3597
- case 20:
3598
- e_5_1 = _v.sent();
3599
- e_5 = { error: e_5_1 };
3600
- return [3 /*break*/, 22];
3601
- case 21:
3602
- try {
3603
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3604
- }
3605
- finally { if (e_5) throw e_5.error; }
3606
- return [7 /*endfinally*/];
3607
- case 22:
3608
- if (resultString !== null) {
3609
- return [3 /*break*/, 26];
3610
- }
3611
- if (scriptPipelineExecutionErrors.length === 1) {
3612
- throw scriptPipelineExecutionErrors[0];
3613
- }
3614
- else {
3615
- 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
3616
- .map(function (error) { return '- ' + error.message; })
3617
- .join('\n\n')), "\n "); }));
3618
- }
3619
- case 23:
3620
- if (tools.userInterface === undefined) {
3621
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3622
- }
3623
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3624
- promptTitle: currentTemplate.title,
3625
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3626
- defaultValue: replaceParameters(preparedContent, parameters),
3627
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3628
- placeholder: undefined,
3629
- priority: priority,
3630
- }))];
3631
- case 24:
3632
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3633
- resultString = _v.sent();
3634
- return [3 /*break*/, 26];
3635
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3636
- case 26:
3637
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3638
- _v.label = 27;
3639
- case 27:
3640
- _v.trys.push([27, 41, 42, 43]);
3641
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3642
- _v.label = 28;
3643
- case 28:
3644
- if (!!_p.done) return [3 /*break*/, 40];
3645
- functionName = _p.value;
3646
- // TODO: DRY [1]
3647
- scriptPipelineExecutionErrors = [];
3648
- postprocessingError = null;
3649
- _v.label = 29;
3650
- case 29:
3651
- _v.trys.push([29, 36, 37, 38]);
3652
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3653
- _v.label = 30;
3654
- case 30:
3655
- if (!!_r.done) return [3 /*break*/, 35];
3656
- scriptTools = _r.value;
3657
- _v.label = 31;
3658
- case 31:
3659
- _v.trys.push([31, 33, , 34]);
3660
- return [4 /*yield*/, scriptTools.execute({
3661
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3662
- script: "".concat(functionName, "(resultString)"),
3663
- parameters: {
3664
- resultString: resultString || '',
3665
- // Note: No ...parametersForTemplate, because working with result only
3666
- },
3667
- })];
3668
- case 32:
3669
- resultString = _v.sent();
3670
- postprocessingError = null;
3671
- return [3 /*break*/, 35];
3672
- case 33:
3673
- error_3 = _v.sent();
3674
- if (!(error_3 instanceof Error)) {
3675
- throw error_3;
3676
- }
3677
- if (error_3 instanceof UnexpectedError) {
3678
- throw error_3;
3679
- }
3680
- postprocessingError = error_3;
3681
- scriptPipelineExecutionErrors.push(error_3);
3682
- return [3 /*break*/, 34];
3683
- case 34:
3684
- _r = _q.next();
3685
- return [3 /*break*/, 30];
3686
- case 35: return [3 /*break*/, 38];
3687
- case 36:
3688
- e_6_1 = _v.sent();
3689
- e_6 = { error: e_6_1 };
3690
- return [3 /*break*/, 38];
3691
- case 37:
3692
- try {
3693
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3694
- }
3695
- finally { if (e_6) throw e_6.error; }
3696
- return [7 /*endfinally*/];
3697
- case 38:
3698
- if (postprocessingError) {
3699
- throw postprocessingError;
3700
- }
3701
- _v.label = 39;
3702
- case 39:
3703
- _p = _o.next();
3704
- return [3 /*break*/, 28];
3705
- case 40: return [3 /*break*/, 43];
3706
- case 41:
3707
- e_7_1 = _v.sent();
3708
- e_7 = { error: e_7_1 };
3709
- return [3 /*break*/, 43];
3710
- case 42:
3711
- try {
3712
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3713
- }
3714
- finally { if (e_7) throw e_7.error; }
3715
- return [7 /*endfinally*/];
3716
- case 43:
3717
- // TODO: [💝] Unite object for expecting amount and format
3718
- if (currentTemplate.format) {
3719
- if (currentTemplate.format === 'JSON') {
3720
- if (!isValidJsonString(resultString || '')) {
3721
- // TODO: [🏢] Do more universally via `FormatDefinition`
3722
- try {
3723
- resultString = extractJsonBlock(resultString || '');
3724
- }
3725
- catch (error) {
3726
- keepUnused(error);
3727
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3728
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3729
- }
3730
- }
3491
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3492
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3493
+ }
3494
+ if (parameters[parameterName] === undefined) {
3495
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3496
+ }
3497
+ var parameterValue = parameters[parameterName];
3498
+ if (parameterValue === undefined) {
3499
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3500
+ }
3501
+ parameterValue = parameterValue.toString();
3502
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3503
+ parameterValue = parameterValue
3504
+ .split('\n')
3505
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3506
+ .join('\n');
3507
+ }
3508
+ replacedTemplate =
3509
+ replacedTemplate.substring(0, match.index + precol.length) +
3510
+ parameterValue +
3511
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3512
+ };
3513
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3514
+ .exec(replacedTemplate))) {
3515
+ _loop_1();
3516
+ }
3517
+ // [💫] Check if there are parameters that are not closed properly
3518
+ if (/{\w+$/.test(replacedTemplate)) {
3519
+ throw new PipelineExecutionError('Parameter is not closed');
3520
+ }
3521
+ // [💫] Check if there are parameters that are not opened properly
3522
+ if (/^\w+}/.test(replacedTemplate)) {
3523
+ throw new PipelineExecutionError('Parameter is not opened');
3524
+ }
3525
+ return replacedTemplate;
3526
+ }
3527
+
3528
+ /**
3529
+ * Counts number of characters in the text
3530
+ *
3531
+ * @public exported from `@promptbook/utils`
3532
+ */
3533
+ function countCharacters(text) {
3534
+ // Remove null characters
3535
+ text = text.replace(/\0/g, '');
3536
+ // Replace emojis (and also ZWJ sequence) with hyphens
3537
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3538
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3539
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3540
+ return text.length;
3541
+ }
3542
+
3543
+ /**
3544
+ * Counts number of lines in the text
3545
+ *
3546
+ * @public exported from `@promptbook/utils`
3547
+ */
3548
+ function countLines(text) {
3549
+ if (text === '') {
3550
+ return 0;
3551
+ }
3552
+ return text.split('\n').length;
3553
+ }
3554
+
3555
+ /**
3556
+ * Counts number of pages in the text
3557
+ *
3558
+ * @public exported from `@promptbook/utils`
3559
+ */
3560
+ function countPages(text) {
3561
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3562
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3563
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3564
+ return pageCount;
3565
+ }
3566
+
3567
+ /**
3568
+ * Counts number of paragraphs in the text
3569
+ *
3570
+ * @public exported from `@promptbook/utils`
3571
+ */
3572
+ function countParagraphs(text) {
3573
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3574
+ }
3575
+
3576
+ /**
3577
+ * Split text into sentences
3578
+ *
3579
+ * @public exported from `@promptbook/utils`
3580
+ */
3581
+ function splitIntoSentences(text) {
3582
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3583
+ }
3584
+ /**
3585
+ * Counts number of sentences in the text
3586
+ *
3587
+ * @public exported from `@promptbook/utils`
3588
+ */
3589
+ function countSentences(text) {
3590
+ return splitIntoSentences(text).length;
3591
+ }
3592
+
3593
+ /**
3594
+ * Counts number of words in the text
3595
+ *
3596
+ * @public exported from `@promptbook/utils`
3597
+ */
3598
+ function countWords(text) {
3599
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3600
+ text = removeDiacritics(text);
3601
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3602
+ }
3603
+
3604
+ /**
3605
+ * Index of all counter functions
3606
+ *
3607
+ * @public exported from `@promptbook/utils`
3608
+ */
3609
+ var CountUtils = {
3610
+ CHARACTERS: countCharacters,
3611
+ WORDS: countWords,
3612
+ SENTENCES: countSentences,
3613
+ PARAGRAPHS: countParagraphs,
3614
+ LINES: countLines,
3615
+ PAGES: countPages,
3616
+ };
3617
+ /**
3618
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3619
+ */
3620
+
3621
+ /**
3622
+ * Function checkExpectations will check if the expectations on given value are met
3623
+ *
3624
+ * Note: There are two simmilar functions:
3625
+ * - `checkExpectations` which throws an error if the expectations are not met
3626
+ * - `isPassingExpectations` which returns a boolean
3627
+ *
3628
+ * @throws {ExpectError} if the expectations are not met
3629
+ * @returns {void} Nothing
3630
+ * @private internal function of `createPipelineExecutor`
3631
+ */
3632
+ function checkExpectations(expectations, value) {
3633
+ var e_1, _a;
3634
+ try {
3635
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3636
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3637
+ var amount = CountUtils[unit.toUpperCase()](value);
3638
+ if (min && amount < min) {
3639
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3640
+ } /* not else */
3641
+ if (max && amount > max) {
3642
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3643
+ }
3644
+ }
3645
+ }
3646
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3647
+ finally {
3648
+ try {
3649
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3650
+ }
3651
+ finally { if (e_1) throw e_1.error; }
3652
+ }
3653
+ }
3654
+ /**
3655
+ * Function checkExpectations will check if the expectations on given value are met
3656
+ *
3657
+ * Note: There are two simmilar functions:
3658
+ * - `checkExpectations` which throws an error if the expectations are not met
3659
+ * - `isPassingExpectations` which returns a boolean
3660
+ *
3661
+ * @returns {boolean} True if the expectations are met
3662
+ * @public exported from `@promptbook/core`
3663
+ */
3664
+ function isPassingExpectations(expectations, value) {
3665
+ try {
3666
+ checkExpectations(expectations, value);
3667
+ return true;
3668
+ }
3669
+ catch (error) {
3670
+ if (!(error instanceof ExpectError)) {
3671
+ throw error;
3672
+ }
3673
+ return false;
3674
+ }
3675
+ }
3676
+ /**
3677
+ * TODO: [💝] Unite object for expecting amount and format
3678
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3679
+ * Note: [💝] and [🤠] are interconnected together
3680
+ */
3681
+
3682
+ /**
3683
+ * @@@
3684
+ *
3685
+ * @private internal utility of `createPipelineExecutor`
3686
+ */
3687
+ function executeAttempts(options) {
3688
+ return __awaiter(this, void 0, void 0, function () {
3689
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3690
+ return __generator(this, function (_a) {
3691
+ switch (_a.label) {
3692
+ case 0:
3693
+ 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;
3694
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3695
+ $ongoingTemplateResult = {
3696
+ $result: null,
3697
+ $resultString: null,
3698
+ $expectError: null,
3699
+ $scriptPipelineExecutionErrors: [],
3700
+ };
3701
+ _loop_1 = function (attempt) {
3702
+ 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;
3703
+ var e_1, _q, e_3, _r, e_2, _s;
3704
+ return __generator(this, function (_t) {
3705
+ switch (_t.label) {
3706
+ case 0:
3707
+ isJokerAttempt = attempt < 0;
3708
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3709
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3710
+ if (isJokerAttempt && !jokerParameterName) {
3711
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3712
+ }
3713
+ $ongoingTemplateResult.$result = null;
3714
+ $ongoingTemplateResult.$resultString = null;
3715
+ $ongoingTemplateResult.$expectError = null;
3716
+ if (isJokerAttempt) {
3717
+ if (parameters[jokerParameterName] === undefined) {
3718
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3719
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3720
+ }
3721
+ else {
3722
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3723
+ }
3724
+ }
3725
+ _t.label = 1;
3726
+ case 1:
3727
+ _t.trys.push([1, 43, 44, 45]);
3728
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3729
+ _b = template.templateType;
3730
+ switch (_b) {
3731
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3732
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3733
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3734
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3735
+ }
3736
+ return [3 /*break*/, 24];
3737
+ case 2:
3738
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3739
+ return [3 /*break*/, 25];
3740
+ case 3:
3741
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3742
+ $ongoingTemplateResult.$prompt = {
3743
+ title: template.title,
3744
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3745
+ ? preparedPipeline.pipelineUrl
3746
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3747
+ parameters: parameters,
3748
+ content: preparedContent,
3749
+ modelRequirements: modelRequirements,
3750
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3751
+ var name = _a.name;
3752
+ return name === template.personaName;
3753
+ }) ||
3754
+ {})), template.expectations),
3755
+ format: template.format,
3756
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3757
+ }; // <- TODO: Not very good type guard
3758
+ _c = modelRequirements.modelVariant;
3759
+ switch (_c) {
3760
+ case 'CHAT': return [3 /*break*/, 4];
3761
+ case 'COMPLETION': return [3 /*break*/, 6];
3762
+ case 'EMBEDDING': return [3 /*break*/, 8];
3763
+ }
3764
+ return [3 /*break*/, 9];
3765
+ case 4:
3766
+ _d = $ongoingTemplateResult;
3767
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3768
+ case 5:
3769
+ _d.$chatResult = _t.sent();
3770
+ // TODO: [🍬] Destroy chatThread
3771
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3772
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3773
+ return [3 /*break*/, 10];
3774
+ case 6:
3775
+ _e = $ongoingTemplateResult;
3776
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3777
+ case 7:
3778
+ _e.$completionResult = _t.sent();
3779
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3780
+ $ongoingTemplateResult.$resultString =
3781
+ $ongoingTemplateResult.$completionResult.content;
3782
+ return [3 /*break*/, 10];
3783
+ 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 "); }));
3784
+ 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 "); }));
3785
+ case 10: return [3 /*break*/, 25];
3786
+ case 11:
3787
+ if (arrayableToArray(tools.script).length === 0) {
3788
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3789
+ }
3790
+ if (!template.contentLanguage) {
3791
+ 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 "); }));
3792
+ }
3793
+ _t.label = 12;
3794
+ case 12:
3795
+ _t.trys.push([12, 19, 20, 21]);
3796
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3797
+ _t.label = 13;
3798
+ case 13:
3799
+ if (!!_g.done) return [3 /*break*/, 18];
3800
+ scriptTools = _g.value;
3801
+ _t.label = 14;
3802
+ case 14:
3803
+ _t.trys.push([14, 16, , 17]);
3804
+ _h = $ongoingTemplateResult;
3805
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3806
+ scriptLanguage: template.contentLanguage,
3807
+ script: preparedContent,
3808
+ parameters: parameters,
3809
+ }))];
3810
+ case 15:
3811
+ _h.$resultString = _t.sent();
3812
+ return [3 /*break*/, 18];
3813
+ case 16:
3814
+ error_1 = _t.sent();
3815
+ if (!(error_1 instanceof Error)) {
3816
+ throw error_1;
3817
+ }
3818
+ if (error_1 instanceof UnexpectedError) {
3819
+ throw error_1;
3820
+ }
3821
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3822
+ return [3 /*break*/, 17];
3823
+ case 17:
3824
+ _g = _f.next();
3825
+ return [3 /*break*/, 13];
3826
+ case 18: return [3 /*break*/, 21];
3827
+ case 19:
3828
+ e_1_1 = _t.sent();
3829
+ e_1 = { error: e_1_1 };
3830
+ return [3 /*break*/, 21];
3831
+ case 20:
3832
+ try {
3833
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3834
+ }
3835
+ finally { if (e_1) throw e_1.error; }
3836
+ return [7 /*endfinally*/];
3837
+ case 21:
3838
+ if ($ongoingTemplateResult.$resultString !== null) {
3839
+ return [3 /*break*/, 25];
3840
+ }
3841
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3842
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3843
+ }
3844
+ else {
3845
+ 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
3846
+ .map(function (error) { return '- ' + error.message; })
3847
+ .join('\n\n')), "\n "); }));
3848
+ }
3849
+ case 22:
3850
+ if (tools.userInterface === undefined) {
3851
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3852
+ }
3853
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3854
+ _j = $ongoingTemplateResult;
3855
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3856
+ promptTitle: template.title,
3857
+ promptMessage: replaceParameters(template.description || '', parameters),
3858
+ defaultValue: replaceParameters(preparedContent, parameters),
3859
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3860
+ placeholder: undefined,
3861
+ priority: priority,
3862
+ }))];
3863
+ case 23:
3864
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3865
+ _j.$resultString = _t.sent();
3866
+ return [3 /*break*/, 25];
3867
+ case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3868
+ case 25:
3869
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3870
+ _t.label = 26;
3871
+ case 26:
3872
+ _t.trys.push([26, 40, 41, 42]);
3873
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3874
+ _t.label = 27;
3875
+ case 27:
3876
+ if (!!_l.done) return [3 /*break*/, 39];
3877
+ functionName = _l.value;
3878
+ postprocessingError = null;
3879
+ _t.label = 28;
3880
+ case 28:
3881
+ _t.trys.push([28, 35, 36, 37]);
3882
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3883
+ _t.label = 29;
3884
+ case 29:
3885
+ if (!!_o.done) return [3 /*break*/, 34];
3886
+ scriptTools = _o.value;
3887
+ _t.label = 30;
3888
+ case 30:
3889
+ _t.trys.push([30, 32, , 33]);
3890
+ _p = $ongoingTemplateResult;
3891
+ return [4 /*yield*/, scriptTools.execute({
3892
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3893
+ script: "".concat(functionName, "(resultString)"),
3894
+ parameters: {
3895
+ resultString: $ongoingTemplateResult.$resultString || '',
3896
+ // Note: No ...parametersForTemplate, because working with result only
3897
+ },
3898
+ })];
3899
+ case 31:
3900
+ _p.$resultString = _t.sent();
3901
+ postprocessingError = null;
3902
+ return [3 /*break*/, 34];
3903
+ case 32:
3904
+ error_2 = _t.sent();
3905
+ if (!(error_2 instanceof Error)) {
3906
+ throw error_2;
3907
+ }
3908
+ if (error_2 instanceof UnexpectedError) {
3909
+ throw error_2;
3910
+ }
3911
+ postprocessingError = error_2;
3912
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3913
+ return [3 /*break*/, 33];
3914
+ case 33:
3915
+ _o = _m.next();
3916
+ return [3 /*break*/, 29];
3917
+ case 34: return [3 /*break*/, 37];
3918
+ case 35:
3919
+ e_2_1 = _t.sent();
3920
+ e_2 = { error: e_2_1 };
3921
+ return [3 /*break*/, 37];
3922
+ case 36:
3923
+ try {
3924
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3925
+ }
3926
+ finally { if (e_2) throw e_2.error; }
3927
+ return [7 /*endfinally*/];
3928
+ case 37:
3929
+ if (postprocessingError) {
3930
+ throw postprocessingError;
3931
+ }
3932
+ _t.label = 38;
3933
+ case 38:
3934
+ _l = _k.next();
3935
+ return [3 /*break*/, 27];
3936
+ case 39: return [3 /*break*/, 42];
3937
+ case 40:
3938
+ e_3_1 = _t.sent();
3939
+ e_3 = { error: e_3_1 };
3940
+ return [3 /*break*/, 42];
3941
+ case 41:
3942
+ try {
3943
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3944
+ }
3945
+ finally { if (e_3) throw e_3.error; }
3946
+ return [7 /*endfinally*/];
3947
+ case 42:
3948
+ // TODO: [💝] Unite object for expecting amount and format
3949
+ if (template.format) {
3950
+ if (template.format === 'JSON') {
3951
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3952
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3953
+ try {
3954
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3731
3955
  }
3732
- else {
3733
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3956
+ catch (error) {
3957
+ keepUnused(error);
3958
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3959
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3734
3960
  }
3735
3961
  }
3736
- // TODO: [💝] Unite object for expecting amount and format
3737
- if (currentTemplate.expectations) {
3738
- checkExpectations(currentTemplate.expectations, resultString || '');
3739
- }
3740
- return [2 /*return*/, "break-attempts"];
3741
- case 44:
3742
- error_4 = _v.sent();
3743
- if (!(error_4 instanceof ExpectError)) {
3744
- throw error_4;
3745
- }
3746
- expectError = error_4;
3747
- return [3 /*break*/, 46];
3748
- case 45:
3749
- if (!isJokerAttempt &&
3750
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3751
- prompt
3752
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3753
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3754
- ) {
3755
- // TODO: [🧠] Maybe put other templateTypes into report
3756
- executionReport.promptExecutions.push({
3757
- prompt: __assign({}, prompt),
3758
- result: result || undefined,
3759
- error: expectError === null ? undefined : serializeError(expectError),
3760
- });
3761
- }
3762
- return [7 /*endfinally*/];
3763
- case 46:
3764
- if (expectError !== null && attempt === maxAttempts - 1) {
3765
- 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
3766
- .split('\n')
3767
- .map(function (line) { return "> ".concat(line); })
3768
- .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) || '')
3962
+ }
3963
+ else {
3964
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3965
+ }
3966
+ }
3967
+ // TODO: [💝] Unite object for expecting amount and format
3968
+ if (template.expectations) {
3969
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3970
+ }
3971
+ return [2 /*return*/, "break-attempts"];
3972
+ case 43:
3973
+ error_3 = _t.sent();
3974
+ if (!(error_3 instanceof ExpectError)) {
3975
+ throw error_3;
3976
+ }
3977
+ $ongoingTemplateResult.$expectError = error_3;
3978
+ return [3 /*break*/, 45];
3979
+ case 44:
3980
+ if (!isJokerAttempt &&
3981
+ template.templateType === 'PROMPT_TEMPLATE' &&
3982
+ $ongoingTemplateResult.$prompt
3983
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3984
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3985
+ ) {
3986
+ // TODO: [🧠] Maybe put other templateTypes into report
3987
+ $executionReport.promptExecutions.push({
3988
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3989
+ result: $ongoingTemplateResult.$result || undefined,
3990
+ error: $ongoingTemplateResult.$expectError === null
3991
+ ? undefined
3992
+ : serializeError($ongoingTemplateResult.$expectError),
3993
+ });
3994
+ }
3995
+ return [7 /*endfinally*/];
3996
+ case 45:
3997
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3998
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3999
+ var _a, _b, _c;
4000
+ 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) || '')
4001
+ .split('\n')
4002
+ .map(function (line) { return "> ".concat(line); })
4003
+ .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) || '')
4004
+ .split('\n')
4005
+ .map(function (line) { return "> ".concat(line); })
4006
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
4007
+ ? 'null'
4008
+ : $ongoingTemplateResult.$resultString
3769
4009
  .split('\n')
3770
4010
  .map(function (line) { return "> ".concat(line); })
3771
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3772
- ? 'null'
3773
- : resultString
3774
- .split('\n')
3775
- .map(function (line) { return "> ".concat(line); })
3776
- .join('\n')), "\n ---\n "); }));
3777
- }
3778
- return [2 /*return*/];
4011
+ .join('\n')), "\n ---\n ");
4012
+ }));
3779
4013
  }
3780
- });
3781
- };
3782
- attempt = -jokerParameterNames.length;
3783
- _h.label = 4;
3784
- case 4:
3785
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3786
- return [5 /*yield**/, _loop_5(attempt)];
3787
- case 5:
3788
- state_2 = _h.sent();
3789
- switch (state_2) {
3790
- case "break-attempts": return [3 /*break*/, 7];
3791
- }
3792
- _h.label = 6;
3793
- case 6:
3794
- attempt++;
3795
- return [3 /*break*/, 4];
3796
- case 7:
3797
- if (resultString === null) {
3798
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3799
- }
3800
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3801
- progress_2 = {
3802
- name: name,
3803
- title: title,
3804
- isStarted: true,
3805
- isDone: true,
3806
- templateType: currentTemplate.templateType,
3807
- parameterName: currentTemplate.resultingParameterName,
3808
- parameterValue: resultString,
3809
- // <- [3]
3810
- };
3811
- if (isReturned) {
3812
- 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)
3813
- .split('\n')
3814
- .map(function (line) { return "> ".concat(line); })
3815
- .join('\n')), "\n\n "); }));
4014
+ return [2 /*return*/];
3816
4015
  }
3817
- return [4 /*yield*/, onProgress(progress_2)];
3818
- case 8:
3819
- _h.sent();
3820
- _h.label = 9;
3821
- case 9:
3822
- 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)));
3823
- return [2 /*return*/];
4016
+ });
4017
+ };
4018
+ attempt = -jokerParameterNames.length;
4019
+ _a.label = 1;
4020
+ case 1:
4021
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
4022
+ return [5 /*yield**/, _loop_1(attempt)];
4023
+ case 2:
4024
+ state_1 = _a.sent();
4025
+ switch (state_1) {
4026
+ case "break-attempts": return [3 /*break*/, 4];
3824
4027
  }
3825
- });
3826
- });
3827
- }
3828
- function filterJustOutputParameters() {
3829
- var e_8, _a;
3830
- var outputParameters = {};
3831
- var _loop_6 = function (parameter) {
3832
- if (parametersToPass[parameter.name] === undefined) {
3833
- // [4]
3834
- 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 "); })));
3835
- return "continue";
3836
- }
3837
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3838
- };
3839
- try {
3840
- // Note: Filter ONLY output parameters
3841
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3842
- var isOutput = _a.isOutput;
3843
- return isOutput;
3844
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3845
- var parameter = _c.value;
3846
- _loop_6(parameter);
3847
- }
4028
+ _a.label = 3;
4029
+ case 3:
4030
+ attempt++;
4031
+ return [3 /*break*/, 1];
4032
+ case 4:
4033
+ if ($ongoingTemplateResult.$resultString === null) {
4034
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4035
+ }
4036
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3848
4037
  }
3849
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3850
- finally {
3851
- try {
3852
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3853
- }
3854
- finally { if (e_8) throw e_8.error; }
4038
+ });
4039
+ });
4040
+ }
4041
+ /**
4042
+ * TODO: Break into smaller functions
4043
+ */
4044
+
4045
+ /**
4046
+ * @@@
4047
+ *
4048
+ * @private internal utility of `createPipelineExecutor`
4049
+ */
4050
+ function executeFormatCells(options) {
4051
+ return __awaiter(this, void 0, void 0, function () {
4052
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
4053
+ var _this = this;
4054
+ return __generator(this, function (_a) {
4055
+ switch (_a.label) {
4056
+ case 0:
4057
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4058
+ if (template.foreach === undefined) {
4059
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
4060
+ }
4061
+ if (jokerParameterNames.length !== 0) {
4062
+ 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 "); }));
4063
+ }
4064
+ parameterValue = parameters[template.foreach.parameterName] || '';
4065
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
4066
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
4067
+ });
4068
+ if (formatDefinition === undefined) {
4069
+ throw new UnexpectedError(
4070
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4071
+ 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; })
4072
+ .map(function (formatName) { return "- ".concat(formatName); })
4073
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4074
+ }
4075
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
4076
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
4077
+ });
4078
+ if (subvalueDefinition === undefined) {
4079
+ throw new UnexpectedError(
4080
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4081
+ 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
4082
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
4083
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
4084
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4085
+ }
4086
+ if (formatDefinition.formatName === 'CSV') {
4087
+ formatSettings = settings.csvSettings;
4088
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
4089
+ }
4090
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4091
+ var mappedParameters, allSubparameters, subresultString;
4092
+ return __generator(this, function (_a) {
4093
+ switch (_a.label) {
4094
+ case 0:
4095
+ // TODO: !!!!!!! Limit to N concurrent executions
4096
+ // TODO: !!!!!!! Report progress
4097
+ try {
4098
+ mappedParameters = mapAvailableToExpectedParameters({
4099
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4100
+ availableParameters: subparameters,
4101
+ });
4102
+ }
4103
+ catch (error) {
4104
+ if (!(error instanceof PipelineExecutionError)) {
4105
+ throw error;
4106
+ }
4107
+ 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 "); }));
4108
+ }
4109
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4110
+ // 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
4111
+ Object.freeze(allSubparameters);
4112
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
4113
+ case 1:
4114
+ subresultString = _a.sent();
4115
+ return [2 /*return*/, subresultString];
4116
+ }
4117
+ });
4118
+ }); })];
4119
+ case 1:
4120
+ resultString = _a.sent();
4121
+ return [2 /*return*/, resultString];
4122
+ }
4123
+ });
4124
+ });
4125
+ }
4126
+ /**
4127
+ * TODO: !!!!!! Make pipelineIdentification more precise
4128
+ * TODO: !!!!!! How FOREACH execution looks in the report
4129
+ */
4130
+
4131
+ /**
4132
+ * @@@
4133
+ *
4134
+ * @private internal utility of `createPipelineExecutor`
4135
+ */
4136
+ function getContextForTemplate(template) {
4137
+ return __awaiter(this, void 0, void 0, function () {
4138
+ return __generator(this, function (_a) {
4139
+ TODO_USE(template);
4140
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
4141
+ });
4142
+ });
4143
+ }
4144
+
4145
+ /**
4146
+ * @@@
4147
+ *
4148
+ * @private internal utility of `createPipelineExecutor`
4149
+ */
4150
+ function getKnowledgeForTemplate(options) {
4151
+ return __awaiter(this, void 0, void 0, function () {
4152
+ var preparedPipeline, template;
4153
+ return __generator(this, function (_a) {
4154
+ preparedPipeline = options.preparedPipeline, template = options.template;
4155
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4156
+ TODO_USE(template);
4157
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4158
+ var content = _a.content;
4159
+ return "- ".concat(content);
4160
+ }).join('\n')];
4161
+ });
4162
+ });
4163
+ }
4164
+
4165
+ /**
4166
+ * @@@
4167
+ *
4168
+ * @private internal utility of `createPipelineExecutor`
4169
+ */
4170
+ function getSamplesForTemplate(template) {
4171
+ return __awaiter(this, void 0, void 0, function () {
4172
+ return __generator(this, function (_a) {
4173
+ // TODO: [♨] Implement Better - use real index and keyword search
4174
+ TODO_USE(template);
4175
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4176
+ });
4177
+ });
4178
+ }
4179
+
4180
+ /**
4181
+ * @@@
4182
+ *
4183
+ * @private internal utility of `createPipelineExecutor`
4184
+ */
4185
+ function getReservedParametersForTemplate(options) {
4186
+ return __awaiter(this, void 0, void 0, function () {
4187
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4188
+ var e_1, _a;
4189
+ return __generator(this, function (_b) {
4190
+ switch (_b.label) {
4191
+ case 0:
4192
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4193
+ return [4 /*yield*/, getContextForTemplate(template)];
4194
+ case 1:
4195
+ context = _b.sent();
4196
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4197
+ case 2:
4198
+ knowledge = _b.sent();
4199
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4200
+ case 3:
4201
+ samples = _b.sent();
4202
+ currentDate = new Date().toISOString();
4203
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4204
+ reservedParameters = {
4205
+ content: RESERVED_PARAMETER_RESTRICTED,
4206
+ context: context,
4207
+ knowledge: knowledge,
4208
+ samples: samples,
4209
+ currentDate: currentDate,
4210
+ modelName: modelName,
4211
+ };
4212
+ _loop_1 = function (parameterName) {
4213
+ if (reservedParameters[parameterName] === undefined) {
4214
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4215
+ }
4216
+ };
4217
+ try {
4218
+ // Note: Doublecheck that ALL reserved parameters are defined:
4219
+ 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()) {
4220
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4221
+ _loop_1(parameterName);
4222
+ }
4223
+ }
4224
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4225
+ finally {
4226
+ try {
4227
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4228
+ }
4229
+ finally { if (e_1) throw e_1.error; }
4230
+ }
4231
+ return [2 /*return*/, reservedParameters];
4232
+ }
4233
+ });
4234
+ });
4235
+ }
4236
+
4237
+ /**
4238
+ * @@@
4239
+ *
4240
+ * @private internal utility of `createPipelineExecutor`
4241
+ */
4242
+ function executeTemplate(options) {
4243
+ return __awaiter(this, void 0, void 0, function () {
4244
+ 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;
4245
+ var e_1, _f, _g;
4246
+ return __generator(this, function (_h) {
4247
+ switch (_h.label) {
4248
+ case 0:
4249
+ 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;
4250
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4251
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4252
+ title = currentTemplate.title;
4253
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4254
+ return [4 /*yield*/, onProgress({
4255
+ name: name,
4256
+ title: title,
4257
+ isStarted: false,
4258
+ isDone: false,
4259
+ templateType: currentTemplate.templateType,
4260
+ parameterName: currentTemplate.resultingParameterName,
4261
+ parameterValue: null,
4262
+ // <- [🍸]
4263
+ })];
4264
+ case 1:
4265
+ _h.sent();
4266
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4267
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4268
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4269
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4270
+ 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)
4271
+ .map(function (name) { return "{".concat(name, "}"); })
4272
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4273
+ .map(function (name) { return "{".concat(name, "}"); })
4274
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4275
+ }
4276
+ _b = (_a = Object).freeze;
4277
+ _c = [{}];
4278
+ return [4 /*yield*/, getReservedParametersForTemplate({
4279
+ preparedPipeline: preparedPipeline,
4280
+ template: currentTemplate,
4281
+ pipelineIdentification: pipelineIdentification,
4282
+ })];
4283
+ case 2:
4284
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4285
+ definedParameterNames = new Set(Object.keys(definedParameters));
4286
+ parameters = {};
4287
+ _loop_1 = function (parameterName) {
4288
+ // Situation: Parameter is defined and used
4289
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4290
+ parameters[parameterName] = definedParameters[parameterName];
4291
+ }
4292
+ // Situation: Parameter is defined but NOT used
4293
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4294
+ // Situation: Parameter is NOT defined BUT used
4295
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4296
+ // Houston, we have a problem
4297
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4298
+ 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 "); }));
4299
+ }
4300
+ };
4301
+ try {
4302
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4303
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4304
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4305
+ parameterName = _e.value;
4306
+ _loop_1(parameterName);
4307
+ }
4308
+ }
4309
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4310
+ finally {
4311
+ try {
4312
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4313
+ }
4314
+ finally { if (e_1) throw e_1.error; }
4315
+ }
4316
+ // 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
4317
+ Object.freeze(parameters);
4318
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4319
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4320
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4321
+ .split('{content}')
4322
+ .join(currentTemplate.content);
4323
+ return [4 /*yield*/, executeFormatCells({
4324
+ jokerParameterNames: jokerParameterNames,
4325
+ priority: priority,
4326
+ maxAttempts: maxAttempts,
4327
+ preparedContent: preparedContent,
4328
+ parameters: parameters,
4329
+ template: currentTemplate,
4330
+ preparedPipeline: preparedPipeline,
4331
+ tools: tools,
4332
+ llmTools: llmTools,
4333
+ settings: settings,
4334
+ $executionReport: $executionReport,
4335
+ pipelineIdentification: pipelineIdentification,
4336
+ })];
4337
+ case 3:
4338
+ resultString = _h.sent();
4339
+ return [4 /*yield*/, onProgress({
4340
+ name: name,
4341
+ title: title,
4342
+ isStarted: true,
4343
+ isDone: true,
4344
+ templateType: currentTemplate.templateType,
4345
+ parameterName: currentTemplate.resultingParameterName,
4346
+ parameterValue: resultString,
4347
+ // <- [🍸]
4348
+ })];
4349
+ case 4:
4350
+ _h.sent();
4351
+ return [2 /*return*/, Object.freeze((_g = {},
4352
+ _g[currentTemplate.resultingParameterName] =
4353
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4354
+ resultString,
4355
+ _g))];
3855
4356
  }
3856
- return outputParameters;
4357
+ });
4358
+ });
4359
+ }
4360
+ /**
4361
+ * TODO: [🤹‍♂️]
4362
+ */
4363
+
4364
+ /**
4365
+ * @@@
4366
+ *
4367
+ * @private internal utility of `createPipelineExecutor`
4368
+ */
4369
+ function filterJustOutputParameters(options) {
4370
+ var e_1, _a;
4371
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4372
+ var outputParameters = {};
4373
+ var _loop_1 = function (parameter) {
4374
+ if (parametersToPass[parameter.name] === undefined) {
4375
+ // [4]
4376
+ $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 "); })));
4377
+ return "continue";
4378
+ }
4379
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4380
+ };
4381
+ try {
4382
+ // Note: Filter ONLY output parameters
4383
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4384
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4385
+ var isOutput = _a.isOutput;
4386
+ return isOutput;
4387
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4388
+ var parameter = _c.value;
4389
+ _loop_1(parameter);
4390
+ }
4391
+ }
4392
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4393
+ finally {
4394
+ try {
4395
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3857
4396
  }
3858
- 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;
4397
+ finally { if (e_1) throw e_1.error; }
4398
+ }
4399
+ return outputParameters;
4400
+ }
4401
+
4402
+ /**
4403
+ * @@@
4404
+ *
4405
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4406
+ *
4407
+ * @private internal utility of `createPipelineExecutor`
4408
+ */
4409
+ function executePipeline(options) {
4410
+ return __awaiter(this, void 0, void 0, function () {
4411
+ 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;
3859
4412
  var e_1, _e, e_2, _f;
3860
4413
  return __generator(this, function (_g) {
3861
4414
  switch (_g.label) {
3862
4415
  case 0:
4416
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4417
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4418
+ preparedPipeline = options.preparedPipeline;
4419
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3863
4420
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3864
4421
  return [4 /*yield*/, preparePipeline(pipeline, {
3865
4422
  llmTools: llmTools,
@@ -3868,6 +4425,7 @@
3868
4425
  })];
3869
4426
  case 1:
3870
4427
  preparedPipeline = _g.sent();
4428
+ setPreparedPipeline(preparedPipeline);
3871
4429
  _g.label = 2;
3872
4430
  case 2:
3873
4431
  errors = [];
@@ -3937,7 +4495,7 @@
3937
4495
  return name === parameterName;
3938
4496
  });
3939
4497
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3940
- 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 "); })));
4498
+ 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 "); })));
3941
4499
  return [3 /*break*/, 4];
3942
4500
  case 1:
3943
4501
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3949,10 +4507,10 @@
3949
4507
  // Note: Wait a short time to prevent race conditions
3950
4508
  _h.sent();
3951
4509
  _h.label = 3;
3952
- 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 "); }), {
4510
+ 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 "); }), {
3953
4511
  isSuccessful: false,
3954
4512
  errors: __spreadArray([
3955
- 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 "); }))
4513
+ 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 "); }))
3956
4514
  ], __read(errors), false).map(serializeError),
3957
4515
  warnings: warnings.map(serializeError),
3958
4516
  executionReport: executionReport,
@@ -4016,7 +4574,7 @@
4016
4574
  case 0:
4017
4575
  if (loopLimit-- < 0) {
4018
4576
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
4019
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4577
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4020
4578
  }
4021
4579
  currentTemplate = unresovedTemplates_1.find(function (template) {
4022
4580
  return template.dependentParameterNames.every(function (name) {
@@ -4026,29 +4584,52 @@
4026
4584
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4027
4585
  throw new UnexpectedError(
4028
4586
  // TODO: [🐎] DRY
4029
- 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
4587
+ 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
4030
4588
  .map(function (_a) {
4031
4589
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4032
4590
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4033
4591
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4034
4592
  .join(' and '));
4035
4593
  })
4036
- .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 "); }));
4594
+ .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 "); }));
4037
4595
  case 1:
4038
4596
  if (!!currentTemplate) return [3 /*break*/, 3];
4039
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4597
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4040
4598
  case 2:
4041
- /* [5] */ _j.sent();
4599
+ /* [🤹‍♂️] */ _j.sent();
4042
4600
  return [3 /*break*/, 4];
4043
4601
  case 3:
4044
4602
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4045
- work_1 = executeSingleTemplate(currentTemplate)
4046
- .then(function () {
4603
+ work_1 = executeTemplate({
4604
+ currentTemplate: currentTemplate,
4605
+ preparedPipeline: preparedPipeline,
4606
+ parametersToPass: parametersToPass,
4607
+ tools: tools,
4608
+ llmTools: llmTools,
4609
+ onProgress: function (progress) {
4610
+ if (isReturned) {
4611
+ 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)
4612
+ .split('\n')
4613
+ .map(function (line) { return "> ".concat(line); })
4614
+ .join('\n')), "\n "); }));
4615
+ }
4616
+ if (onProgress) {
4617
+ onProgress(progress);
4618
+ }
4619
+ },
4620
+ settings: settings,
4621
+ $executionReport: executionReport,
4622
+ pipelineIdentification: pipelineIdentification,
4623
+ })
4624
+ .then(function (newParametersToPass) {
4625
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4047
4626
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4048
4627
  })
4049
4628
  .then(function () {
4050
4629
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4051
4630
  });
4631
+ // <- Note: Errors are catched here [3]
4632
+ // 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
4052
4633
  resolving_1.push(work_1);
4053
4634
  _j.label = 4;
4054
4635
  case 4: return [2 /*return*/];
@@ -4075,7 +4656,12 @@
4075
4656
  var result = _a.result;
4076
4657
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4077
4658
  })), false));
4078
- outputParameters_1 = filterJustOutputParameters();
4659
+ outputParameters_1 = filterJustOutputParameters({
4660
+ preparedPipeline: preparedPipeline,
4661
+ parametersToPass: parametersToPass,
4662
+ $warnings: warnings,
4663
+ pipelineIdentification: pipelineIdentification,
4664
+ });
4079
4665
  isReturned = true;
4080
4666
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4081
4667
  // Note: Wait a short time to prevent race conditions
@@ -4098,7 +4684,12 @@
4098
4684
  var result = _a.result;
4099
4685
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4100
4686
  })), false));
4101
- outputParameters = filterJustOutputParameters();
4687
+ outputParameters = filterJustOutputParameters({
4688
+ preparedPipeline: preparedPipeline,
4689
+ parametersToPass: parametersToPass,
4690
+ $warnings: warnings,
4691
+ pipelineIdentification: pipelineIdentification,
4692
+ });
4102
4693
  isReturned = true;
4103
4694
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4104
4695
  // Note: Wait a short time to prevent race conditions
@@ -4118,22 +4709,63 @@
4118
4709
  })];
4119
4710
  }
4120
4711
  });
4121
- }); };
4122
- return pipelineExecutor;
4712
+ });
4123
4713
  }
4714
+
4124
4715
  /**
4125
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4126
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4127
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4128
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4129
- * TODO: [♈] Probbably move expectations from templates to parameters
4130
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4131
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4132
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4133
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4134
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4135
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4716
+ * Creates executor function from pipeline and execution tools.
4717
+ *
4718
+ * @returns The executor function
4719
+ * @throws {PipelineLogicError} on logical error in the pipeline
4720
+ * @public exported from `@promptbook/core`
4136
4721
  */
4722
+ function createPipelineExecutor(options) {
4723
+ var _this = this;
4724
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4725
+ 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;
4726
+ validatePipeline(pipeline);
4727
+ var pipelineIdentification = (function () {
4728
+ // Note: This is a 😐 implementation of [🚞]
4729
+ var _ = [];
4730
+ if (pipeline.sourceFile !== undefined) {
4731
+ _.push("File: ".concat(pipeline.sourceFile));
4732
+ }
4733
+ if (pipeline.pipelineUrl !== undefined) {
4734
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4735
+ }
4736
+ return _.join('\n');
4737
+ })();
4738
+ var preparedPipeline;
4739
+ if (isPipelinePrepared(pipeline)) {
4740
+ preparedPipeline = pipeline;
4741
+ }
4742
+ else if (isNotPreparedWarningSupressed !== true) {
4743
+ 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 "); }));
4744
+ }
4745
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4746
+ return __generator(this, function (_a) {
4747
+ return [2 /*return*/, executePipeline({
4748
+ pipeline: pipeline,
4749
+ preparedPipeline: preparedPipeline,
4750
+ setPreparedPipeline: function (newPreparedPipeline) {
4751
+ preparedPipeline = newPreparedPipeline;
4752
+ },
4753
+ inputParameters: inputParameters,
4754
+ tools: tools,
4755
+ onProgress: onProgress,
4756
+ pipelineIdentification: pipelineIdentification,
4757
+ settings: {
4758
+ maxExecutionAttempts: maxExecutionAttempts,
4759
+ maxParallelCount: maxParallelCount,
4760
+ csvSettings: csvSettings,
4761
+ isVerbose: isVerbose,
4762
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4763
+ },
4764
+ })];
4765
+ });
4766
+ }); };
4767
+ return pipelineExecutor;
4768
+ }
4137
4769
 
4138
4770
  /**
4139
4771
  * @@@
@@ -4185,7 +4817,7 @@
4185
4817
  outputParameters = result.outputParameters;
4186
4818
  knowledgePiecesRaw = outputParameters.knowledgePieces;
4187
4819
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4188
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4820
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4189
4821
  if (isVerbose) {
4190
4822
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
4191
4823
  }
@@ -4243,8 +4875,13 @@
4243
4875
  case 6: return [3 /*break*/, 8];
4244
4876
  case 7:
4245
4877
  error_1 = _c.sent();
4878
+ // Note: Here is expected error:
4879
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4880
+ if (!(error_1 instanceof PipelineExecutionError)) {
4881
+ throw error_1;
4882
+ }
4246
4883
  // TODO: [🟥] Detect browser / node and make it colorfull
4247
- console.error(error_1);
4884
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4248
4885
  return [3 /*break*/, 8];
4249
4886
  case 8: return [2 /*return*/, {
4250
4887
  name: name,
@@ -4265,7 +4902,7 @@
4265
4902
  });
4266
4903
  }
4267
4904
  /**
4268
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4905
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4269
4906
  * TODO: [🪂] Do it in parallel 11:11
4270
4907
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4271
4908
  */
@@ -4289,7 +4926,7 @@
4289
4926
  var partialPieces, pieces;
4290
4927
  return __generator(this, function (_a) {
4291
4928
  switch (_a.label) {
4292
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4929
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4293
4930
  options)];
4294
4931
  case 1:
4295
4932
  partialPieces = _a.sent();
@@ -4481,7 +5118,7 @@
4481
5118
  });
4482
5119
  }
4483
5120
  /**
4484
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
5121
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4485
5122
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4486
5123
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4487
5124
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4530,7 +5167,7 @@
4530
5167
  case 0:
4531
5168
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4532
5169
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4533
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
5170
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4534
5171
  TODO_USE(parameters);
4535
5172
  templatesPrepared = new Array(
4536
5173
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4562,7 +5199,7 @@
4562
5199
  /**
4563
5200
  * TODO: [🧠] Add context to each template (if missing)
4564
5201
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4565
- * TODO: [♨] !!! Prepare index the samples and maybe templates
5202
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4566
5203
  * TODO: Write tests for `preparePipeline`
4567
5204
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4568
5205
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4734,7 +5371,7 @@
4734
5371
  if (sourceContent === '') {
4735
5372
  throw new ParseError("Source is not defined");
4736
5373
  }
4737
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5374
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4738
5375
  if (sourceContent.startsWith('http://')) {
4739
5376
  throw new ParseError("Source is not secure");
4740
5377
  }
@@ -4919,7 +5556,7 @@
4919
5556
  if (command.templateType === 'KNOWLEDGE') {
4920
5557
  knowledgeCommandParser.$applyToPipelineJson({
4921
5558
  type: 'KNOWLEDGE',
4922
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5559
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4923
5560
  }, $pipelineJson);
4924
5561
  $templateJson.isTemplate = false;
4925
5562
  return;
@@ -5269,6 +5906,171 @@
5269
5906
  * TODO: [🌺] Use some intermediate util splitWords
5270
5907
  */
5271
5908
 
5909
+ /**
5910
+ * @@@
5911
+ *
5912
+ * @param text @@@
5913
+ * @param _isFirstLetterCapital @@@
5914
+ * @returns @@@
5915
+ * @example 'helloWorld'
5916
+ * @example 'iLovePromptbook'
5917
+ * @public exported from `@promptbook/utils`
5918
+ */
5919
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5920
+ var e_1, _a;
5921
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5922
+ var charType;
5923
+ var lastCharType = null;
5924
+ var normalizedName = '';
5925
+ try {
5926
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5927
+ var char = text_1_1.value;
5928
+ var normalizedChar = void 0;
5929
+ if (/^[a-z]$/.test(char)) {
5930
+ charType = 'LOWERCASE';
5931
+ normalizedChar = char;
5932
+ }
5933
+ else if (/^[A-Z]$/.test(char)) {
5934
+ charType = 'UPPERCASE';
5935
+ normalizedChar = char.toLowerCase();
5936
+ }
5937
+ else if (/^[0-9]$/.test(char)) {
5938
+ charType = 'NUMBER';
5939
+ normalizedChar = char;
5940
+ }
5941
+ else {
5942
+ charType = 'OTHER';
5943
+ normalizedChar = '';
5944
+ }
5945
+ if (!lastCharType) {
5946
+ if (_isFirstLetterCapital) {
5947
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5948
+ }
5949
+ }
5950
+ else if (charType !== lastCharType &&
5951
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5952
+ !(lastCharType === 'NUMBER') &&
5953
+ !(charType === 'NUMBER')) {
5954
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5955
+ }
5956
+ normalizedName += normalizedChar;
5957
+ lastCharType = charType;
5958
+ }
5959
+ }
5960
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5961
+ finally {
5962
+ try {
5963
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5964
+ }
5965
+ finally { if (e_1) throw e_1.error; }
5966
+ }
5967
+ return normalizedName;
5968
+ }
5969
+ /**
5970
+ * TODO: [🌺] Use some intermediate util splitWords
5971
+ */
5972
+
5973
+ /**
5974
+ * Removes quotes from a string
5975
+ *
5976
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5977
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5978
+ * Note: There are two simmilar functions:
5979
+ * - `removeQuotes` which removes only bounding quotes
5980
+ * - `unwrapResult` which removes whole introduce sentence
5981
+ *
5982
+ * @param text optionally quoted text
5983
+ * @returns text without quotes
5984
+ * @public exported from `@promptbook/utils`
5985
+ */
5986
+ function removeQuotes(text) {
5987
+ if (text.startsWith('"') && text.endsWith('"')) {
5988
+ return text.slice(1, -1);
5989
+ }
5990
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5991
+ return text.slice(1, -1);
5992
+ }
5993
+ return text;
5994
+ }
5995
+
5996
+ /**
5997
+ * Function `validateParameterName` will @@@
5998
+ *
5999
+ * @param parameterName @@@
6000
+ * @returns @@@
6001
+ * @throws {ParseError} @@@
6002
+ * @private within the repository
6003
+ */
6004
+ function validateParameterName(parameterName) {
6005
+ var e_1, _a;
6006
+ var rawParameterName = parameterName;
6007
+ try {
6008
+ for (var _b = __values([
6009
+ ['`', '`'],
6010
+ ['{', '}'],
6011
+ ['[', ']'],
6012
+ ['(', ')'],
6013
+ ['<', '>'],
6014
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
6015
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
6016
+ if (parameterName.substring(0, 1) === start &&
6017
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
6018
+ // <- TODO: More universal that 1 character
6019
+ ) {
6020
+ parameterName = parameterName.substring(1, parameterName.length - 1);
6021
+ // <- TODO: More universal that 1 character
6022
+ }
6023
+ }
6024
+ }
6025
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
6026
+ finally {
6027
+ try {
6028
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
6029
+ }
6030
+ finally { if (e_1) throw e_1.error; }
6031
+ }
6032
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
6033
+ try {
6034
+ /*
6035
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
6036
+ if (parameterName.includes(' ')) {
6037
+ throw new ParseError(`Parameter name cannot contain spaces`);
6038
+ }
6039
+ */
6040
+ if (parameterName.includes('.')) {
6041
+ throw new ParseError("Parameter name cannot contain dots");
6042
+ }
6043
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
6044
+ throw new ParseError("Parameter name cannot contain slashes");
6045
+ }
6046
+ if (parameterName.includes('(') ||
6047
+ parameterName.includes(')') ||
6048
+ parameterName.includes('{') ||
6049
+ parameterName.includes('}') ||
6050
+ parameterName.includes('[') ||
6051
+ parameterName.includes(']')) {
6052
+ throw new ParseError("Parameter name cannot contain braces");
6053
+ }
6054
+ parameterName = removeDiacritics(parameterName);
6055
+ parameterName = removeEmojis(parameterName);
6056
+ parameterName = removeQuotes(parameterName);
6057
+ parameterName = normalizeTo_camelCase(parameterName);
6058
+ if (parameterName === '') {
6059
+ throw new ParseError("Parameter name cannot be empty");
6060
+ }
6061
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
6062
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
6063
+ }
6064
+ }
6065
+ catch (error) {
6066
+ if (!(error instanceof ParseError)) {
6067
+ throw error;
6068
+ }
6069
+ 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 "); }));
6070
+ }
6071
+ return parameterName;
6072
+ }
6073
+
5272
6074
  /**
5273
6075
  * Parses the foreach command
5274
6076
  *
@@ -5298,67 +6100,61 @@
5298
6100
  /**
5299
6101
  * Link to discussion
5300
6102
  */
5301
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
6103
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5302
6104
  /**
5303
6105
  * Example usages of the FOREACH command
5304
6106
  */
5305
6107
  examples: [
5306
- 'FOREACH List Line -> `{customer}`',
5307
- 'FOR List Line -> `{customer}`',
5308
- 'EACH List Line -> `{customer}`',
5309
- // <- TODO: [🍭] !!!!!! More
6108
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
6109
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
6110
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
5310
6111
  ],
5311
6112
  /**
5312
6113
  * Parses the FOREACH command
5313
6114
  */
5314
6115
  parse: function (input) {
5315
- var args = input.args, rawArgs = input.rawArgs;
6116
+ var args = input.args;
5316
6117
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5317
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5318
- var assignSign = args[2];
5319
- var parameter = args[3];
5320
- if (![
5321
- 'LIST',
5322
- 'CSV',
5323
- // <- TODO: [🏢] Unhardcode formats
5324
- ].includes(formatName)) {
5325
- console.info({ args: args, formatName: formatName });
5326
- throw new Error("Unsupported format \"".concat(formatName, "\""));
6118
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
6119
+ var parameterNameArg = args[2] || '';
6120
+ var assignSign = args[3];
6121
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
6122
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
6123
+ });
6124
+ if (formatDefinition === undefined) {
6125
+ 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; })
6126
+ .map(function (formatName) { return "- ".concat(formatName); })
6127
+ .join('\n')), "\n "); }));
5327
6128
  // <- TODO: [🏢] List all supported format names
5328
6129
  }
5329
- if (![
5330
- 'LINE',
5331
- 'ROW',
5332
- 'COLUMN',
5333
- 'CELL',
5334
- // <- TODO: [🏢] Unhardcode format cekks
5335
- ].includes(cellName)) {
5336
- console.info({ args: args, cellName: cellName });
5337
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5338
- // <- TODO: [🏢] List all supported cell names for the format
6130
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
6131
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
6132
+ });
6133
+ if (subvalueDefinition === undefined) {
6134
+ 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
6135
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6136
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6137
+ .join('\n')), "\n "); }));
6138
+ // <- TODO: [🏢] List all supported subformat names for the format
5339
6139
  }
5340
6140
  if (assignSign !== '->') {
5341
- console.info({ args: args, assignSign: assignSign });
5342
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5343
- }
5344
- var parameterNames = extractParameterNames(parameter || rawArgs);
5345
- if (parameterNames.size !== 1) {
5346
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5347
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5348
- }
5349
- var parameterName = parameterNames.values().next().value;
5350
- if (typeof parameterName !== 'string'
5351
- // <- TODO: !!!!!! Replace with propper parameter name validation
5352
- ) {
5353
- console.info({ args: args, parameterName: parameterName });
5354
- throw new Error("Invalid parameter name");
5355
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
6141
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6142
+ }
6143
+ var parameterName = validateParameterName(parameterNameArg);
6144
+ var subparameterNames = args
6145
+ .slice(4)
6146
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6147
+ .filter(function (parameterName) { return parameterName !== ''; })
6148
+ .map(validateParameterName);
6149
+ if (subparameterNames.length === 0) {
6150
+ throw new ParseError("FOREACH command must have at least one subparameter");
5356
6151
  }
5357
6152
  return {
5358
6153
  type: 'FOREACH',
5359
6154
  formatName: formatName,
5360
- cellName: cellName,
6155
+ subformatName: subformatName,
5361
6156
  parameterName: parameterName,
6157
+ subparameterNames: subparameterNames,
5362
6158
  };
5363
6159
  },
5364
6160
  /**
@@ -5367,8 +6163,12 @@
5367
6163
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5368
6164
  */
5369
6165
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5370
- keepUnused(command, $templateJson, $pipelineJson);
5371
- // <- TODO: [🍭] !!!!!! Implement
6166
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6167
+ // TODO: [🍭] Detect double use
6168
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6169
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
6170
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
6171
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5372
6172
  },
5373
6173
  /**
5374
6174
  * Converts the FOREACH command back to string
@@ -5377,8 +6177,7 @@
5377
6177
  */
5378
6178
  stringify: function (command) {
5379
6179
  keepUnused(command);
5380
- return "";
5381
- // <- TODO: [🍭] !!!!!! Implement
6180
+ return "---"; // <- TODO: [🛋] Implement
5382
6181
  },
5383
6182
  /**
5384
6183
  * Reads the FOREACH command from the `TemplateJson`
@@ -5387,13 +6186,11 @@
5387
6186
  */
5388
6187
  takeFromTemplateJson: function ($templateJson) {
5389
6188
  keepUnused($templateJson);
5390
- return [];
5391
- // <- TODO: [🍭] !!!!!! Implement
6189
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5392
6190
  },
5393
6191
  };
5394
6192
  /**
5395
- * TODO: !!!!!! Comment console logs
5396
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6193
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5397
6194
  */
5398
6195
 
5399
6196
  /**
@@ -5503,11 +6300,11 @@
5503
6300
  */
5504
6301
  parse: function (input) {
5505
6302
  var args = input.args;
5506
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5507
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5508
- throw new ParseError("Invalid joker");
6303
+ if (args.length !== 1) {
6304
+ throw new ParseError("JOKE command expects exactly one parameter name");
5509
6305
  }
5510
- var parameterName = parametersMatch.groups.parameterName;
6306
+ var parameterNameArg = args[0] || '';
6307
+ var parameterName = validateParameterName(parameterNameArg);
5511
6308
  return {
5512
6309
  type: 'JOKER',
5513
6310
  parameterName: parameterName,
@@ -5582,6 +6379,9 @@
5582
6379
  */
5583
6380
  parse: function (input) {
5584
6381
  var args = input.args, normalized = input.normalized;
6382
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6383
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6384
+ }).join('\n')), "\n "); });
5585
6385
  // TODO: Make this more elegant and dynamically
5586
6386
  if (normalized.startsWith('MODEL_VARIANT')) {
5587
6387
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5597,17 +6397,13 @@
5597
6397
  key: 'modelVariant',
5598
6398
  value: 'COMPLETION',
5599
6399
  };
6400
+ // <- Note: [🤖]
5600
6401
  }
5601
6402
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5602
- return {
5603
- type: 'MODEL',
5604
- key: 'modelVariant',
5605
- value: 'EMBEDDING',
5606
- };
5607
- // <- Note: [🤖]
6403
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5608
6404
  }
5609
6405
  else {
5610
- 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 "); }));
6406
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5611
6407
  }
5612
6408
  }
5613
6409
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5632,6 +6428,7 @@
5632
6428
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5633
6429
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5634
6430
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6431
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5635
6432
  }
5636
6433
  else {
5637
6434
  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 ")));
@@ -5731,14 +6528,13 @@
5731
6528
  * Parses the PARAMETER command
5732
6529
  */
5733
6530
  parse: function (input) {
5734
- var normalized = input.normalized, raw = input.raw;
5735
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5736
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5737
- throw new ParseError("Invalid parameter");
5738
- }
5739
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5740
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5741
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6531
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6532
+ var parameterNameRaw = args.shift() || '';
6533
+ var parameterDescriptionRaw = args.join(' ');
6534
+ // <- TODO: When [🥶] fixed, change to:
6535
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6536
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6537
+ 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 "); }));
5742
6538
  }
5743
6539
  var isInput = normalized.startsWith('INPUT');
5744
6540
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5746,11 +6542,12 @@
5746
6542
  isInput = false;
5747
6543
  isOutput = false;
5748
6544
  }
5749
- // TODO: !!!!!! Add parameter name validation
6545
+ var parameterName = validateParameterName(parameterNameRaw);
6546
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5750
6547
  return {
5751
6548
  type: 'PARAMETER',
5752
6549
  parameterName: parameterName,
5753
- parameterDescription: parameterDescription.trim() || null,
6550
+ parameterDescription: parameterDescription,
5754
6551
  isInput: isInput,
5755
6552
  isOutput: isOutput,
5756
6553
  };
@@ -6075,6 +6872,7 @@
6075
6872
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
6076
6873
  */
6077
6874
  $applyToPipelineJson: function (command, $pipelineJson) {
6875
+ // TODO: Warn if the version is overridden
6078
6876
  $pipelineJson.promptbookVersion = command.promptbookVersion;
6079
6877
  },
6080
6878
  /**
@@ -6557,7 +7355,9 @@
6557
7355
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6558
7356
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6559
7357
  var args = items.slice(commandNameSegmentsCount + 1);
6560
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7358
+ var rawArgs = raw
7359
+ .substring(commandNameRaw.length)
7360
+ .trim();
6561
7361
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6562
7362
  if (command !== null) {
6563
7363
  return command;
@@ -6568,7 +7368,9 @@
6568
7368
  {
6569
7369
  var commandNameRaw = items.slice(-1).join('_');
6570
7370
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6571
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7371
+ var rawArgs = raw
7372
+ .substring(0, raw.length - commandNameRaw.length)
7373
+ .trim();
6572
7374
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6573
7375
  if (command !== null) {
6574
7376
  return command;
@@ -6708,7 +7510,7 @@
6708
7510
  function extractOneBlockFromMarkdown(markdown) {
6709
7511
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6710
7512
  if (codeBlocks.length !== 1) {
6711
- 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 "); }));
7513
+ 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 "); }));
6712
7514
  }
6713
7515
  return codeBlocks[0];
6714
7516
  }
@@ -6895,7 +7697,7 @@
6895
7697
  var $pipelineJson = {
6896
7698
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6897
7699
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6898
- promptbookVersion: PROMPTBOOK_VERSION,
7700
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6899
7701
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6900
7702
  parameters: [],
6901
7703
  templates: [],
@@ -7186,7 +7988,7 @@
7186
7988
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7187
7989
  }
7188
7990
  /**
7189
- * TODO: !!!! Warn if used only sync version
7991
+ * TODO:[main] !!!! Warn if used only sync version
7190
7992
  * TODO: [🚞] Report here line/column of error
7191
7993
  * TODO: Use spaceTrim more effectively
7192
7994
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7267,70 +8069,6 @@
7267
8069
  * TODO: [🏛] This can be part of markdown builder
7268
8070
  */
7269
8071
 
7270
- /**
7271
- * @@@
7272
- *
7273
- * @param text @@@
7274
- * @param _isFirstLetterCapital @@@
7275
- * @returns @@@
7276
- * @example 'helloWorld'
7277
- * @example 'iLovePromptbook'
7278
- * @public exported from `@promptbook/utils`
7279
- */
7280
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
7281
- var e_1, _a;
7282
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
7283
- var charType;
7284
- var lastCharType = null;
7285
- var normalizedName = '';
7286
- try {
7287
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
7288
- var char = text_1_1.value;
7289
- var normalizedChar = void 0;
7290
- if (/^[a-z]$/.test(char)) {
7291
- charType = 'LOWERCASE';
7292
- normalizedChar = char;
7293
- }
7294
- else if (/^[A-Z]$/.test(char)) {
7295
- charType = 'UPPERCASE';
7296
- normalizedChar = char.toLowerCase();
7297
- }
7298
- else if (/^[0-9]$/.test(char)) {
7299
- charType = 'NUMBER';
7300
- normalizedChar = char;
7301
- }
7302
- else {
7303
- charType = 'OTHER';
7304
- normalizedChar = '';
7305
- }
7306
- if (!lastCharType) {
7307
- if (_isFirstLetterCapital) {
7308
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
7309
- }
7310
- }
7311
- else if (charType !== lastCharType &&
7312
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
7313
- !(lastCharType === 'NUMBER') &&
7314
- !(charType === 'NUMBER')) {
7315
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
7316
- }
7317
- normalizedName += normalizedChar;
7318
- lastCharType = charType;
7319
- }
7320
- }
7321
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
7322
- finally {
7323
- try {
7324
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
7325
- }
7326
- finally { if (e_1) throw e_1.error; }
7327
- }
7328
- return normalizedName;
7329
- }
7330
- /**
7331
- * TODO: [🌺] Use some intermediate util splitWords
7332
- */
7333
-
7334
8072
  /**
7335
8073
  * Creates a Mermaid graph based on the promptbook
7336
8074
  *
@@ -7387,6 +8125,9 @@
7387
8125
  return promptbookMermaid;
7388
8126
  }
7389
8127
  /**
8128
+ * TODO: !!!!! FOREACH in mermaid graph
8129
+ * TODO: !!!!! Knowledge in mermaid graph
8130
+ * TODO: !!!!! Personas in mermaid graph
7390
8131
  * TODO: Maybe use some Mermaid package instead of string templating
7391
8132
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
7392
8133
  */
@@ -7461,7 +8202,7 @@
7461
8202
  }
7462
8203
  }
7463
8204
  /**
7464
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8205
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7465
8206
  * TODO: [🧠][💺] Can be done this on type-level?
7466
8207
  */
7467
8208
 
@@ -7528,21 +8269,41 @@
7528
8269
  * @public exported from `@promptbook/core`
7529
8270
  */
7530
8271
  function usageToHuman(usage) {
7531
- var report = 'Usage:';
8272
+ var reportItems = [];
7532
8273
  var uncertainNumberToHuman = function (_a) {
7533
8274
  var value = _a.value, isUncertain = _a.isUncertain;
7534
8275
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7535
8276
  };
7536
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7537
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7538
- return spaceTrim__default["default"](report);
8277
+ if (usage.price.value > 0.01
8278
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8279
+ ) {
8280
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8281
+ }
8282
+ else {
8283
+ reportItems.push("Negligible cost");
8284
+ }
8285
+ var worktime = usageToWorktime(usage);
8286
+ if (worktime.value >
8287
+ 1 / 60
8288
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8289
+ ) {
8290
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8291
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8292
+ }
8293
+ if (usage.output.charactersCount.value > 0) {
8294
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8295
+ }
8296
+ if (reportItems.length === 0) {
8297
+ // Note: For negligible usage, we report at least something
8298
+ reportItems.push('Negligible');
8299
+ }
8300
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7539
8301
  }
7540
8302
  /**
7541
- * TODO: Use "$1" not "1 USD"
7542
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7543
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8303
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8304
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8305
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7544
8306
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7545
- * TODO: When negligible usage, report "Negligible" or just don't report it
7546
8307
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7547
8308
  * TODO: [🏛] Maybe make some markdown builder
7548
8309
  */
@@ -8191,8 +8952,8 @@
8191
8952
  */
8192
8953
  function createMarkdownTable(table) {
8193
8954
  var columnWidths = table.reduce(function (widths, row) {
8194
- row.forEach(function (cell, columnIndex) {
8195
- var cellLength = cell.length;
8955
+ row.forEach(function (subformat, columnIndex) {
8956
+ var cellLength = subformat.length;
8196
8957
  if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
8197
8958
  widths[columnIndex] = cellLength;
8198
8959
  }
@@ -8200,12 +8961,12 @@
8200
8961
  return widths;
8201
8962
  }, []);
8202
8963
  var header = "| ".concat(table[0]
8203
- .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
8964
+ .map(function (subformat, columnIndex) { return subformat.padEnd(columnWidths[columnIndex]); })
8204
8965
  .join(' | '), " |");
8205
8966
  var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
8206
8967
  var rows = table.slice(1).map(function (row) {
8207
- var paddedRow = row.map(function (cell, columnIndex) {
8208
- return cell.padEnd(columnWidths[columnIndex]);
8968
+ var paddedRow = row.map(function (subformat, columnIndex) {
8969
+ return subformat.padEnd(columnWidths[columnIndex]);
8209
8970
  });
8210
8971
  return "| ".concat(paddedRow.join(' | '), " |");
8211
8972
  });
@@ -8486,6 +9247,8 @@
8486
9247
  exports.CLAIM = CLAIM;
8487
9248
  exports.CallbackInterfaceTools = CallbackInterfaceTools;
8488
9249
  exports.CollectionError = CollectionError;
9250
+ exports.CsvFormatDefinition = CsvFormatDefinition;
9251
+ exports.DEFAULT_CSV_SETTINGS = DEFAULT_CSV_SETTINGS;
8489
9252
  exports.DEFAULT_REMOTE_URL = DEFAULT_REMOTE_URL;
8490
9253
  exports.DEFAULT_REMOTE_URL_PATH = DEFAULT_REMOTE_URL_PATH;
8491
9254
  exports.ERRORS = ERRORS;
@@ -8496,6 +9259,7 @@
8496
9259
  exports.ExpectError = ExpectError;
8497
9260
  exports.IS_VERBOSE = IS_VERBOSE;
8498
9261
  exports.LimitReachedError = LimitReachedError;
9262
+ exports.MANDATORY_CSV_SETTINGS = MANDATORY_CSV_SETTINGS;
8499
9263
  exports.MAX_EXECUTION_ATTEMPTS = MAX_EXECUTION_ATTEMPTS;
8500
9264
  exports.MAX_FILENAME_LENGTH = MAX_FILENAME_LENGTH;
8501
9265
  exports.MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH = MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH;
@@ -8514,6 +9278,7 @@
8514
9278
  exports.PrefixStorage = PrefixStorage;
8515
9279
  exports.RESERVED_PARAMETER_NAMES = RESERVED_PARAMETER_NAMES;
8516
9280
  exports.TemplateTypes = TemplateTypes;
9281
+ exports.TextFormatDefinition = TextFormatDefinition;
8517
9282
  exports.UnexpectedError = UnexpectedError;
8518
9283
  exports.ZERO_USAGE = ZERO_USAGE;
8519
9284
  exports._AnthropicClaudeMetadataRegistration = _AnthropicClaudeMetadataRegistration;