@promptbook/core 0.69.0-1 → 0.69.0-11

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 (55) hide show
  1. package/README.md +17 -58
  2. package/esm/index.es.js +1917 -1169
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/core.index.d.ts +5 -1
  5. package/esm/typings/src/_packages/types.index.d.ts +8 -0
  6. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  7. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +2 -6
  8. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +26 -0
  9. package/esm/typings/src/commands/FOREACH/foreachCommand.test.d.ts +3 -0
  10. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +2 -1
  11. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  12. package/esm/typings/src/config.d.ts +7 -1
  13. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  14. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  15. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +5 -0
  16. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +5 -3
  17. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +21 -0
  18. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  19. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +33 -0
  20. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +21 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  31. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  32. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +9 -12
  33. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  34. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +3 -2
  35. package/esm/typings/src/formats/index.d.ts +1 -1
  36. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +1 -1
  37. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +17 -0
  38. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +1 -1
  39. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  40. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  41. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  42. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  43. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  44. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  45. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  46. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  47. package/package.json +2 -1
  48. package/umd/index.umd.js +1921 -1172
  49. package/umd/index.umd.js.map +1 -1
  50. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  51. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  52. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  53. /package/esm/typings/src/{collection/constructors/createCollectionFromDirectory.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  54. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  55. /package/esm/typings/src/{execution/utils/usageToHuman.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,7 +16,7 @@
16
16
  /**
17
17
  * The version of the Promptbook library
18
18
  */
19
- var PROMPTBOOK_VERSION = '0.69.0-0';
19
+ var PROMPTBOOK_VERSION = '0.69.0-10';
20
20
  // TODO: !!!! List here all the versions and annotate + put into script
21
21
 
22
22
  /*! *****************************************************************************
@@ -658,13 +658,13 @@
658
658
  *
659
659
  * @public exported from `@promptbook/core`
660
660
  */
661
- var MAX_PARALLEL_COUNT = 5;
661
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
662
662
  /**
663
663
  * The maximum number of attempts to execute LLM task before giving up
664
664
  *
665
665
  * @public exported from `@promptbook/core`
666
666
  */
667
- var MAX_EXECUTION_ATTEMPTS = 3;
667
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
668
668
  /**
669
669
  * The maximum length of the (generated) filename
670
670
  *
@@ -715,6 +715,7 @@
715
715
  'samples',
716
716
  'modelName',
717
717
  'currentDate',
718
+ // <- TODO: !!!!! list here all command names
718
719
  // <- TODO: Add more like 'date', 'modelName',...
719
720
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
720
721
  ]);
@@ -758,6 +759,15 @@
758
759
  * @public exported from `@promptbook/core`
759
760
  */
760
761
  var IS_VERBOSE = false;
762
+ /**
763
+ * @@@
764
+ *
765
+ * @private within the repository
766
+ */
767
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
768
+ /**/
769
+ // Note: In normal situations, we check the pipeline logic:
770
+ true);
761
771
  /**
762
772
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
763
773
  */
@@ -967,6 +977,26 @@
967
977
  * @public exported from `@promptbook/core`
968
978
  */
969
979
  function validatePipeline(pipeline) {
980
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
981
+ validatePipelineCore(pipeline);
982
+ }
983
+ else {
984
+ try {
985
+ validatePipelineCore(pipeline);
986
+ }
987
+ catch (error) {
988
+ if (!(error instanceof PipelineLogicError)) {
989
+ throw error;
990
+ }
991
+ 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 "); }));
992
+ }
993
+ }
994
+ return pipeline;
995
+ }
996
+ /**
997
+ * @private internal function for `validatePipeline`
998
+ */
999
+ function validatePipelineCore(pipeline) {
970
1000
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
971
1001
  var e_1, _a, e_2, _b, e_3, _c;
972
1002
  var pipelineIdentification = (function () {
@@ -991,12 +1021,12 @@
991
1021
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
992
1022
  if (!Array.isArray(pipeline.parameters)) {
993
1023
  // 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 "); }));
1024
+ 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
1025
  }
996
1026
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
997
1027
  if (!Array.isArray(pipeline.templates)) {
998
1028
  // 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 "); }));
1029
+ 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
1030
  }
1001
1031
  var _loop_1 = function (parameter) {
1002
1032
  if (parameter.isInput && parameter.isOutput) {
@@ -1165,9 +1195,9 @@
1165
1195
  while (unresovedTemplates.length > 0) {
1166
1196
  _loop_3();
1167
1197
  }
1168
- return pipeline;
1169
1198
  }
1170
1199
  /**
1200
+ * TODO: !!!!!! [🧞‍♀️] Do not allow joker + foreach
1171
1201
  * TODO: [🧠] Work with promptbookVersion
1172
1202
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1173
1203
  * > /**
@@ -1794,7 +1824,7 @@
1794
1824
  });
1795
1825
  }
1796
1826
 
1797
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.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.69.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.69.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.69.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"}];
1827
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-10",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.69.0-10",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.69.0-10",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.69.0-10",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
1828
 
1799
1829
  var defaultDiacriticsRemovalMap = [
1800
1830
  {
@@ -2323,113 +2353,35 @@
2323
2353
  */
2324
2354
 
2325
2355
  /**
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
2356
+ * Determine if the pipeline is fully prepared
2376
2357
  *
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`
2358
+ * @public exported from `@promptbook/core`
2381
2359
  */
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
- }
2360
+ function isPipelinePrepared(pipeline) {
2361
+ // Note: Ignoring `pipeline.preparations` @@@
2362
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2363
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2364
+ return false;
2419
2365
  }
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; }
2366
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2367
+ return false;
2426
2368
  }
2427
- parameterNames.delete('content');
2428
- // <- Note {websiteContent} is used in `preparedContent`
2429
- return parameterNames;
2369
+ /*
2370
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2371
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2372
+ > return false;
2373
+ > }
2374
+ */
2375
+ return true;
2430
2376
  }
2431
2377
  /**
2432
- * TODO: [🔣] If script require contentLanguage
2378
+ * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2379
+ * TODO: [🐠] Maybe base this on `makeValidator`
2380
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2381
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2382
+ * - [🏍] ? Is context in each template
2383
+ * - [♨] Are samples prepared
2384
+ * - [♨] Are templates prepared
2433
2385
  */
2434
2386
 
2435
2387
  /**
@@ -2449,27 +2401,6 @@
2449
2401
  };
2450
2402
  }
2451
2403
 
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
2404
  /**
2474
2405
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2475
2406
  *
@@ -2764,288 +2695,153 @@
2764
2695
  */
2765
2696
 
2766
2697
  /**
2767
- * Extracts all code blocks from markdown.
2698
+ * Takes an item or an array of items and returns an array of items
2768
2699
  *
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
2700
+ * 1) Any item except array and undefined returns array with that one item (also null)
2701
+ * 2) Undefined returns empty array
2702
+ * 3) Array returns itself
2774
2703
  *
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`
2704
+ * @private internal utility
2779
2705
  */
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;
2706
+ function arrayableToArray(input) {
2707
+ if (input === undefined) {
2708
+ return [];
2709
+ }
2710
+ if (input instanceof Array) {
2711
+ return input;
2712
+ }
2713
+ return [input];
2714
+ }
2715
+
2716
+ /**
2717
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2718
+ *
2719
+ * @param script from which to extract the variables
2720
+ * @returns the list of variable names
2721
+ * @throws {ParseError} if the script is invalid
2722
+ * @public exported from `@promptbook/utils`
2723
+ */
2724
+ function extractVariables(script) {
2725
+ var variables = new Set();
2726
+ script = "(()=>{".concat(script, "})()");
2787
2727
  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;
2728
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2729
+ try {
2730
+ eval(script);
2804
2731
  }
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: '' };
2732
+ catch (error) {
2733
+ if (!(error instanceof ReferenceError)) {
2734
+ throw error;
2810
2735
  }
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;
2736
+ var undefinedName = error.message.split(' ')[0];
2737
+ /*
2738
+ Note: Parsing the error
2739
+ [PipelineUrlError: thing is not defined]
2740
+ */
2741
+ if (!undefinedName) {
2742
+ throw error;
2817
2743
  }
2818
- }
2819
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2820
- if (currentCodeBlock.content !== '') {
2821
- currentCodeBlock.content += '\n';
2744
+ if (script.includes(undefinedName + '(')) {
2745
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2746
+ }
2747
+ else {
2748
+ variables.add(undefinedName);
2749
+ script = "const ".concat(undefinedName, " = '';") + script;
2822
2750
  }
2823
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2824
2751
  }
2752
+ }
2753
+ catch (error) {
2754
+ if (!(error instanceof Error)) {
2755
+ throw error;
2825
2756
  }
2757
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2826
2758
  }
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; }
2833
- }
2834
- if (currentCodeBlock !== null) {
2835
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2836
- }
2837
- return codeBlocks;
2838
- }
2839
- /**
2840
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2841
- */
2842
-
2843
- /**
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
2856
- *
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
2922
- */
2923
- function arrayableToArray(input) {
2924
- if (input === undefined) {
2925
- return [];
2926
- }
2927
- if (input instanceof Array) {
2928
- return input;
2929
- }
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];
2951
- }
2759
+ return variables;
2952
2760
  }
2953
-
2954
2761
  /**
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
2762
+ * TODO: [🔣] Support for multiple languages - python, java,...
2963
2763
  */
2964
- function TODO_USE() {
2965
- var value = [];
2966
- for (var _i = 0; _i < arguments.length; _i++) {
2967
- value[_i] = arguments[_i];
2968
- }
2969
- }
2970
2764
 
2971
2765
  /**
2972
- * Replaces parameters in template with values from parameters object
2766
+ * Parses the template and returns the set of all used parameters
2973
2767
  *
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
2768
+ * @param template the template with used parameters
2769
+ * @returns the set of parameter names
2770
+ * @throws {ParseError} if the script is invalid
2978
2771
  * @public exported from `@promptbook/utils`
2979
2772
  */
2980
- function replaceParameters(template, parameters) {
2981
- var e_1, _a;
2773
+ function extractParameterNamesFromTemplate(template) {
2774
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2775
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2776
+ var parameterNames = new Set();
2982
2777
  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
- }
2778
+ 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()) {
2779
+ var parameterName = _f.value;
2780
+ parameterNames.add(parameterName);
2992
2781
  }
2993
2782
  }
