@promptbook/core 0.69.0-1 → 0.69.0-10

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 -57
  2. package/esm/index.es.js +1900 -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/esm/typings/src/utils/validators/parameterName/validateParameterName.test.d.ts +1 -0
  48. package/package.json +2 -1
  49. package/umd/index.umd.js +1904 -1172
  50. package/umd/index.umd.js.map +1 -1
  51. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  52. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  53. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  54. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  55. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -2,6 +2,7 @@ import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
2
2
  import { format } from 'prettier';
3
3
  import parserHtml from 'prettier/parser-html';
4
4
  import { forTime } from 'waitasecond';
5
+ import { unparse, parse } from 'papaparse';
5
6
  import hexEncoder from 'crypto-js/enc-hex';
6
7
  import sha256 from 'crypto-js/sha256';
7
8
  import moment from 'moment';
@@ -10,7 +11,7 @@ import moment from 'moment';
10
11
  /**
11
12
  * The version of the Promptbook library
12
13
  */
13
- var PROMPTBOOK_VERSION = '0.69.0-0';
14
+ var PROMPTBOOK_VERSION = '0.69.0-9';
14
15
  // TODO: !!!! List here all the versions and annotate + put into script
15
16
 
16
17
  /*! *****************************************************************************
@@ -652,13 +653,13 @@ var IMMEDIATE_TIME = 10;
652
653
  *
653
654
  * @public exported from `@promptbook/core`
654
655
  */
655
- var MAX_PARALLEL_COUNT = 5;
656
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
656
657
  /**
657
658
  * The maximum number of attempts to execute LLM task before giving up
658
659
  *
659
660
  * @public exported from `@promptbook/core`
660
661
  */
661
- var MAX_EXECUTION_ATTEMPTS = 3;
662
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
662
663
  /**
663
664
  * The maximum length of the (generated) filename
664
665
  *
@@ -709,6 +710,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
709
710
  'samples',
710
711
  'modelName',
711
712
  'currentDate',
713
+ // <- TODO: !!!!! list here all command names
712
714
  // <- TODO: Add more like 'date', 'modelName',...
713
715
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
714
716
  ]);
@@ -752,6 +754,15 @@ var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
752
754
  * @public exported from `@promptbook/core`
753
755
  */
754
756
  var IS_VERBOSE = false;
757
+ /**
758
+ * @@@
759
+ *
760
+ * @private within the repository
761
+ */
762
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
763
+ /**/
764
+ // Note: In normal situations, we check the pipeline logic:
765
+ true);
755
766
  /**
756
767
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
757
768
  */
