@promptbook/core 0.69.0-1 → 0.69.0-11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +17 -58
  2. package/esm/index.es.js +1917 -1169
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/core.index.d.ts +5 -1
  5. package/esm/typings/src/_packages/types.index.d.ts +8 -0
  6. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  7. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +2 -6
  8. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +26 -0
  9. package/esm/typings/src/commands/FOREACH/foreachCommand.test.d.ts +3 -0
  10. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +2 -1
  11. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  12. package/esm/typings/src/config.d.ts +7 -1
  13. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  14. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  15. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +5 -0
  16. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +5 -3
  17. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +21 -0
  18. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  19. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +33 -0
  20. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +21 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  31. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  32. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +9 -12
  33. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  34. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +3 -2
  35. package/esm/typings/src/formats/index.d.ts +1 -1
  36. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +1 -1
  37. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +17 -0
  38. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +1 -1
  39. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  40. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  41. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  42. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  43. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  44. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  45. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  46. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  47. package/package.json +2 -1
  48. package/umd/index.umd.js +1921 -1172
  49. package/umd/index.umd.js.map +1 -1
  50. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  51. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  52. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  53. /package/esm/typings/src/{collection/constructors/createCollectionFromDirectory.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  54. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  55. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/validators/parameterName/validateParameterName.test.d.ts} +0 -0
package/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-10';
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-10",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-10",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-10",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-10",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
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,364 @@ 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
+ var _this = this;
2964
+ return __generator(this, function (_a) {
2965
+ switch (_a.label) {
2966
+ case 0:
2967
+ csv = parse(value, {
2968
+ header: true,
2969
+ delimiter: ',',
2970
+ quoteChar: '"',
2971
+ newline: '\r\n',
2972
+ skipEmptyLines: true,
2973
+ // encoding: 'utf8',
2974
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2975
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2976
+ });
2977
+ if (csv.errors.length !== 0) {
2978
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2979
+ spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2980
+ }
2981
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2982
+ var _a;
2983
+ var _b;
2984
+ return __generator(this, function (_c) {
2985
+ switch (_c.label) {
2986
+ case 0:
2987
+ _a = [__assign({}, row)];
2988
+ _b = {};
2989
+ // <- TODO: !!!!!! Dynamic new column name and position
2990
+ return [4 /*yield*/, mapCallback(row, index)];
2991
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2992
+ // <- TODO: !!!!!! Dynamic new column name and position
2993
+ _c.sent(), _b)])))];
2994
+ }
2995
+ });
2996
+ }); }))];
2997
+ case 1:
2998
+ mappedData = _a.sent();
2999
+ return [2 /*return*/, unparse(mappedData, {
3000
+ header: true,
3001
+ delimiter: ',',
3002
+ quoteChar: '"',
3003
+ newline: '\r\n',
3004
+ skipEmptyLines: true,
3005
+ // encoding: 'utf8',
3006
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3007
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3008
+ })];
3009
+ }
3010
+ });
3011
+ });
3012
+ },
3013
+ },
3014
+ {
3015
+ subvalueName: 'CELL',
3016
+ mapValues: function (value, mapCallback) {
3017
+ return __awaiter(this, void 0, void 0, function () {
3018
+ var csv, mappedData;
3019
+ var _this = this;
3020
+ return __generator(this, function (_a) {
3021
+ switch (_a.label) {
3022
+ case 0:
3023
+ csv = parse(value, {
3024
+ header: true,
3025
+ delimiter: ',',
3026
+ quoteChar: '"',
3027
+ newline: '\r\n',
3028
+ skipEmptyLines: true,
3029
+ // encoding: 'utf8',
3030
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3031
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3032
+ });
3033
+ if (csv.errors.length !== 0) {
3034
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3035
+ spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
3036
+ }
3037
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3038
+ var _this = this;
3039
+ return __generator(this, function (_a) {
3040
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
3041
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
3042
+ return __awaiter(_this, void 0, void 0, function () {
3043
+ var index;
3044
+ var _c;
3045
+ return __generator(this, function (_d) {
3046
+ index = rowIndex * Object.keys(row).length + columnIndex;
3047
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
3048
+ });
3049
+ });
3050
+ }))];
3051
+ });
3052
+ }); }))];
3053
+ case 1:
3054
+ mappedData = _a.sent();
3055
+ return [2 /*return*/, unparse(mappedData, {
3056
+ header: true,
3057
+ delimiter: ',',
3058
+ quoteChar: '"',
3059
+ newline: '\r\n',
3060
+ skipEmptyLines: true,
3061
+ // encoding: 'utf8',
3062
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
3063
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
3064
+ })];
3065
+ }
3066
+ });
3067
+ });
3068
+ },
3069
+ },
3070
+ ],
3071
+ };
3072
+ /**
3073
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
3074
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
3075
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
3076
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
3077
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3150
3078
  */
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
3079
 
3158
3080
  /**
3159
- * Counts number of paragraphs in the text
3081
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3160
3082
  *
3161
3083
  * @public exported from `@promptbook/utils`
3162
3084
  */
3163
- function countParagraphs(text) {
3164
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3085
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
3086
+ try {
3087
+ JSON.parse(value);
3088
+ return true;
3089
+ }
3090
+ catch (error) {
3091
+ if (!(error instanceof Error)) {
3092
+ throw error;
3093
+ }
3094
+ if (error.message.includes('Unexpected token')) {
3095
+ return false;
3096
+ }
3097
+ return false;
3098
+ }
3165
3099
  }
3166
3100
 
3167
3101
  /**
3168
- * Split text into sentences
3102
+ * Definition for JSON format
3169
3103
  *
3170
- * @public exported from `@promptbook/utils`
3104
+ * @private still in development [🏢]
3171
3105
  */
3172
- function splitIntoSentences(text) {
3173
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3174
- }
3106
+ var JsonFormatDefinition = {
3107
+ formatName: 'JSON',
3108
+ mimeType: 'application/json',
3109
+ isValid: function (value, schema) {
3110
+ TODO_USE(schema /* <- TODO: Use schema here */);
3111
+ return isValidJsonString(value);
3112
+ },
3113
+ canBeValid: function (partialValue, schema) {
3114
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3115
+ TODO_USE(schema /* <- TODO: Use schema here */);
3116
+ return true;
3117
+ },
3118
+ heal: function (value, schema) {
3119
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3120
+ TODO_USE(schema /* <- TODO: Use schema here */);
3121
+ throw new Error('Not implemented');
3122
+ },
3123
+ subvalueDefinitions: [],
3124
+ };
3175
3125
  /**
3176
- * Counts number of sentences in the text
3177
- *
3178
- * @public exported from `@promptbook/utils`
3126
+ * TODO: [🧠] Maybe propper instance of object
3127
+ * TODO: [0] Make string_serialized_json
3128
+ * TODO: [1] Make type for JSON Schema
3129
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3130
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3131
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3132
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3133
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3134
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3179
3135
  */
3180
- function countSentences(text) {
3181
- return splitIntoSentences(text).length;
3182
- }
3183
3136
 
3184
3137
  /**
3185
- * Counts number of words in the text
3138
+ * Definition for any text - this will be always valid
3186
3139
  *
3187
- * @public exported from `@promptbook/utils`
3140
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3141
+ *
3142
+ * @public exported from `@promptbook/core`
3143
+ */
3144
+ var TextFormatDefinition = {
3145
+ formatName: 'TEXT',
3146
+ isValid: function (value) {
3147
+ return typeof value === 'string';
3148
+ },
3149
+ canBeValid: function (partialValue) {
3150
+ return typeof partialValue === 'string';
3151
+ },
3152
+ heal: function () {
3153
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3154
+ },
3155
+ subvalueDefinitions: [
3156
+ {
3157
+ subvalueName: 'LINE',
3158
+ mapValues: function (value, mapCallback) {
3159
+ return __awaiter(this, void 0, void 0, function () {
3160
+ var lines, mappedLines;
3161
+ return __generator(this, function (_a) {
3162
+ switch (_a.label) {
3163
+ case 0:
3164
+ lines = value.split('\n');
3165
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3166
+ // TODO: [🧠] Maybe option to skip empty line
3167
+ /* not await */ return mapCallback({
3168
+ lineContent: lineContent,
3169
+ // TODO: [🧠] Maybe also put here `lineNumber`
3170
+ }, lineNumber);
3171
+ }))];
3172
+ case 1:
3173
+ mappedLines = _a.sent();
3174
+ return [2 /*return*/, mappedLines.join('\n')];
3175
+ }
3176
+ });
3177
+ });
3178
+ },
3179
+ },
3180
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3181
+ ],
3182
+ };
3183
+ /**
3184
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3185
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3186
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3187
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3188
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3189
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3188
3190
  */
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
3191
 