2994
2783
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2995
2784
  finally {
2996
2785
  try {
2997
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2786
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2998
2787
  }
2999
2788
  finally { if (e_1) throw e_1.error; }
3000
2789
  }
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`');
2790
+ if (templateType === 'SCRIPT_TEMPLATE') {
2791
+ try {
2792
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2793
+ var parameterName = _h.value;
2794
+ parameterNames.add(parameterName);
2795
+ }
3007
2796
  }
3008
- var precol = match.groups.precol;
3009
- var parameterName = match.groups.parameterName;
3010
- if (parameterName === '') {
3011
- return "continue";
2797
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2798
+ finally {
2799
+ try {
2800
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2801
+ }
2802
+ finally { if (e_2) throw e_2.error; }
3012
2803
  }
3013
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3014
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2804
+ }
2805
+ try {
2806
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2807
+ var jokerName = _k.value;
2808
+ parameterNames.add(jokerName);
3015
2809
  }
3016
- if (parameters[parameterName] === undefined) {
3017
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2810
+ }
2811
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2812
+ finally {
2813
+ try {
2814
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
3018
2815
  }
3019
- var parameterValue = parameters[parameterName];
3020
- if (parameterValue === undefined) {
3021
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2816
+ finally { if (e_3) throw e_3.error; }
2817
+ }
2818
+ parameterNames.delete('content');
2819
+ // <- Note {websiteContent} is used in `preparedContent`
2820
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2821
+ if (foreach !== undefined) {
2822
+ try {
2823
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2824
+ var subparameterName = _m.value;
2825
+ if (parameterNames.has(subparameterName)) {
2826
+ parameterNames.delete(subparameterName);
2827
+ parameterNames.add(foreach.parameterName);
2828
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2829
+ }
2830
+ }
3022
2831
  }
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');
2832
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2833
+ finally {
2834
+ try {
2835
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2836
+ }
2837
+ finally { if (e_4) throw e_4.error; }
3029
2838
  }
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
2839
  }
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
- }
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;
2840
+ return parameterNames;
3048
2841
  }
2842
+ /**
2843
+ * TODO: [🔣] If script require contentLanguage
2844
+ */
3049
2845
 
3050
2846
  /**
3051
2847
  * Create difference set of two sets.
@@ -3123,117 +2919,364 @@
3123
2919
  }
3124
2920
 
3125
2921
  /**
3126
- * Counts number of characters in the text
2922
+ * Just marks a place of place where should be something implemented
2923
+ * No side effects.
3127
2924
  *
3128
- * @public exported from `@promptbook/utils`
3129
- */
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;
3138
- }
3139
-
3140
- /**
3141
- * Counts number of lines in the text
2925
+ * Note: It can be usefull suppressing eslint errors of unused variables
3142
2926
  *
3143
- * @public exported from `@promptbook/utils`
2927
+ * @param value any values
2928
+ * @returns void
2929
+ * @private within the repository
3144
2930
  */
3145
- function countLines(text) {
3146
- if (text === '') {
3147
- return 0;
2931
+ function TODO_USE() {
2932
+ var value = [];
2933
+ for (var _i = 0; _i < arguments.length; _i++) {
2934
+ value[_i] = arguments[_i];
3148
2935
  }
3149
- return text.split('\n').length;
3150
2936
  }
3151
2937
 
3152
2938
  /**
3153
- * Counts number of pages in the text
2939
+ * Definition for CSV spreadsheet
3154
2940
  *
3155
- * @public exported from `@promptbook/utils`
2941
+ * @public exported from `@promptbook/core`
2942
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2943
+ */
2944
+ var CsvFormatDefinition = {
2945
+ formatName: 'CSV',
2946
+ aliases: ['SPREADSHEET', 'TABLE'],
2947
+ isValid: function (value, schema) {
2948
+ TODO_USE(value /* <- TODO: Use value here */);
2949
+ TODO_USE(schema /* <- TODO: Use schema here */);
2950
+ return true;
2951
+ },
2952
+ canBeValid: function (partialValue, schema) {
2953
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2954
+ TODO_USE(schema /* <- TODO: Use schema here */);
2955
+ return true;
2956
+ },
2957
+ heal: function (value, schema) {
2958
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2959
+ TODO_USE(schema /* <- TODO: Use schema here */);
2960
+ throw new Error('Not implemented');
2961
+ },
2962
+ subvalueDefinitions: [
2963
+ {
2964
+ subvalueName: 'ROW',
2965
+ mapValues: function (value, mapCallback) {
2966
+ return __awaiter(this, void 0, void 0, function () {
2967
+ var csv, mappedData;
2968
+ var _this = this;
2969
+ return __generator(this, function (_a) {
2970
+ switch (_a.label) {
2971
+ case 0:
2972
+ csv = papaparse.parse(value, {
2973
+ header: true,
2974
+ delimiter: ',',
2975
+ quoteChar: '"',
2976
+ newline: '\r\n',
2977
+ skipEmptyLines: true,
2978
+ // encoding: 'utf8',
2979
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2980
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2981
+ });
2982
+ if (csv.errors.length !== 0) {
2983
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2984
+ 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 "); }));
2985
+ }
2986
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2987
+ var _a;
2988
+ var _b;
2989
+ return __generator(this, function (_c) {
2990
+ switch (_c.label) {
2991
+ case 0:
2992
+ _a = [__assign({}, row)];
2993
+ _b = {};
2994
+ // <- TODO: !!!!!! Dynamic new column name and position
2995
+ return [4 /*yield*/, mapCallback(row, index)];
2996
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2997
+ // <- TODO: !!!!!! Dynamic new column name and position
2998
+ _c.sent(), _b)])))];
2999
+ }
3000
+ });
3001
+ }); }))];
3002
+ case 1:
3003
+ mappedData = _a.sent();
3004
+ return [2 /*return*/, papaparse.unparse(mappedData, {
3005
+ header: true,
3006
+ delimiter: ',',
3007
+ quoteChar: '"',
3008
+ newline: '\r\n',
3009
+ skipEmptyLines: true,
3010
+ // encoding: 'utf8',
3011
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3012
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3013
+ })];
3014
+ }
3015
+ });
3016
+ });
3017
+ },
3018
+ },
3019
+ {
3020
+ subvalueName: 'CELL',
3021
+ mapValues: function (value, mapCallback) {
3022
+ return __awaiter(this, void 0, void 0, function () {
3023
+ var csv, mappedData;
3024
+ var _this = this;
3025
+ return __generator(this, function (_a) {
3026
+ switch (_a.label) {
3027
+ case 0:
3028
+ csv = papaparse.parse(value, {
3029
+ header: true,
3030
+ delimiter: ',',
3031
+ quoteChar: '"',
3032
+ newline: '\r\n',
3033
+ skipEmptyLines: true,
3034
+ // encoding: 'utf8',
3035
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3036
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3037
+ });
3038
+ if (csv.errors.length !== 0) {
3039
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3040
+ 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 "); }));
3041
+ }
3042
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3043
+ var _this = this;
3044
+ return __generator(this, function (_a) {
3045
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
3046
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
3047
+ return __awaiter(_this, void 0, void 0, function () {
3048
+ var index;
3049
+ var _c;
3050
+ return __generator(this, function (_d) {
3051
+ index = rowIndex * Object.keys(row).length + columnIndex;
3052
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
3053
+ });
3054
+ });
3055
+ }))];
3056
+ });
3057
+ }); }))];
3058
+ case 1:
3059
+ mappedData = _a.sent();
3060
+ return [2 /*return*/, papaparse.unparse(mappedData, {
3061
+ header: true,
3062
+ delimiter: ',',
3063
+ quoteChar: '"',
3064
+ newline: '\r\n',
3065
+ skipEmptyLines: true,
3066
+ // encoding: 'utf8',
3067
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3068
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3069
+ })];
3070
+ }
3071
+ });
3072
+ });
3073
+ },
3074
+ },
3075
+ ],
3076
+ };
3077
+ /**
3078
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
3079
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
3080
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
3081
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
3082
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3156
3083
  */
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
3084
 
3164
3085
  /**
3165
- * Counts number of paragraphs in the text
3086
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3166
3087
  *
3167
3088
  * @public exported from `@promptbook/utils`
3168
3089
  */
3169
- function countParagraphs(text) {
3170
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3090
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
3091
+ try {
3092
+ JSON.parse(value);
3093
+ return true;
3094
+ }
3095
+ catch (error) {
3096
+ if (!(error instanceof Error)) {
3097
+ throw error;
3098
+ }
3099
+ if (error.message.includes('Unexpected token')) {
3100
+ return false;
3101
+ }
3102
+ return false;
3103
+ }
3171
3104
  }
3172
3105
 
3173
3106
  /**
3174
- * Split text into sentences
3107
+ * Definition for JSON format
3175
3108
  *
3176
- * @public exported from `@promptbook/utils`
3109
+ * @private still in development [🏢]
3177
3110
  */
3178
- function splitIntoSentences(text) {
3179
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3180
- }
3111
+ var JsonFormatDefinition = {
3112
+ formatName: 'JSON',
3113
+ mimeType: 'application/json',
3114
+ isValid: function (value, schema) {
3115
+ TODO_USE(schema /* <- TODO: Use schema here */);
3116
+ return isValidJsonString(value);
3117
+ },
3118
+ canBeValid: function (partialValue, schema) {
3119
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3120
+ TODO_USE(schema /* <- TODO: Use schema here */);
3121
+ return true;
3122
+ },
3123
+ heal: function (value, schema) {
3124
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3125
+ TODO_USE(schema /* <- TODO: Use schema here */);
3126
+ throw new Error('Not implemented');
3127
+ },
3128
+ subvalueDefinitions: [],
3129
+ };
3181
3130
  /**
3182
- * Counts number of sentences in the text
3183
- *
3184
- * @public exported from `@promptbook/utils`
3131
+ * TODO: [🧠] Maybe propper instance of object
3132
+ * TODO: [0] Make string_serialized_json
3133
+ * TODO: [1] Make type for JSON Schema
3134
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3135
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3136
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3137
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3138
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3139
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3185
3140
  */
3186
- function countSentences(text) {
3187
- return splitIntoSentences(text).length;
3188
- }
3189
3141
 
3190
3142
  /**
3191
- * Counts number of words in the text
3143
+ * Definition for any text - this will be always valid
3192
3144
  *
3193
- * @public exported from `@promptbook/utils`
3145
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3146
+ *
3147
+ * @public exported from `@promptbook/core`
3148
+ */
3149
+ var TextFormatDefinition = {
3150
+ formatName: 'TEXT',
3151
+ isValid: function (value) {
3152
+ return typeof value === 'string';
3153
+ },
3154
+ canBeValid: function (partialValue) {
3155
+ return typeof partialValue === 'string';
3156
+ },
3157
+ heal: function () {
3158
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3159
+ },
3160
+ subvalueDefinitions: [
3161
+ {
3162
+ subvalueName: 'LINE',
3163
+ mapValues: function (value, mapCallback) {
3164
+ return __awaiter(this, void 0, void 0, function () {
3165
+ var lines, mappedLines;
3166
+ return __generator(this, function (_a) {
3167
+ switch (_a.label) {
3168
+ case 0:
3169
+ lines = value.split('\n');
3170
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3171
+ // TODO: [🧠] Maybe option to skip empty line
3172
+ /* not await */ return mapCallback({
3173
+ lineContent: lineContent,
3174
+ // TODO: [🧠] Maybe also put here `lineNumber`
3175
+ }, lineNumber);
3176
+ }))];
3177
+ case 1:
3178
+ mappedLines = _a.sent();
3179
+ return [2 /*return*/, mappedLines.join('\n')];
3180
+ }
3181
+ });
3182
+ });
3183
+ },
3184
+ },
3185
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3186
+ ],
3187
+ };
3188
+ /**
3189
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3190
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3191
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3192
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3193
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3194
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3194
3195
  */
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
3196
 
3201
3197
  /**
3202
- * Index of all counter functions
3198
+ * Definition for XML format
3203
3199
  *
3204
- * @public exported from `@promptbook/utils`
3200
+ * @private still in development [🏢]
3205
3201
  */
3206
- var CountUtils = {
3207
- CHARACTERS: countCharacters,
3208
- WORDS: countWords,
3209
- SENTENCES: countSentences,
3210
- PARAGRAPHS: countParagraphs,
3211
- LINES: countLines,
3212
- PAGES: countPages,
3202
+ var XmlFormatDefinition = {
3203
+ formatName: 'XML',
3204
+ mimeType: 'application/xml',
3205
+ isValid: function (value, schema) {
3206
+ TODO_USE(value /* <- TODO: Use value here */);
3207
+ TODO_USE(schema /* <- TODO: Use schema here */);
3208
+ return true;
3209
+ },
3210
+ canBeValid: function (partialValue, schema) {
3211
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3212
+ TODO_USE(schema /* <- TODO: Use schema here */);
3213
+ return true;
3214
+ },
3215
+ heal: function (value, schema) {
3216
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3217
+ TODO_USE(schema /* <- TODO: Use schema here */);
3218
+ throw new Error('Not implemented');
3219
+ },
3220
+ subvalueDefinitions: [],
3213
3221
  };
3222
+ /**
3223
+ * TODO: [🧠] Maybe propper instance of object
3224
+ * TODO: [0] Make string_serialized_xml
3225
+ * TODO: [1] Make type for XML Schema
3226
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3227
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3228
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3229
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3230
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3231
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3232
+ */
3214
3233
 
3215
3234
  /**
3216
- * Function checkExpectations will check if the expectations on given value are met
3235
+ * Definitions for all formats supported by Promptbook
3217
3236
  *
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
3237
+ * @private internal index of `...` <- TODO [🏢]
3238
+ */
3239
+ var FORMAT_DEFINITIONS = [
3240
+ JsonFormatDefinition,
3241
+ XmlFormatDefinition,
3242
+ TextFormatDefinition,
3243
+ CsvFormatDefinition,
3244
+ ];
3245
+
3246
+ /**
3247
+ * Maps available parameters to expected parameters
3221
3248
  *
3222
- * @throws {ExpectError} if the expectations are not met
3223
- * @returns {void} Nothing
3224
- * @private internal function of `createPipelineExecutor`
3249
+ * The strategy is:
3250
+ * 1) @@@
3251
+ * 2) @@@
3252
+ *
3253
+ * @throws {PipelineExecutionError} @@@
3254
+ * @private within the repository used in `createPipelineExecutor`
3225
3255
  */
3226
- function checkExpectations(expectations, value) {
3256
+ function mapAvailableToExpectedParameters(options) {
3227
3257
  var e_1, _a;
3258
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3259
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3260
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3261
+ var mappedParameters = {};
3228
3262
  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));
3263
+ // Phase 1️⃣: Matching mapping
3264
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3265
+ var parameterName = _c.value;
3266
+ // Situation: Parameter is available and expected
3267
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3268
+ mappedParameters[parameterName] = availableParameters[parameterName];
3269
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3270
+ availableParametersNames.delete(parameterName);
3271
+ expectedParameterNames.delete(parameterName);
3272
+ }
3273
+ // Situation: Parameter is available but NOT expected
3274
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3275
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3276
+ }
3277
+ // Situation: Parameter is NOT available BUT expected
3278
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3279
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3237
3280
  }
3238
3281
  }
3239
3282
  }
@@ -3244,622 +3287,1145 @@
3244
3287
  }
3245
3288
  finally { if (e_1) throw e_1.error; }
3246
3289
  }
3290
+ if (expectedParameterNames.size === 0) {
3291
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3292
+ Object.freeze(mappedParameters);
3293
+ return mappedParameters;
3294
+ }
3295
+ // Phase 2️⃣: Non-matching mapping
3296
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3297
+ 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)
3298
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3299
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3300
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3301
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3302
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3303
+ .join('\n')), "\n\n "); }));
3304
+ }
3305
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3306
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3307
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3308
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3309
+ }
3310
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3311
+ Object.freeze(mappedParameters);
3312
+ return mappedParameters;
3247
3313
  }
3314
+
3248
3315
  /**
3249
- * Function checkExpectations will check if the expectations on given value are met
3316
+ * Extracts all code blocks from markdown.
3250
3317
  *
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
3318
+ * Note: There are multiple simmilar function:
3319
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3320
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3321
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3322
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3254
3323
  *
3255
- * @returns {boolean} True if the expectations are met
3256
- * @public exported from `@promptbook/core`
3324
+ * @param markdown any valid markdown
3325
+ * @returns code blocks with language and content
3326
+ * @throws {ParseError} if block is not closed properly
3327
+ * @public exported from `@promptbook/markdown-utils`
3257
3328
  */
3258
- function isPassingExpectations(expectations, value) {
3329
+ function extractAllBlocksFromMarkdown(markdown) {
3330
+ var e_1, _a;
3331
+ var codeBlocks = [];
3332
+ var lines = markdown.split('\n');
3333
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3334
+ lines.push('');
3335
+ var currentCodeBlock = null;
3259
3336
  try {
3260
- checkExpectations(expectations, value);
3261
- return true;
3337
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3338
+ var line = lines_1_1.value;
3339
+ if (line.startsWith('> ') || line === '>') {
3340
+ if (currentCodeBlock === null) {
3341
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3342
+ } /* not else */
3343
+ if (currentCodeBlock.blockNotation === '>') {
3344
+ if (currentCodeBlock.content !== '') {
3345
+ currentCodeBlock.content += '\n';
3346
+ }
3347
+ currentCodeBlock.content += line.slice(2);
3348
+ }
3349
+ }
3350
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3351
+ codeBlocks.push(currentCodeBlock);
3352
+ currentCodeBlock = null;
3353
+ }
3354
+ /* not else */
3355
+ if (line.startsWith('```')) {
3356
+ var language = line.slice(3).trim() || null;
3357
+ if (currentCodeBlock === null) {
3358
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3359
+ }
3360
+ else {
3361
+ if (language !== null) {
3362
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3363
+ }
3364
+ codeBlocks.push(currentCodeBlock);
3365
+ currentCodeBlock = null;
3366
+ }
3367
+ }
3368
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3369
+ if (currentCodeBlock.content !== '') {
3370
+ currentCodeBlock.content += '\n';
3371
+ }
3372
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3373
+ }
3374
+ }
3262
3375
  }