@@ -961,6 +972,26 @@ function isValidPipelineUrl(url) {
961
972
  * @public exported from `@promptbook/core`
962
973
  */
963
974
  function validatePipeline(pipeline) {
975
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
976
+ validatePipelineCore(pipeline);
977
+ }
978
+ else {
979
+ try {
980
+ validatePipelineCore(pipeline);
981
+ }
982
+ catch (error) {
983
+ if (!(error instanceof PipelineLogicError)) {
984
+ throw error;
985
+ }
986
+ console.error(spaceTrim$1(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 "); }));
987
+ }
988
+ }
989
+ return pipeline;
990
+ }
991
+ /**
992
+ * @private internal function for `validatePipeline`
993
+ */
994
+ function validatePipelineCore(pipeline) {
964
995
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
965
996
  var e_1, _a, e_2, _b, e_3, _c;
966
997
  var pipelineIdentification = (function () {
@@ -985,12 +1016,12 @@ function validatePipeline(pipeline) {
985
1016
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
986
1017
  if (!Array.isArray(pipeline.parameters)) {
987
1018
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
988
- throw new ParseError(spaceTrim$1(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 "); }));
1019
+ throw new ParseError(spaceTrim$1(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 "); }));
989
1020
  }
990
1021
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
991
1022
  if (!Array.isArray(pipeline.templates)) {
992
1023
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
993
- throw new ParseError(spaceTrim$1(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 "); }));
1024
+ throw new ParseError(spaceTrim$1(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 "); }));
994
1025
  }
995
1026
  var _loop_1 = function (parameter) {
996
1027
  if (parameter.isInput && parameter.isOutput) {
@@ -1159,9 +1190,9 @@ function validatePipeline(pipeline) {
1159
1190
  while (unresovedTemplates.length > 0) {
1160
1191
  _loop_3();
1161
1192
  }
1162
- return pipeline;
1163
1193
  }
1164
1194
  /**
1195
+ * TODO: !!!!!! [🧞‍♀️] Do not allow joker + foreach
1165
1196
  * TODO: [🧠] Work with promptbookVersion
1166
1197
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1167
1198
  * > /**
@@ -1788,7 +1819,7 @@ function forEachAsync(array, options, callbackfunction) {
1788
1819
  });
1789
1820
  }
1790
1821
 
1791
- 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"}];
1822
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-9",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-9",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-9",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-9",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"}];
1792
1823
 
1793
1824
  var defaultDiacriticsRemovalMap = [
1794
1825
  {
@@ -2317,113 +2348,35 @@ function assertsExecutionSuccessful(executionResult) {
2317
2348
  */
2318
2349
 
2319
2350
  /**
2320
- * Parses the given script and returns the list of all used variables that are not defined in the script
2321
- *
2322
- * @param script from which to extract the variables
2323
- * @returns the list of variable names
2324
- * @throws {ParseError} if the script is invalid
2325
- * @public exported from `@promptbook/utils`
2326
- */
2327
- function extractVariables(script) {
2328
- var variables = new Set();
2329
- script = "(()=>{".concat(script, "})()");
2330
- try {
2331
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2332
- try {
2333
- eval(script);
2334
- }
2335
- catch (error) {
2336
- if (!(error instanceof ReferenceError)) {
2337
- throw error;
2338
- }
2339
- var undefinedName = error.message.split(' ')[0];
2340
- /*
2341
- Note: Parsing the error
2342
- [PipelineUrlError: thing is not defined]
2343
- */
2344
- if (!undefinedName) {
2345
- throw error;
2346
- }
2347
- if (script.includes(undefinedName + '(')) {
2348
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2349
- }
2350
- else {
2351
- variables.add(undefinedName);
2352
- script = "const ".concat(undefinedName, " = '';") + script;
2353
- }
2354
- }
2355
- }
2356
- catch (error) {
2357
- if (!(error instanceof Error)) {
2358
- throw error;
2359
- }
2360
- throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2361
- }
2362
- return variables;
2363
- }
2364
- /**
2365
- * TODO: [🔣] Support for multiple languages - python, java,...
2366
- */
2367
-
2368
- /**
2369
- * Parses the template and returns the set of all used parameters
2351
+ * Determine if the pipeline is fully prepared
2370
2352
  *
2371
- * @param template the template with used parameters
2372
- * @returns the set of parameter names
2373
- * @throws {ParseError} if the script is invalid
2374
- * @public exported from `@promptbook/utils`
2353
+ * @public exported from `@promptbook/core`
2375
2354
  */
2376
- function extractParameterNamesFromTemplate(template) {
2377
- var e_1, _a, e_2, _b, e_3, _c;
2378
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2379
- var parameterNames = new Set();
2380
- try {
2381
- 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()) {
2382
- var parameterName = _e.value;
2383
- parameterNames.add(parameterName);
2384
- }
2385
- }
2386
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2387
- finally {
2388
- try {
2389
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2390
- }
2391
- finally { if (e_1) throw e_1.error; }
2392
- }
2393
- if (templateType === 'SCRIPT_TEMPLATE') {
2394
- try {
2395
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2396
- var parameterName = _g.value;
2397
- parameterNames.add(parameterName);
2398
- }
2399
- }
2400
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2401
- finally {
2402
- try {
2403
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2404
- }
2405
- finally { if (e_2) throw e_2.error; }
2406
- }
2407
- }
2408
- try {
2409
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2410
- var jokerName = _j.value;
2411
- parameterNames.add(jokerName);
2412
- }
2355
+ function isPipelinePrepared(pipeline) {
2356
+ // Note: Ignoring `pipeline.preparations` @@@
2357
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2358
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2359
+ return false;
2413
2360
  }
2414
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2415
- finally {
2416
- try {
2417
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2418
- }
2419
- finally { if (e_3) throw e_3.error; }
2361
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2362
+ return false;
2420
2363
  }
2421
- parameterNames.delete('content');
2422
- // <- Note {websiteContent} is used in `preparedContent`
2423
- return parameterNames;
2364
+ /*
2365
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2366
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2367
+ > return false;
2368
+ > }
2369
+ */
2370
+ return true;
2424
2371
  }
2425
2372
  /**
2426
- * TODO: [🔣] If script require contentLanguage
2373
+ * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2374
+ * TODO: [🐠] Maybe base this on `makeValidator`
2375
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2376
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2377
+ * - [🏍] ? Is context in each template
2378
+ * - [♨] Are samples prepared
2379
+ * - [♨] Are templates prepared
2427
2380
  */
2428
2381
 
2429
2382
  /**
@@ -2443,27 +2396,6 @@ function serializeError(error) {
2443
2396
  };
2444
2397
  }
2445
2398
 
2446
- /**
2447
- * Function isValidJsonString will tell you if the string is valid JSON or not
2448
- *
2449
- * @public exported from `@promptbook/utils`
2450
- */
2451
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2452
- try {
2453
- JSON.parse(value);
2454
- return true;
2455
- }
2456
- catch (error) {
2457
- if (!(error instanceof Error)) {
2458
- throw error;
2459
- }
2460
- if (error.message.includes('Unexpected token')) {
2461
- return false;
2462
- }
2463
- return false;
2464
- }
2465
- }
2466
-
2467
2399
  /**
2468
2400
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2469
2401
  *
@@ -2758,288 +2690,153 @@ function joinLlmExecutionTools() {
2758
2690
  */
2759
2691
 
2760
2692
  /**
2761
- * Extracts all code blocks from markdown.
2693
+ * Takes an item or an array of items and returns an array of items
2762
2694
  *
2763
- * Note: There are multiple simmilar function:
2764
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2765
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2766
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2767
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2695
+ * 1) Any item except array and undefined returns array with that one item (also null)
2696
+ * 2) Undefined returns empty array
2697
+ * 3) Array returns itself
2768
2698
  *
2769
- * @param markdown any valid markdown
2770
- * @returns code blocks with language and content
2771
- * @throws {ParseError} if block is not closed properly
2772
- * @public exported from `@promptbook/markdown-utils`
2699
+ * @private internal utility
2773
2700
  */
2774
- function extractAllBlocksFromMarkdown(markdown) {
2775
- var e_1, _a;
2776
- var codeBlocks = [];
2777
- var lines = markdown.split('\n');
2778
- // Note: [0] Ensure that the last block notated by gt > will be closed
2779
- lines.push('');
2780
- var currentCodeBlock = null;
2701
+ function arrayableToArray(input) {
2702
+ if (input === undefined) {
2703
+ return [];
2704
+ }
2705
+ if (input instanceof Array) {
2706
+ return input;
2707
+ }
2708
+ return [input];
2709
+ }
2710
+
2711
+ /**
2712
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2713
+ *
2714
+ * @param script from which to extract the variables
2715
+ * @returns the list of variable names
2716
+ * @throws {ParseError} if the script is invalid
2717
+ * @public exported from `@promptbook/utils`
2718
+ */
2719
+ function extractVariables(script) {
2720
+ var variables = new Set();
2721
+ script = "(()=>{".concat(script, "})()");
2781
2722
  try {
2782
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2783
- var line = lines_1_1.value;
2784
- if (line.startsWith('> ') || line === '>') {
2785
- if (currentCodeBlock === null) {
2786
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2787
- } /* not else */
2788
- if (currentCodeBlock.blockNotation === '>') {
2789
- if (currentCodeBlock.content !== '') {
2790
- currentCodeBlock.content += '\n';
2791
- }
2792
- currentCodeBlock.content += line.slice(2);
2793
- }
2794
- }
2795
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2796
- codeBlocks.push(currentCodeBlock);
2797
- currentCodeBlock = null;
2723
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2724
+ try {
2725
+ eval(script);
2798
2726
  }
2799
- /* not else */
2800
- if (line.startsWith('```')) {
2801
- var language = line.slice(3).trim() || null;
2802
- if (currentCodeBlock === null) {
2803
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2727
+ catch (error) {
2728
+ if (!(error instanceof ReferenceError)) {
2729
+ throw error;
2804
2730
  }
2805
- else {
2806
- if (language !== null) {
2807
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2808
- }
2809
- codeBlocks.push(currentCodeBlock);
2810
- currentCodeBlock = null;
2731
+ var undefinedName = error.message.split(' ')[0];
2732
+ /*
2733
+ Note: Parsing the error
2734
+ [PipelineUrlError: thing is not defined]
2735
+ */
2736
+ if (!undefinedName) {
2737
+ throw error;
2811
2738
  }
2812
- }
2813
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2814
- if (currentCodeBlock.content !== '') {
2815
- currentCodeBlock.content += '\n';
2739
+ if (script.includes(undefinedName + '(')) {
2740
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2741
+ }
2742
+ else {
2743
+ variables.add(undefinedName);
2744
+ script = "const ".concat(undefinedName, " = '';") + script;
2816
2745
  }
2817
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2818
2746
  }
2747
+ }
2748
+ catch (error) {
2749
+ if (!(error instanceof Error)) {
2750
+ throw error;
2819
2751
  }
2752
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2820
2753
  }
2821
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2822
- finally {
2823
- try {
2824
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2825
- }
2826
- finally { if (e_1) throw e_1.error; }
2827
- }
2828
- if (currentCodeBlock !== null) {
2829
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2830
- }
2831
- return codeBlocks;
2832
- }
2833
- /**
2834
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2835
- */
2836
-
2837
- /**
2838
- * Extracts extracts exactly one valid JSON code block
2839
- *
2840
- * - When given string is a valid JSON as it is, it just returns it
2841
- * - When there is no JSON code block the function throws a `ParseError`
2842
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2843
- *
2844
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2845
- * Note: There are multiple simmilar function:
2846
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2847
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2848
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2849
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2850
- *
2851
- * @public exported from `@promptbook/markdown-utils`
2852
- * @throws {ParseError} if there is no valid JSON block in the markdown
2853
- */
2854
- function extractJsonBlock(markdown) {
2855
- if (isValidJsonString(markdown)) {
2856
- return markdown;
2857
- }
2858
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2859
- var jsonBlocks = codeBlocks.filter(function (_a) {
2860
- var content = _a.content;
2861
- return isValidJsonString(content);
2862
- });
2863
- if (jsonBlocks.length === 0) {
2864
- throw new Error('There is no valid JSON block in the markdown');
2865
- }
2866
- if (jsonBlocks.length > 1) {
2867
- throw new Error('There are multiple JSON code blocks in the markdown');
2868
- }
2869
- return jsonBlocks[0].content;
2870
- }
2871
- /**
2872
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2873
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2874
- */
2875
-
2876
- /**
2877
- * Determine if the pipeline is fully prepared
2878
- *
2879
- * @public exported from `@promptbook/core`
2880
- */
2881
- function isPipelinePrepared(pipeline) {
2882
- // Note: Ignoring `pipeline.preparations` @@@
2883
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2884
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2885
- return false;
2886
- }
2887
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2888
- return false;
2889
- }
2890
- /*
2891
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2892
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2893
- > return false;
2894
- > }
2895
- */
2896
- return true;
2897
- }
2898
- /**
2899
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2900
- * TODO: [🐠] Maybe base this on `makeValidator`
2901
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2902
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2903
- * - [🏍] ? Is context in each template
2904
- * - [♨] Are samples prepared
2905
- * - [♨] Are templates prepared
2906
- */
2907
-
2908
- /**
2909
- * Takes an item or an array of items and returns an array of items
2910
- *
2911
- * 1) Any item except array and undefined returns array with that one item (also null)
2912
- * 2) Undefined returns empty array
2913
- * 3) Array returns itself
2914
- *
2915
- * @private internal utility
2916
- */
2917
- function arrayableToArray(input) {
2918
- if (input === undefined) {
2919
- return [];
2920
- }
2921
- if (input instanceof Array) {
2922
- return input;
2923
- }
2924
- return [input];
2925
- }
2926
-
2927
- /**
2928
- * Just says that the variable is not used but should be kept
2929
- * No side effects.
2930
- *
2931
- * Note: It can be usefull for:
2932
- *
2933
- * 1) Suppressing eager optimization of unused imports
2934
- * 2) Suppressing eslint errors of unused variables in the tests
2935
- * 3) Keeping the type of the variable for type testing
2936
- *
2937
- * @param value any values
2938
- * @returns void
2939
- * @private within the repository
2940
- */
2941
- function keepUnused() {
2942
- var valuesToKeep = [];
2943
- for (var _i = 0; _i < arguments.length; _i++) {
2944
- valuesToKeep[_i] = arguments[_i];
2945
- }
2754
+ return variables;
2946
2755
  }
2947
-
2948
2756
  /**
2949
- * Just marks a place of place where should be something implemented
2950
- * No side effects.
2951
- *
2952
- * Note: It can be usefull suppressing eslint errors of unused variables
2953
- *
2954
- * @param value any values
2955
- * @returns void
2956
- * @private within the repository
2757
+ * TODO: [🔣] Support for multiple languages - python, java,...
2957
2758
  */
2958
- function TODO_USE() {
2959
- var value = [];
2960
- for (var _i = 0; _i < arguments.length; _i++) {
2961
- value[_i] = arguments[_i];
2962
- }
2963
- }
2964
2759
 
2965
2760
  /**
2966
- * Replaces parameters in template with values from parameters object
2761
+ * Parses the template and returns the set of all used parameters
2967
2762
  *
2968
- * @param template the template with parameters in {curly} braces
2969
- * @param parameters the object with parameters
2970
- * @returns the template with replaced parameters
2971
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2763
+ * @param template the template with used parameters
2764
+ * @returns the set of parameter names
2765
+ * @throws {ParseError} if the script is invalid
2972
2766
  * @public exported from `@promptbook/utils`
2973
2767
  */
2974
- function replaceParameters(template, parameters) {
2975
- var e_1, _a;
2768
+ function extractParameterNamesFromTemplate(template) {
2769
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2770
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2771
+ var parameterNames = new Set();
2976
2772
  try {
2977
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2978
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2979
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2980
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2981
- }
2982
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2983
- // TODO: [🍵]
2984
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2985
- }
2773
+ 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()) {
2774
+ var parameterName = _f.value;
2775
+ parameterNames.add(parameterName);
2986
2776
  }
2987
2777
  }
2988
2778
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2989
2779
  finally {
2990
2780
  try {
2991
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2781
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2992
2782
  }
2993
2783
  finally { if (e_1) throw e_1.error; }
2994
2784
  }
2995
- var replacedTemplate = template;
2996
- var match;
2997
- var loopLimit = LOOP_LIMIT;
2998
- var _loop_1 = function () {
2999
- if (loopLimit-- < 0) {
3000
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2785
+ if (templateType === 'SCRIPT_TEMPLATE') {
2786
+ try {
2787
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2788
+ var parameterName = _h.value;
2789
+ parameterNames.add(parameterName);
2790
+ }
3001
2791
  }
3002
- var precol = match.groups.precol;
3003
- var parameterName = match.groups.parameterName;
3004
- if (parameterName === '') {
3005
- return "continue";
2792
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2793
+ finally {
2794
+ try {
2795
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2796
+ }
2797
+ finally { if (e_2) throw e_2.error; }
3006
2798
  }
3007
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3008
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2799
+ }
2800
+ try {
2801
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2802
+ var jokerName = _k.value;
2803
+ parameterNames.add(jokerName);
3009
2804
  }
3010
- if (parameters[parameterName] === undefined) {
3011
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2805
+ }
2806
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2807
+ finally {
2808
+ try {
2809
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
3012
2810
  }
3013
- var parameterValue = parameters[parameterName];
3014
- if (parameterValue === undefined) {
3015
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2811
+ finally { if (e_3) throw e_3.error; }
2812
+ }
2813
+ parameterNames.delete('content');
2814
+ // <- Note {websiteContent} is used in `preparedContent`
2815
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2816
+ if (foreach !== undefined) {
2817
+ try {
2818
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2819
+ var subparameterName = _m.value;
2820
+ if (parameterNames.has(subparameterName)) {
2821
+ parameterNames.delete(subparameterName);
2822
+ parameterNames.add(foreach.parameterName);
2823
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2824
+ }
2825
+ }
3016
2826
  }
3017
- parameterValue = parameterValue.toString();
3018
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3019
- parameterValue = parameterValue
3020
- .split('\n')
3021
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3022
- .join('\n');
2827
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2828
+ finally {
2829
+ try {
2830
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2831
+ }
2832
+ finally { if (e_4) throw e_4.error; }
3023
2833
  }
3024
- replacedTemplate =
3025
- replacedTemplate.substring(0, match.index + precol.length) +
3026
- parameterValue +
3027
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3028
- };
3029
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3030
- .exec(replacedTemplate))) {
3031
- _loop_1();
3032
2834
  }
3033
- // [💫] Check if there are parameters that are not closed properly
3034
- if (/{\w+$/.test(replacedTemplate)) {
3035
- throw new PipelineExecutionError('Parameter is not closed');
3036
- }
3037
- // [💫] Check if there are parameters that are not opened properly
3038
- if (/^\w+}/.test(replacedTemplate)) {
3039
- throw new PipelineExecutionError('Parameter is not opened');
3040
- }
3041
- return replacedTemplate;
2835
+ return parameterNames;
3042
2836
  }
2837
+ /**
2838
+ * TODO: [🔣] If script require contentLanguage
2839
+ */
3043
2840
 
3044
2841
  /**
3045
2842
  * Create difference set of two sets.
@@ -3117,117 +2914,348 @@ function union() {
3117
2914
  }
3118
2915
 
3119
2916
  /**
3120
- * Counts number of characters in the text
2917
+ * Just marks a place of place where should be something implemented
2918
+ * No side effects.
3121
2919
  *
3122
- * @public exported from `@promptbook/utils`
3123
- */
3124
- function countCharacters(text) {
3125
- // Remove null characters
3126
- text = text.replace(/\0/g, '');
3127
- // Replace emojis (and also ZWJ sequence) with hyphens
3128
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3129
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3130
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3131
- return text.length;
3132
- }
3133
-
3134
- /**
3135
- * Counts number of lines in the text
2920
+ * Note: It can be usefull suppressing eslint errors of unused variables
3136
2921
  *
3137
- * @public exported from `@promptbook/utils`
2922
+ * @param value any values
2923
+ * @returns void
2924
+ * @private within the repository
3138
2925
  */
3139
- function countLines(text) {
3140
- if (text === '') {
3141
- return 0;
2926
+ function TODO_USE() {
2927
+ var value = [];
2928
+ for (var _i = 0; _i < arguments.length; _i++) {
2929
+ value[_i] = arguments[_i];
3142
2930
  }
3143
- return text.split('\n').length;
3144
2931
  }
3145
2932
 
3146
2933
  /**
3147
- * Counts number of pages in the text
2934
+ * Definition for CSV spreadsheet
3148
2935
  *
3149
- * @public exported from `@promptbook/utils`
2936
+ * @public exported from `@promptbook/core`
2937
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2938
+ */
2939
+ var CsvFormatDefinition = {
2940
+ formatName: 'CSV',
2941
+ aliases: ['SPREADSHEET', 'TABLE'],
2942
+ isValid: function (value, schema) {
2943
+ TODO_USE(value /* <- TODO: Use value here */);
2944
+ TODO_USE(schema /* <- TODO: Use schema here */);
2945
+ return true;
2946
+ },
2947
+ canBeValid: function (partialValue, schema) {
2948
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2949
+ TODO_USE(schema /* <- TODO: Use schema here */);
2950
+ return true;
2951
+ },
2952
+ heal: function (value, schema) {
2953
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2954
+ TODO_USE(schema /* <- TODO: Use schema here */);
2955
+ throw new Error('Not implemented');
2956
+ },
2957
+ subvalueDefinitions: [
2958
+ {
2959
+ subvalueName: 'ROW',
2960
+ mapValues: function (value, mapCallback) {
2961
+ return __awaiter(this, void 0, void 0, function () {
2962
+ var csv, mappedData;
2963
+ return __generator(this, function (_a) {
2964
+ switch (_a.label) {
2965
+ case 0:
2966
+ csv = parse(value, {
2967
+ header: true,
2968
+ delimiter: ',',
2969
+ quoteChar: '"',
2970
+ newline: '\r\n',
2971
+ skipEmptyLines: true,
2972
+ // encoding: 'utf8',
2973
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2974
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2975
+ });
2976
+ if (csv.errors.length !== 0) {
2977
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2978
+ spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2979
+ }
2980
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { /*not await */ return mapCallback(row, index); }))];
2981
+ case 1:
2982
+ mappedData = _a.sent();
2983
+ return [2 /*return*/, unparse(mappedData, {
2984
+ header: true,
2985
+ delimiter: ',',
2986
+ quoteChar: '"',
2987
+ newline: '\r\n',
2988
+ skipEmptyLines: true,
2989
+ // encoding: 'utf8',
2990
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2991
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2992
+ })];
2993
+ }
2994
+ });
2995
+ });
2996
+ },
2997
+ },
2998
+ {
2999
+ subvalueName: 'CELL',
3000
+ mapValues: function (value, mapCallback) {
3001
+ return __awaiter(this, void 0, void 0, function () {
3002
+ var csv, mappedData;
3003
+ var _this = this;
3004
+ return __generator(this, function (_a) {
3005
+ switch (_a.label) {
3006
+ case 0:
3007
+ csv = parse(value, {
3008
+ header: true,
3009
+ delimiter: ',',
3010
+ quoteChar: '"',
3011
+ newline: '\r\n',
3012
+ skipEmptyLines: true,
3013
+ // encoding: 'utf8',
3014
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3015
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3016
+ });
3017
+ if (csv.errors.length !== 0) {
3018
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3019
+ spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
3020
+ }
3021
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3022
+ var _this = this;
3023
+ return __generator(this, function (_a) {
3024
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
3025
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
3026
+ return __awaiter(_this, void 0, void 0, function () {
3027
+ var index;
3028
+ var _c;
3029
+ return __generator(this, function (_d) {
3030
+ index = rowIndex * Object.keys(row).length + columnIndex;
3031
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
3032
+ });
3033
+ });
3034
+ }))];
3035
+ });
3036
+ }); }))];
3037
+ case 1:
3038
+ mappedData = _a.sent();
3039
+ return [2 /*return*/, unparse(mappedData, {
3040
+ header: true,
3041
+ delimiter: ',',
3042
+ quoteChar: '"',
3043
+ newline: '\r\n',
3044
+ skipEmptyLines: true,
3045
+ // encoding: 'utf8',
3046
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3047
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3048
+ })];
3049
+ }
3050
+ });
3051
+ });
3052
+ },
3053
+ },
3054
+ ],
3055
+ };
3056
+ /**
3057
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
3058
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
3059
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
3060
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
3061
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3150
3062
  */
3151
- function countPages(text) {
3152
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
3153
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3154
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3155
- return pageCount;
3156
- }
3157
3063
 
3158
3064
  /**
3159
- * Counts number of paragraphs in the text
3065
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3160
3066
  *
3161
3067
  * @public exported from `@promptbook/utils`
3162
3068
  */
3163
- function countParagraphs(text) {
3164
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3069
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
3070
+ try {
3071
+ JSON.parse(value);
3072
+ return true;
3073
+ }
3074
+ catch (error) {
3075
+ if (!(error instanceof Error)) {
3076
+ throw error;
3077
+ }
3078
+ if (error.message.includes('Unexpected token')) {
3079
+ return false;
3080
+ }
3081
+ return false;
3082
+ }
3165
3083
  }
3166
3084
 
3167
3085
  /**
3168
- * Split text into sentences
3086
+ * Definition for JSON format
3169
3087
  *
3170
- * @public exported from `@promptbook/utils`
3088
+ * @private still in development [🏢]
3171
3089
  */
3172
- function splitIntoSentences(text) {
3173
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3174
- }
3090
+ var JsonFormatDefinition = {
3091
+ formatName: 'JSON',
3092
+ mimeType: 'application/json',
3093
+ isValid: function (value, schema) {
3094
+ TODO_USE(schema /* <- TODO: Use schema here */);
3095
+ return isValidJsonString(value);
3096
+ },
3097
+ canBeValid: function (partialValue, schema) {
3098
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3099
+ TODO_USE(schema /* <- TODO: Use schema here */);
3100
+ return true;
3101
+ },
3102
+ heal: function (value, schema) {
3103
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3104
+ TODO_USE(schema /* <- TODO: Use schema here */);
3105
+ throw new Error('Not implemented');
3106
+ },
3107
+ subvalueDefinitions: [],
3108
+ };
3175
3109
  /**
3176
- * Counts number of sentences in the text
3177
- *
3178
- * @public exported from `@promptbook/utils`
3110
+ * TODO: [🧠] Maybe propper instance of object
3111
+ * TODO: [0] Make string_serialized_json
3112
+ * TODO: [1] Make type for JSON Schema
3113
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3114
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3115
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3116
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3117
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3118
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3179
3119
  */
3180
- function countSentences(text) {
3181
- return splitIntoSentences(text).length;
3182
- }
3183
3120
 
3184
3121
  /**
3185
- * Counts number of words in the text
3122
+ * Definition for any text - this will be always valid
3186
3123
  *
3187
- * @public exported from `@promptbook/utils`
3124
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3125
+ *
3126
+ * @public exported from `@promptbook/core`
3127
+ */
3128
+ var TextFormatDefinition = {
3129
+ formatName: 'TEXT',
3130
+ isValid: function (value) {
3131
+ return typeof value === 'string';
3132
+ },
3133
+ canBeValid: function (partialValue) {
3134
+ return typeof partialValue === 'string';
3135
+ },
3136
+ heal: function () {
3137
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3138
+ },
3139
+ subvalueDefinitions: [
3140
+ {
3141
+ subvalueName: 'LINE',
3142
+ mapValues: function (value, mapCallback) {
3143
+ return __awaiter(this, void 0, void 0, function () {
3144
+ var lines, mappedLines;
3145
+ return __generator(this, function (_a) {
3146
+ switch (_a.label) {
3147
+ case 0:
3148
+ lines = value.split('\n');
3149
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3150
+ // TODO: [🧠] Maybe option to skip empty line
3151
+ /* not await */ return mapCallback({
3152
+ lineContent: lineContent,
3153
+ // TODO: [🧠] Maybe also put here `lineNumber`
3154
+ }, lineNumber);
3155
+ }))];
3156
+ case 1:
3157
+ mappedLines = _a.sent();
3158
+ return [2 /*return*/, mappedLines.join('\n')];
3159
+ }
3160
+ });
3161
+ });
3162
+ },
3163
+ },
3164
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3165
+ ],
3166
+ };
3167
+ /**
3168
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3169
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3170
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3171
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3172
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3173
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3188
3174
  */