3195
3192
  /**
3196
- * Index of all counter functions
3193
+ * Definition for XML format
3197
3194
  *
3198
- * @public exported from `@promptbook/utils`
3195
+ * @private still in development [🏢]
3199
3196
  */
3200
- var CountUtils = {
3201
- CHARACTERS: countCharacters,
3202
- WORDS: countWords,
3203
- SENTENCES: countSentences,
3204
- PARAGRAPHS: countParagraphs,
3205
- LINES: countLines,
3206
- PAGES: countPages,
3197
+ var XmlFormatDefinition = {
3198
+ formatName: 'XML',
3199
+ mimeType: 'application/xml',
3200
+ isValid: function (value, schema) {
3201
+ TODO_USE(value /* <- TODO: Use value here */);
3202
+ TODO_USE(schema /* <- TODO: Use schema here */);
3203
+ return true;
3204
+ },
3205
+ canBeValid: function (partialValue, schema) {
3206
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3207
+ TODO_USE(schema /* <- TODO: Use schema here */);
3208
+ return true;
3209
+ },
3210
+ heal: function (value, schema) {
3211
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3212
+ TODO_USE(schema /* <- TODO: Use schema here */);
3213
+ throw new Error('Not implemented');
3214
+ },
3215
+ subvalueDefinitions: [],
3207
3216
  };
3217
+ /**
3218
+ * TODO: [🧠] Maybe propper instance of object
3219
+ * TODO: [0] Make string_serialized_xml
3220
+ * TODO: [1] Make type for XML Schema
3221
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3222
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3223
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3224
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3225
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3226
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3227
+ */
3208
3228
 
3209
3229
  /**
3210
- * Function checkExpectations will check if the expectations on given value are met
3230
+ * Definitions for all formats supported by Promptbook
3211
3231
  *
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
3232
+ * @private internal index of `...` <- TODO [🏢]
3233
+ */
3234
+ var FORMAT_DEFINITIONS = [
3235
+ JsonFormatDefinition,
3236
+ XmlFormatDefinition,
3237
+ TextFormatDefinition,
3238
+ CsvFormatDefinition,
3239
+ ];
3240
+
3241
+ /**
3242
+ * Maps available parameters to expected parameters
3215
3243
  *
3216
- * @throws {ExpectError} if the expectations are not met
3217
- * @returns {void} Nothing
3218
- * @private internal function of `createPipelineExecutor`
3244
+ * The strategy is:
3245
+ * 1) @@@
3246
+ * 2) @@@
3247
+ *
3248
+ * @throws {PipelineExecutionError} @@@
3249
+ * @private within the repository used in `createPipelineExecutor`
3219
3250
  */
3220
- function checkExpectations(expectations, value) {
3251
+ function mapAvailableToExpectedParameters(options) {
3221
3252
  var e_1, _a;
3253
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3254
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3255
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3256
+ var mappedParameters = {};
3222
3257
  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));
3258
+ // Phase 1️⃣: Matching mapping
3259
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3260
+ var parameterName = _c.value;
3261
+ // Situation: Parameter is available and expected
3262
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3263
+ mappedParameters[parameterName] = availableParameters[parameterName];
3264
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3265
+ availableParametersNames.delete(parameterName);
3266
+ expectedParameterNames.delete(parameterName);
3267
+ }
3268
+ // Situation: Parameter is available but NOT expected
3269
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3270
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3271
+ }
3272
+ // Situation: Parameter is NOT available BUT expected
3273
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3274
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3231
3275
  }
3232
3276
  }
3233
3277
  }
@@ -3238,622 +3282,1145 @@ function checkExpectations(expectations, value) {
3238
3282
  }
3239
3283
  finally { if (e_1) throw e_1.error; }
3240
3284
  }
3285
+ if (expectedParameterNames.size === 0) {
3286
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3287
+ Object.freeze(mappedParameters);
3288
+ return mappedParameters;
3289
+ }
3290
+ // Phase 2️⃣: Non-matching mapping
3291
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3292
+ 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)
3293
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3294
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3295
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3296
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3297
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3298
+ .join('\n')), "\n\n "); }));
3299
+ }
3300
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3301
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3302
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3303
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3304
+ }
3305
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3306
+ Object.freeze(mappedParameters);
3307
+ return mappedParameters;
3241
3308
  }
3309
+
3242
3310
  /**
3243
- * Function checkExpectations will check if the expectations on given value are met
3311
+ * Extracts all code blocks from markdown.
3244
3312
  *
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
3313
+ * Note: There are multiple simmilar function:
3314
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3315
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3316
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3317
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3248
3318
  *
3249
- * @returns {boolean} True if the expectations are met
3250
- * @public exported from `@promptbook/core`
3319
+ * @param markdown any valid markdown
3320
+ * @returns code blocks with language and content
3321
+ * @throws {ParseError} if block is not closed properly
3322
+ * @public exported from `@promptbook/markdown-utils`
3251
3323
  */
3252
- function isPassingExpectations(expectations, value) {
3324
+ function extractAllBlocksFromMarkdown(markdown) {
3325
+ var e_1, _a;
3326
+ var codeBlocks = [];
3327
+ var lines = markdown.split('\n');
3328
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3329
+ lines.push('');
3330
+ var currentCodeBlock = null;
3253
3331
  try {
3254
- checkExpectations(expectations, value);
3255
- return true;
3332
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3333
+ var line = lines_1_1.value;
3334
+ if (line.startsWith('> ') || line === '>') {
3335
+ if (currentCodeBlock === null) {
3336
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3337
+ } /* not else */
3338
+ if (currentCodeBlock.blockNotation === '>') {
3339
+ if (currentCodeBlock.content !== '') {
3340
+ currentCodeBlock.content += '\n';
3341
+ }
3342
+ currentCodeBlock.content += line.slice(2);
3343
+ }
3344
+ }
3345
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3346
+ codeBlocks.push(currentCodeBlock);
3347
+ currentCodeBlock = null;
3348
+ }
3349
+ /* not else */
3350
+ if (line.startsWith('```')) {
3351
+ var language = line.slice(3).trim() || null;
3352
+ if (currentCodeBlock === null) {
3353
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3354
+ }
3355
+ else {
3356
+ if (language !== null) {
3357
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3358
+ }
3359
+ codeBlocks.push(currentCodeBlock);
3360
+ currentCodeBlock = null;
3361
+ }
3362
+ }
3363
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3364
+ if (currentCodeBlock.content !== '') {
3365
+ currentCodeBlock.content += '\n';
3366
+ }
3367
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3368
+ }
3369
+ }
3256
3370
  }