3263
- catch (error) {
3264
- if (!(error instanceof ExpectError)) {
3265
- throw error;
3376
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3377
+ finally {
3378
+ try {
3379
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3266
3380
  }
3267
- return false;
3381
+ finally { if (e_1) throw e_1.error; }
3382
+ }
3383
+ if (currentCodeBlock !== null) {
3384
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3268
3385
  }
3386
+ return codeBlocks;
3269
3387
  }
3270
3388
  /**
3271
- * TODO: [💝] Unite object for expecting amount and format
3389
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3272
3390
  */
3273
3391
 
3274
3392
  /**
3275
- * Creates executor function from pipeline and execution tools.
3393
+ * Extracts extracts exactly one valid JSON code block
3276
3394
  *
3277
- * @returns The executor function
3278
- * @throws {PipelineLogicError} on logical error in the pipeline
3279
- * @public exported from `@promptbook/core`
3395
+ * - When given string is a valid JSON as it is, it just returns it
3396
+ * - When there is no JSON code block the function throws a `ParseError`
3397
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3398
+ *
3399
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3400
+ * Note: There are multiple simmilar function:
3401
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3402
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3403
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3404
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3405
+ *
3406
+ * @public exported from `@promptbook/markdown-utils`
3407
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3280
3408
  */
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;
3409
+ function extractJsonBlock(markdown) {
3410
+ if (isValidJsonString(markdown)) {
3411
+ return markdown;
3301
3412
  }
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 "); }));
3413
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3414
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3415
+ var content = _a.content;
3416
+ return isValidJsonString(content);
3417
+ });
3418
+ if (jsonBlocks.length === 0) {
3419
+ throw new Error('There is no valid JSON block in the markdown');
3304
3420
  }
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
- });
3421
+ if (jsonBlocks.length > 1) {
3422
+ throw new Error('There are multiple JSON code blocks in the markdown');
3423
+ }
3424
+ return jsonBlocks[0].content;
3425
+ }
3426
+ /**
3427
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3428
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3429
+ */
3430
+
3431
+ /**
3432
+ * Just says that the variable is not used but should be kept
3433
+ * No side effects.
3434
+ *
3435
+ * Note: It can be usefull for:
3436
+ *
3437
+ * 1) Suppressing eager optimization of unused imports
3438
+ * 2) Suppressing eslint errors of unused variables in the tests
3439
+ * 3) Keeping the type of the variable for type testing
3440
+ *
3441
+ * @param value any values
3442
+ * @returns void
3443
+ * @private within the repository
3444
+ */
3445
+ function keepUnused() {
3446
+ var valuesToKeep = [];
3447
+ for (var _i = 0; _i < arguments.length; _i++) {
3448
+ valuesToKeep[_i] = arguments[_i];
3449
+ }
3450
+ }
3451
+
3452
+ /**
3453
+ * Replaces parameters in template with values from parameters object
3454
+ *
3455
+ * @param template the template with parameters in {curly} braces
3456
+ * @param parameters the object with parameters
3457
+ * @returns the template with replaced parameters
3458
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3459
+ * @public exported from `@promptbook/utils`
3460
+ */
3461
+ function replaceParameters(template, parameters) {
3462
+ var e_1, _a;
3463
+ try {
3464
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3465
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3466
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3467
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3468
+ }
3469
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3470
+ // TODO: [🍵]
3471
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3472
+ }
3314
3473
  }
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
- });
3474
+ }
3475
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3476
+ finally {
3477
+ try {
3478
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3326
3479
  }
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
- });
3480
+ finally { if (e_1) throw e_1.error; }
3481
+ }
3482
+ var replacedTemplate = template;
3483
+ var match;
3484
+ var loopLimit = LOOP_LIMIT;
3485
+ var _loop_1 = function () {
3486
+ if (loopLimit-- < 0) {
3487
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3335
3488
  }
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
- });
3489
+ var precol = match.groups.precol;
3490
+ var parameterName = match.groups.parameterName;
3491
+ if (parameterName === '') {
3492
+ return "continue";
3493
+ }
3494
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3495
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3496
+ }
3497
+ if (parameters[parameterName] === undefined) {
3498
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3499
+ }
3500
+ var parameterValue = parameters[parameterName];
3501
+ if (parameterValue === undefined) {
3502
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3503
+ }
3504
+ parameterValue = parameterValue.toString();
3505
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3506
+ parameterValue = parameterValue
3507
+ .split('\n')
3508
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3509
+ .join('\n');
3510
+ }
3511
+ replacedTemplate =
3512
+ replacedTemplate.substring(0, match.index + precol.length) +
3513
+ parameterValue +
3514
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3515
+ };
3516
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3517
+ .exec(replacedTemplate))) {
3518
+ _loop_1();
3519
+ }
3520
+ // [💫] Check if there are parameters that are not closed properly
3521
+ if (/{\w+$/.test(replacedTemplate)) {
3522
+ throw new PipelineExecutionError('Parameter is not closed');
3523
+ }
3524
+ // [💫] Check if there are parameters that are not opened properly
3525
+ if (/^\w+}/.test(replacedTemplate)) {
3526
+ throw new PipelineExecutionError('Parameter is not opened');
3527
+ }
3528
+ return replacedTemplate;
3529
+ }
3530
+
3531
+ /**
3532
+ * Counts number of characters in the text
3533
+ *
3534
+ * @public exported from `@promptbook/utils`
3535
+ */
3536
+ function countCharacters(text) {
3537
+ // Remove null characters
3538
+ text = text.replace(/\0/g, '');
3539
+ // Replace emojis (and also ZWJ sequence) with hyphens
3540
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3541
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3542
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3543
+ return text.length;
3544
+ }
3545
+
3546
+ /**
3547
+ * Counts number of lines in the text
3548
+ *
3549
+ * @public exported from `@promptbook/utils`
3550
+ */
3551
+ function countLines(text) {
3552
+ if (text === '') {
3553
+ return 0;
3554
+ }
3555
+ return text.split('\n').length;
3556
+ }
3557
+
3558
+ /**
3559
+ * Counts number of pages in the text
3560
+ *
3561
+ * @public exported from `@promptbook/utils`
3562
+ */
3563
+ function countPages(text) {
3564
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3565
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3566
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3567
+ return pageCount;
3568
+ }
3569
+
3570
+ /**
3571
+ * Counts number of paragraphs in the text
3572
+ *
3573
+ * @public exported from `@promptbook/utils`
3574
+ */
3575
+ function countParagraphs(text) {
3576
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3577
+ }
3578
+
3579
+ /**
3580
+ * Split text into sentences
3581
+ *
3582
+ * @public exported from `@promptbook/utils`
3583
+ */
3584
+ function splitIntoSentences(text) {
3585
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3586
+ }
3587
+ /**
3588
+ * Counts number of sentences in the text
3589
+ *
3590
+ * @public exported from `@promptbook/utils`
3591
+ */
3592
+ function countSentences(text) {
3593
+ return splitIntoSentences(text).length;
3594
+ }
3595
+
3596
+ /**
3597
+ * Counts number of words in the text
3598
+ *
3599
+ * @public exported from `@promptbook/utils`
3600
+ */
3601
+ function countWords(text) {
3602
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3603
+ text = removeDiacritics(text);
3604
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3605
+ }
3606
+
3607
+ /**
3608
+ * Index of all counter functions
3609
+ *
3610
+ * @public exported from `@promptbook/utils`
3611
+ */
3612
+ var CountUtils = {
3613
+ CHARACTERS: countCharacters,
3614
+ WORDS: countWords,
3615
+ SENTENCES: countSentences,
3616
+ PARAGRAPHS: countParagraphs,
3617
+ LINES: countLines,
3618
+ PAGES: countPages,
3619
+ };
3620
+ /**
3621
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3622
+ */
3623
+
3624
+ /**
3625
+ * Function checkExpectations will check if the expectations on given value are met
3626
+ *
3627
+ * Note: There are two simmilar functions:
3628
+ * - `checkExpectations` which throws an error if the expectations are not met
3629
+ * - `isPassingExpectations` which returns a boolean
3630
+ *
3631
+ * @throws {ExpectError} if the expectations are not met
3632
+ * @returns {void} Nothing
3633
+ * @private internal function of `createPipelineExecutor`
3634
+ */
3635
+ function checkExpectations(expectations, value) {
3636
+ var e_1, _a;
3637
+ try {
3638
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3639
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3640
+ var amount = CountUtils[unit.toUpperCase()](value);
3641
+ if (min && amount < min) {
3642
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3643
+ } /* not else */
3644
+ if (max && amount > max) {
3645
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3646
+ }
3647
+ }
3648
+ }
3649
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3650
+ finally {
3651
+ try {
3652
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3653
+ }
3654
+ finally { if (e_1) throw e_1.error; }
3655
+ }
3656
+ }
3657
+ /**
3658
+ * Function checkExpectations will check if the expectations on given value are met
3659
+ *
3660
+ * Note: There are two simmilar functions:
3661
+ * - `checkExpectations` which throws an error if the expectations are not met
3662
+ * - `isPassingExpectations` which returns a boolean
3663
+ *
3664
+ * @returns {boolean} True if the expectations are met
3665
+ * @public exported from `@promptbook/core`
3666
+ */
3667
+ function isPassingExpectations(expectations, value) {
3668
+ try {
3669
+ checkExpectations(expectations, value);
3670
+ return true;
3671
+ }
3672
+ catch (error) {
3673
+ if (!(error instanceof ExpectError)) {
3674
+ throw error;
3384
3675
  }
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
- }
3676
+ return false;
3677
+ }
3678
+ }
3679
+ /**
3680
+ * TODO: [💝] Unite object for expecting amount and format
3681
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3682
+ * Note: [💝] and [🤠] are interconnected together
3683
+ */
3684
+
3685
+ /**
3686
+ * @@@
3687
+ *
3688
+ * @private internal utility of `createPipelineExecutor`
3689
+ */
3690
+ function executeAttempts(options) {
3691
+ return __awaiter(this, void 0, void 0, function () {
3692
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3693
+ return __generator(this, function (_a) {
3694
+ switch (_a.label) {
3695
+ case 0:
3696
+ 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;
3697
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3698
+ $ongoingTemplateResult = {
3699
+ $result: null,
3700
+ $resultString: null,
3701
+ $expectError: null,
3702
+ $scriptPipelineExecutionErrors: [],
3703
+ };
3704
+ _loop_1 = function (attempt) {
3705
+ var isJokerAttempt, jokerParameterName, _b, modelRequirements, _c, _d, _e, _f, _g, _h, scriptTools, _j, error_1, e_1_1, _k, _l, _m, functionName, postprocessingError, _o, _p, scriptTools, _q, error_2, e_2_1, e_3_1, error_3;
3706
+ var e_1, _r, e_3, _s, e_2, _t;
3707
+ return __generator(this, function (_u) {
3708
+ switch (_u.label) {
3709
+ case 0:
3710
+ isJokerAttempt = attempt < 0;
3711
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3712
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3713
+ if (isJokerAttempt && !jokerParameterName) {
3714
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3715
+ }
3716
+ $ongoingTemplateResult.$result = null;
3717
+ $ongoingTemplateResult.$resultString = null;
3718
+ $ongoingTemplateResult.$expectError = null;
3719
+ if (isJokerAttempt) {
3720
+ if (parameters[jokerParameterName] === undefined) {
3721
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3722
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3723
+ }
3724
+ else {
3725
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3726
+ }
3727
+ }
3728
+ _u.label = 1;
3729
+ case 1:
3730
+ _u.trys.push([1, 44, 45, 46]);
3731
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3732
+ _b = template.templateType;
3733
+ switch (_b) {
3734
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3735
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3736
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3737
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3738
+ }
3739
+ return [3 /*break*/, 25];
3740
+ case 2:
3741
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3742
+ return [3 /*break*/, 26];
3743
+ case 3:
3744
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3745
+ $ongoingTemplateResult.$prompt = {
3746
+ title: template.title,
3747
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3748
+ ? preparedPipeline.pipelineUrl
3749
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3750
+ parameters: parameters,
3751
+ content: preparedContent,
3752
+ modelRequirements: modelRequirements,
3753
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3754
+ var name = _a.name;
3755
+ return name === template.personaName;
3756
+ }) ||
3757
+ {})), template.expectations),
3758
+ format: template.format,
3759
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3760
+ }; // <- TODO: Not very good type guard
3761
+ _c = modelRequirements.modelVariant;
3762
+ switch (_c) {
3763
+ case 'CHAT': return [3 /*break*/, 4];
3764
+ case 'COMPLETION': return [3 /*break*/, 6];
3765
+ case 'EMBEDDING': return [3 /*break*/, 8];
3766
+ }
3767
+ return [3 /*break*/, 10];
3768
+ case 4:
3769
+ _d = $ongoingTemplateResult;
3770
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3771
+ case 5:
3772
+ _d.$chatResult = _u.sent();
3773
+ // TODO: [🍬] Destroy chatThread
3774
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3775
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3776
+ return [3 /*break*/, 11];
3777
+ case 6:
3778
+ _e = $ongoingTemplateResult;
3779
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3780
+ case 7:
3781
+ _e.$completionResult = _u.sent();
3782
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3783
+ $ongoingTemplateResult.$resultString =
3784
+ $ongoingTemplateResult.$completionResult.content;
3785
+ return [3 /*break*/, 11];
3786
+ case 8:
3787
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3788
+ _f = $ongoingTemplateResult;
3789
+ return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze($ongoingTemplateResult.$prompt))];
3790
+ case 9:
3791
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3792
+ _f.$embeddingResult = _u.sent();
3793
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$embeddingResult;
3794
+ $ongoingTemplateResult.$resultString =
3795
+ $ongoingTemplateResult.$embeddingResult.content.join(',');
3796
+ return [3 /*break*/, 11];
3797
+ case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3798
+ case 11: return [3 /*break*/, 26];
3799
+ case 12:
3800
+ if (arrayableToArray(tools.script).length === 0) {
3801
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3802
+ }
3803
+ if (!template.contentLanguage) {
3804
+ 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 "); }));
3805
+ }
3806
+ _u.label = 13;
3807
+ case 13:
3808
+ _u.trys.push([13, 20, 21, 22]);
3809
+ _g = (e_1 = void 0, __values(arrayableToArray(tools.script))), _h = _g.next();
3810
+ _u.label = 14;
3811
+ case 14:
3812
+ if (!!_h.done) return [3 /*break*/, 19];
3813
+ scriptTools = _h.value;
3814
+ _u.label = 15;
3815
+ case 15:
3816
+ _u.trys.push([15, 17, , 18]);
3817
+ _j = $ongoingTemplateResult;
3818
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3819
+ scriptLanguage: template.contentLanguage,
3820
+ script: preparedContent,
3821
+ parameters: parameters,
3822
+ }))];
3823
+ case 16:
3824
+ _j.$resultString = _u.sent();
3825
+ return [3 /*break*/, 19];
3826
+ case 17:
3827
+ error_1 = _u.sent();
3828
+ if (!(error_1 instanceof Error)) {
3829
+ throw error_1;
3830
+ }
3831
+ if (error_1 instanceof UnexpectedError) {
3832
+ throw error_1;
3833
+ }
3834
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3835
+ return [3 /*break*/, 18];
3836
+ case 18:
3837
+ _h = _g.next();
3838
+ return [3 /*break*/, 14];
3839
+ case 19: return [3 /*break*/, 22];
3840
+ case 20:
3841
+ e_1_1 = _u.sent();
3842
+ e_1 = { error: e_1_1 };
3843
+ return [3 /*break*/, 22];
3844
+ case 21:
3845
+ try {
3846
+ if (_h && !_h.done && (_r = _g.return)) _r.call(_g);
3847
+ }
3848
+ finally { if (e_1) throw e_1.error; }
3849
+ return [7 /*endfinally*/];
3850
+ case 22:
3851
+ if ($ongoingTemplateResult.$resultString !== null) {
3852
+ return [3 /*break*/, 26];
3853
+ }
3854
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3855
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3856
+ }
3857
+ else {
3858
+ 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
3859
+ .map(function (error) { return '- ' + error.message; })
3860
+ .join('\n\n')), "\n "); }));
3861
+ }
3862
+ case 23:
3863
+ if (tools.userInterface === undefined) {
3864
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3865
+ }
3866
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3867
+ _k = $ongoingTemplateResult;
3868
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3869
+ promptTitle: template.title,
3870
+ promptMessage: replaceParameters(template.description || '', parameters),
3871
+ defaultValue: replaceParameters(preparedContent, parameters),
3872
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3873
+ placeholder: undefined,
3874
+ priority: priority,
3875
+ }))];
3876
+ case 24:
3877
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3878
+ _k.$resultString = _u.sent();
3879
+ return [3 /*break*/, 26];
3880
+ case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3881
+ case 26:
3882
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 43];
3883
+ _u.label = 27;
3884
+ case 27:
3885
+ _u.trys.push([27, 41, 42, 43]);
3886
+ _l = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _m = _l.next();
3887
+ _u.label = 28;
3888
+ case 28:
3889
+ if (!!_m.done) return [3 /*break*/, 40];
3890
+ functionName = _m.value;
3891
+ postprocessingError = null;
3892
+ _u.label = 29;
3893
+ case 29:
3894
+ _u.trys.push([29, 36, 37, 38]);
3895
+ _o = (e_2 = void 0, __values(arrayableToArray(tools.script))), _p = _o.next();
3896
+ _u.label = 30;
3897
+ case 30:
3898
+ if (!!_p.done) return [3 /*break*/, 35];
3899
+ scriptTools = _p.value;
3900
+ _u.label = 31;
3901
+ case 31:
3902
+ _u.trys.push([31, 33, , 34]);
3903
+ _q = $ongoingTemplateResult;
3904
+ return [4 /*yield*/, scriptTools.execute({
3905
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3906
+ script: "".concat(functionName, "(resultString)"),
3907
+ parameters: {
3908
+ resultString: $ongoingTemplateResult.$resultString || '',
3909
+ // Note: No ...parametersForTemplate, because working with result only
3910
+ },
3911
+ })];
3912
+ case 32:
3913
+ _q.$resultString = _u.sent();
3914
+ postprocessingError = null;
3915
+ return [3 /*break*/, 35];
3916
+ case 33:
3917
+ error_2 = _u.sent();
3918
+ if (!(error_2 instanceof Error)) {
3919
+ throw error_2;
3920
+ }
3921
+ if (error_2 instanceof UnexpectedError) {
3922
+ throw error_2;
3923
+ }
3924
+ postprocessingError = error_2;
3925
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3926
+ return [3 /*break*/, 34];
3927
+ case 34:
3928
+ _p = _o.next();
3929
+ return [3 /*break*/, 30];
3930
+ case 35: return [3 /*break*/, 38];
3931
+ case 36:
3932
+ e_2_1 = _u.sent();
3933
+ e_2 = { error: e_2_1 };
3934
+ return [3 /*break*/, 38];
3935
+ case 37:
3936
+ try {
3937
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3938
+ }
3939
+ finally { if (e_2) throw e_2.error; }
3940
+ return [7 /*endfinally*/];
3941
+ case 38:
3942
+ if (postprocessingError) {
3943
+ throw postprocessingError;
3944
+ }
3945
+ _u.label = 39;
3946
+ case 39:
3947
+ _m = _l.next();
3948
+ return [3 /*break*/, 28];
3949
+ case 40: return [3 /*break*/, 43];
3950
+ case 41:
3951
+ e_3_1 = _u.sent();
3952
+ e_3 = { error: e_3_1 };
3953
+ return [3 /*break*/, 43];
3954
+ case 42:
3955
+ try {
3956
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3957
+ }
3958
+ finally { if (e_3) throw e_3.error; }
3959
+ return [7 /*endfinally*/];
3960
+ case 43:
3961
+ // TODO: [💝] Unite object for expecting amount and format
3962
+ if (template.format) {
3963
+ if (template.format === 'JSON') {
3964
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3965
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3966
+ try {
3967
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3731
3968
  }
3732
- else {
3733
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3969
+ catch (error) {
3970
+ keepUnused(error);
3971
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3972
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3734
3973
  }
3735
3974
  }
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) || '')
3975
+ }
3976
+ else {
3977
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3978
+ }
3979
+ }
3980
+ // TODO: [💝] Unite object for expecting amount and format
3981
+ if (template.expectations) {
3982
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3983
+ }
3984
+ return [2 /*return*/, "break-attempts"];
3985
+ case 44:
3986
+ error_3 = _u.sent();
3987
+ if (!(error_3 instanceof ExpectError)) {
3988
+ throw error_3;
3989
+ }
3990
+ $ongoingTemplateResult.$expectError = error_3;
3991
+ return [3 /*break*/, 46];
3992
+ case 45:
3993
+ if (!isJokerAttempt &&
3994
+ template.templateType === 'PROMPT_TEMPLATE' &&
3995
+ $ongoingTemplateResult.$prompt
3996
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3997
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3998
+ ) {
3999
+ // TODO: [🧠] Maybe put other templateTypes into report
4000
+ $executionReport.promptExecutions.push({
4001
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
4002
+ result: $ongoingTemplateResult.$result || undefined,
4003
+ error: $ongoingTemplateResult.$expectError === null
4004
+ ? undefined
4005
+ : serializeError($ongoingTemplateResult.$expectError),
4006
+ });
4007
+ }
4008
+ return [7 /*endfinally*/];
4009
+ case 46:
4010
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
4011
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
4012
+ var _a, _b, _c;
4013
+ 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) || '')
4014
+ .split('\n')
4015
+ .map(function (line) { return "> ".concat(line); })
4016
+ .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) || '')
4017
+ .split('\n')
4018
+ .map(function (line) { return "> ".concat(line); })
4019
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
4020
+ ? 'null'
4021
+ : $ongoingTemplateResult.$resultString
3769
4022
  .split('\n')