3189
- function countWords(text) {
3190
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3191
- text = removeDiacritics(text);
3192
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3193
- }
3194
3175
 
3195
3176
  /**
3196
- * Index of all counter functions
3177
+ * Definition for XML format
3197
3178
  *
3198
- * @public exported from `@promptbook/utils`
3179
+ * @private still in development [🏢]
3199
3180
  */
3200
- var CountUtils = {
3201
- CHARACTERS: countCharacters,
3202
- WORDS: countWords,
3203
- SENTENCES: countSentences,
3204
- PARAGRAPHS: countParagraphs,
3205
- LINES: countLines,
3206
- PAGES: countPages,
3181
+ var XmlFormatDefinition = {
3182
+ formatName: 'XML',
3183
+ mimeType: 'application/xml',
3184
+ isValid: function (value, schema) {
3185
+ TODO_USE(value /* <- TODO: Use value here */);
3186
+ TODO_USE(schema /* <- TODO: Use schema here */);
3187
+ return true;
3188
+ },
3189
+ canBeValid: function (partialValue, schema) {
3190
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3191
+ TODO_USE(schema /* <- TODO: Use schema here */);
3192
+ return true;
3193
+ },
3194
+ heal: function (value, schema) {
3195
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3196
+ TODO_USE(schema /* <- TODO: Use schema here */);
3197
+ throw new Error('Not implemented');
3198
+ },
3199
+ subvalueDefinitions: [],
3207
3200
  };
3201
+ /**
3202
+ * TODO: [🧠] Maybe propper instance of object
3203
+ * TODO: [0] Make string_serialized_xml
3204
+ * TODO: [1] Make type for XML Schema
3205
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3206
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3207
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3208
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3209
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3210
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3211
+ */
3208
3212
 
3209
3213
  /**
3210
- * Function checkExpectations will check if the expectations on given value are met
3214
+ * Definitions for all formats supported by Promptbook
3211
3215
  *
3212
- * Note: There are two simmilar functions:
3213
- * - `checkExpectations` which throws an error if the expectations are not met
3214
- * - `isPassingExpectations` which returns a boolean
3216
+ * @private internal index of `...` <- TODO [🏢]
3217
+ */
3218
+ var FORMAT_DEFINITIONS = [
3219
+ JsonFormatDefinition,
3220
+ XmlFormatDefinition,
3221
+ TextFormatDefinition,
3222
+ CsvFormatDefinition,
3223
+ ];
3224
+
3225
+ /**
3226
+ * Maps available parameters to expected parameters
3215
3227
  *
3216
- * @throws {ExpectError} if the expectations are not met
3217
- * @returns {void} Nothing
3218
- * @private internal function of `createPipelineExecutor`
3228
+ * The strategy is:
3229
+ * 1) @@@
3230
+ * 2) @@@
3231
+ *
3232
+ * @throws {PipelineExecutionError} @@@
3233
+ * @private within the repository used in `createPipelineExecutor`
3219
3234
  */
3220
- function checkExpectations(expectations, value) {
3235
+ function mapAvailableToExpectedParameters(options) {
3221
3236
  var e_1, _a;
3237
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3238
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3239
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3240
+ var mappedParameters = {};
3222
3241
  try {
3223
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3224
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3225
- var amount = CountUtils[unit.toUpperCase()](value);
3226
- if (min && amount < min) {
3227
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3228
- } /* not else */
3229
- if (max && amount > max) {
3230
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3242
+ // Phase 1️⃣: Matching mapping
3243
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3244
+ var parameterName = _c.value;
3245
+ // Situation: Parameter is available and expected
3246
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3247
+ mappedParameters[parameterName] = availableParameters[parameterName];
3248
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3249
+ availableParametersNames.delete(parameterName);
3250
+ expectedParameterNames.delete(parameterName);
3251
+ }
3252
+ // Situation: Parameter is available but NOT expected
3253
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3254
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3255
+ }
3256
+ // Situation: Parameter is NOT available BUT expected
3257
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3258
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3231
3259
  }
3232
3260
  }
3233
3261
  }
@@ -3238,622 +3266,1145 @@ function checkExpectations(expectations, value) {
3238
3266
  }
3239
3267
  finally { if (e_1) throw e_1.error; }
3240
3268
  }
3269
+ if (expectedParameterNames.size === 0) {
3270
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3271
+ Object.freeze(mappedParameters);
3272
+ return mappedParameters;
3273
+ }
3274
+ // Phase 2️⃣: Non-matching mapping
3275
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3276
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3277
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3278
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3279
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3280
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3281
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3282
+ .join('\n')), "\n\n "); }));
3283
+ }
3284
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3285
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3286
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3287
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3288
+ }
3289
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3290
+ Object.freeze(mappedParameters);
3291
+ return mappedParameters;
3241
3292
  }
3293
+
3242
3294
  /**
3243
- * Function checkExpectations will check if the expectations on given value are met
3295
+ * Extracts all code blocks from markdown.
3244
3296
  *
3245
- * Note: There are two simmilar functions:
3246
- * - `checkExpectations` which throws an error if the expectations are not met
3247
- * - `isPassingExpectations` which returns a boolean
3297
+ * Note: There are multiple simmilar function:
3298
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3299
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3300
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3301
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3248
3302
  *
3249
- * @returns {boolean} True if the expectations are met
3250
- * @public exported from `@promptbook/core`
3303
+ * @param markdown any valid markdown
3304
+ * @returns code blocks with language and content
3305
+ * @throws {ParseError} if block is not closed properly
3306
+ * @public exported from `@promptbook/markdown-utils`
3251
3307
  */
3252
- function isPassingExpectations(expectations, value) {
3308
+ function extractAllBlocksFromMarkdown(markdown) {
3309
+ var e_1, _a;
3310
+ var codeBlocks = [];
3311
+ var lines = markdown.split('\n');
3312
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3313
+ lines.push('');
3314
+ var currentCodeBlock = null;
3253
3315
  try {
3254
- checkExpectations(expectations, value);
3255
- return true;
3316
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3317
+ var line = lines_1_1.value;
3318
+ if (line.startsWith('> ') || line === '>') {
3319
+ if (currentCodeBlock === null) {
3320
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3321
+ } /* not else */
3322
+ if (currentCodeBlock.blockNotation === '>') {
3323
+ if (currentCodeBlock.content !== '') {
3324
+ currentCodeBlock.content += '\n';
3325
+ }
3326
+ currentCodeBlock.content += line.slice(2);
3327
+ }
3328
+ }
3329
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3330
+ codeBlocks.push(currentCodeBlock);
3331
+ currentCodeBlock = null;
3332
+ }
3333
+ /* not else */
3334
+ if (line.startsWith('```')) {
3335
+ var language = line.slice(3).trim() || null;
3336
+ if (currentCodeBlock === null) {
3337
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3338
+ }
3339
+ else {
3340
+ if (language !== null) {
3341
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3342
+ }
3343
+ codeBlocks.push(currentCodeBlock);
3344
+ currentCodeBlock = null;
3345
+ }
3346
+ }
3347
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3348
+ if (currentCodeBlock.content !== '') {
3349
+ currentCodeBlock.content += '\n';
3350
+ }
3351
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3352
+ }
3353
+ }
3256
3354
  }