3257
- catch (error) {
3258
- if (!(error instanceof ExpectError)) {
3259
- throw error;
3371
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3372
+ finally {
3373
+ try {
3374
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3260
3375
  }
3261
- return false;
3376
+ finally { if (e_1) throw e_1.error; }
3377
+ }
3378
+ if (currentCodeBlock !== null) {
3379
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3262
3380
  }
3381
+ return codeBlocks;
3263
3382
  }
3264
3383
  /**
3265
- * TODO: [💝] Unite object for expecting amount and format
3384
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3266
3385
  */
3267
3386
 
3268
3387
  /**
3269
- * Creates executor function from pipeline and execution tools.
3388
+ * Extracts extracts exactly one valid JSON code block
3270
3389
  *
3271
- * @returns The executor function
3272
- * @throws {PipelineLogicError} on logical error in the pipeline
3273
- * @public exported from `@promptbook/core`
3390
+ * - When given string is a valid JSON as it is, it just returns it
3391
+ * - When there is no JSON code block the function throws a `ParseError`
3392
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3393
+ *
3394
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3395
+ * Note: There are multiple simmilar function:
3396
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3397
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3398
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3399
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3400
+ *
3401
+ * @public exported from `@promptbook/markdown-utils`
3402
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3274
3403
  */
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;
3404
+ function extractJsonBlock(markdown) {
3405
+ if (isValidJsonString(markdown)) {
3406
+ return markdown;
3295
3407
  }
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 "); }));
3408
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3409
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3410
+ var content = _a.content;
3411
+ return isValidJsonString(content);
3412
+ });
3413
+ if (jsonBlocks.length === 0) {
3414
+ throw new Error('There is no valid JSON block in the markdown');
3298
3415
  }
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
- });
3416
+ if (jsonBlocks.length > 1) {
3417
+ throw new Error('There are multiple JSON code blocks in the markdown');
3418
+ }
3419
+ return jsonBlocks[0].content;
3420
+ }
3421
+ /**
3422
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3423
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3424
+ */
3425
+
3426
+ /**
3427
+ * Just says that the variable is not used but should be kept
3428
+ * No side effects.
3429
+ *
3430
+ * Note: It can be usefull for:
3431
+ *
3432
+ * 1) Suppressing eager optimization of unused imports
3433
+ * 2) Suppressing eslint errors of unused variables in the tests
3434
+ * 3) Keeping the type of the variable for type testing
3435
+ *
3436
+ * @param value any values
3437
+ * @returns void
3438
+ * @private within the repository
3439
+ */
3440
+ function keepUnused() {
3441
+ var valuesToKeep = [];
3442
+ for (var _i = 0; _i < arguments.length; _i++) {
3443
+ valuesToKeep[_i] = arguments[_i];
3444
+ }
3445
+ }
3446
+
3447
+ /**
3448
+ * Replaces parameters in template with values from parameters object
3449
+ *
3450
+ * @param template the template with parameters in {curly} braces
3451
+ * @param parameters the object with parameters
3452
+ * @returns the template with replaced parameters
3453
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3454
+ * @public exported from `@promptbook/utils`
3455
+ */
3456
+ function replaceParameters(template, parameters) {
3457
+ var e_1, _a;
3458
+ try {
3459
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3460
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3461
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3462
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3463
+ }
3464
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3465
+ // TODO: [🍵]
3466
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3467
+ }
3308
3468
  }
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
- });
3469
+ }
3470
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3471
+ finally {
3472
+ try {
3473
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3320
3474
  }
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
- });
3475
+ finally { if (e_1) throw e_1.error; }
3476
+ }
3477
+ var replacedTemplate = template;
3478
+ var match;
3479
+ var loopLimit = LOOP_LIMIT;
3480
+ var _loop_1 = function () {
3481
+ if (loopLimit-- < 0) {
3482
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3329
3483
  }
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
- });
3484
+ var precol = match.groups.precol;
3485
+ var parameterName = match.groups.parameterName;
3486
+ if (parameterName === '') {
3487
+ return "continue";
3488
+ }
3489
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3490
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3491
+ }
3492
+ if (parameters[parameterName] === undefined) {
3493
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3494
+ }
3495
+ var parameterValue = parameters[parameterName];
3496
+ if (parameterValue === undefined) {
3497
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3498
+ }
3499
+ parameterValue = parameterValue.toString();
3500
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3501
+ parameterValue = parameterValue
3502
+ .split('\n')
3503
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3504
+ .join('\n');
3505
+ }
3506
+ replacedTemplate =
3507
+ replacedTemplate.substring(0, match.index + precol.length) +
3508
+ parameterValue +
3509
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3510
+ };
3511
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3512
+ .exec(replacedTemplate))) {
3513
+ _loop_1();
3514
+ }
3515
+ // [💫] Check if there are parameters that are not closed properly
3516
+ if (/{\w+$/.test(replacedTemplate)) {
3517
+ throw new PipelineExecutionError('Parameter is not closed');
3518
+ }
3519
+ // [💫] Check if there are parameters that are not opened properly
3520
+ if (/^\w+}/.test(replacedTemplate)) {
3521
+ throw new PipelineExecutionError('Parameter is not opened');
3522
+ }
3523
+ return replacedTemplate;
3524
+ }
3525
+
3526
+ /**
3527
+ * Counts number of characters in the text
3528
+ *
3529
+ * @public exported from `@promptbook/utils`
3530
+ */
3531
+ function countCharacters(text) {
3532
+ // Remove null characters
3533
+ text = text.replace(/\0/g, '');
3534
+ // Replace emojis (and also ZWJ sequence) with hyphens
3535
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3536
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3537
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3538
+ return text.length;
3539
+ }
3540
+
3541
+ /**
3542
+ * Counts number of lines in the text
3543
+ *
3544
+ * @public exported from `@promptbook/utils`
3545
+ */
3546
+ function countLines(text) {
3547
+ if (text === '') {
3548
+ return 0;
3549
+ }
3550
+ return text.split('\n').length;
3551
+ }
3552
+
3553
+ /**
3554
+ * Counts number of pages in the text
3555
+ *
3556
+ * @public exported from `@promptbook/utils`
3557
+ */
3558
+ function countPages(text) {
3559
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3560
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3561
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3562
+ return pageCount;
3563
+ }
3564
+
3565
+ /**
3566
+ * Counts number of paragraphs in the text
3567
+ *
3568
+ * @public exported from `@promptbook/utils`
3569
+ */
3570
+ function countParagraphs(text) {
3571
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3572
+ }
3573
+
3574
+ /**
3575
+ * Split text into sentences
3576
+ *
3577
+ * @public exported from `@promptbook/utils`
3578
+ */
3579
+ function splitIntoSentences(text) {
3580
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3581
+ }
3582
+ /**
3583
+ * Counts number of sentences in the text
3584
+ *
3585
+ * @public exported from `@promptbook/utils`
3586
+ */
3587
+ function countSentences(text) {
3588
+ return splitIntoSentences(text).length;
3589
+ }
3590
+
3591
+ /**
3592
+ * Counts number of words in the text
3593
+ *
3594
+ * @public exported from `@promptbook/utils`
3595
+ */
3596
+ function countWords(text) {
3597
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3598
+ text = removeDiacritics(text);
3599
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3600
+ }
3601
+
3602
+ /**
3603
+ * Index of all counter functions
3604
+ *
3605
+ * @public exported from `@promptbook/utils`
3606
+ */
3607
+ var CountUtils = {
3608
+ CHARACTERS: countCharacters,
3609
+ WORDS: countWords,
3610
+ SENTENCES: countSentences,
3611
+ PARAGRAPHS: countParagraphs,
3612
+ LINES: countLines,
3613
+ PAGES: countPages,
3614
+ };
3615
+ /**
3616
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3617
+ */
3618
+
3619
+ /**
3620
+ * Function checkExpectations will check if the expectations on given value are met
3621
+ *
3622
+ * Note: There are two simmilar functions:
3623
+ * - `checkExpectations` which throws an error if the expectations are not met
3624
+ * - `isPassingExpectations` which returns a boolean
3625
+ *
3626
+ * @throws {ExpectError} if the expectations are not met
3627
+ * @returns {void} Nothing
3628
+ * @private internal function of `createPipelineExecutor`
3629
+ */
3630
+ function checkExpectations(expectations, value) {
3631
+ var e_1, _a;
3632
+ try {
3633
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3634
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3635
+ var amount = CountUtils[unit.toUpperCase()](value);
3636
+ if (min && amount < min) {
3637
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3638
+ } /* not else */
3639
+ if (max && amount > max) {
3640
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3641
+ }
3642
+ }
3643
+ }
3644
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3645
+ finally {
3646
+ try {
3647
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3648
+ }
3649
+ finally { if (e_1) throw e_1.error; }
3650
+ }
3651
+ }
3652
+ /**
3653
+ * Function checkExpectations will check if the expectations on given value are met
3654
+ *
3655
+ * Note: There are two simmilar functions:
3656
+ * - `checkExpectations` which throws an error if the expectations are not met
3657
+ * - `isPassingExpectations` which returns a boolean
3658
+ *
3659
+ * @returns {boolean} True if the expectations are met
3660
+ * @public exported from `@promptbook/core`
3661
+ */
3662
+ function isPassingExpectations(expectations, value) {
3663
+ try {
3664
+ checkExpectations(expectations, value);
3665
+ return true;
3666
+ }
3667
+ catch (error) {
3668
+ if (!(error instanceof ExpectError)) {
3669
+ throw error;
3378
3670
  }
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
- }
3671
+ return false;
3672
+ }
3673
+ }
3674
+ /**
3675
+ * TODO: [💝] Unite object for expecting amount and format
3676
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3677
+ * Note: [💝] and [🤠] are interconnected together
3678
+ */
3679
+
3680
+ /**
3681
+ * @@@
3682
+ *
3683
+ * @private internal utility of `createPipelineExecutor`
3684
+ */
3685
+ function executeAttempts(options) {
3686
+ return __awaiter(this, void 0, void 0, function () {
3687
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3688
+ return __generator(this, function (_a) {
3689
+ switch (_a.label) {
3690
+ case 0:
3691
+ 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;
3692
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3693
+ $ongoingTemplateResult = {
3694
+ $result: null,
3695
+ $resultString: null,
3696
+ $expectError: null,
3697
+ $scriptPipelineExecutionErrors: [],
3698
+ };
3699
+ _loop_1 = function (attempt) {
3700
+ 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;
3701
+ var e_1, _r, e_3, _s, e_2, _t;
3702
+ return __generator(this, function (_u) {
3703
+ switch (_u.label) {
3704
+ case 0:
3705
+ isJokerAttempt = attempt < 0;
3706
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3707
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3708
+ if (isJokerAttempt && !jokerParameterName) {
3709
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3710
+ }
3711
+ $ongoingTemplateResult.$result = null;
3712
+ $ongoingTemplateResult.$resultString = null;
3713
+ $ongoingTemplateResult.$expectError = null;
3714
+ if (isJokerAttempt) {
3715
+ if (parameters[jokerParameterName] === undefined) {
3716
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3717
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3718
+ }
3719
+ else {
3720
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3721
+ }
3722
+ }
3723
+ _u.label = 1;
3724
+ case 1:
3725
+ _u.trys.push([1, 44, 45, 46]);
3726
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3727
+ _b = template.templateType;
3728
+ switch (_b) {
3729
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3730
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3731
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3732
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3733
+ }
3734
+ return [3 /*break*/, 25];
3735
+ case 2:
3736
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3737
+ return [3 /*break*/, 26];
3738
+ case 3:
3739
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3740
+ $ongoingTemplateResult.$prompt = {
3741
+ title: template.title,
3742
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3743
+ ? preparedPipeline.pipelineUrl
3744
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3745
+ parameters: parameters,
3746
+ content: preparedContent,
3747
+ modelRequirements: modelRequirements,
3748
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3749
+ var name = _a.name;
3750
+ return name === template.personaName;
3751
+ }) ||
3752
+ {})), template.expectations),
3753
+ format: template.format,
3754
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3755
+ }; // <- TODO: Not very good type guard
3756
+ _c = modelRequirements.modelVariant;
3757
+ switch (_c) {
3758
+ case 'CHAT': return [3 /*break*/, 4];
3759
+ case 'COMPLETION': return [3 /*break*/, 6];
3760
+ case 'EMBEDDING': return [3 /*break*/, 8];
3761
+ }
3762
+ return [3 /*break*/, 10];
3763
+ case 4:
3764
+ _d = $ongoingTemplateResult;
3765
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3766
+ case 5:
3767
+ _d.$chatResult = _u.sent();
3768
+ // TODO: [🍬] Destroy chatThread
3769
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3770
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3771
+ return [3 /*break*/, 11];
3772
+ case 6:
3773
+ _e = $ongoingTemplateResult;
3774
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3775
+ case 7:
3776
+ _e.$completionResult = _u.sent();
3777
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3778
+ $ongoingTemplateResult.$resultString =
3779
+ $ongoingTemplateResult.$completionResult.content;
3780
+ return [3 /*break*/, 11];
3781
+ case 8:
3782
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3783
+ _f = $ongoingTemplateResult;
3784
+ return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze($ongoingTemplateResult.$prompt))];
3785
+ case 9:
3786
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3787
+ _f.$embeddingResult = _u.sent();
3788
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$embeddingResult;
3789
+ $ongoingTemplateResult.$resultString =
3790
+ $ongoingTemplateResult.$embeddingResult.content.join(',');
3791
+ return [3 /*break*/, 11];
3792
+ 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 "); }));
3793
+ case 11: return [3 /*break*/, 26];
3794
+ case 12:
3795
+ if (arrayableToArray(tools.script).length === 0) {
3796
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3797
+ }
3798
+ if (!template.contentLanguage) {
3799
+ 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 "); }));
3800
+ }
3801
+ _u.label = 13;
3802
+ case 13:
3803
+ _u.trys.push([13, 20, 21, 22]);
3804
+ _g = (e_1 = void 0, __values(arrayableToArray(tools.script))), _h = _g.next();
3805
+ _u.label = 14;
3806
+ case 14:
3807
+ if (!!_h.done) return [3 /*break*/, 19];
3808
+ scriptTools = _h.value;
3809
+ _u.label = 15;
3810
+ case 15:
3811
+ _u.trys.push([15, 17, , 18]);
3812
+ _j = $ongoingTemplateResult;
3813
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3814
+ scriptLanguage: template.contentLanguage,
3815
+ script: preparedContent,
3816
+ parameters: parameters,
3817
+ }))];
3818
+ case 16:
3819
+ _j.$resultString = _u.sent();
3820
+ return [3 /*break*/, 19];
3821
+ case 17:
3822
+ error_1 = _u.sent();
3823
+ if (!(error_1 instanceof Error)) {
3824
+ throw error_1;
3825
+ }
3826
+ if (error_1 instanceof UnexpectedError) {
3827
+ throw error_1;
3828
+ }
3829
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3830
+ return [3 /*break*/, 18];
3831
+ case 18:
3832
+ _h = _g.next();
3833
+ return [3 /*break*/, 14];
3834
+ case 19: return [3 /*break*/, 22];
3835
+ case 20:
3836
+ e_1_1 = _u.sent();
3837
+ e_1 = { error: e_1_1 };
3838
+ return [3 /*break*/, 22];
3839
+ case 21:
3840
+ try {
3841
+ if (_h && !_h.done && (_r = _g.return)) _r.call(_g);
3842
+ }
3843
+ finally { if (e_1) throw e_1.error; }
3844
+ return [7 /*endfinally*/];
3845
+ case 22:
3846
+ if ($ongoingTemplateResult.$resultString !== null) {
3847
+ return [3 /*break*/, 26];
3848
+ }
3849
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3850
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3851
+ }
3852
+ else {
3853
+ 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
3854
+ .map(function (error) { return '- ' + error.message; })
3855
+ .join('\n\n')), "\n "); }));
3856
+ }
3857
+ case 23:
3858
+ if (tools.userInterface === undefined) {
3859
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3860
+ }
3861
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3862
+ _k = $ongoingTemplateResult;
3863
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3864
+ promptTitle: template.title,
3865
+ promptMessage: replaceParameters(template.description || '', parameters),
3866
+ defaultValue: replaceParameters(preparedContent, parameters),
3867
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3868
+ placeholder: undefined,
3869
+ priority: priority,
3870
+ }))];
3871
+ case 24:
3872
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3873
+ _k.$resultString = _u.sent();
3874
+ return [3 /*break*/, 26];
3875
+ case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3876
+ case 26:
3877
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 43];
3878
+ _u.label = 27;
3879
+ case 27:
3880
+ _u.trys.push([27, 41, 42, 43]);
3881
+ _l = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _m = _l.next();
3882
+ _u.label = 28;
3883
+ case 28:
3884
+ if (!!_m.done) return [3 /*break*/, 40];
3885
+ functionName = _m.value;
3886
+ postprocessingError = null;
3887
+ _u.label = 29;
3888
+ case 29:
3889
+ _u.trys.push([29, 36, 37, 38]);
3890
+ _o = (e_2 = void 0, __values(arrayableToArray(tools.script))), _p = _o.next();
3891
+ _u.label = 30;
3892
+ case 30:
3893
+ if (!!_p.done) return [3 /*break*/, 35];
3894
+ scriptTools = _p.value;
3895
+ _u.label = 31;
3896
+ case 31:
3897
+ _u.trys.push([31, 33, , 34]);
3898
+ _q = $ongoingTemplateResult;
3899
+ return [4 /*yield*/, scriptTools.execute({
3900
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3901
+ script: "".concat(functionName, "(resultString)"),
3902
+ parameters: {
3903
+ resultString: $ongoingTemplateResult.$resultString || '',
3904
+ // Note: No ...parametersForTemplate, because working with result only
3905
+ },
3906
+ })];
3907
+ case 32:
3908
+ _q.$resultString = _u.sent();
3909
+ postprocessingError = null;
3910
+ return [3 /*break*/, 35];
3911
+ case 33:
3912
+ error_2 = _u.sent();
3913
+ if (!(error_2 instanceof Error)) {
3914
+ throw error_2;
3915
+ }
3916
+ if (error_2 instanceof UnexpectedError) {
3917
+ throw error_2;
3918
+ }
3919
+ postprocessingError = error_2;
3920
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3921
+ return [3 /*break*/, 34];
3922
+ case 34:
3923
+ _p = _o.next();
3924
+ return [3 /*break*/, 30];
3925
+ case 35: return [3 /*break*/, 38];
3926
+ case 36:
3927
+ e_2_1 = _u.sent();
3928
+ e_2 = { error: e_2_1 };
3929
+ return [3 /*break*/, 38];
3930
+ case 37:
3931
+ try {
3932
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3933
+ }
3934
+ finally { if (e_2) throw e_2.error; }
3935
+ return [7 /*endfinally*/];
3936
+ case 38:
3937
+ if (postprocessingError) {
3938
+ throw postprocessingError;
3939
+ }
3940
+ _u.label = 39;
3941
+ case 39:
3942
+ _m = _l.next();
3943
+ return [3 /*break*/, 28];
3944
+ case 40: return [3 /*break*/, 43];
3945
+ case 41:
3946
+ e_3_1 = _u.sent();
3947
+ e_3 = { error: e_3_1 };
3948
+ return [3 /*break*/, 43];
3949
+ case 42:
3950
+ try {
3951
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3952
+ }
3953
+ finally { if (e_3) throw e_3.error; }
3954
+ return [7 /*endfinally*/];
3955
+ case 43:
3956
+ // TODO: [💝] Unite object for expecting amount and format
3957
+ if (template.format) {
3958
+ if (template.format === 'JSON') {
3959
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3960
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3961
+ try {
3962
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3725
3963
  }
3726
- else {
3727
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3964
+ catch (error) {
3965
+ keepUnused(error);
3966
+ throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3967
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3728
3968
  }
3729
3969
  }
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) || '')
3970
+ }
3971
+ else {
3972
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3973
+ }
3974
+ }
3975
+ // TODO: [💝] Unite object for expecting amount and format
3976
+ if (template.expectations) {
3977
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3978
+ }
3979
+ return [2 /*return*/, "break-attempts"];
3980
+ case 44:
3981
+ error_3 = _u.sent();
3982
+ if (!(error_3 instanceof ExpectError)) {
3983
+ throw error_3;
3984
+ }
3985
+ $ongoingTemplateResult.$expectError = error_3;
3986
+ return [3 /*break*/, 46];
3987
+ case 45:
3988
+ if (!isJokerAttempt &&
3989
+ template.templateType === 'PROMPT_TEMPLATE' &&
3990
+ $ongoingTemplateResult.$prompt
3991
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3992
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3993
+ ) {
3994
+ // TODO: [🧠] Maybe put other templateTypes into report
3995
+ $executionReport.promptExecutions.push({
3996
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3997
+ result: $ongoingTemplateResult.$result || undefined,
3998
+ error: $ongoingTemplateResult.$expectError === null
3999
+ ? undefined
4000
+ : serializeError($ongoingTemplateResult.$expectError),
4001
+ });
4002
+ }
4003
+ return [7 /*endfinally*/];
4004
+ case 46:
4005
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
4006
+ throw new PipelineExecutionError(spaceTrim$1(function (block) {
4007
+ var _a, _b, _c;
4008
+ 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) || '')
4009
+ .split('\n')
4010
+ .map(function (line) { return "> ".concat(line); })
4011
+ .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) || '')
4012
+ .split('\n')
4013
+ .map(function (line) { return "> ".concat(line); })
4014
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
4015
+ ? 'null'
4016
+ : $ongoingTemplateResult.$resultString
3763
4017
  .split('\n')