3770
4023
  .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*/];
4024
+ .join('\n')), "\n ---\n ");
4025
+ }));
3779
4026
  }
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 "); }));
4027
+ return [2 /*return*/];
3799
4028
  }
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 "); }));
3816
- }
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*/];
4029
+ });
4030
+ };
4031
+ attempt = -jokerParameterNames.length;
4032
+ _a.label = 1;
4033
+ case 1:
4034
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
4035
+ return [5 /*yield**/, _loop_1(attempt)];
4036
+ case 2:
4037
+ state_1 = _a.sent();
4038
+ switch (state_1) {
4039
+ case "break-attempts": return [3 /*break*/, 4];
3824
4040
  }
3825
- });
3826
- });
4041
+ _a.label = 3;
4042
+ case 3:
4043
+ attempt++;
4044
+ return [3 /*break*/, 1];
4045
+ case 4:
4046
+ if ($ongoingTemplateResult.$resultString === null) {
4047
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4048
+ }
4049
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
4050
+ }
4051
+ });
4052
+ });
4053
+ }
4054
+ /**
4055
+ * TODO: Break into smaller functions
4056
+ */
4057
+
4058
+ /**
4059
+ * @@@
4060
+ *
4061
+ * @private internal utility of `createPipelineExecutor`
4062
+ */
4063
+ function executeFormatCells(options) {
4064
+ return __awaiter(this, void 0, void 0, function () {
4065
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, parameterValue, formatDefinition, subvalueDefinition, resultString;
4066
+ var _this = this;
4067
+ return __generator(this, function (_a) {
4068
+ switch (_a.label) {
4069
+ case 0:
4070
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification;
4071
+ if (template.foreach === undefined) {
4072
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
4073
+ }
4074
+ if (jokerParameterNames.length !== 0) {
4075
+ 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 "); }));
4076
+ }
4077
+ parameterValue = parameters[template.foreach.parameterName] || '';
4078
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
4079
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
4080
+ });
4081
+ if (formatDefinition === undefined) {
4082
+ throw new UnexpectedError(
4083
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4084
+ 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; })
4085
+ .map(function (formatName) { return "- ".concat(formatName); })
4086
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4087
+ }
4088
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
4089
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.cellName);
4090
+ });
4091
+ if (subvalueDefinition === undefined) {
4092
+ throw new UnexpectedError(
4093
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4094
+ spaceTrim__default["default"](function (block) { return "\n Unsupported cell name \"".concat(template.foreach.cellName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available cell names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
4095
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
4096
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
4097
+ .join('\n')), "\n\n [\u26F7] This should never happen because cell name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4098
+ }
4099
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4100
+ var mappedParameters, allSubparameters, subresultString;
4101
+ return __generator(this, function (_a) {
4102
+ switch (_a.label) {
4103
+ case 0:
4104
+ try {
4105
+ mappedParameters = mapAvailableToExpectedParameters({
4106
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4107
+ availableParameters: subparameters,
4108
+ });
4109
+ }
4110
+ catch (error) {
4111
+ if (!(error instanceof PipelineExecutionError)) {
4112
+ throw error;
4113
+ }
4114
+ 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 "); }));
4115
+ }
4116
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4117
+ // 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
4118
+ Object.freeze(allSubparameters);
4119
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
4120
+ case 1:
4121
+ subresultString = _a.sent();
4122
+ return [2 /*return*/, subresultString];
4123
+ }
4124
+ });
4125
+ }); })];
4126
+ case 1:
4127
+ resultString = _a.sent();
4128
+ return [2 /*return*/, resultString];
4129
+ }
4130
+ });
4131
+ });
4132
+ }
4133
+ /**
4134
+ * TODO: !!!!!! Make pipelineIdentification more precise
4135
+ * TODO: !!!!!! How FOREACH execution looks in the report
4136
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
4137
+ * TODO: []
4138
+ */
4139
+
4140
+ /**
4141
+ * @@@
4142
+ *
4143
+ * @private internal utility of `createPipelineExecutor`
4144
+ */
4145
+ function getContextForTemplate(template) {
4146
+ return __awaiter(this, void 0, void 0, function () {
4147
+ return __generator(this, function (_a) {
4148
+ TODO_USE(template);
4149
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
4150
+ });
4151
+ });
4152
+ }
4153
+
4154
+ /**
4155
+ * @@@
4156
+ *
4157
+ * @private internal utility of `createPipelineExecutor`
4158
+ */
4159
+ function getKnowledgeForTemplate(options) {
4160
+ return __awaiter(this, void 0, void 0, function () {
4161
+ var preparedPipeline, template;
4162
+ return __generator(this, function (_a) {
4163
+ preparedPipeline = options.preparedPipeline, template = options.template;
4164
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4165
+ TODO_USE(template);
4166
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4167
+ var content = _a.content;
4168
+ return "- ".concat(content);
4169
+ }).join('\n')];
4170
+ });
4171
+ });
4172
+ }
4173
+
4174
+ /**
4175
+ * @@@
4176
+ *
4177
+ * @private internal utility of `createPipelineExecutor`
4178
+ */
4179
+ function getSamplesForTemplate(template) {
4180
+ return __awaiter(this, void 0, void 0, function () {
4181
+ return __generator(this, function (_a) {
4182
+ // TODO: [♨] Implement Better - use real index and keyword search
4183
+ TODO_USE(template);
4184
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4185
+ });
4186
+ });
4187
+ }
4188
+
4189
+ /**
4190
+ * @@@
4191
+ *
4192
+ * @private internal utility of `createPipelineExecutor`
4193
+ */
4194
+ function getReservedParametersForTemplate(options) {
4195
+ return __awaiter(this, void 0, void 0, function () {
4196
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4197
+ var e_1, _a;
4198
+ return __generator(this, function (_b) {
4199
+ switch (_b.label) {
4200
+ case 0:
4201
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4202
+ return [4 /*yield*/, getContextForTemplate(template)];
4203
+ case 1:
4204
+ context = _b.sent();
4205
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4206
+ case 2:
4207
+ knowledge = _b.sent();
4208
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4209
+ case 3:
4210
+ samples = _b.sent();
4211
+ currentDate = new Date().toISOString();
4212
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4213
+ reservedParameters = {
4214
+ content: RESERVED_PARAMETER_RESTRICTED,
4215
+ context: context,
4216
+ knowledge: knowledge,
4217
+ samples: samples,
4218
+ currentDate: currentDate,
4219
+ modelName: modelName,
4220
+ };
4221
+ _loop_1 = function (parameterName) {
4222
+ if (reservedParameters[parameterName] === undefined) {
4223
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4224
+ }
4225
+ };
4226
+ try {
4227
+ // Note: Doublecheck that ALL reserved parameters are defined:
4228
+ 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()) {
4229
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4230
+ _loop_1(parameterName);
4231
+ }
4232
+ }
4233
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4234
+ finally {
4235
+ try {
4236
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4237
+ }
4238
+ finally { if (e_1) throw e_1.error; }
4239
+ }
4240
+ return [2 /*return*/, reservedParameters];
4241
+ }
4242
+ });
4243
+ });
4244
+ }
4245
+
4246
+ /**
4247
+ * @@@
4248
+ *
4249
+ * @private internal utility of `createPipelineExecutor`
4250
+ */
4251
+ function executeTemplate(options) {
4252
+ return __awaiter(this, void 0, void 0, function () {
4253
+ 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;
4254
+ var e_1, _f, _g;
4255
+ return __generator(this, function (_h) {
4256
+ switch (_h.label) {
4257
+ case 0:
4258
+ 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;
4259
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4260
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4261
+ title = currentTemplate.title;
4262
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4263
+ return [4 /*yield*/, onProgress({
4264
+ name: name,
4265
+ title: title,
4266
+ isStarted: false,
4267
+ isDone: false,
4268
+ templateType: currentTemplate.templateType,
4269
+ parameterName: currentTemplate.resultingParameterName,
4270
+ parameterValue: null,
4271
+ // <- [🍸]
4272
+ })];
4273
+ case 1:
4274
+ _h.sent();
4275
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4276
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4277
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4278
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4279
+ 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)
4280
+ .map(function (name) { return "{".concat(name, "}"); })
4281
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4282
+ .map(function (name) { return "{".concat(name, "}"); })
4283
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4284
+ }
4285
+ _b = (_a = Object).freeze;
4286
+ _c = [{}];
4287
+ return [4 /*yield*/, getReservedParametersForTemplate({
4288
+ preparedPipeline: preparedPipeline,
4289
+ template: currentTemplate,
4290
+ pipelineIdentification: pipelineIdentification,
4291
+ })];
4292
+ case 2:
4293
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4294
+ definedParameterNames = new Set(Object.keys(definedParameters));
4295
+ parameters = {};
4296
+ _loop_1 = function (parameterName) {
4297
+ // Situation: Parameter is defined and used
4298
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4299
+ parameters[parameterName] = definedParameters[parameterName];
4300
+ }
4301
+ // Situation: Parameter is defined but NOT used
4302
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4303
+ // Situation: Parameter is NOT defined BUT used
4304
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4305
+ // Houston, we have a problem
4306
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4307
+ 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 "); }));
4308
+ }
4309
+ };
4310
+ try {
4311
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4312
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4313
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4314
+ parameterName = _e.value;
4315
+ _loop_1(parameterName);
4316
+ }
4317
+ }
4318
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4319
+ finally {
4320
+ try {
4321
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4322
+ }
4323
+ finally { if (e_1) throw e_1.error; }
4324
+ }
4325
+ // 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
4326
+ Object.freeze(parameters);
4327
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4328
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4329
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4330
+ .split('{content}')
4331
+ .join(currentTemplate.content);
4332
+ return [4 /*yield*/, executeFormatCells({
4333
+ jokerParameterNames: jokerParameterNames,
4334
+ priority: priority,
4335
+ maxAttempts: maxAttempts,
4336
+ preparedContent: preparedContent,
4337
+ parameters: parameters,
4338
+ template: currentTemplate,
4339
+ preparedPipeline: preparedPipeline,
4340
+ tools: tools,
4341
+ llmTools: llmTools,
4342
+ settings: settings,
4343
+ $executionReport: $executionReport,
4344
+ pipelineIdentification: pipelineIdentification,
4345
+ })];
4346
+ case 3:
4347
+ resultString = _h.sent();
4348
+ return [4 /*yield*/, onProgress({
4349
+ name: name,
4350
+ title: title,
4351
+ isStarted: true,
4352
+ isDone: true,
4353
+ templateType: currentTemplate.templateType,
4354
+ parameterName: currentTemplate.resultingParameterName,
4355
+ parameterValue: resultString,
4356
+ // <- [🍸]
4357
+ })];
4358
+ case 4:
4359
+ _h.sent();
4360
+ return [2 /*return*/, Object.freeze((_g = {},
4361
+ _g[currentTemplate.resultingParameterName] =
4362
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4363
+ resultString,
4364
+ _g))];
4365
+ }
4366
+ });
4367
+ });
4368
+ }
4369
+ /**
4370
+ * TODO: [🤹‍♂️]
4371
+ */
4372
+
4373
+ /**
4374
+ * @@@
4375
+ *
4376
+ * @private internal utility of `createPipelineExecutor`
4377
+ */
4378
+ function filterJustOutputParameters(options) {
4379
+ var e_1, _a;
4380
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4381
+ var outputParameters = {};
4382
+ var _loop_1 = function (parameter) {
4383
+ if (parametersToPass[parameter.name] === undefined) {
4384
+ // [4]
4385
+ $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 "); })));
4386
+ return "continue";
4387
+ }
4388
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4389
+ };
4390
+ try {
4391
+ // Note: Filter ONLY output parameters
4392
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4393
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4394
+ var isOutput = _a.isOutput;
4395
+ return isOutput;
4396
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4397
+ var parameter = _c.value;
4398
+ _loop_1(parameter);
3827
4399
  }
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
- }
3848
- }
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; }
3855
- }
3856
- return outputParameters;
4400
+ }
4401
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4402
+ finally {
4403
+ try {
4404
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3857
4405
  }
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;
4406
+ finally { if (e_1) throw e_1.error; }
4407
+ }
4408
+ return outputParameters;
4409
+ }
4410
+
4411
+ /**
4412
+ * @@@
4413
+ *
4414
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4415
+ *
4416
+ * @private internal utility of `createPipelineExecutor`
4417
+ */
4418
+ function executePipeline(options) {
4419
+ return __awaiter(this, void 0, void 0, function () {
4420
+ 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
4421
  var e_1, _e, e_2, _f;
3860
4422
  return __generator(this, function (_g) {
3861
4423
  switch (_g.label) {
3862
4424
  case 0:
4425
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4426
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4427
+ preparedPipeline = options.preparedPipeline;
4428
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3863
4429
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3864
4430
  return [4 /*yield*/, preparePipeline(pipeline, {
3865
4431
  llmTools: llmTools,
@@ -3868,6 +4434,7 @@
3868
4434
  })];
3869
4435
  case 1:
3870
4436
  preparedPipeline = _g.sent();
4437
+ setPreparedPipeline(preparedPipeline);
3871
4438
  _g.label = 2;
3872
4439
  case 2:
3873
4440
  errors = [];
@@ -3937,7 +4504,7 @@
3937
4504
  return name === parameterName;
3938
4505
  });
3939
4506
  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 "); })));
4507
+ 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
4508
  return [3 /*break*/, 4];
3942
4509
  case 1:
3943
4510
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3949,10 +4516,10 @@
3949
4516
  // Note: Wait a short time to prevent race conditions
3950
4517
  _h.sent();
3951
4518
  _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 "); }), {
4519
+ 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
4520
  isSuccessful: false,
3954
4521
  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 "); }))
4522
+ 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
4523
  ], __read(errors), false).map(serializeError),
3957
4524
  warnings: warnings.map(serializeError),
3958
4525
  executionReport: executionReport,
@@ -4016,7 +4583,7 @@
4016
4583
  case 0:
4017
4584
  if (loopLimit-- < 0) {
4018
4585
  // 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 "); }));
4586
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4020
4587
  }
4021
4588
  currentTemplate = unresovedTemplates_1.find(function (template) {
4022
4589
  return template.dependentParameterNames.every(function (name) {
@@ -4026,29 +4593,52 @@
4026
4593
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4027
4594
  throw new UnexpectedError(
4028
4595
  // 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
4596
+ 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
4597
  .map(function (_a) {
4031
4598
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4032
4599
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4033
4600
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4034
4601
  .join(' and '));
4035
4602
  })
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 "); }));
4603
+ .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
4604
  case 1:
4038
4605
  if (!!currentTemplate) return [3 /*break*/, 3];
4039
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4606
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4040
4607
  case 2:
4041
- /* [5] */ _j.sent();
4608
+ /* [🤹‍♂️] */ _j.sent();
4042
4609
  return [3 /*break*/, 4];
4043
4610
  case 3:
4044
4611
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4045
- work_1 = executeSingleTemplate(currentTemplate)
4046
- .then(function () {
4612
+ work_1 = executeTemplate({
4613
+ currentTemplate: currentTemplate,
4614
+ preparedPipeline: preparedPipeline,
4615
+ parametersToPass: parametersToPass,
4616
+ tools: tools,
4617
+ llmTools: llmTools,
4618
+ onProgress: function (progress) {
4619
+ if (isReturned) {
4620
+ 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)
4621
+ .split('\n')
4622
+ .map(function (line) { return "> ".concat(line); })
4623
+ .join('\n')), "\n "); }));
4624
+ }
4625
+ if (onProgress) {
4626
+ onProgress(progress);
4627
+ }
4628
+ },
4629
+ settings: settings,
4630
+ $executionReport: executionReport,
4631
+ pipelineIdentification: pipelineIdentification,
4632
+ })
4633
+ .then(function (newParametersToPass) {
4634
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4047
4635
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4048
4636
  })
4049
4637
  .then(function () {
4050
4638
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4051
4639
  });
4640
+ // <- Note: Errors are catched here [3]
4641
+ // 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
4642
  resolving_1.push(work_1);
4053
4643
  _j.label = 4;
4054
4644
  case 4: return [2 /*return*/];
@@ -4075,7 +4665,12 @@
4075
4665
  var result = _a.result;
4076
4666
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4077
4667
  })), false));