3257
- catch (error) {
3258
- if (!(error instanceof ExpectError)) {
3259
- throw error;
3355
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3356
+ finally {
3357
+ try {
3358
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3260
3359
  }
3261
- return false;
3360
+ finally { if (e_1) throw e_1.error; }
3262
3361
  }
3362
+ if (currentCodeBlock !== null) {
3363
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3364
+ }
3365
+ return codeBlocks;
3263
3366
  }
3264
3367
  /**
3265
- * TODO: [💝] Unite object for expecting amount and format
3368
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3266
3369
  */
3267
3370
 
3268
3371
  /**
3269
- * Creates executor function from pipeline and execution tools.
3372
+ * Extracts extracts exactly one valid JSON code block
3270
3373
  *
3271
- * @returns The executor function
3272
- * @throws {PipelineLogicError} on logical error in the pipeline
3273
- * @public exported from `@promptbook/core`
3374
+ * - When given string is a valid JSON as it is, it just returns it
3375
+ * - When there is no JSON code block the function throws a `ParseError`
3376
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3377
+ *
3378
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3379
+ * Note: There are multiple simmilar function:
3380
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3381
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3382
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3383
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3384
+ *
3385
+ * @public exported from `@promptbook/markdown-utils`
3386
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3274
3387
  */
3275
- function createPipelineExecutor(options) {
3276
- var _this = this;
3277
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3278
- 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;
3279
- validatePipeline(pipeline);
3280
- var pipelineIdentification = (function () {
3281
- // Note: This is a 😐 implementation of [🚞]
3282
- var _ = [];
3283
- if (pipeline.sourceFile !== undefined) {
3284
- _.push("File: ".concat(pipeline.sourceFile));
3285
- }
3286
- if (pipeline.pipelineUrl !== undefined) {
3287
- _.push("Url: ".concat(pipeline.pipelineUrl));
3288
- }
3289
- return _.join('\n');
3290
- })();
3291
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3292
- var preparedPipeline;
3293
- if (isPipelinePrepared(pipeline)) {
3294
- preparedPipeline = pipeline;
3295
- }
3296
- else if (isNotPreparedWarningSupressed !== true) {
3297
- console.warn(spaceTrim$1(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 "); }));
3388
+ function extractJsonBlock(markdown) {
3389
+ if (isValidJsonString(markdown)) {
3390
+ return markdown;
3298
3391
  }
3299
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3300
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3301
- function getContextForTemplate(template) {
3302
- return __awaiter(this, void 0, void 0, function () {
3303
- return __generator(this, function (_a) {
3304
- TODO_USE(template);
3305
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3306
- });
3307
- });
3392
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3393
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3394
+ var content = _a.content;
3395
+ return isValidJsonString(content);
3396
+ });
3397
+ if (jsonBlocks.length === 0) {
3398
+ throw new Error('There is no valid JSON block in the markdown');
3399
+ }
3400
+ if (jsonBlocks.length > 1) {
3401
+ throw new Error('There are multiple JSON code blocks in the markdown');
3402
+ }
3403
+ return jsonBlocks[0].content;
3404
+ }
3405
+ /**
3406
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3407
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3408
+ */
3409
+
3410
+ /**
3411
+ * Just says that the variable is not used but should be kept
3412
+ * No side effects.
3413
+ *
3414
+ * Note: It can be usefull for:
3415
+ *
3416
+ * 1) Suppressing eager optimization of unused imports
3417
+ * 2) Suppressing eslint errors of unused variables in the tests
3418
+ * 3) Keeping the type of the variable for type testing
3419
+ *
3420
+ * @param value any values
3421
+ * @returns void
3422
+ * @private within the repository
3423
+ */
3424
+ function keepUnused() {
3425
+ var valuesToKeep = [];
3426
+ for (var _i = 0; _i < arguments.length; _i++) {
3427
+ valuesToKeep[_i] = arguments[_i];
3428
+ }
3429
+ }
3430
+
3431
+ /**
3432
+ * Replaces parameters in template with values from parameters object
3433
+ *
3434
+ * @param template the template with parameters in {curly} braces
3435
+ * @param parameters the object with parameters
3436
+ * @returns the template with replaced parameters
3437
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3438
+ * @public exported from `@promptbook/utils`
3439
+ */
3440
+ function replaceParameters(template, parameters) {
3441
+ var e_1, _a;
3442
+ try {
3443
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3444
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3445
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3446
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3447
+ }
3448
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3449
+ // TODO: [🍵]
3450
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3451
+ }
3308
3452
  }
3309
- function getKnowledgeForTemplate(template) {
3310
- return __awaiter(this, void 0, void 0, function () {
3311
- return __generator(this, function (_a) {
3312
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3313
- TODO_USE(template);
3314
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3315
- var content = _a.content;
3316
- return "- ".concat(content);
3317
- }).join('\n')];
3318
- });
3319
- });
3453
+ }
3454
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3455
+ finally {
3456
+ try {
3457
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3320
3458
  }
3321
- function getSamplesForTemplate(template) {
3322
- return __awaiter(this, void 0, void 0, function () {
3323
- return __generator(this, function (_a) {
3324
- // TODO: [♨] Implement Better - use real index and keyword search
3325
- TODO_USE(template);
3326
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3327
- });
3328
- });
3459
+ finally { if (e_1) throw e_1.error; }
3460
+ }
3461
+ var replacedTemplate = template;
3462
+ var match;
3463
+ var loopLimit = LOOP_LIMIT;
3464
+ var _loop_1 = function () {
3465
+ if (loopLimit-- < 0) {
3466
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3329
3467
  }
3330
- function getReservedParametersForTemplate(template) {
3331
- return __awaiter(this, void 0, void 0, function () {
3332
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3333
- var e_3, _a;
3334
- return __generator(this, function (_b) {
3335
- switch (_b.label) {
3336
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3337
- case 1:
3338
- context = _b.sent();
3339
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3340
- case 2:
3341
- knowledge = _b.sent();
3342
- return [4 /*yield*/, getSamplesForTemplate(template)];
3343
- case 3:
3344
- samples = _b.sent();
3345
- currentDate = new Date().toISOString();
3346
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3347
- reservedParameters = {
3348
- content: RESERVED_PARAMETER_RESTRICTED,
3349
- context: context,
3350
- knowledge: knowledge,
3351
- samples: samples,
3352
- currentDate: currentDate,
3353
- modelName: modelName,
3354
- };
3355
- _loop_3 = function (parameterName) {
3356
- if (reservedParameters[parameterName] === undefined) {
3357
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3358
- }
3359
- };
3360
- try {
3361
- // Note: Doublecheck that ALL reserved parameters are defined:
3362
- 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()) {
3363
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3364
- _loop_3(parameterName);
3365
- }
3366
- }
3367
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3368
- finally {
3369
- try {
3370
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3371
- }
3372
- finally { if (e_3) throw e_3.error; }
3373
- }
3374
- return [2 /*return*/, reservedParameters];
3375
- }
3376
- });
3377
- });
3468
+ var precol = match.groups.precol;
3469
+ var parameterName = match.groups.parameterName;
3470
+ if (parameterName === '') {
3471
+ return "continue";
3472
+ }
3473
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3474
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3475
+ }
3476
+ if (parameters[parameterName] === undefined) {
3477
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3478
+ }
3479
+ var parameterValue = parameters[parameterName];
3480
+ if (parameterValue === undefined) {
3481
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3482
+ }
3483
+ parameterValue = parameterValue.toString();
3484
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3485
+ parameterValue = parameterValue
3486
+ .split('\n')
3487
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3488
+ .join('\n');
3489
+ }
3490
+ replacedTemplate =
3491
+ replacedTemplate.substring(0, match.index + precol.length) +
3492
+ parameterValue +
3493
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3494
+ };
3495
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3496
+ .exec(replacedTemplate))) {
3497
+ _loop_1();
3498
+ }
3499
+ // [💫] Check if there are parameters that are not closed properly
3500
+ if (/{\w+$/.test(replacedTemplate)) {
3501
+ throw new PipelineExecutionError('Parameter is not closed');
3502
+ }
3503
+ // [💫] Check if there are parameters that are not opened properly
3504
+ if (/^\w+}/.test(replacedTemplate)) {
3505
+ throw new PipelineExecutionError('Parameter is not opened');
3506
+ }
3507
+ return replacedTemplate;
3508
+ }
3509
+
3510
+ /**
3511
+ * Counts number of characters in the text
3512
+ *
3513
+ * @public exported from `@promptbook/utils`
3514
+ */
3515
+ function countCharacters(text) {
3516
+ // Remove null characters
3517
+ text = text.replace(/\0/g, '');
3518
+ // Replace emojis (and also ZWJ sequence) with hyphens
3519
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3520
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3521
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3522
+ return text.length;
3523
+ }
3524
+
3525
+ /**
3526
+ * Counts number of lines in the text
3527
+ *
3528
+ * @public exported from `@promptbook/utils`
3529
+ */
3530
+ function countLines(text) {
3531
+ if (text === '') {
3532
+ return 0;
3533
+ }
3534
+ return text.split('\n').length;
3535
+ }
3536
+
3537
+ /**
3538
+ * Counts number of pages in the text
3539
+ *
3540
+ * @public exported from `@promptbook/utils`
3541
+ */
3542
+ function countPages(text) {
3543
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3544
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3545
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3546
+ return pageCount;
3547
+ }
3548
+
3549
+ /**
3550
+ * Counts number of paragraphs in the text
3551
+ *
3552
+ * @public exported from `@promptbook/utils`
3553
+ */
3554
+ function countParagraphs(text) {
3555
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3556
+ }
3557
+
3558
+ /**
3559
+ * Split text into sentences
3560
+ *
3561
+ * @public exported from `@promptbook/utils`
3562
+ */
3563
+ function splitIntoSentences(text) {
3564
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3565
+ }
3566
+ /**
3567
+ * Counts number of sentences in the text
3568
+ *
3569
+ * @public exported from `@promptbook/utils`
3570
+ */
3571
+ function countSentences(text) {
3572
+ return splitIntoSentences(text).length;
3573
+ }
3574
+
3575
+ /**
3576
+ * Counts number of words in the text
3577
+ *
3578
+ * @public exported from `@promptbook/utils`
3579
+ */
3580
+ function countWords(text) {
3581
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3582
+ text = removeDiacritics(text);
3583
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3584
+ }
3585
+
3586
+ /**
3587
+ * Index of all counter functions
3588
+ *
3589
+ * @public exported from `@promptbook/utils`
3590
+ */
3591
+ var CountUtils = {
3592
+ CHARACTERS: countCharacters,
3593
+ WORDS: countWords,
3594
+ SENTENCES: countSentences,
3595
+ PARAGRAPHS: countParagraphs,
3596
+ LINES: countLines,
3597
+ PAGES: countPages,
3598
+ };
3599
+ /**
3600
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3601
+ */
3602
+
3603
+ /**
3604
+ * Function checkExpectations will check if the expectations on given value are met
3605
+ *
3606
+ * Note: There are two simmilar functions:
3607
+ * - `checkExpectations` which throws an error if the expectations are not met
3608
+ * - `isPassingExpectations` which returns a boolean
3609
+ *
3610
+ * @throws {ExpectError} if the expectations are not met
3611
+ * @returns {void} Nothing
3612
+ * @private internal function of `createPipelineExecutor`
3613
+ */
3614
+ function checkExpectations(expectations, value) {
3615
+ var e_1, _a;
3616
+ try {
3617
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3618
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3619
+ var amount = CountUtils[unit.toUpperCase()](value);
3620
+ if (min && amount < min) {
3621
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3622
+ } /* not else */
3623
+ if (max && amount > max) {
3624
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3625
+ }
3626
+ }
3627
+ }
3628
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3629
+ finally {
3630
+ try {
3631
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3632
+ }
3633
+ finally { if (e_1) throw e_1.error; }
3634
+ }
3635
+ }
3636
+ /**
3637
+ * Function checkExpectations will check if the expectations on given value are met
3638
+ *
3639
+ * Note: There are two simmilar functions:
3640
+ * - `checkExpectations` which throws an error if the expectations are not met
3641
+ * - `isPassingExpectations` which returns a boolean
3642
+ *
3643
+ * @returns {boolean} True if the expectations are met
3644
+ * @public exported from `@promptbook/core`
3645
+ */
3646
+ function isPassingExpectations(expectations, value) {
3647
+ try {
3648
+ checkExpectations(expectations, value);
3649
+ return true;
3650
+ }
3651
+ catch (error) {
3652
+ if (!(error instanceof ExpectError)) {
3653
+ throw error;
3378
3654
  }
3379
- function executeSingleTemplate(currentTemplate) {
3380
- return __awaiter(this, void 0, void 0, function () {
3381
- 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;
3382
- var e_4, _f, _g;
3383
- return __generator(this, function (_h) {
3384
- switch (_h.label) {
3385
- case 0:
3386
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3387
- title = currentTemplate.title;
3388
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3389
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3390
- progress_1 = {
3391
- name: name,
3392
- title: title,
3393
- isStarted: false,
3394
- isDone: false,
3395
- templateType: currentTemplate.templateType,
3396
- parameterName: currentTemplate.resultingParameterName,
3397
- parameterValue: null,
3398
- // <- [3]
3399
- };
3400
- if (isReturned) {
3401
- throw new UnexpectedError(spaceTrim$1(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)
3402
- .split('\n')
3403
- .map(function (line) { return "> ".concat(line); })
3404
- .join('\n')), "\n "); }));
3405
- }
3406
- return [4 /*yield*/, onProgress(progress_1)];
3407
- case 1:
3408
- _h.sent();
3409
- _h.label = 2;
3410
- case 2:
3411
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3412
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3413
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3414
- throw new UnexpectedError(spaceTrim$1(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)
3415
- .map(function (name) { return "{".concat(name, "}"); })
3416
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3417
- .map(function (name) { return "{".concat(name, "}"); })
3418
- .join(', '), "\n\n "); }));
3419
- }
3420
- _b = (_a = Object).freeze;
3421
- _c = [{}];
3422
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3423
- case 3:
3424
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3425
- definedParameterNames = new Set(Object.keys(definedParameters));
3426
- parameters = {};
3427
- _loop_4 = function (parameterName) {
3428
- // Situation: Parameter is defined and used
3429
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3430
- parameters[parameterName] = definedParameters[parameterName];
3431
- }
3432
- // Situation: Parameter is defined but NOT used
3433
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3434
- // Situation: Parameter is NOT defined BUT used
3435
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3436
- // Houston, we have a problem
3437
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3438
- throw new UnexpectedError(spaceTrim$1(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 "); }));
3439
- }
3440
- };
3441
- try {
3442
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3443
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3444
- parameterName = _e.value;
3445
- _loop_4(parameterName);
3446
- }
3447
- }
3448
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3449
- finally {
3450
- try {
3451
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3452
- }
3453
- finally { if (e_4) throw e_4.error; }
3454
- }
3455
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3456
- Object.freeze(parameters);
3457
- result = null;
3458
- resultString = null;
3459
- expectError = null;
3460
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3461
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3462
- preparedContent = (currentTemplate.preparedContent || '{content}')
3463
- .split('{content}')
3464
- .join(currentTemplate.content);
3465
- _loop_5 = function (attempt) {
3466
- 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;
3467
- var e_5, _s, e_7, _t, e_6, _u;
3468
- return __generator(this, function (_v) {
3469
- switch (_v.label) {
3470
- case 0:
3471
- isJokerAttempt = attempt < 0;
3472
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3473
- if (isJokerAttempt && !jokerParameterName) {
3474
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3475
- }
3476
- result = null;
3477
- resultString = null;
3478
- expectError = null;
3479
- if (isJokerAttempt) {
3480
- if (parameters[jokerParameterName] === undefined) {
3481
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3482
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3483
- }
3484
- else {
3485
- resultString = parameters[jokerParameterName];
3486
- }
3487
- }
3488
- _v.label = 1;
3489
- case 1:
3490
- _v.trys.push([1, 44, 45, 46]);
3491
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3492
- _j = currentTemplate.templateType;
3493
- switch (_j) {
3494
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3495
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3496
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3497
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3498
- }
3499
- return [3 /*break*/, 25];
3500
- case 2:
3501
- resultString = replaceParameters(preparedContent, parameters);
3502
- return [3 /*break*/, 26];
3503
- case 3:
3504
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3505
- prompt = {
3506
- title: currentTemplate.title,
3507
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3508
- ? preparedPipeline.pipelineUrl
3509
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3510
- parameters: parameters,
3511
- content: preparedContent,
3512
- modelRequirements: modelRequirements,
3513
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3514
- var name = _a.name;
3515
- return name === currentTemplate.personaName;
3516
- }) || {})), currentTemplate.expectations),
3517
- format: currentTemplate.format,
3518
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3519
- }; // <- TODO: Not very good type guard
3520
- _k = modelRequirements.modelVariant;
3521
- switch (_k) {
3522
- case 'CHAT': return [3 /*break*/, 4];
3523
- case 'COMPLETION': return [3 /*break*/, 6];
3524
- case 'EMBEDDING': return [3 /*break*/, 8];
3525
- }
3526
- return [3 /*break*/, 10];
3527
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3528
- case 5:
3529
- chatResult = _v.sent();
3530
- // TODO: [🍬] Destroy chatThread
3531
- result = chatResult;
3532
- resultString = chatResult.content;
3533
- return [3 /*break*/, 11];
3534
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3535
- case 7:
3536
- completionResult = _v.sent();
3537
- result = completionResult;
3538
- resultString = completionResult.content;
3539
- return [3 /*break*/, 11];
3540
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3541
- case 9:
3542
- embeddingResult = _v.sent();
3543
- result = embeddingResult;
3544
- resultString = embeddingResult.content.join(',');
3545
- return [3 /*break*/, 11];
3546
- case 10: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3547
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3548
- case 11: return [3 /*break*/, 26];
3549
- case 12:
3550
- if (arrayableToArray(tools.script).length === 0) {
3551
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3552
- }
3553
- if (!currentTemplate.contentLanguage) {
3554
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3555
- }
3556
- // TODO: DRY [1]
3557
- scriptPipelineExecutionErrors = [];
3558
- _v.label = 13;
3559
- case 13:
3560
- _v.trys.push([13, 20, 21, 22]);
3561
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3562
- _v.label = 14;
3563
- case 14:
3564
- if (!!_m.done) return [3 /*break*/, 19];
3565
- scriptTools = _m.value;
3566
- _v.label = 15;
3567
- case 15:
3568
- _v.trys.push([15, 17, , 18]);
3569
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3570
- scriptLanguage: currentTemplate.contentLanguage,
3571
- script: preparedContent,
3572
- parameters: parameters,
3573
- }))];
3574
- case 16:
3575
- resultString = _v.sent();
3576
- return [3 /*break*/, 19];
3577
- case 17:
3578
- error_2 = _v.sent();
3579
- if (!(error_2 instanceof Error)) {
3580
- throw error_2;
3581
- }
3582
- if (error_2 instanceof UnexpectedError) {
3583
- throw error_2;
3584
- }
3585
- scriptPipelineExecutionErrors.push(error_2);
3586
- return [3 /*break*/, 18];
3587
- case 18:
3588
- _m = _l.next();
3589
- return [3 /*break*/, 14];
3590
- case 19: return [3 /*break*/, 22];
3591
- case 20:
3592
- e_5_1 = _v.sent();
3593
- e_5 = { error: e_5_1 };
3594
- return [3 /*break*/, 22];
3595
- case 21:
3596
- try {
3597
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3598
- }
3599
- finally { if (e_5) throw e_5.error; }
3600
- return [7 /*endfinally*/];
3601
- case 22:
3602
- if (resultString !== null) {
3603
- return [3 /*break*/, 26];
3604
- }
3605
- if (scriptPipelineExecutionErrors.length === 1) {
3606
- throw scriptPipelineExecutionErrors[0];
3607
- }
3608
- else {
3609
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3610
- .map(function (error) { return '- ' + error.message; })
3611
- .join('\n\n')), "\n "); }));
3612
- }
3613
- case 23:
3614
- if (tools.userInterface === undefined) {
3615
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3616
- }
3617
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3618
- promptTitle: currentTemplate.title,
3619
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3620
- defaultValue: replaceParameters(preparedContent, parameters),
3621
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3622
- placeholder: undefined,
3623
- priority: priority,
3624
- }))];
3625
- case 24:
3626
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3627
- resultString = _v.sent();
3628
- return [3 /*break*/, 26];
3629
- case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3630
- case 26:
3631
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3632
- _v.label = 27;
3633
- case 27:
3634
- _v.trys.push([27, 41, 42, 43]);
3635
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3636
- _v.label = 28;
3637
- case 28:
3638
- if (!!_p.done) return [3 /*break*/, 40];
3639
- functionName = _p.value;
3640
- // TODO: DRY [1]
3641
- scriptPipelineExecutionErrors = [];
3642
- postprocessingError = null;
3643
- _v.label = 29;
3644
- case 29:
3645
- _v.trys.push([29, 36, 37, 38]);
3646
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3647
- _v.label = 30;
3648
- case 30:
3649
- if (!!_r.done) return [3 /*break*/, 35];
3650
- scriptTools = _r.value;
3651
- _v.label = 31;
3652
- case 31:
3653
- _v.trys.push([31, 33, , 34]);
3654
- return [4 /*yield*/, scriptTools.execute({
3655
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3656
- script: "".concat(functionName, "(resultString)"),
3657
- parameters: {
3658
- resultString: resultString || '',
3659
- // Note: No ...parametersForTemplate, because working with result only
3660
- },
3661
- })];
3662
- case 32:
3663
- resultString = _v.sent();
3664
- postprocessingError = null;
3665
- return [3 /*break*/, 35];
3666
- case 33:
3667
- error_3 = _v.sent();
3668
- if (!(error_3 instanceof Error)) {
3669
- throw error_3;
3670
- }
3671
- if (error_3 instanceof UnexpectedError) {
3672
- throw error_3;
3673
- }
3674
- postprocessingError = error_3;
3675
- scriptPipelineExecutionErrors.push(error_3);
3676
- return [3 /*break*/, 34];
3677
- case 34:
3678
- _r = _q.next();
3679
- return [3 /*break*/, 30];
3680
- case 35: return [3 /*break*/, 38];
3681
- case 36:
3682
- e_6_1 = _v.sent();
3683
- e_6 = { error: e_6_1 };
3684
- return [3 /*break*/, 38];
3685
- case 37:
3686
- try {
3687
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3688
- }
3689
- finally { if (e_6) throw e_6.error; }
3690
- return [7 /*endfinally*/];
3691
- case 38:
3692
- if (postprocessingError) {
3693
- throw postprocessingError;
3694
- }
3695
- _v.label = 39;
3696
- case 39:
3697
- _p = _o.next();
3698
- return [3 /*break*/, 28];
3699
- case 40: return [3 /*break*/, 43];
3700
- case 41:
3701
- e_7_1 = _v.sent();
3702
- e_7 = { error: e_7_1 };
3703
- return [3 /*break*/, 43];
3704
- case 42:
3705
- try {
3706
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3707
- }
3708
- finally { if (e_7) throw e_7.error; }
3709
- return [7 /*endfinally*/];
3710
- case 43:
3711
- // TODO: [💝] Unite object for expecting amount and format
3712
- if (currentTemplate.format) {
3713
- if (currentTemplate.format === 'JSON') {
3714
- if (!isValidJsonString(resultString || '')) {
3715
- // TODO: [🏢] Do more universally via `FormatDefinition`
3716
- try {
3717
- resultString = extractJsonBlock(resultString || '');
3718
- }
3719
- catch (error) {
3720
- keepUnused(error);
3721
- throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3722
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3723
- }
3724
- }
3655
+ return false;
3656
+ }
3657
+ }
3658
+ /**
3659
+ * TODO: [💝] Unite object for expecting amount and format
3660
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3661
+ * Note: [💝] and [🤠] are interconnected together
3662
+ */
3663
+
3664
+ /**
3665
+ * @@@
3666
+ *
3667
+ * @private internal utility of `createPipelineExecutor`
3668
+ */
3669
+ function executeAttempts(options) {
3670
+ return __awaiter(this, void 0, void 0, function () {
3671
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3672
+ return __generator(this, function (_a) {
3673
+ switch (_a.label) {
3674
+ case 0:
3675
+ 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;
3676
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3677
+ $ongoingTemplateResult = {
3678
+ $result: null,
3679
+ $resultString: null,
3680
+ $expectError: null,
3681
+ $scriptPipelineExecutionErrors: [],
3682
+ };
3683
+ _loop_1 = function (attempt) {
3684
+ 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;
3685
+ var e_1, _r, e_3, _s, e_2, _t;
3686
+ return __generator(this, function (_u) {
3687
+ switch (_u.label) {
3688
+ case 0:
3689
+ isJokerAttempt = attempt < 0;
3690
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3691
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3692
+ if (isJokerAttempt && !jokerParameterName) {
3693
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3694
+ }
3695
+ $ongoingTemplateResult.$result = null;
3696
+ $ongoingTemplateResult.$resultString = null;
3697
+ $ongoingTemplateResult.$expectError = null;
3698
+ if (isJokerAttempt) {
3699
+ if (parameters[jokerParameterName] === undefined) {
3700
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3701
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3702
+ }
3703
+ else {
3704
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3705
+ }
3706
+ }
3707
+ _u.label = 1;
3708
+ case 1:
3709
+ _u.trys.push([1, 44, 45, 46]);
3710
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3711
+ _b = template.templateType;
3712
+ switch (_b) {
3713
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3714
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3715
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3716
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3717
+ }
3718
+ return [3 /*break*/, 25];
3719
+ case 2:
3720
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3721
+ return [3 /*break*/, 26];
3722
+ case 3:
3723
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3724
+ $ongoingTemplateResult.$prompt = {
3725
+ title: template.title,
3726
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3727
+ ? preparedPipeline.pipelineUrl
3728
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3729
+ parameters: parameters,
3730
+ content: preparedContent,
3731
+ modelRequirements: modelRequirements,
3732
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3733
+ var name = _a.name;
3734
+ return name === template.personaName;
3735
+ }) ||
3736
+ {})), template.expectations),
3737
+ format: template.format,
3738
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3739
+ }; // <- TODO: Not very good type guard
3740
+ _c = modelRequirements.modelVariant;
3741
+ switch (_c) {
3742
+ case 'CHAT': return [3 /*break*/, 4];
3743
+ case 'COMPLETION': return [3 /*break*/, 6];
3744
+ case 'EMBEDDING': return [3 /*break*/, 8];
3745
+ }
3746
+ return [3 /*break*/, 10];
3747
+ case 4:
3748
+ _d = $ongoingTemplateResult;
3749
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3750
+ case 5:
3751
+ _d.$chatResult = _u.sent();
3752
+ // TODO: [🍬] Destroy chatThread
3753
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3754
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3755
+ return [3 /*break*/, 11];
3756
+ case 6:
3757
+ _e = $ongoingTemplateResult;
3758
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3759
+ case 7:
3760
+ _e.$completionResult = _u.sent();
3761
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3762
+ $ongoingTemplateResult.$resultString =
3763
+ $ongoingTemplateResult.$completionResult.content;
3764
+ return [3 /*break*/, 11];
3765
+ case 8:
3766
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3767
+ _f = $ongoingTemplateResult;
3768
+ return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze($ongoingTemplateResult.$prompt))];
3769
+ case 9:
3770
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3771
+ _f.$embeddingResult = _u.sent();
3772
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$embeddingResult;
3773
+ $ongoingTemplateResult.$resultString =
3774
+ $ongoingTemplateResult.$embeddingResult.content.join(',');
3775
+ return [3 /*break*/, 11];
3776
+ case 10: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3777
+ case 11: return [3 /*break*/, 26];
3778
+ case 12:
3779
+ if (arrayableToArray(tools.script).length === 0) {
3780
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3781
+ }
3782
+ if (!template.contentLanguage) {
3783
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3784
+ }
3785
+ _u.label = 13;
3786
+ case 13:
3787
+ _u.trys.push([13, 20, 21, 22]);
3788
+ _g = (e_1 = void 0, __values(arrayableToArray(tools.script))), _h = _g.next();
3789
+ _u.label = 14;
3790
+ case 14:
3791
+ if (!!_h.done) return [3 /*break*/, 19];
3792
+ scriptTools = _h.value;
3793
+ _u.label = 15;
3794
+ case 15:
3795
+ _u.trys.push([15, 17, , 18]);
3796
+ _j = $ongoingTemplateResult;
3797
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3798
+ scriptLanguage: template.contentLanguage,
3799
+ script: preparedContent,
3800
+ parameters: parameters,
3801
+ }))];
3802
+ case 16:
3803
+ _j.$resultString = _u.sent();
3804
+ return [3 /*break*/, 19];
3805
+ case 17:
3806
+ error_1 = _u.sent();
3807
+ if (!(error_1 instanceof Error)) {
3808
+ throw error_1;
3809
+ }
3810
+ if (error_1 instanceof UnexpectedError) {
3811
+ throw error_1;
3812
+ }
3813
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3814
+ return [3 /*break*/, 18];
3815
+ case 18:
3816
+ _h = _g.next();
3817
+ return [3 /*break*/, 14];
3818
+ case 19: return [3 /*break*/, 22];
3819
+ case 20:
3820
+ e_1_1 = _u.sent();
3821
+ e_1 = { error: e_1_1 };
3822
+ return [3 /*break*/, 22];
3823
+ case 21:
3824
+ try {
3825
+ if (_h && !_h.done && (_r = _g.return)) _r.call(_g);
3826
+ }
3827
+ finally { if (e_1) throw e_1.error; }
3828
+ return [7 /*endfinally*/];
3829
+ case 22:
3830
+ if ($ongoingTemplateResult.$resultString !== null) {
3831
+ return [3 /*break*/, 26];
3832
+ }
3833
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3834
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3835
+ }
3836
+ else {
3837
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3838
+ .map(function (error) { return '- ' + error.message; })
3839
+ .join('\n\n')), "\n "); }));
3840
+ }
3841
+ case 23:
3842
+ if (tools.userInterface === undefined) {
3843
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3844
+ }
3845
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3846
+ _k = $ongoingTemplateResult;
3847
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3848
+ promptTitle: template.title,
3849
+ promptMessage: replaceParameters(template.description || '', parameters),
3850
+ defaultValue: replaceParameters(preparedContent, parameters),
3851
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3852
+ placeholder: undefined,
3853
+ priority: priority,
3854
+ }))];
3855
+ case 24:
3856
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3857
+ _k.$resultString = _u.sent();
3858
+ return [3 /*break*/, 26];
3859
+ case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3860
+ case 26:
3861
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 43];
3862
+ _u.label = 27;
3863
+ case 27:
3864
+ _u.trys.push([27, 41, 42, 43]);
3865
+ _l = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _m = _l.next();
3866
+ _u.label = 28;
3867
+ case 28:
3868
+ if (!!_m.done) return [3 /*break*/, 40];
3869
+ functionName = _m.value;
3870
+ postprocessingError = null;
3871
+ _u.label = 29;
3872
+ case 29:
3873
+ _u.trys.push([29, 36, 37, 38]);
3874
+ _o = (e_2 = void 0, __values(arrayableToArray(tools.script))), _p = _o.next();
3875
+ _u.label = 30;
3876
+ case 30:
3877
+ if (!!_p.done) return [3 /*break*/, 35];
3878
+ scriptTools = _p.value;
3879
+ _u.label = 31;
3880
+ case 31:
3881
+ _u.trys.push([31, 33, , 34]);
3882
+ _q = $ongoingTemplateResult;
3883
+ return [4 /*yield*/, scriptTools.execute({
3884
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3885
+ script: "".concat(functionName, "(resultString)"),
3886
+ parameters: {
3887
+ resultString: $ongoingTemplateResult.$resultString || '',
3888
+ // Note: No ...parametersForTemplate, because working with result only
3889
+ },
3890
+ })];
3891
+ case 32:
3892
+ _q.$resultString = _u.sent();
3893
+ postprocessingError = null;
3894
+ return [3 /*break*/, 35];
3895
+ case 33:
3896
+ error_2 = _u.sent();
3897
+ if (!(error_2 instanceof Error)) {
3898
+ throw error_2;
3899
+ }
3900
+ if (error_2 instanceof UnexpectedError) {
3901
+ throw error_2;
3902
+ }
3903
+ postprocessingError = error_2;
3904
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3905
+ return [3 /*break*/, 34];
3906
+ case 34:
3907
+ _p = _o.next();
3908
+ return [3 /*break*/, 30];
3909
+ case 35: return [3 /*break*/, 38];
3910
+ case 36:
3911
+ e_2_1 = _u.sent();
3912
+ e_2 = { error: e_2_1 };
3913
+ return [3 /*break*/, 38];
3914
+ case 37:
3915
+ try {
3916
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3917
+ }
3918
+ finally { if (e_2) throw e_2.error; }
3919
+ return [7 /*endfinally*/];
3920
+ case 38:
3921
+ if (postprocessingError) {
3922
+ throw postprocessingError;
3923
+ }
3924
+ _u.label = 39;
3925
+ case 39:
3926
+ _m = _l.next();
3927
+ return [3 /*break*/, 28];
3928
+ case 40: return [3 /*break*/, 43];
3929
+ case 41:
3930
+ e_3_1 = _u.sent();
3931
+ e_3 = { error: e_3_1 };
3932
+ return [3 /*break*/, 43];
3933
+ case 42:
3934
+ try {
3935
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3936
+ }
3937
+ finally { if (e_3) throw e_3.error; }
3938
+ return [7 /*endfinally*/];
3939
+ case 43:
3940
+ // TODO: [💝] Unite object for expecting amount and format
3941
+ if (template.format) {
3942
+ if (template.format === 'JSON') {
3943
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3944
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3945
+ try {
3946
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3725
3947
  }
3726
- else {
3727
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3948
+ catch (error) {
3949
+ keepUnused(error);
3950
+ throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3951
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3728
3952
  }
3729
3953
  }
3730
- // TODO: [💝] Unite object for expecting amount and format
3731
- if (currentTemplate.expectations) {
3732
- checkExpectations(currentTemplate.expectations, resultString || '');
3733
- }
3734
- return [2 /*return*/, "break-attempts"];
3735
- case 44:
3736
- error_4 = _v.sent();
3737
- if (!(error_4 instanceof ExpectError)) {
3738
- throw error_4;
3739
- }
3740
- expectError = error_4;
3741
- return [3 /*break*/, 46];
3742
- case 45:
3743
- if (!isJokerAttempt &&
3744
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3745
- prompt
3746
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3747
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3748
- ) {
3749
- // TODO: [🧠] Maybe put other templateTypes into report
3750
- executionReport.promptExecutions.push({
3751
- prompt: __assign({}, prompt),
3752
- result: result || undefined,
3753
- error: expectError === null ? undefined : serializeError(expectError),
3754
- });
3755
- }
3756
- return [7 /*endfinally*/];
3757
- case 46:
3758
- if (expectError !== null && attempt === maxAttempts - 1) {
3759
- throw new PipelineExecutionError(spaceTrim$1(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
3760
- .split('\n')
3761
- .map(function (line) { return "> ".concat(line); })
3762
- .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) || '')
3954
+ }
3955
+ else {
3956
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3957
+ }
3958
+ }
3959
+ // TODO: [💝] Unite object for expecting amount and format
3960
+ if (template.expectations) {
3961
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3962
+ }
3963
+ return [2 /*return*/, "break-attempts"];
3964
+ case 44:
3965
+ error_3 = _u.sent();
3966
+ if (!(error_3 instanceof ExpectError)) {
3967
+ throw error_3;
3968
+ }
3969
+ $ongoingTemplateResult.$expectError = error_3;
3970
+ return [3 /*break*/, 46];
3971
+ case 45:
3972
+ if (!isJokerAttempt &&
3973
+ template.templateType === 'PROMPT_TEMPLATE' &&
3974
+ $ongoingTemplateResult.$prompt
3975
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3976
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3977
+ ) {
3978
+ // TODO: [🧠] Maybe put other templateTypes into report
3979
+ $executionReport.promptExecutions.push({
3980
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3981
+ result: $ongoingTemplateResult.$result || undefined,
3982
+ error: $ongoingTemplateResult.$expectError === null
3983
+ ? undefined
3984
+ : serializeError($ongoingTemplateResult.$expectError),
3985
+ });
3986
+ }
3987
+ return [7 /*endfinally*/];
3988
+ case 46:
3989
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3990
+ throw new PipelineExecutionError(spaceTrim$1(function (block) {
3991
+ var _a, _b, _c;
3992
+ 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) || '')
3993
+ .split('\n')
3994
+ .map(function (line) { return "> ".concat(line); })
3995
+ .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) || '')
3996
+ .split('\n')
3997
+ .map(function (line) { return "> ".concat(line); })
3998
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3999
+ ? 'null'
4000
+ : $ongoingTemplateResult.$resultString
3763
4001
  .split('\n')