3764
4018
  .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*/];
4019
+ .join('\n')), "\n ---\n ");
4020
+ }));
3773
4021
  }
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 "); }));
4022
+ return [2 /*return*/];
3793
4023
  }
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*/];
4024
+ });
4025
+ };
4026
+ attempt = -jokerParameterNames.length;
4027
+ _a.label = 1;
4028
+ case 1:
4029
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
4030
+ return [5 /*yield**/, _loop_1(attempt)];
4031
+ case 2:
4032
+ state_1 = _a.sent();
4033
+ switch (state_1) {
4034
+ case "break-attempts": return [3 /*break*/, 4];
3818
4035
  }
3819
- });
3820
- });
4036
+ _a.label = 3;
4037
+ case 3:
4038
+ attempt++;
4039
+ return [3 /*break*/, 1];
4040
+ case 4:
4041
+ if ($ongoingTemplateResult.$resultString === null) {
4042
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4043
+ }
4044
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
4045
+ }
4046
+ });
4047
+ });
4048
+ }
4049
+ /**
4050
+ * TODO: Break into smaller functions
4051
+ */
4052
+
4053
+ /**
4054
+ * @@@
4055
+ *
4056
+ * @private internal utility of `createPipelineExecutor`
4057
+ */
4058
+ function executeFormatCells(options) {
4059
+ return __awaiter(this, void 0, void 0, function () {
4060
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, parameterValue, formatDefinition, subvalueDefinition, resultString;
4061
+ var _this = this;
4062
+ return __generator(this, function (_a) {
4063
+ switch (_a.label) {
4064
+ case 0:
4065
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification;
4066
+ if (template.foreach === undefined) {
4067
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
4068
+ }
4069
+ if (jokerParameterNames.length !== 0) {
4070
+ 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 "); }));
4071
+ }
4072
+ parameterValue = parameters[template.foreach.parameterName] || '';
4073
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
4074
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
4075
+ });
4076
+ if (formatDefinition === undefined) {
4077
+ throw new UnexpectedError(
4078
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4079
+ 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; })
4080
+ .map(function (formatName) { return "- ".concat(formatName); })
4081
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4082
+ }
4083
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
4084
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.cellName);
4085
+ });
4086
+ if (subvalueDefinition === undefined) {
4087
+ throw new UnexpectedError(
4088
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4089
+ 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
4090
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
4091
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
4092
+ .join('\n')), "\n\n [\u26F7] This should never happen because cell name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4093
+ }
4094
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4095
+ var mappedParameters, allSubparameters, subresultString;
4096
+ return __generator(this, function (_a) {
4097
+ switch (_a.label) {
4098
+ case 0:
4099
+ try {
4100
+ mappedParameters = mapAvailableToExpectedParameters({
4101
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4102
+ availableParameters: subparameters,
4103
+ });
4104
+ }
4105
+ catch (error) {
4106
+ if (!(error instanceof PipelineExecutionError)) {
4107
+ throw error;
4108
+ }
4109
+ 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 "); }));
4110
+ }
4111
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4112
+ // 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
4113
+ Object.freeze(allSubparameters);
4114
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
4115
+ case 1:
4116
+ subresultString = _a.sent();
4117
+ return [2 /*return*/, subresultString];
4118
+ }
4119
+ });
4120
+ }); })];
4121
+ case 1:
4122
+ resultString = _a.sent();
4123
+ return [2 /*return*/, resultString];
4124
+ }
4125
+ });
4126
+ });
4127
+ }
4128
+ /**
4129
+ * TODO: !!!!!! Make pipelineIdentification more precise
4130
+ * TODO: !!!!!! How FOREACH execution looks in the report
4131
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
4132
+ * TODO: []
4133
+ */
4134
+
4135
+ /**
4136
+ * @@@
4137
+ *
4138
+ * @private internal utility of `createPipelineExecutor`
4139
+ */
4140
+ function getContextForTemplate(template) {
4141
+ return __awaiter(this, void 0, void 0, function () {
4142
+ return __generator(this, function (_a) {
4143
+ TODO_USE(template);
4144
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
4145
+ });
4146
+ });
4147
+ }
4148
+
4149
+ /**
4150
+ * @@@
4151
+ *
4152
+ * @private internal utility of `createPipelineExecutor`
4153
+ */
4154
+ function getKnowledgeForTemplate(options) {
4155
+ return __awaiter(this, void 0, void 0, function () {
4156
+ var preparedPipeline, template;
4157
+ return __generator(this, function (_a) {
4158
+ preparedPipeline = options.preparedPipeline, template = options.template;
4159
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4160
+ TODO_USE(template);
4161
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4162
+ var content = _a.content;
4163
+ return "- ".concat(content);
4164
+ }).join('\n')];
4165
+ });
4166
+ });
4167
+ }
4168
+
4169
+ /**
4170
+ * @@@
4171
+ *
4172
+ * @private internal utility of `createPipelineExecutor`
4173
+ */
4174
+ function getSamplesForTemplate(template) {
4175
+ return __awaiter(this, void 0, void 0, function () {
4176
+ return __generator(this, function (_a) {
4177
+ // TODO: [♨] Implement Better - use real index and keyword search
4178
+ TODO_USE(template);
4179
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4180
+ });
4181
+ });
4182
+ }
4183
+
4184
+ /**
4185
+ * @@@
4186
+ *
4187
+ * @private internal utility of `createPipelineExecutor`
4188
+ */
4189
+ function getReservedParametersForTemplate(options) {
4190
+ return __awaiter(this, void 0, void 0, function () {
4191
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4192
+ var e_1, _a;
4193
+ return __generator(this, function (_b) {
4194
+ switch (_b.label) {
4195
+ case 0:
4196
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4197
+ return [4 /*yield*/, getContextForTemplate(template)];
4198
+ case 1:
4199
+ context = _b.sent();
4200
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4201
+ case 2:
4202
+ knowledge = _b.sent();
4203
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4204
+ case 3:
4205
+ samples = _b.sent();
4206
+ currentDate = new Date().toISOString();
4207
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4208
+ reservedParameters = {
4209
+ content: RESERVED_PARAMETER_RESTRICTED,
4210
+ context: context,
4211
+ knowledge: knowledge,
4212
+ samples: samples,
4213
+ currentDate: currentDate,
4214
+ modelName: modelName,
4215
+ };
4216
+ _loop_1 = function (parameterName) {
4217
+ if (reservedParameters[parameterName] === undefined) {
4218
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4219
+ }
4220
+ };
4221
+ try {
4222
+ // Note: Doublecheck that ALL reserved parameters are defined:
4223
+ 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()) {
4224
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4225
+ _loop_1(parameterName);
4226
+ }
4227
+ }
4228
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4229
+ finally {
4230
+ try {
4231
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4232
+ }
4233
+ finally { if (e_1) throw e_1.error; }
4234
+ }
4235
+ return [2 /*return*/, reservedParameters];
4236
+ }
4237
+ });
4238
+ });
4239
+ }
4240
+
4241
+ /**
4242
+ * @@@
4243
+ *
4244
+ * @private internal utility of `createPipelineExecutor`
4245
+ */
4246
+ function executeTemplate(options) {
4247
+ return __awaiter(this, void 0, void 0, function () {
4248
+ 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;
4249
+ var e_1, _f, _g;
4250
+ return __generator(this, function (_h) {
4251
+ switch (_h.label) {
4252
+ case 0:
4253
+ 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;
4254
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4255
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4256
+ title = currentTemplate.title;
4257
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4258
+ return [4 /*yield*/, onProgress({
4259
+ name: name,
4260
+ title: title,
4261
+ isStarted: false,
4262
+ isDone: false,
4263
+ templateType: currentTemplate.templateType,
4264
+ parameterName: currentTemplate.resultingParameterName,
4265
+ parameterValue: null,
4266
+ // <- [🍸]
4267
+ })];
4268
+ case 1:
4269
+ _h.sent();
4270
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4271
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4272
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4273
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4274
+ 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)
4275
+ .map(function (name) { return "{".concat(name, "}"); })
4276
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4277
+ .map(function (name) { return "{".concat(name, "}"); })
4278
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4279
+ }
4280
+ _b = (_a = Object).freeze;
4281
+ _c = [{}];
4282
+ return [4 /*yield*/, getReservedParametersForTemplate({
4283
+ preparedPipeline: preparedPipeline,
4284
+ template: currentTemplate,
4285
+ pipelineIdentification: pipelineIdentification,
4286
+ })];
4287
+ case 2:
4288
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4289
+ definedParameterNames = new Set(Object.keys(definedParameters));
4290
+ parameters = {};
4291
+ _loop_1 = function (parameterName) {
4292
+ // Situation: Parameter is defined and used
4293
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4294
+ parameters[parameterName] = definedParameters[parameterName];
4295
+ }
4296
+ // Situation: Parameter is defined but NOT used
4297
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4298
+ // Situation: Parameter is NOT defined BUT used
4299
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4300
+ // Houston, we have a problem
4301
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4302
+ 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 "); }));
4303
+ }
4304
+ };
4305
+ try {
4306
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4307
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4308
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4309
+ parameterName = _e.value;
4310
+ _loop_1(parameterName);
4311
+ }
4312
+ }
4313
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4314
+ finally {
4315
+ try {
4316
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4317
+ }
4318
+ finally { if (e_1) throw e_1.error; }
4319
+ }
4320
+ // 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
4321
+ Object.freeze(parameters);
4322
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4323
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4324
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4325
+ .split('{content}')
4326
+ .join(currentTemplate.content);
4327
+ return [4 /*yield*/, executeFormatCells({
4328
+ jokerParameterNames: jokerParameterNames,
4329
+ priority: priority,
4330
+ maxAttempts: maxAttempts,
4331
+ preparedContent: preparedContent,
4332
+ parameters: parameters,
4333
+ template: currentTemplate,
4334
+ preparedPipeline: preparedPipeline,
4335
+ tools: tools,
4336
+ llmTools: llmTools,
4337
+ settings: settings,
4338
+ $executionReport: $executionReport,
4339
+ pipelineIdentification: pipelineIdentification,
4340
+ })];
4341
+ case 3:
4342
+ resultString = _h.sent();
4343
+ return [4 /*yield*/, onProgress({
4344
+ name: name,
4345
+ title: title,
4346
+ isStarted: true,
4347
+ isDone: true,
4348
+ templateType: currentTemplate.templateType,
4349
+ parameterName: currentTemplate.resultingParameterName,
4350
+ parameterValue: resultString,
4351
+ // <- [🍸]
4352
+ })];
4353
+ case 4:
4354
+ _h.sent();
4355
+ return [2 /*return*/, Object.freeze((_g = {},
4356
+ _g[currentTemplate.resultingParameterName] =
4357
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4358
+ resultString,
4359
+ _g))];
4360
+ }
4361
+ });
4362
+ });
4363
+ }
4364
+ /**
4365
+ * TODO: [🤹‍♂️]
4366
+ */
4367
+
4368
+ /**
4369
+ * @@@
4370
+ *
4371
+ * @private internal utility of `createPipelineExecutor`
4372
+ */
4373
+ function filterJustOutputParameters(options) {
4374
+ var e_1, _a;
4375
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4376
+ var outputParameters = {};
4377
+ var _loop_1 = function (parameter) {
4378
+ if (parametersToPass[parameter.name] === undefined) {
4379
+ // [4]
4380
+ $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 "); })));
4381
+ return "continue";
4382
+ }
4383
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4384
+ };
4385
+ try {
4386
+ // Note: Filter ONLY output parameters
4387
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4388
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4389
+ var isOutput = _a.isOutput;
4390
+ return isOutput;
4391
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4392
+ var parameter = _c.value;
4393
+ _loop_1(parameter);
3821
4394
  }
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;
4395
+ }
4396
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4397
+ finally {
4398
+ try {
4399
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3851
4400
  }
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;
4401
+ finally { if (e_1) throw e_1.error; }
4402
+ }
4403
+ return outputParameters;
4404
+ }
4405
+
4406
+ /**
4407
+ * @@@
4408
+ *
4409
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4410
+ *
4411
+ * @private internal utility of `createPipelineExecutor`
4412
+ */
4413
+ function executePipeline(options) {
4414
+ return __awaiter(this, void 0, void 0, function () {
4415
+ 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
4416
  var e_1, _e, e_2, _f;
3854
4417
  return __generator(this, function (_g) {
3855
4418
  switch (_g.label) {
3856
4419
  case 0:
4420
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4421
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4422
+ preparedPipeline = options.preparedPipeline;
4423
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3857
4424
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3858
4425
  return [4 /*yield*/, preparePipeline(pipeline, {
3859
4426
  llmTools: llmTools,
@@ -3862,6 +4429,7 @@ function createPipelineExecutor(options) {
3862
4429
  })];
3863
4430
  case 1:
3864
4431
  preparedPipeline = _g.sent();
4432
+ setPreparedPipeline(preparedPipeline);
3865
4433
  _g.label = 2;
3866
4434
  case 2:
3867
4435
  errors = [];
@@ -3931,7 +4499,7 @@ function createPipelineExecutor(options) {
3931
4499
  return name === parameterName;
3932
4500
  });
3933
4501
  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 "); })));
4502
+ 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
4503
  return [3 /*break*/, 4];
3936
4504
  case 1:
3937
4505
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3943,10 +4511,10 @@ function createPipelineExecutor(options) {
3943
4511
  // Note: Wait a short time to prevent race conditions
3944
4512
  _h.sent();
3945
4513
  _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 "); }), {
4514
+ 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
4515
  isSuccessful: false,
3948
4516
  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 "); }))
4517
+ 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
4518
  ], __read(errors), false).map(serializeError),
3951
4519
  warnings: warnings.map(serializeError),
3952
4520
  executionReport: executionReport,
@@ -4010,7 +4578,7 @@ function createPipelineExecutor(options) {
4010
4578
  case 0:
4011
4579
  if (loopLimit-- < 0) {
4012
4580
  // 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 "); }));
4581
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4014
4582
  }
4015
4583
  currentTemplate = unresovedTemplates_1.find(function (template) {
4016
4584
  return template.dependentParameterNames.every(function (name) {
@@ -4020,29 +4588,52 @@ function createPipelineExecutor(options) {
4020
4588
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4021
4589
  throw new UnexpectedError(
4022
4590
  // 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
4591
+ 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
4592
  .map(function (_a) {
4025
4593
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4026
4594
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4027
4595
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4028
4596
  .join(' and '));
4029
4597
  })
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 "); }));
4598
+ .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
4599
  case 1:
4032
4600
  if (!!currentTemplate) return [3 /*break*/, 3];
4033
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4601
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4034
4602
  case 2:
4035
- /* [5] */ _j.sent();
4603
+ /* [🤹‍♂️] */ _j.sent();
4036
4604
  return [3 /*break*/, 4];
4037
4605
  case 3:
4038
4606
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4039
- work_1 = executeSingleTemplate(currentTemplate)
4040
- .then(function () {
4607
+ work_1 = executeTemplate({
4608
+ currentTemplate: currentTemplate,
4609
+ preparedPipeline: preparedPipeline,
4610
+ parametersToPass: parametersToPass,
4611
+ tools: tools,
4612
+ llmTools: llmTools,
4613
+ onProgress: function (progress) {
4614
+ if (isReturned) {
4615
+ 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)
4616
+ .split('\n')
4617
+ .map(function (line) { return "> ".concat(line); })
4618
+ .join('\n')), "\n "); }));
4619
+ }
4620
+ if (onProgress) {
4621
+ onProgress(progress);
4622
+ }
4623
+ },
4624
+ settings: settings,
4625
+ $executionReport: executionReport,
4626
+ pipelineIdentification: pipelineIdentification,
4627
+ })
4628
+ .then(function (newParametersToPass) {
4629
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4041
4630
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4042
4631
  })
4043
4632
  .then(function () {
4044
4633
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4045
4634
  });
4635
+ // <- Note: Errors are catched here [3]
4636
+ // 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
4637
  resolving_1.push(work_1);
4047
4638
  _j.label = 4;
4048
4639
  case 4: return [2 /*return*/];
@@ -4069,7 +4660,12 @@ function createPipelineExecutor(options) {
4069
4660
  var result = _a.result;
4070
4661
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4071
4662
  })), false));
4072
- outputParameters_1 = filterJustOutputParameters();
4663
+ outputParameters_1 = filterJustOutputParameters({
4664
+ preparedPipeline: preparedPipeline,
4665
+ parametersToPass: parametersToPass,
4666
+ $warnings: warnings,
4667
+ pipelineIdentification: pipelineIdentification,
4668
+ });
4073
4669
  isReturned = true;
4074
4670
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4075
4671
  // Note: Wait a short time to prevent race conditions
@@ -4092,7 +4688,12 @@ function createPipelineExecutor(options) {
4092
4688
  var result = _a.result;
4093
4689
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4094
4690
  })), false));