4078
- outputParameters_1 = filterJustOutputParameters();
4668
+ outputParameters_1 = filterJustOutputParameters({
4669
+ preparedPipeline: preparedPipeline,
4670
+ parametersToPass: parametersToPass,
4671
+ $warnings: warnings,
4672
+ pipelineIdentification: pipelineIdentification,
4673
+ });
4079
4674
  isReturned = true;
4080
4675
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4081
4676
  // Note: Wait a short time to prevent race conditions
@@ -4098,7 +4693,12 @@
4098
4693
  var result = _a.result;
4099
4694
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4100
4695
  })), false));
4101
- outputParameters = filterJustOutputParameters();
4696
+ outputParameters = filterJustOutputParameters({
4697
+ preparedPipeline: preparedPipeline,
4698
+ parametersToPass: parametersToPass,
4699
+ $warnings: warnings,
4700
+ pipelineIdentification: pipelineIdentification,
4701
+ });
4102
4702
  isReturned = true;
4103
4703
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4104
4704
  // Note: Wait a short time to prevent race conditions
@@ -4118,22 +4718,62 @@
4118
4718
  })];
4119
4719
  }
4120
4720
  });
4121
- }); };
4122
- return pipelineExecutor;
4721
+ });
4123
4722
  }
4723
+
4124
4724
  /**
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
4725
+ * Creates executor function from pipeline and execution tools.
4726
+ *
4727
+ * @returns The executor function
4728
+ * @throws {PipelineLogicError} on logical error in the pipeline
4729
+ * @public exported from `@promptbook/core`
4136
4730
  */