3764
4002
  .map(function (line) { return "> ".concat(line); })
3765
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3766
- ? 'null'
3767
- : resultString
3768
- .split('\n')
3769
- .map(function (line) { return "> ".concat(line); })
3770
- .join('\n')), "\n ---\n "); }));
3771
- }
3772
- return [2 /*return*/];
4003
+ .join('\n')), "\n ---\n ");
4004
+ }));
3773
4005
  }
3774
- });
3775
- };
3776
- attempt = -jokerParameterNames.length;
3777
- _h.label = 4;
3778
- case 4:
3779
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3780
- return [5 /*yield**/, _loop_5(attempt)];
3781
- case 5:
3782
- state_2 = _h.sent();
3783
- switch (state_2) {
3784
- case "break-attempts": return [3 /*break*/, 7];
3785
- }
3786
- _h.label = 6;
3787
- case 6:
3788
- attempt++;
3789
- return [3 /*break*/, 4];
3790
- case 7:
3791
- if (resultString === null) {
3792
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4006
+ return [2 /*return*/];
3793
4007
  }
3794
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3795
- progress_2 = {
3796
- name: name,
3797
- title: title,
3798
- isStarted: true,
3799
- isDone: true,
3800
- templateType: currentTemplate.templateType,
3801
- parameterName: currentTemplate.resultingParameterName,
3802
- parameterValue: resultString,
3803
- // <- [3]
3804
- };
3805
- if (isReturned) {
3806
- throw new UnexpectedError(spaceTrim$1(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)
3807
- .split('\n')
3808
- .map(function (line) { return "> ".concat(line); })
3809
- .join('\n')), "\n\n "); }));
3810
- }
3811
- return [4 /*yield*/, onProgress(progress_2)];
3812
- case 8:
3813
- _h.sent();
3814
- _h.label = 9;
3815
- case 9:
3816
- 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)));
3817
- return [2 /*return*/];
4008
+ });
4009
+ };
4010
+ attempt = -jokerParameterNames.length;
4011
+ _a.label = 1;
4012
+ case 1:
4013
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
4014
+ return [5 /*yield**/, _loop_1(attempt)];
4015
+ case 2:
4016
+ state_1 = _a.sent();
4017
+ switch (state_1) {
4018
+ case "break-attempts": return [3 /*break*/, 4];
3818
4019
  }