4095
- outputParameters = filterJustOutputParameters();
4691
+ outputParameters = filterJustOutputParameters({
4692
+ preparedPipeline: preparedPipeline,
4693
+ parametersToPass: parametersToPass,
4694
+ $warnings: warnings,
4695
+ pipelineIdentification: pipelineIdentification,
4696
+ });
4096
4697
  isReturned = true;
4097
4698
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4098
4699
  // Note: Wait a short time to prevent race conditions
@@ -4112,22 +4713,62 @@ function createPipelineExecutor(options) {
4112
4713
  })];
4113
4714
  }
4114
4715
  });
4115
- }); };
4116
- return pipelineExecutor;
4716
+ });
4117
4717
  }
4718
+
4118
4719
  /**
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
4720
+ * Creates executor function from pipeline and execution tools.
4721
+ *
4722
+ * @returns The executor function
4723
+ * @throws {PipelineLogicError} on logical error in the pipeline
4724
+ * @public exported from `@promptbook/core`
4130
4725
  */
4726
+ function createPipelineExecutor(options) {
4727
+ var _this = this;
4728
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4729
+ 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;
4730
+ validatePipeline(pipeline);
4731
+ var pipelineIdentification = (function () {
4732
+ // Note: This is a 😐 implementation of [🚞]
4733
+ var _ = [];
4734
+ if (pipeline.sourceFile !== undefined) {
4735
+ _.push("File: ".concat(pipeline.sourceFile));
4736
+ }
4737
+ if (pipeline.pipelineUrl !== undefined) {
4738
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4739
+ }
4740
+ return _.join('\n');
4741
+ })();
4742
+ var preparedPipeline;
4743
+ if (isPipelinePrepared(pipeline)) {
4744
+ preparedPipeline = pipeline;
4745
+ }
4746
+ else if (isNotPreparedWarningSupressed !== true) {
4747
+ 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 "); }));
4748
+ }
4749
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4750
+ return __generator(this, function (_a) {
4751
+ return [2 /*return*/, executePipeline({
4752
+ pipeline: pipeline,
4753
+ preparedPipeline: preparedPipeline,
4754
+ setPreparedPipeline: function (newPreparedPipeline) {
4755
+ preparedPipeline = newPreparedPipeline;
4756
+ },
4757
+ inputParameters: inputParameters,
4758
+ tools: tools,
4759
+ onProgress: onProgress,
4760
+ pipelineIdentification: pipelineIdentification,
4761
+ settings: {
4762
+ maxExecutionAttempts: maxExecutionAttempts,
4763
+ maxParallelCount: maxParallelCount,
4764
+ isVerbose: isVerbose,
4765
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4766
+ },
4767
+ })];
4768
+ });
4769
+ }); };
4770
+ return pipelineExecutor;
4771
+ }
4131
4772
 