4731
+ function createPipelineExecutor(options) {
4732
+ var _this = this;
4733
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4734
+ 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;
4735
+ validatePipeline(pipeline);
4736
+ var pipelineIdentification = (function () {
4737
+ // Note: This is a 😐 implementation of [🚞]
4738
+ var _ = [];
4739
+ if (pipeline.sourceFile !== undefined) {
4740
+ _.push("File: ".concat(pipeline.sourceFile));
4741
+ }
4742
+ if (pipeline.pipelineUrl !== undefined) {
4743
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4744
+ }
4745
+ return _.join('\n');
4746
+ })();
4747
+ var preparedPipeline;
4748
+ if (isPipelinePrepared(pipeline)) {
4749
+ preparedPipeline = pipeline;
4750
+ }
4751
+ else if (isNotPreparedWarningSupressed !== true) {
4752
+ 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 "); }));
4753
+ }
4754
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4755
+ return __generator(this, function (_a) {
4756
+ return [2 /*return*/, executePipeline({
4757
+ pipeline: pipeline,
4758
+ preparedPipeline: preparedPipeline,
4759
+ setPreparedPipeline: function (newPreparedPipeline) {
4760
+ preparedPipeline = newPreparedPipeline;
4761
+ },
4762
+ inputParameters: inputParameters,
4763
+ tools: tools,
4764
+ onProgress: onProgress,
4765
+ pipelineIdentification: pipelineIdentification,
4766
+ settings: {
4767
+ maxExecutionAttempts: maxExecutionAttempts,
4768
+ maxParallelCount: maxParallelCount,
4769
+ isVerbose: isVerbose,
4770
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4771
+ },
4772
+ })];
4773
+ });
4774
+ }); };
4775
+ return pipelineExecutor;
4776
+ }
4137
4777
 