3819
- });
3820
- });
4020
+ _a.label = 3;
4021
+ case 3:
4022
+ attempt++;
4023
+ return [3 /*break*/, 1];
4024
+ case 4:
4025
+ if ($ongoingTemplateResult.$resultString === null) {
4026
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4027
+ }
4028
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
4029
+ }
4030
+ });
4031
+ });
4032
+ }
4033
+ /**
4034
+ * TODO: Break into smaller functions
4035
+ */
4036
+
4037
+ /**
4038
+ * @@@
4039
+ *
4040
+ * @private internal utility of `createPipelineExecutor`
4041
+ */
4042
+ function executeFormatCells(options) {
4043
+ return __awaiter(this, void 0, void 0, function () {
4044
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, parameterValue, formatDefinition, subvalueDefinition, resultString;
4045
+ var _this = this;
4046
+ return __generator(this, function (_a) {
4047
+ switch (_a.label) {
4048
+ case 0:
4049
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification;
4050
+ if (template.foreach === undefined) {
4051
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
4052
+ }
4053
+ if (jokerParameterNames.length !== 0) {
4054
+ throw new UnexpectedError(spaceTrim(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 "); }));
4055
+ }
4056
+ parameterValue = parameters[template.foreach.parameterName] || '';
4057
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
4058
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
4059
+ });
4060
+ if (formatDefinition === undefined) {
4061
+ throw new UnexpectedError(
4062
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4063
+ spaceTrim(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; })
4064
+ .map(function (formatName) { return "- ".concat(formatName); })
4065
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4066
+ }
4067
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
4068
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.cellName);
4069
+ });
4070
+ if (subvalueDefinition === undefined) {
4071
+ throw new UnexpectedError(
4072
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4073
+ spaceTrim(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
4074
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
4075
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
4076
+ .join('\n')), "\n\n [\u26F7] This should never happen because cell name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4077
+ }
4078
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4079
+ var mappedParameters, allSubparameters, subresultString;
4080
+ return __generator(this, function (_a) {
4081
+ switch (_a.label) {
4082
+ case 0:
4083
+ try {
4084
+ mappedParameters = mapAvailableToExpectedParameters({
4085
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4086
+ availableParameters: subparameters,
4087
+ });
4088
+ }
4089
+ catch (error) {
4090
+ if (!(error instanceof PipelineExecutionError)) {
4091
+ throw error;
4092
+ }
4093
+ throw new PipelineExecutionError(spaceTrim(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 "); }));
4094
+ }
4095
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4096
+ // 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
4097
+ Object.freeze(allSubparameters);
4098
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
4099
+ case 1:
4100
+ subresultString = _a.sent();
4101
+ return [2 /*return*/, subresultString];
4102
+ }
4103
+ });
4104
+ }); })];
4105
+ case 1:
4106
+ resultString = _a.sent();
4107
+ return [2 /*return*/, resultString];
4108
+ }
4109
+ });
4110
+ });
4111
+ }
4112
+ /**
4113
+ * TODO: !!!!!! Make pipelineIdentification more precise
4114
+ * TODO: !!!!!! How FOREACH execution looks in the report
4115
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
4116
+ * TODO: []
4117
+ */
4118
+
4119
+ /**
4120
+ * @@@
4121
+ *
4122
+ * @private internal utility of `createPipelineExecutor`
4123
+ */
4124
+ function getContextForTemplate(template) {
4125
+ return __awaiter(this, void 0, void 0, function () {
4126
+ return __generator(this, function (_a) {
4127
+ TODO_USE(template);
4128
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
4129
+ });
4130
+ });
4131
+ }
4132
+
4133
+ /**
4134
+ * @@@
4135
+ *
4136
+ * @private internal utility of `createPipelineExecutor`
4137
+ */
4138
+ function getKnowledgeForTemplate(options) {
4139
+ return __awaiter(this, void 0, void 0, function () {
4140
+ var preparedPipeline, template;
4141
+ return __generator(this, function (_a) {
4142
+ preparedPipeline = options.preparedPipeline, template = options.template;
4143
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4144
+ TODO_USE(template);
4145
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4146
+ var content = _a.content;
4147
+ return "- ".concat(content);
4148
+ }).join('\n')];
4149
+ });
4150
+ });
4151
+ }
4152
+
4153
+ /**
4154
+ * @@@
4155
+ *
4156
+ * @private internal utility of `createPipelineExecutor`
4157
+ */
4158
+ function getSamplesForTemplate(template) {
4159
+ return __awaiter(this, void 0, void 0, function () {
4160
+ return __generator(this, function (_a) {
4161
+ // TODO: [♨] Implement Better - use real index and keyword search
4162
+ TODO_USE(template);
4163
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4164
+ });
4165
+ });
4166
+ }
4167
+
4168
+ /**
4169
+ * @@@
4170
+ *
4171
+ * @private internal utility of `createPipelineExecutor`
4172
+ */
4173
+ function getReservedParametersForTemplate(options) {
4174
+ return __awaiter(this, void 0, void 0, function () {
4175
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4176
+ var e_1, _a;
4177
+ return __generator(this, function (_b) {
4178
+ switch (_b.label) {
4179
+ case 0:
4180
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4181
+ return [4 /*yield*/, getContextForTemplate(template)];
4182
+ case 1:
4183
+ context = _b.sent();
4184
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4185
+ case 2:
4186
+ knowledge = _b.sent();
4187
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4188
+ case 3:
4189
+ samples = _b.sent();
4190
+ currentDate = new Date().toISOString();
4191
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4192
+ reservedParameters = {
4193
+ content: RESERVED_PARAMETER_RESTRICTED,
4194
+ context: context,
4195
+ knowledge: knowledge,
4196
+ samples: samples,
4197
+ currentDate: currentDate,
4198
+ modelName: modelName,
4199
+ };
4200
+ _loop_1 = function (parameterName) {
4201
+ if (reservedParameters[parameterName] === undefined) {
4202
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4203
+ }
4204
+ };
4205
+ try {
4206
+ // Note: Doublecheck that ALL reserved parameters are defined:
4207
+ 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()) {
4208
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4209
+ _loop_1(parameterName);
4210
+ }
4211
+ }
4212
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4213
+ finally {
4214
+ try {
4215
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4216
+ }
4217
+ finally { if (e_1) throw e_1.error; }
4218
+ }
4219
+ return [2 /*return*/, reservedParameters];
4220
+ }
4221
+ });
4222
+ });
4223
+ }
4224
+
4225
+ /**
4226
+ * @@@
4227
+ *
4228
+ * @private internal utility of `createPipelineExecutor`
4229
+ */
4230
+ function executeTemplate(options) {
4231
+ return __awaiter(this, void 0, void 0, function () {
4232
+ 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;
4233
+ var e_1, _f, _g;
4234
+ return __generator(this, function (_h) {
4235
+ switch (_h.label) {
4236
+ case 0:
4237
+ 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;
4238
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4239
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4240
+ title = currentTemplate.title;
4241
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4242
+ return [4 /*yield*/, onProgress({
4243
+ name: name,
4244
+ title: title,
4245
+ isStarted: false,
4246
+ isDone: false,
4247
+ templateType: currentTemplate.templateType,
4248
+ parameterName: currentTemplate.resultingParameterName,
4249
+ parameterValue: null,
4250
+ // <- [🍸]
4251
+ })];
4252
+ case 1:
4253
+ _h.sent();
4254
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4255
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4256
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4257
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4258
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
4259
+ .map(function (name) { return "{".concat(name, "}"); })
4260
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4261
+ .map(function (name) { return "{".concat(name, "}"); })
4262
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4263
+ }
4264
+ _b = (_a = Object).freeze;
4265
+ _c = [{}];
4266
+ return [4 /*yield*/, getReservedParametersForTemplate({
4267
+ preparedPipeline: preparedPipeline,
4268
+ template: currentTemplate,
4269
+ pipelineIdentification: pipelineIdentification,
4270
+ })];
4271
+ case 2:
4272
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4273
+ definedParameterNames = new Set(Object.keys(definedParameters));
4274
+ parameters = {};
4275
+ _loop_1 = function (parameterName) {
4276
+ // Situation: Parameter is defined and used
4277
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4278
+ parameters[parameterName] = definedParameters[parameterName];
4279
+ }
4280
+ // Situation: Parameter is defined but NOT used
4281
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4282
+ // Situation: Parameter is NOT defined BUT used
4283
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4284
+ // Houston, we have a problem
4285
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4286
+ throw new UnexpectedError(spaceTrim$1(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 "); }));
4287
+ }
4288
+ };
4289
+ try {
4290
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4291
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4292
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4293
+ parameterName = _e.value;
4294
+ _loop_1(parameterName);
4295
+ }
4296
+ }
4297
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4298
+ finally {
4299
+ try {
4300
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4301
+ }
4302
+ finally { if (e_1) throw e_1.error; }
4303
+ }
4304
+ // 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
4305
+ Object.freeze(parameters);
4306
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4307
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4308
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4309
+ .split('{content}')
4310
+ .join(currentTemplate.content);
4311
+ return [4 /*yield*/, executeFormatCells({
4312
+ jokerParameterNames: jokerParameterNames,
4313
+ priority: priority,
4314
+ maxAttempts: maxAttempts,
4315
+ preparedContent: preparedContent,
4316
+ parameters: parameters,
4317
+ template: currentTemplate,
4318
+ preparedPipeline: preparedPipeline,
4319
+ tools: tools,
4320
+ llmTools: llmTools,
4321
+ settings: settings,
4322
+ $executionReport: $executionReport,
4323
+ pipelineIdentification: pipelineIdentification,
4324
+ })];
4325
+ case 3:
4326
+ resultString = _h.sent();
4327
+ return [4 /*yield*/, onProgress({
4328
+ name: name,
4329
+ title: title,
4330
+ isStarted: true,
4331
+ isDone: true,
4332
+ templateType: currentTemplate.templateType,
4333
+ parameterName: currentTemplate.resultingParameterName,
4334
+ parameterValue: resultString,
4335
+ // <- [🍸]
4336
+ })];
4337
+ case 4:
4338
+ _h.sent();
4339
+ return [2 /*return*/, Object.freeze((_g = {},
4340
+ _g[currentTemplate.resultingParameterName] =
4341
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4342
+ resultString,
4343
+ _g))];
4344
+ }
4345
+ });
4346
+ });
4347
+ }
4348
+ /**
4349
+ * TODO: [🤹‍♂️]
4350
+ */
4351
+
4352
+ /**
4353
+ * @@@
4354
+ *
4355
+ * @private internal utility of `createPipelineExecutor`
4356
+ */
4357
+ function filterJustOutputParameters(options) {
4358
+ var e_1, _a;
4359
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4360
+ var outputParameters = {};
4361
+ var _loop_1 = function (parameter) {
4362
+ if (parametersToPass[parameter.name] === undefined) {
4363
+ // [4]
4364
+ $warnings.push(new PipelineExecutionError(spaceTrim$1(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 "); })));
4365
+ return "continue";
4366
+ }
4367
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4368
+ };
4369
+ try {
4370
+ // Note: Filter ONLY output parameters
4371
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4372
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4373
+ var isOutput = _a.isOutput;
4374
+ return isOutput;
4375
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4376
+ var parameter = _c.value;
4377
+ _loop_1(parameter);
3821
4378
  }
3822
- function filterJustOutputParameters() {
3823
- var e_8, _a;
3824
- var outputParameters = {};
3825
- var _loop_6 = function (parameter) {
3826
- if (parametersToPass[parameter.name] === undefined) {
3827
- // [4]
3828
- warnings.push(new PipelineExecutionError(spaceTrim$1(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 "); })));
3829
- return "continue";
3830
- }
3831
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3832
- };
3833
- try {
3834
- // Note: Filter ONLY output parameters
3835
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3836
- var isOutput = _a.isOutput;
3837
- return isOutput;
3838
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3839
- var parameter = _c.value;
3840
- _loop_6(parameter);
3841
- }
3842
- }
3843
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3844
- finally {
3845
- try {
3846
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3847
- }
3848
- finally { if (e_8) throw e_8.error; }
3849
- }
3850
- return outputParameters;
4379
+ }
4380
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4381
+ finally {
4382
+ try {
4383
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3851
4384
  }
3852
- 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;
4385
+ finally { if (e_1) throw e_1.error; }
4386
+ }
4387
+ return outputParameters;
4388
+ }
4389
+
4390
+ /**
4391
+ * @@@
4392
+ *
4393
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4394
+ *
4395
+ * @private internal utility of `createPipelineExecutor`
4396
+ */
4397
+ function executePipeline(options) {
4398
+ return __awaiter(this, void 0, void 0, function () {
4399
+ 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;
3853
4400
  var e_1, _e, e_2, _f;
3854
4401
  return __generator(this, function (_g) {
3855
4402
  switch (_g.label) {
3856
4403
  case 0:
4404
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4405
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4406
+ preparedPipeline = options.preparedPipeline;
4407
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3857
4408
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3858
4409
  return [4 /*yield*/, preparePipeline(pipeline, {
3859
4410
  llmTools: llmTools,
@@ -3862,6 +4413,7 @@ function createPipelineExecutor(options) {
3862
4413
  })];
3863
4414
  case 1:
3864
4415
  preparedPipeline = _g.sent();
4416
+ setPreparedPipeline(preparedPipeline);
3865
4417
  _g.label = 2;
3866
4418
  case 2:
3867
4419
  errors = [];
@@ -3931,7 +4483,7 @@ function createPipelineExecutor(options) {
3931
4483
  return name === parameterName;
3932
4484
  });
3933
4485
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3934
- warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4486
+ warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3935
4487
  return [3 /*break*/, 4];
3936
4488
  case 1:
3937
4489
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3943,10 +4495,10 @@ function createPipelineExecutor(options) {
3943
4495
  // Note: Wait a short time to prevent race conditions
3944
4496
  _h.sent();
3945
4497
  _h.label = 3;
3946
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim$1(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4498
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim$1(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3947
4499
  isSuccessful: false,
3948
4500
  errors: __spreadArray([
3949
- new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4501
+ new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3950
4502
  ], __read(errors), false).map(serializeError),
3951
4503
  warnings: warnings.map(serializeError),
3952
4504
  executionReport: executionReport,
@@ -4010,7 +4562,7 @@ function createPipelineExecutor(options) {
4010
4562
  case 0:
4011
4563
  if (loopLimit-- < 0) {
4012
4564
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
4013
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4565
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4014
4566
  }
4015
4567
  currentTemplate = unresovedTemplates_1.find(function (template) {
4016
4568
  return template.dependentParameterNames.every(function (name) {
@@ -4020,29 +4572,52 @@ function createPipelineExecutor(options) {
4020
4572
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4021
4573
  throw new UnexpectedError(
4022
4574
  // TODO: [🐎] DRY
4023
- spaceTrim$1(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4575
+ spaceTrim$1(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4024
4576
  .map(function (_a) {
4025
4577
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4026
4578
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4027
4579
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4028
4580
  .join(' and '));
4029
4581
  })
4030
- .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 "); }));
4582
+ .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 "); }));
4031
4583
  case 1:
4032
4584
  if (!!currentTemplate) return [3 /*break*/, 3];
4033
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4585
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4034
4586
  case 2:
4035
- /* [5] */ _j.sent();
4587
+ /* [🤹‍♂️] */ _j.sent();
4036
4588
  return [3 /*break*/, 4];
4037
4589
  case 3:
4038
4590
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4039
- work_1 = executeSingleTemplate(currentTemplate)
4040
- .then(function () {
4591
+ work_1 = executeTemplate({
4592
+ currentTemplate: currentTemplate,
4593
+ preparedPipeline: preparedPipeline,
4594
+ parametersToPass: parametersToPass,
4595
+ tools: tools,
4596
+ llmTools: llmTools,
4597
+ onProgress: function (progress) {
4598
+ if (isReturned) {
4599
+ throw new UnexpectedError(spaceTrim$1(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)
4600
+ .split('\n')
4601
+ .map(function (line) { return "> ".concat(line); })
4602
+ .join('\n')), "\n "); }));
4603
+ }
4604
+ if (onProgress) {
4605
+ onProgress(progress);
4606
+ }
4607
+ },
4608
+ settings: settings,
4609
+ $executionReport: executionReport,
4610
+ pipelineIdentification: pipelineIdentification,
4611
+ })
4612
+ .then(function (newParametersToPass) {
4613
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4041
4614
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4042
4615
  })
4043
4616
  .then(function () {
4044
4617
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4045
4618
  });
4619
+ // <- Note: Errors are catched here [3]
4620
+ // 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
4046
4621
  resolving_1.push(work_1);
4047
4622
  _j.label = 4;
4048
4623
  case 4: return [2 /*return*/];
@@ -4069,7 +4644,12 @@ function createPipelineExecutor(options) {
4069
4644
  var result = _a.result;
4070
4645
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4071
4646
  })), false));
4072
- outputParameters_1 = filterJustOutputParameters();
4647
+ outputParameters_1 = filterJustOutputParameters({
4648
+ preparedPipeline: preparedPipeline,
4649
+ parametersToPass: parametersToPass,
4650
+ $warnings: warnings,
4651
+ pipelineIdentification: pipelineIdentification,
4652
+ });
4073
4653
  isReturned = true;
4074
4654
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4075
4655
  // Note: Wait a short time to prevent race conditions
@@ -4092,7 +4672,12 @@ function createPipelineExecutor(options) {
4092
4672
  var result = _a.result;
4093
4673
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4094
4674
  })), false));
4095
- outputParameters = filterJustOutputParameters();
4675
+ outputParameters = filterJustOutputParameters({
4676
+ preparedPipeline: preparedPipeline,
4677
+ parametersToPass: parametersToPass,
4678
+ $warnings: warnings,
4679
+ pipelineIdentification: pipelineIdentification,
4680
+ });
4096
4681
  isReturned = true;
4097
4682
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4098
4683
  // Note: Wait a short time to prevent race conditions
@@ -4112,22 +4697,62 @@ function createPipelineExecutor(options) {
4112
4697
  })];
4113
4698
  }
4114
4699
  });
4115
- }); };
4116
- return pipelineExecutor;
4700
+ });
4117
4701
  }
4702
+
4118
4703
  /**
4119
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4120
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4121
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4122
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4123
- * TODO: [♈] Probbably move expectations from templates to parameters
4124
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4125
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4126
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4127
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4128
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4129
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4704
+ * Creates executor function from pipeline and execution tools.
4705
+ *
4706
+ * @returns The executor function
4707
+ * @throws {PipelineLogicError} on logical error in the pipeline
4708
+ * @public exported from `@promptbook/core`
4130
4709
  */
4710
+ function createPipelineExecutor(options) {
4711
+ var _this = this;
4712
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4713
+ 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;
4714
+ validatePipeline(pipeline);
4715
+ var pipelineIdentification = (function () {
4716
+ // Note: This is a 😐 implementation of [🚞]
4717
+ var _ = [];
4718
+ if (pipeline.sourceFile !== undefined) {
4719
+ _.push("File: ".concat(pipeline.sourceFile));
4720
+ }
4721
+ if (pipeline.pipelineUrl !== undefined) {
4722
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4723
+ }
4724
+ return _.join('\n');
4725
+ })();
4726
+ var preparedPipeline;
4727
+ if (isPipelinePrepared(pipeline)) {
4728
+ preparedPipeline = pipeline;
4729
+ }
4730
+ else if (isNotPreparedWarningSupressed !== true) {
4731
+ console.warn(spaceTrim$1(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 "); }));
4732
+ }
4733
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4734
+ return __generator(this, function (_a) {
4735
+ return [2 /*return*/, executePipeline({
4736
+ pipeline: pipeline,
4737
+ preparedPipeline: preparedPipeline,
4738
+ setPreparedPipeline: function (newPreparedPipeline) {
4739
+ preparedPipeline = newPreparedPipeline;
4740
+ },
4741
+ inputParameters: inputParameters,
4742
+ tools: tools,
4743
+ onProgress: onProgress,
4744
+ pipelineIdentification: pipelineIdentification,
4745
+ settings: {
4746
+ maxExecutionAttempts: maxExecutionAttempts,
4747
+ maxParallelCount: maxParallelCount,
4748
+ isVerbose: isVerbose,
4749
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4750
+ },
4751
+ })];
4752
+ });
4753
+ }); };
4754
+ return pipelineExecutor;
4755
+ }
4131
4756
 