4132
4773
  /**
4133
4774
  * @@@
@@ -5263,6 +5904,145 @@ function normalizeTo_SCREAMING_CASE(text) {
5263
5904
  * TODO: [🌺] Use some intermediate util splitWords
5264
5905
  */
5265
5906
 
5907
+ /**
5908
+ * @@@
5909
+ *
5910
+ * @param text @@@
5911
+ * @param _isFirstLetterCapital @@@
5912
+ * @returns @@@
5913
+ * @example 'helloWorld'
5914
+ * @example 'iLovePromptbook'
5915
+ * @public exported from `@promptbook/utils`
5916
+ */
5917
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5918
+ var e_1, _a;
5919
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5920
+ var charType;
5921
+ var lastCharType = null;
5922
+ var normalizedName = '';
5923
+ try {
5924
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5925
+ var char = text_1_1.value;
5926
+ var normalizedChar = void 0;
5927
+ if (/^[a-z]$/.test(char)) {
5928
+ charType = 'LOWERCASE';
5929
+ normalizedChar = char;
5930
+ }
5931
+ else if (/^[A-Z]$/.test(char)) {
5932
+ charType = 'UPPERCASE';
5933
+ normalizedChar = char.toLowerCase();
5934
+ }
5935
+ else if (/^[0-9]$/.test(char)) {
5936
+ charType = 'NUMBER';
5937
+ normalizedChar = char;
5938
+ }
5939
+ else {
5940
+ charType = 'OTHER';
5941
+ normalizedChar = '';
5942
+ }
5943
+ if (!lastCharType) {
5944
+ if (_isFirstLetterCapital) {
5945
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5946
+ }
5947
+ }
5948
+ else if (charType !== lastCharType &&
5949
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5950
+ !(lastCharType === 'NUMBER') &&
5951
+ !(charType === 'NUMBER')) {
5952
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5953
+ }
5954
+ normalizedName += normalizedChar;
5955
+ lastCharType = charType;
5956
+ }
5957
+ }
5958
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5959
+ finally {
5960
+ try {
5961
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5962
+ }
5963
+ finally { if (e_1) throw e_1.error; }
5964
+ }
5965
+ return normalizedName;
5966
+ }
5967
+ /**
5968
+ * TODO: [🌺] Use some intermediate util splitWords
5969
+ */
5970
+
5971
+ /**
5972
+ * Function `validateParameterName` will @@@
5973
+ *
5974
+ * @param parameterName @@@
5975
+ * @returns @@@
5976
+ * @throws {ParseError} @@@
5977
+ * @private within the repository
5978
+ */
5979
+ function validateParameterName(parameterName) {
5980
+ var e_1, _a;
5981
+ var rawParameterName = parameterName;
5982
+ try {
5983
+ for (var _b = __values([
5984
+ ['`', '`'],
5985
+ ['{', '}'],
5986
+ ['[', ']'],
5987
+ ['(', ')'],
5988
+ ['<', '>'],
5989
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5990
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5991
+ if (parameterName.substring(0, 1) === start &&
5992
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5993
+ // <- TODO: More universal that 1 character
5994
+ ) {
5995
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5996
+ // <- TODO: More universal that 1 character
5997
+ }
5998
+ }
5999
+ }
6000
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
6001
+ finally {
6002
+ try {
6003
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
6004
+ }
6005
+ finally { if (e_1) throw e_1.error; }
6006
+ }
6007
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
6008
+ try {
6009
+ /*
6010
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
6011
+ if (parameterName.includes(' ')) {
6012
+ throw new ParseError(`Parameter name cannot contain spaces`);
6013
+ }
6014
+ */
6015
+ if (parameterName.includes('.')) {
6016
+ throw new ParseError("Parameter name cannot contain dots");
6017
+ }
6018
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
6019
+ throw new ParseError("Parameter name cannot contain slashes");
6020
+ }
6021
+ if (parameterName.includes('(') ||
6022
+ parameterName.includes(')') ||
6023
+ parameterName.includes('{') ||
6024
+ parameterName.includes('}') ||
6025
+ parameterName.includes('[') ||
6026
+ parameterName.includes(']')) {
6027
+ throw new ParseError("Parameter name cannot contain braces");
6028
+ }
6029
+ parameterName = normalizeTo_camelCase(parameterName);
6030
+ if (parameterName === '') {
6031
+ throw new ParseError("Parameter name cannot be empty");
6032
+ }
6033
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
6034
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
6035
+ }
6036
+ }
6037
+ catch (error) {
6038
+ if (!(error instanceof ParseError)) {
6039
+ throw error;
6040
+ }
6041
+ throw new ParseError(spaceTrim(function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
6042
+ }
6043
+ return parameterName;
6044
+ }
6045
+
5266
6046
  /**
5267
6047
  * Parses the foreach command
5268
6048
  *
@@ -5297,62 +6077,66 @@ var foreachCommandParser = {
5297
6077
  * Example usages of the FOREACH command
5298
6078
  */
5299
6079
  examples: [
5300
- 'FOREACH List Line -> `{customer}`',
5301
- 'FOR List Line -> `{customer}`',
5302
- 'EACH List Line -> `{customer}`',
6080
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
6081
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
6082
+ 'EACH Csv Cell `{customers}` -> `{cell}`',
5303
6083
  // <- TODO: [🍭] !!!!!! More
5304
6084
  ],
5305
6085
  /**
5306
6086
  * Parses the FOREACH command
5307
6087
  */
5308
6088
  parse: function (input) {
5309
- var args = input.args, rawArgs = input.rawArgs;
6089
+ var args = input.args;
5310
6090
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5311
6091
  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)) {
6092
+ var parameterNameWrapped = args[2];
6093
+ var assignSign = args[3];
6094
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
6095
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
6096
+ });
6097
+ if (formatDefinition === undefined) {
5319
6098
  console.info({ args: args, formatName: formatName });
5320
- throw new Error("Unsupported format \"".concat(formatName, "\""));
6099
+ 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; })
6100
+ .map(function (formatName) { return "- ".concat(formatName); })
6101
+ .join('\n')), "\n "); }));
5321
6102
  // <- TODO: [🏢] List all supported format names