4138
4778
  /**
4139
4779
  * @@@
@@ -5269,6 +5909,145 @@
5269
5909
  * TODO: [🌺] Use some intermediate util splitWords
5270
5910
  */
5271
5911
 
5912
+ /**
5913
+ * @@@
5914
+ *
5915
+ * @param text @@@
5916
+ * @param _isFirstLetterCapital @@@
5917
+ * @returns @@@
5918
+ * @example 'helloWorld'
5919
+ * @example 'iLovePromptbook'
5920
+ * @public exported from `@promptbook/utils`
5921
+ */
5922
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5923
+ var e_1, _a;
5924
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5925
+ var charType;
5926
+ var lastCharType = null;
5927
+ var normalizedName = '';
5928
+ try {
5929
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5930
+ var char = text_1_1.value;
5931
+ var normalizedChar = void 0;
5932
+ if (/^[a-z]$/.test(char)) {
5933
+ charType = 'LOWERCASE';
5934
+ normalizedChar = char;
5935
+ }
5936
+ else if (/^[A-Z]$/.test(char)) {
5937
+ charType = 'UPPERCASE';
5938
+ normalizedChar = char.toLowerCase();
5939
+ }
5940
+ else if (/^[0-9]$/.test(char)) {
5941
+ charType = 'NUMBER';
5942
+ normalizedChar = char;
5943
+ }
5944
+ else {
5945
+ charType = 'OTHER';
5946
+ normalizedChar = '';
5947
+ }
5948
+ if (!lastCharType) {
5949
+ if (_isFirstLetterCapital) {
5950
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5951
+ }
5952
+ }
5953
+ else if (charType !== lastCharType &&
5954
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5955
+ !(lastCharType === 'NUMBER') &&
5956
+ !(charType === 'NUMBER')) {
5957
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5958
+ }
5959
+ normalizedName += normalizedChar;
5960
+ lastCharType = charType;
5961
+ }
5962
+ }
5963
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5964
+ finally {
5965
+ try {
5966
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5967
+ }
5968
+ finally { if (e_1) throw e_1.error; }
5969
+ }
5970
+ return normalizedName;
5971
+ }
5972
+ /**
5973
+ * TODO: [🌺] Use some intermediate util splitWords
5974
+ */
5975
+
5976
+ /**
5977
+ * Function `validateParameterName` will @@@
5978
+ *
5979
+ * @param parameterName @@@
5980
+ * @returns @@@
5981
+ * @throws {ParseError} @@@
5982
+ * @private within the repository
5983
+ */
5984
+ function validateParameterName(parameterName) {
5985
+ var e_1, _a;
5986
+ var rawParameterName = parameterName;
5987
+ try {
5988
+ for (var _b = __values([
5989
+ ['`', '`'],
5990
+ ['{', '}'],
5991
+ ['[', ']'],
5992
+ ['(', ')'],
5993
+ ['<', '>'],
5994
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5995
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5996
+ if (parameterName.substring(0, 1) === start &&
5997
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5998
+ // <- TODO: More universal that 1 character
5999
+ ) {
6000
+ parameterName = parameterName.substring(1, parameterName.length - 1);
6001
+ // <- TODO: More universal that 1 character
6002
+ }
6003
+ }
6004
+ }
6005
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
6006
+ finally {
6007
+ try {
6008
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
6009
+ }
6010
+ finally { if (e_1) throw e_1.error; }
6011
+ }
6012
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
6013
+ try {
6014
+ /*
6015
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
6016
+ if (parameterName.includes(' ')) {
6017
+ throw new ParseError(`Parameter name cannot contain spaces`);
6018
+ }
6019
+ */
6020
+ if (parameterName.includes('.')) {
6021
+ throw new ParseError("Parameter name cannot contain dots");
6022
+ }
6023
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
6024
+ throw new ParseError("Parameter name cannot contain slashes");
6025
+ }
6026
+ if (parameterName.includes('(') ||
6027
+ parameterName.includes(')') ||
6028
+ parameterName.includes('{') ||
6029
+ parameterName.includes('}') ||
6030
+ parameterName.includes('[') ||
6031
+ parameterName.includes(']')) {
6032
+ throw new ParseError("Parameter name cannot contain braces");
6033
+ }
6034
+ parameterName = normalizeTo_camelCase(parameterName);
6035
+ if (parameterName === '') {
6036
+ throw new ParseError("Parameter name cannot be empty");
6037
+ }
6038
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
6039
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
6040
+ }
6041
+ }
6042
+ catch (error) {
6043
+ if (!(error instanceof ParseError)) {
6044
+ throw error;
6045
+ }
6046
+ 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 "); }));
6047
+ }
6048
+ return parameterName;
6049
+ }
6050
+
5272
6051
  /**
5273
6052
  * Parses the foreach command
5274
6053
  *
@@ -5303,62 +6082,66 @@
5303
6082
  * Example usages of the FOREACH command
5304
6083
  */