4132
4757
  /**
4133
4758
  * @@@
@@ -5263,6 +5888,145 @@ function normalizeTo_SCREAMING_CASE(text) {
5263
5888
  * TODO: [🌺] Use some intermediate util splitWords
5264
5889
  */
5265
5890
 
5891
+ /**
5892
+ * @@@
5893
+ *
5894
+ * @param text @@@
5895
+ * @param _isFirstLetterCapital @@@
5896
+ * @returns @@@
5897
+ * @example 'helloWorld'
5898
+ * @example 'iLovePromptbook'
5899
+ * @public exported from `@promptbook/utils`
5900
+ */
5901
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5902
+ var e_1, _a;
5903
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5904
+ var charType;
5905
+ var lastCharType = null;
5906
+ var normalizedName = '';
5907
+ try {
5908
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5909
+ var char = text_1_1.value;
5910
+ var normalizedChar = void 0;
5911
+ if (/^[a-z]$/.test(char)) {
5912
+ charType = 'LOWERCASE';
5913
+ normalizedChar = char;
5914
+ }
5915
+ else if (/^[A-Z]$/.test(char)) {
5916
+ charType = 'UPPERCASE';
5917
+ normalizedChar = char.toLowerCase();
5918
+ }
5919
+ else if (/^[0-9]$/.test(char)) {
5920
+ charType = 'NUMBER';
5921
+ normalizedChar = char;
5922
+ }
5923
+ else {
5924
+ charType = 'OTHER';
5925
+ normalizedChar = '';
5926
+ }
5927
+ if (!lastCharType) {
5928
+ if (_isFirstLetterCapital) {
5929
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5930
+ }
5931
+ }
5932
+ else if (charType !== lastCharType &&
5933
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5934
+ !(lastCharType === 'NUMBER') &&
5935
+ !(charType === 'NUMBER')) {
5936
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5937
+ }
5938
+ normalizedName += normalizedChar;
5939
+ lastCharType = charType;
5940
+ }
5941
+ }
5942
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5943
+ finally {
5944
+ try {
5945
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5946
+ }
5947
+ finally { if (e_1) throw e_1.error; }
5948
+ }
5949
+ return normalizedName;
5950
+ }
5951
+ /**
5952
+ * TODO: [🌺] Use some intermediate util splitWords
5953
+ */
5954
+
5955
+ /**
5956
+ * Function `validateParameterName` will @@@
5957
+ *
5958
+ * @param parameterName @@@
5959
+ * @returns @@@
5960
+ * @throws {ParseError} @@@
5961
+ * @private within the repository
5962
+ */
5963
+ function validateParameterName(parameterName) {
5964
+ var e_1, _a;
5965
+ var rawParameterName = parameterName;
5966
+ try {
5967
+ for (var _b = __values([
5968
+ ['`', '`'],
5969
+ ['{', '}'],
5970
+ ['[', ']'],
5971
+ ['(', ')'],
5972
+ ['<', '>'],
5973
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5974
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5975
+ if (parameterName.substring(0, 1) === start &&
5976
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5977
+ // <- TODO: More universal that 1 character
5978
+ ) {
5979
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5980
+ // <- TODO: More universal that 1 character
5981
+ }
5982
+ }
5983
+ }
5984
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5985
+ finally {
5986
+ try {
5987
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5988
+ }
5989
+ finally { if (e_1) throw e_1.error; }
5990
+ }
5991
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5992
+ try {
5993
+ /*
5994
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5995
+ if (parameterName.includes(' ')) {
5996
+ throw new ParseError(`Parameter name cannot contain spaces`);
5997
+ }
5998
+ */
5999
+ if (parameterName.includes('.')) {
6000
+ throw new ParseError("Parameter name cannot contain dots");
6001
+ }
6002
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
6003
+ throw new ParseError("Parameter name cannot contain slashes");
6004
+ }
6005
+ if (parameterName.includes('(') ||
6006
+ parameterName.includes(')') ||
6007
+ parameterName.includes('{') ||
6008
+ parameterName.includes('}') ||
6009
+ parameterName.includes('[') ||
6010
+ parameterName.includes(']')) {
6011
+ throw new ParseError("Parameter name cannot contain braces");
6012
+ }
6013
+ parameterName = normalizeTo_camelCase(parameterName);
6014
+ if (parameterName === '') {
6015
+ throw new ParseError("Parameter name cannot be empty");
6016
+ }
6017
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
6018
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
6019
+ }
6020
+ }
6021
+ catch (error) {
6022
+ if (!(error instanceof ParseError)) {
6023
+ throw error;
6024
+ }
6025
+ throw new ParseError(spaceTrim(function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
6026
+ }
6027
+ return parameterName;
6028
+ }
6029
+
5266
6030
  /**
5267
6031
  * Parses the foreach command
5268
6032
  *
@@ -5297,62 +6061,66 @@ var foreachCommandParser = {
5297
6061
  * Example usages of the FOREACH command
5298
6062
  */
5299
6063
  examples: [
5300
- 'FOREACH List Line -> `{customer}`',
5301
- 'FOR List Line -> `{customer}`',
5302
- 'EACH List Line -> `{customer}`',
6064
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
6065
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
6066
+ 'EACH Csv Cell `{customers}` -> `{cell}`',
5303
6067
  // <- TODO: [🍭] !!!!!! More
5304
6068
  ],
5305
6069
  /**
5306
6070
  * Parses the FOREACH command
5307
6071
  */
5308
6072
  parse: function (input) {
5309
- var args = input.args, rawArgs = input.rawArgs;
6073
+ var args = input.args;
5310
6074
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5311
6075
  var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5312
- var assignSign = args[2];
5313
- var parameter = args[3];
5314
- if (![
5315
- 'LIST',
5316
- 'CSV',
5317
- // <- TODO: [🏢] Unhardcode formats
5318
- ].includes(formatName)) {
6076
+ var parameterNameWrapped = args[2];
6077
+ var assignSign = args[3];
6078
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
6079
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
6080
+ });
6081
+ if (formatDefinition === undefined) {
5319
6082
  console.info({ args: args, formatName: formatName });
5320
- throw new Error("Unsupported format \"".concat(formatName, "\""));
6083
+ throw new ParseError(spaceTrim(function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
6084
+ .map(function (formatName) { return "- ".concat(formatName); })
6085
+ .join('\n')), "\n "); }));
5321
6086
  // <- TODO: [🏢] List all supported format names