5322
6103
  }
5323
- if (![
5324
- 'LINE',
5325
- 'ROW',
5326
- 'COLUMN',
5327
- 'CELL',
5328
- // <- TODO: [🏢] Unhardcode format cekks
5329
- ].includes(cellName)) {
6104
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
6105
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(cellName);
6106
+ });
6107
+ if (subvalueDefinition === undefined) {
5330
6108
  console.info({ args: args, cellName: cellName });
5331
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
6109
+ 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
6110
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6111
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6112
+ .join('\n')), "\n "); }));
5332
6113
  // <- TODO: [🏢] List all supported cell names for the format
5333
6114
  }
5334
6115
  if (assignSign !== '->') {
5335
6116
  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
6117
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6118
+ }
6119
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
6120
+ if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
6121
+ (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
6122
+ 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));
6123
+ throw new ParseError("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
6124
+ }
6125
+ var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
6126
+ var subparameterNames = args
6127
+ .slice(4)
6128
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6129
+ .filter(function (parameterName) { return parameterName !== ''; })
6130
+ .map(validateParameterName);
6131
+ if (subparameterNames.length === 0) {
6132
+ throw new ParseError("FOREACH command must have at least one subparameter");
5350
6133
  }
5351
6134
  return {
5352
6135
  type: 'FOREACH',
5353
6136
  formatName: formatName,
5354
6137
  cellName: cellName,
5355
6138
  parameterName: parameterName,
6139
+ subparameterNames: subparameterNames,
5356
6140
  };