5305
6084
  examples: [
5306
- 'FOREACH List Line -> `{customer}`',
5307
- 'FOR List Line -> `{customer}`',
5308
- 'EACH List Line -> `{customer}`',
6085
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
6086
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
6087
+ 'EACH Csv Cell `{customers}` -> `{cell}`',
5309
6088
  // <- TODO: [🍭] !!!!!! More
5310
6089
  ],
5311
6090
  /**
5312
6091
  * Parses the FOREACH command
5313
6092
  */
5314
6093
  parse: function (input) {
5315
- var args = input.args, rawArgs = input.rawArgs;
6094
+ var args = input.args;
5316
6095
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5317
6096
  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)) {
6097
+ var parameterNameWrapped = args[2];
6098
+ var assignSign = args[3];
6099
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
6100
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
6101
+ });
6102
+ if (formatDefinition === undefined) {
5325
6103
  console.info({ args: args, formatName: formatName });
5326
- throw new Error("Unsupported format \"".concat(formatName, "\""));
6104
+ 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; })
6105
+ .map(function (formatName) { return "- ".concat(formatName); })
6106
+ .join('\n')), "\n "); }));
5327
6107
  // <- TODO: [🏢] List all supported format names
5328
6108
  }
5329
- if (![
5330
- 'LINE',
5331
- 'ROW',
5332
- 'COLUMN',
5333
- 'CELL',
5334
- // <- TODO: [🏢] Unhardcode format cekks
5335
- ].includes(cellName)) {
6109
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
6110
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(cellName);
6111
+ });
6112
+ if (subvalueDefinition === undefined) {
5336
6113
  console.info({ args: args, cellName: cellName });
5337
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
6114
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported cell name \"".concat(cellName, "\" for format \"").concat(formatName, "\"\n\n Available cell names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
6115
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6116
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6117
+ .join('\n')), "\n "); }));
5338
6118
  // <- TODO: [🏢] List all supported cell names for the format
5339
6119
  }
5340
6120
  if (assignSign !== '->') {
5341
6121
  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
6122
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6123
+ }
6124
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
6125
+ if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
6126
+ (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
6127
+ console.info({ args: args, parameterNameWrapped: parameterNameWrapped }, parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1), parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length));
6128
+ throw new ParseError("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
6129
+ }
6130
+ var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
6131
+ var subparameterNames = args
6132
+ .slice(4)
6133
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6134
+ .filter(function (parameterName) { return parameterName !== ''; })
6135
+ .map(validateParameterName);
6136
+ if (subparameterNames.length === 0) {
6137
+ throw new ParseError("FOREACH command must have at least one subparameter");
5356
6138
  }
5357
6139
  return {
5358
6140
  type: 'FOREACH',
5359
6141
  formatName: formatName,
5360
6142
  cellName: cellName,
5361
6143
  parameterName: parameterName,
6144
+ subparameterNames: subparameterNames,
5362
6145
  };
5363
6146
  },
5364
6147
  /**
@@ -5367,8 +6150,12 @@
5367
6150
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5368
6151
  */
5369
6152
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5370
- keepUnused(command, $templateJson, $pipelineJson);
5371
- // <- TODO: [🍭] !!!!!! Implement
6153
+ var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6154
+ // TODO: !!!!!! Detect double use
6155
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
6156
+ $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterNames: subparameterNames };
6157
+ keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6158
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5372
6159
  },
5373
6160
  /**
5374
6161
  * Converts the FOREACH command back to string
@@ -5377,8 +6164,7 @@
5377
6164
  */
5378
6165
  stringify: function (command) {
5379
6166
  keepUnused(command);
5380
- return "";
5381
- // <- TODO: [🍭] !!!!!! Implement
6167
+ return "---"; // <- TODO: [🛋] Implement
5382
6168
  },
5383
6169
  /**
5384
6170
  * Reads the FOREACH command from the `TemplateJson`
@@ -5387,12 +6173,12 @@
5387
6173
  */
5388
6174
  takeFromTemplateJson: function ($templateJson) {
5389
6175
  keepUnused($templateJson);
5390
- return [];
5391
- // <- TODO: [🍭] !!!!!! Implement
6176
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5392
6177
  },
5393
6178
  };
5394
6179
  /**
5395
- * TODO: !!!!!! Comment console logs
6180
+ * TODO: !!!!!! Remove console logs
6181
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
5396
6182
  * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5397
6183
  */
5398
6184
 
@@ -5503,6 +6289,7 @@
5503
6289
  */
5504
6290
  parse: function (input) {
5505
6291
  var args = input.args;
6292
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5506
6293
  var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5507
6294
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5508
6295
  throw new ParseError("Invalid joker");
@@ -5632,6 +6419,7 @@
5632
6419
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5633
6420
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5634
6421
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6422
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5635
6423
  }
5636
6424
  else {
5637
6425
  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 ")));
@@ -6708,7 +7496,7 @@
6708
7496
  function extractOneBlockFromMarkdown(markdown) {
6709
7497
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6710
7498
  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 "); }));
7499
+ 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
7500
  }
6713
7501
  return codeBlocks[0];
6714
7502
  }
@@ -7267,70 +8055,6 @@
7267
8055
  * TODO: [🏛] This can be part of markdown builder
7268
8056
  */
7269
8057
 
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
8058
  /**
7335
8059
  * Creates a Mermaid graph based on the promptbook
7336
8060
  *
@@ -7387,6 +8111,9 @@
7387
8111
  return promptbookMermaid;
7388
8112
  }
7389
8113
  /**
8114
+ * TODO: !!!!!! FOREACH in mermaid graph
8115
+ * TODO: !!!!!! Knowledge in mermaid graph
8116
+ * TODO: !!!!!! Personas in mermaid graph
7390
8117
  * TODO: Maybe use some Mermaid package instead of string templating
7391
8118
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
7392
8119
  */
@@ -7528,21 +8255,41 @@
7528
8255
  * @public exported from `@promptbook/core`
7529
8256
  */
7530
8257
  function usageToHuman(usage) {
7531
- var report = 'Usage:';
8258
+ var reportItems = [];
7532
8259
  var uncertainNumberToHuman = function (_a) {
7533
8260
  var value = _a.value, isUncertain = _a.isUncertain;
7534
8261
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7535
8262
  };
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);
8263
+ if (usage.price.value > 0.01
8264
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8265
+ ) {
8266
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8267
+ }
8268
+ else {
8269
+ reportItems.push("Negligible cost");
8270
+ }
8271
+ var worktime = usageToWorktime(usage);
8272
+ if (worktime.value >
8273
+ 1 / 60
8274
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8275
+ ) {
8276
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8277
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8278
+ }
8279
+ if (usage.output.charactersCount.value > 0) {
8280
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8281
+ }
8282
+ if (reportItems.length === 0) {
8283
+ // Note: For negligible usage, we report at least something
8284
+ reportItems.push('Negligible');
8285
+ }
8286
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7539
8287
  }
7540
8288
  /**
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
8289
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8290
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8291
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7544
8292
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7545
- * TODO: When negligible usage, report "Negligible" or just don't report it
7546
8293
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7547
8294
  * TODO: [🏛] Maybe make some markdown builder
7548
8295
  */
@@ -8486,6 +9233,7 @@
8486
9233
  exports.CLAIM = CLAIM;
8487
9234
  exports.CallbackInterfaceTools = CallbackInterfaceTools;
8488
9235
  exports.CollectionError = CollectionError;
9236
+ exports.CsvFormatDefinition = CsvFormatDefinition;
8489
9237
  exports.DEFAULT_REMOTE_URL = DEFAULT_REMOTE_URL;
8490
9238
  exports.DEFAULT_REMOTE_URL_PATH = DEFAULT_REMOTE_URL_PATH;
8491
9239
  exports.ERRORS = ERRORS;
@@ -8514,6 +9262,7 @@
8514
9262
  exports.PrefixStorage = PrefixStorage;
8515
9263
  exports.RESERVED_PARAMETER_NAMES = RESERVED_PARAMETER_NAMES;
8516
9264
  exports.TemplateTypes = TemplateTypes;
9265
+ exports.TextFormatDefinition = TextFormatDefinition;
8517
9266
  exports.UnexpectedError = UnexpectedError;
8518
9267
  exports.ZERO_USAGE = ZERO_USAGE;
8519
9268
  exports._AnthropicClaudeMetadataRegistration = _AnthropicClaudeMetadataRegistration;