5322
6087
  }
5323
- if (![
5324
- 'LINE',
5325
- 'ROW',
5326
- 'COLUMN',
5327
- 'CELL',
5328
- // <- TODO: [🏢] Unhardcode format cekks
5329
- ].includes(cellName)) {
6088
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
6089
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(cellName);
6090
+ });
6091
+ if (subvalueDefinition === undefined) {
5330
6092
  console.info({ args: args, cellName: cellName });
5331
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
6093
+ throw new ParseError(spaceTrim(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
6094
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6095
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6096
+ .join('\n')), "\n "); }));
5332
6097
  // <- TODO: [🏢] List all supported cell names for the format
5333
6098
  }
5334
6099
  if (assignSign !== '->') {
5335
6100
  console.info({ args: args, assignSign: assignSign });
5336
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5337
- }
5338
- var parameterNames = extractParameterNames(parameter || rawArgs);
5339
- if (parameterNames.size !== 1) {
5340
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5341
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5342
- }
5343
- var parameterName = parameterNames.values().next().value;
5344
- if (typeof parameterName !== 'string'
5345
- // <- TODO: !!!!!! Replace with propper parameter name validation
5346
- ) {
5347
- console.info({ args: args, parameterName: parameterName });
5348
- throw new Error("Invalid parameter name");
5349
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
6101
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6102
+ }
6103
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
6104
+ if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
6105
+ (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
6106
+ 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));
6107
+ throw new ParseError("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
6108
+ }
6109
+ var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
6110
+ var subparameterNames = args
6111
+ .slice(4)
6112
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6113
+ .filter(function (parameterName) { return parameterName !== ''; })
6114
+ .map(validateParameterName);
6115
+ if (subparameterNames.length === 0) {
6116
+ throw new ParseError("FOREACH command must have at least one subparameter");
5350
6117
  }
5351
6118
  return {
5352
6119
  type: 'FOREACH',
5353
6120
  formatName: formatName,
5354
6121
  cellName: cellName,
5355
6122
  parameterName: parameterName,
6123
+ subparameterNames: subparameterNames,
5356
6124
  };
5357
6125
  },
5358
6126
  /**
@@ -5361,8 +6129,12 @@ var foreachCommandParser = {
5361
6129
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5362
6130
  */
5363
6131
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5364
- keepUnused(command, $templateJson, $pipelineJson);
5365
- // <- TODO: [🍭] !!!!!! Implement
6132
+ var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6133
+ // TODO: !!!!!! Detect double use
6134
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
6135
+ $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterNames: subparameterNames };
6136
+ keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6137
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5366
6138
  },
5367
6139
  /**
5368
6140
  * Converts the FOREACH command back to string
@@ -5371,8 +6143,7 @@ var foreachCommandParser = {
5371
6143
  */
5372
6144
  stringify: function (command) {
5373
6145
  keepUnused(command);
5374
- return "";
5375
- // <- TODO: [🍭] !!!!!! Implement
6146
+ return "---"; // <- TODO: [🛋] Implement
5376
6147
  },
5377
6148
  /**
5378
6149
  * Reads the FOREACH command from the `TemplateJson`
@@ -5381,12 +6152,12 @@ var foreachCommandParser = {
5381
6152
  */
5382
6153
  takeFromTemplateJson: function ($templateJson) {
5383
6154
  keepUnused($templateJson);
5384
- return [];
5385
- // <- TODO: [🍭] !!!!!! Implement
6155
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5386
6156
  },
5387
6157
  };
5388
6158
  /**
5389
- * TODO: !!!!!! Comment console logs
6159
+ * TODO: !!!!!! Remove console logs
6160
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
5390
6161
  * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5391
6162
  */
5392
6163
 
@@ -5497,6 +6268,7 @@ var jokerCommandParser = {
5497
6268
  */
5498
6269
  parse: function (input) {
5499
6270
  var args = input.args;
6271
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5500
6272
  var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5501
6273
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5502
6274
  throw new ParseError("Invalid joker");
@@ -5626,6 +6398,7 @@ var modelCommandParser = {
5626
6398
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5627
6399
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5628
6400
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6401
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5629
6402
  }
5630
6403
  else {
5631
6404
  throw new ParseError(spaceTrim("\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 ")));
@@ -7261,70 +8034,6 @@ function addAutoGeneratedSection(content, options) {
7261
8034
  * TODO: [🏛] This can be part of markdown builder
7262
8035
  */
7263
8036
 
7264
- /**
7265
- * @@@
7266
- *
7267
- * @param text @@@
7268
- * @param _isFirstLetterCapital @@@
7269
- * @returns @@@
7270
- * @example 'helloWorld'
7271
- * @example 'iLovePromptbook'
7272
- * @public exported from `@promptbook/utils`
7273
- */
7274
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
7275
- var e_1, _a;
7276
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
7277
- var charType;
7278
- var lastCharType = null;
7279
- var normalizedName = '';
7280
- try {
7281
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
7282
- var char = text_1_1.value;
7283
- var normalizedChar = void 0;
7284
- if (/^[a-z]$/.test(char)) {
7285
- charType = 'LOWERCASE';
7286
- normalizedChar = char;
7287
- }
7288
- else if (/^[A-Z]$/.test(char)) {
7289
- charType = 'UPPERCASE';
7290
- normalizedChar = char.toLowerCase();
7291
- }
7292
- else if (/^[0-9]$/.test(char)) {
7293
- charType = 'NUMBER';
7294
- normalizedChar = char;
7295
- }
7296
- else {
7297
- charType = 'OTHER';
7298
- normalizedChar = '';
7299
- }
7300
- if (!lastCharType) {
7301
- if (_isFirstLetterCapital) {
7302
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
7303
- }
7304
- }
7305
- else if (charType !== lastCharType &&
7306
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
7307
- !(lastCharType === 'NUMBER') &&
7308
- !(charType === 'NUMBER')) {
7309
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
7310
- }
7311
- normalizedName += normalizedChar;
7312
- lastCharType = charType;
7313
- }
7314
- }
7315
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
7316
- finally {
7317
- try {
7318
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
7319
- }
7320
- finally { if (e_1) throw e_1.error; }
7321
- }
7322
- return normalizedName;
7323
- }
7324
- /**
7325
- * TODO: [🌺] Use some intermediate util splitWords
7326
- */
7327
-
7328
8037
  /**
7329
8038
  * Creates a Mermaid graph based on the promptbook
7330
8039
  *
@@ -7381,6 +8090,9 @@ function renderPromptbookMermaid(pipelineJson, options) {
7381
8090
  return promptbookMermaid;
7382
8091
  }
7383
8092
  /**
8093
+ * TODO: !!!!!! FOREACH in mermaid graph
8094
+ * TODO: !!!!!! Knowledge in mermaid graph
8095
+ * TODO: !!!!!! Personas in mermaid graph
7384
8096
  * TODO: Maybe use some Mermaid package instead of string templating
7385
8097
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
7386
8098
  */
@@ -7522,21 +8234,40 @@ function usageToWorktime(usage) {
7522
8234
  * @public exported from `@promptbook/core`
7523
8235
  */
7524
8236
  function usageToHuman(usage) {
7525
- var report = 'Usage:';
8237
+ var reportItems = [];
7526
8238
  var uncertainNumberToHuman = function (_a) {
7527
8239
  var value = _a.value, isUncertain = _a.isUncertain;
7528
8240
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7529
8241
  };
7530
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7531
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7532
- return spaceTrim(report);
8242
+ if (usage.price.value > 0.1
8243
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8244
+ ) {
8245
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8246
+ }
8247
+ else {
8248
+ reportItems.push("Negligible cost");
8249
+ }
8250
+ var worktime = usageToWorktime(usage);
8251
+ if (worktime.value > 0.5
8252
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8253
+ ) {
8254
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8255
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8256
+ }
8257
+ if (usage.output.charactersCount.value > 0) {
8258
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8259
+ }
8260
+ if (reportItems.length === 0) {
8261
+ // Note: For negligible usage, we report at least something
8262
+ reportItems.push('Negligible');
8263
+ }
8264
+ return spaceTrim(function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7533
8265
  }
7534
8266
  /**
7535
- * TODO: Use "$1" not "1 USD"
7536
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7537
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8267
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8268
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8269
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7538
8270
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7539
- * TODO: When negligible usage, report "Negligible" or just don't report it
7540
8271
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7541
8272
  * TODO: [🏛] Maybe make some markdown builder
7542
8273
  */
@@ -8475,5 +9206,5 @@ function executionReportJsonToString(executionReportJson, options) {
8475
9206
  * TODO: [🧠] Should be in generated file GENERATOR_WARNING
8476
9207
  */
8477
9208
 
8478
- export { $llmToolsMetadataRegister, $llmToolsRegister, CLAIM, CallbackInterfaceTools, CollectionError, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, ERRORS, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, IS_VERBOSE, LimitReachedError, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, RESERVED_PARAMETER_NAMES, TemplateTypes, UnexpectedError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _OpenAiMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
9209
+ export { $llmToolsMetadataRegister, $llmToolsRegister, CLAIM, CallbackInterfaceTools, CollectionError, CsvFormatDefinition, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, ERRORS, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, IS_VERBOSE, LimitReachedError, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, RESERVED_PARAMETER_NAMES, TemplateTypes, TextFormatDefinition, UnexpectedError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _OpenAiMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
8479
9210
  //# sourceMappingURL=index.es.js.map