5357
6141
  },
5358
6142
  /**
@@ -5361,8 +6145,12 @@ var foreachCommandParser = {
5361
6145
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5362
6146
  */
5363
6147
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5364
- keepUnused(command, $templateJson, $pipelineJson);
5365
- // <- TODO: [🍭] !!!!!! Implement
6148
+ var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6149
+ // TODO: !!!!!! Detect double use
6150
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
6151
+ $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterNames: subparameterNames };
6152
+ keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6153
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5366
6154
  },
5367
6155
  /**
5368
6156
  * Converts the FOREACH command back to string
@@ -5371,8 +6159,7 @@ var foreachCommandParser = {
5371
6159
  */
5372
6160
  stringify: function (command) {
5373
6161
  keepUnused(command);
5374
- return "";
5375
- // <- TODO: [🍭] !!!!!! Implement
6162
+ return "---"; // <- TODO: [🛋] Implement
5376
6163
  },
5377
6164
  /**
5378
6165
  * Reads the FOREACH command from the `TemplateJson`
@@ -5381,12 +6168,12 @@ var foreachCommandParser = {
5381
6168
  */
5382
6169
  takeFromTemplateJson: function ($templateJson) {
5383
6170
  keepUnused($templateJson);
5384
- return [];
5385
- // <- TODO: [🍭] !!!!!! Implement
6171
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5386
6172
  },
5387
6173
  };
5388
6174
  /**
5389
- * TODO: !!!!!! Comment console logs
6175
+ * TODO: !!!!!! Remove console logs
6176
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
5390
6177
  * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5391
6178
  */
5392
6179
 
@@ -5497,6 +6284,7 @@ var jokerCommandParser = {
5497
6284
  */
5498
6285
  parse: function (input) {
5499
6286
  var args = input.args;
6287
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5500
6288
  var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5501
6289
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5502
6290
  throw new ParseError("Invalid joker");
@@ -5626,6 +6414,7 @@ var modelCommandParser = {
5626
6414
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5627
6415
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5628
6416
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6417
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5629
6418
  }
5630
6419
  else {
5631
6420
  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 ")));
@@ -6702,7 +7491,7 @@ function extractAllListItemsFromMarkdown(markdown) {
6702
7491
  function extractOneBlockFromMarkdown(markdown) {
6703
7492
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6704
7493
  if (codeBlocks.length !== 1) {
6705
- throw new ParseError(spaceTrim(function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7494
+ throw new ParseError(spaceTrim(function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6706
7495
  }
6707
7496
  return codeBlocks[0];
6708
7497
  }
@@ -7261,70 +8050,6 @@ function addAutoGeneratedSection(content, options) {
7261
8050
  * TODO: [🏛] This can be part of markdown builder
7262
8051
  */
7263
8052
 
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
8053
  /**
7329
8054
  * Creates a Mermaid graph based on the promptbook
7330
8055
  *
@@ -7381,6 +8106,9 @@ function renderPromptbookMermaid(pipelineJson, options) {
7381
8106
  return promptbookMermaid;
7382
8107
  }
7383
8108
  /**
8109
+ * TODO: !!!!!! FOREACH in mermaid graph
8110
+ * TODO: !!!!!! Knowledge in mermaid graph
8111
+ * TODO: !!!!!! Personas in mermaid graph
7384
8112
  * TODO: Maybe use some Mermaid package instead of string templating
7385
8113
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
7386
8114
  */
@@ -7522,21 +8250,41 @@ function usageToWorktime(usage) {
7522
8250
  * @public exported from `@promptbook/core`
7523
8251
  */
7524
8252
  function usageToHuman(usage) {
7525
- var report = 'Usage:';
8253
+ var reportItems = [];
7526
8254
  var uncertainNumberToHuman = function (_a) {
7527
8255
  var value = _a.value, isUncertain = _a.isUncertain;
7528
8256
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7529
8257
  };
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);
8258
+ if (usage.price.value > 0.01
8259
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8260
+ ) {
8261
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8262
+ }
8263
+ else {
8264
+ reportItems.push("Negligible cost");
8265
+ }
8266
+ var worktime = usageToWorktime(usage);
8267
+ if (worktime.value >
8268
+ 1 / 60
8269
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8270
+ ) {
8271
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8272
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8273
+ }
8274
+ if (usage.output.charactersCount.value > 0) {
8275
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8276
+ }
8277
+ if (reportItems.length === 0) {
8278
+ // Note: For negligible usage, we report at least something
8279
+ reportItems.push('Negligible');
8280
+ }
8281
+ return spaceTrim(function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7533
8282
  }
7534
8283
  /**
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
8284
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8285
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8286
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7538
8287
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7539
- * TODO: When negligible usage, report "Negligible" or just don't report it
7540
8288
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7541
8289
  * TODO: [🏛] Maybe make some markdown builder
7542
8290
  */
@@ -8475,5 +9223,5 @@ function executionReportJsonToString(executionReportJson, options) {
8475
9223
  * TODO: [🧠] Should be in generated file GENERATOR_WARNING
8476
9224
  */
8477
9225
 
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 };
9226
+ 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
9227
  //# sourceMappingURL=index.es.js.map