@promptbook/node 0.70.0-1 → 0.71.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +22 -59
  2. package/esm/index.es.js +1875 -1072
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/promptbook-collection/index.d.ts +0 -3
  5. package/esm/typings/src/_packages/core.index.d.ts +9 -1
  6. package/esm/typings/src/_packages/types.index.d.ts +12 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  8. package/esm/typings/src/cli/cli-commands/make.d.ts +1 -1
  9. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +1 -1
  10. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +3 -7
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +23 -0
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  14. package/esm/typings/src/config.d.ts +16 -3
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +10 -5
  19. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +9 -8
  20. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +45 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +40 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +19 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  31. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  32. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  33. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  34. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  35. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  36. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  37. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  38. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  39. package/esm/typings/src/formats/index.d.ts +1 -1
  40. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  41. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  42. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  43. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  44. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  45. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  48. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  50. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  51. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  52. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  53. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +9 -2
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  57. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  58. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  59. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  60. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  61. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  62. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  63. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  64. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  65. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  67. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  68. package/package.json +18 -13
  69. package/umd/index.umd.js +1878 -1076
  70. package/umd/index.umd.js.map +1 -1
  71. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  72. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  73. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  74. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  75. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  76. /package/esm/typings/src/{personas/preparePersona.test.d.ts → utils/validators/parameterName/validateParameterName.test.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -5,6 +5,7 @@ import spaceTrim$1, { spaceTrim } from 'spacetrim';
5
5
  import { format } from 'prettier';
6
6
  import parserHtml from 'prettier/parser-html';
7
7
  import { forTime } from 'waitasecond';
8
+ import { unparse, parse } from 'papaparse';
8
9
  import hexEncoder from 'crypto-js/enc-hex';
9
10
  import sha256 from 'crypto-js/sha256';
10
11
  import { join } from 'path/posix';
@@ -14,8 +15,8 @@ import * as dotenv from 'dotenv';
14
15
  /**
15
16
  * The version of the Promptbook library
16
17
  */
17
- var PROMPTBOOK_VERSION = '0.70.0-0';
18
- // TODO: !!!! List here all the versions and annotate + put into script
18
+ var PROMPTBOOK_VERSION = '0.70.0-1';
19
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
19
20
 
20
21
  /*! *****************************************************************************
21
22
  Copyright (c) Microsoft Corporation.
@@ -325,7 +326,7 @@ function checkSerializableAsJson(name, value) {
325
326
  }
326
327
  /**
327
328
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
328
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
329
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
329
330
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
330
331
  */
331
332
 
@@ -367,13 +368,13 @@ var IMMEDIATE_TIME = 10;
367
368
  *
368
369
  * @public exported from `@promptbook/core`
369
370
  */
370
- var MAX_PARALLEL_COUNT = 5;
371
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
371
372
  /**
372
373
  * The maximum number of attempts to execute LLM task before giving up
373
374
  *
374
375
  * @public exported from `@promptbook/core`
375
376
  */
376
- var MAX_EXECUTION_ATTEMPTS = 3;
377
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
377
378
  /**
378
379
  * The maximum length of the (generated) filename
379
380
  *
@@ -404,6 +405,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
404
405
  'samples',
405
406
  'modelName',
406
407
  'currentDate',
408
+ // <- TODO: !!!!! list here all command names
407
409
  // <- TODO: Add more like 'date', 'modelName',...
408
410
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
409
411
  ]);
@@ -420,12 +422,32 @@ var RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
420
422
  */
421
423
  var RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
422
424
  // <- TODO: [🧜‍♂️]
425
+ /**
426
+ * @@@
427
+ *
428
+ * @public exported from `@promptbook/core`
429
+ */
430
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
431
+ delimiter: ',',
432
+ quoteChar: '"',
433
+ newline: '\n',
434
+ skipEmptyLines: true,
435
+ });
423
436
  /**
424
437
  * @@@
425
438
  *
426
439
  * @public exported from `@promptbook/core`
427
440
  */
428
441
  var IS_VERBOSE = false;
442
+ /**
443
+ * @@@
444
+ *
445
+ * @private within the repository
446
+ */
447
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
448
+ /**/
449
+ // Note: In normal situations, we check the pipeline logic:
450
+ true);
429
451
  /**
430
452
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
431
453
  */
@@ -494,7 +516,7 @@ function pipelineJsonToString(pipelineJson) {
494
516
  commands.push("PIPELINE URL ".concat(pipelineUrl));
495
517
  }
496
518
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
497
- // TODO: !!! This increase size of the bundle and is probbably not necessary
519
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
498
520
  pipelineString = prettifyMarkdown(pipelineString);
499
521
  try {
500
522
  for (var _g = __values(parameters.filter(function (_a) {
@@ -642,12 +664,12 @@ function pipelineJsonToString(pipelineJson) {
642
664
  pipelineString += '```' + contentLanguage;
643
665
  pipelineString += '\n';
644
666
  pipelineString += spaceTrim$1(content);
645
- // <- TODO: !!! Escape
667
+ // <- TODO:[main] !!! Escape
646
668
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
647
669
  pipelineString += '\n';
648
670
  pipelineString += '```';
649
671
  pipelineString += '\n\n';
650
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
672
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
651
673
  }
652
674
  }
653
675
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -874,7 +896,7 @@ function forEachAsync(array, options, callbackfunction) {
874
896
  });
875
897
  }
876
898
 
877
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
899
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
878
900
 
879
901
  /**
880
902
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -949,7 +971,7 @@ function isValidPromptbookVersion(version) {
949
971
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
950
972
  return false;
951
973
  }
952
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
974
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
953
975
  return true;
954
976
  }
955
977
 
@@ -1081,6 +1103,26 @@ function isValidPipelineUrl(url) {
1081
1103
  * @public exported from `@promptbook/core`
1082
1104
  */
1083
1105
  function validatePipeline(pipeline) {
1106
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1107
+ validatePipelineCore(pipeline);
1108
+ }
1109
+ else {
1110
+ try {
1111
+ validatePipelineCore(pipeline);
1112
+ }
1113
+ catch (error) {
1114
+ if (!(error instanceof PipelineLogicError)) {
1115
+ throw error;
1116
+ }
1117
+ console.error(spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1118
+ }
1119
+ }
1120
+ return pipeline;
1121
+ }
1122
+ /**
1123
+ * @private internal function for `validatePipeline`
1124
+ */
1125
+ function validatePipelineCore(pipeline) {
1084
1126
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1085
1127
  var e_1, _a, e_2, _b, e_3, _c;
1086
1128
  var pipelineIdentification = (function () {
@@ -1098,19 +1140,19 @@ function validatePipeline(pipeline) {
1098
1140
  // <- Note: [🚲]
1099
1141
  throw new PipelineLogicError(spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1100
1142
  }
1101
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1143
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1102
1144
  // <- Note: [🚲]
1103
1145
  throw new PipelineLogicError(spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1104
1146
  }
1105
1147
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1106
1148
  if (!Array.isArray(pipeline.parameters)) {
1107
1149
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1108
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1150
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1109
1151
  }
1110
1152
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1111
1153
  if (!Array.isArray(pipeline.templates)) {
1112
1154
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1113
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1155
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1114
1156
  }
1115
1157
  var _loop_1 = function (parameter) {
1116
1158
  if (parameter.isInput && parameter.isOutput) {
@@ -1279,9 +1321,9 @@ function validatePipeline(pipeline) {
1279
1321
  while (unresovedTemplates.length > 0) {
1280
1322
  _loop_3();
1281
1323
  }
1282
- return pipeline;
1283
1324
  }
1284
1325
  /**
1326
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1285
1327
  * TODO: [🧠] Work with promptbookVersion
1286
1328
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1287
1329
  * > /**
@@ -1293,11 +1335,11 @@ function validatePipeline(pipeline) {
1293
1335
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1294
1336
  */
1295
1337
  /**
1296
- * TODO: [🐣] !!!! Validate that all samples match expectations
1297
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1298
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1299
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1300
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1338
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1339
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1340
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1341
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1342
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1301
1343
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1302
1344
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1303
1345
  */
@@ -2019,113 +2061,35 @@ function assertsExecutionSuccessful(executionResult) {
2019
2061
  */
2020
2062
 
2021
2063
  /**
2022
- * Parses the given script and returns the list of all used variables that are not defined in the script
2023
- *
2024
- * @param script from which to extract the variables
2025
- * @returns the list of variable names
2026
- * @throws {ParseError} if the script is invalid
2027
- * @public exported from `@promptbook/utils`
2028
- */
2029
- function extractVariables(script) {
2030
- var variables = new Set();
2031
- script = "(()=>{".concat(script, "})()");
2032
- try {
2033
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2034
- try {
2035
- eval(script);
2036
- }
2037
- catch (error) {
2038
- if (!(error instanceof ReferenceError)) {
2039
- throw error;
2040
- }
2041
- var undefinedName = error.message.split(' ')[0];
2042
- /*
2043
- Note: Parsing the error
2044
- [PipelineUrlError: thing is not defined]
2045
- */
2046
- if (!undefinedName) {
2047
- throw error;
2048
- }
2049
- if (script.includes(undefinedName + '(')) {
2050
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2051
- }
2052
- else {
2053
- variables.add(undefinedName);
2054
- script = "const ".concat(undefinedName, " = '';") + script;
2055
- }
2056
- }
2057
- }
2058
- catch (error) {
2059
- if (!(error instanceof Error)) {
2060
- throw error;
2061
- }
2062
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2063
- }
2064
- return variables;
2065
- }
2066
- /**
2067
- * TODO: [🔣] Support for multiple languages - python, java,...
2068
- */
2069
-
2070
- /**
2071
- * Parses the template and returns the set of all used parameters
2064
+ * Determine if the pipeline is fully prepared
2072
2065
  *
2073
- * @param template the template with used parameters
2074
- * @returns the set of parameter names
2075
- * @throws {ParseError} if the script is invalid
2076
- * @public exported from `@promptbook/utils`
2066
+ * @public exported from `@promptbook/core`
2077
2067
  */
2078
- function extractParameterNamesFromTemplate(template) {
2079
- var e_1, _a, e_2, _b, e_3, _c;
2080
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2081
- var parameterNames = new Set();
2082
- try {
2083
- 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()) {
2084
- var parameterName = _e.value;
2085
- parameterNames.add(parameterName);
2086
- }
2087
- }
2088
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2089
- finally {
2090
- try {
2091
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2092
- }
2093
- finally { if (e_1) throw e_1.error; }
2094
- }
2095
- if (templateType === 'SCRIPT_TEMPLATE') {
2096
- try {
2097
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2098
- var parameterName = _g.value;
2099
- parameterNames.add(parameterName);
2100
- }
2101
- }
2102
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2103
- finally {
2104
- try {
2105
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2106
- }
2107
- finally { if (e_2) throw e_2.error; }
2108
- }
2109
- }
2110
- try {
2111
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2112
- var jokerName = _j.value;
2113
- parameterNames.add(jokerName);
2114
- }
2068
+ function isPipelinePrepared(pipeline) {
2069
+ // Note: Ignoring `pipeline.preparations` @@@
2070
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2071
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2072
+ return false;
2115
2073
  }
2116
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2117
- finally {
2118
- try {
2119
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2120
- }
2121
- finally { if (e_3) throw e_3.error; }
2074
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2075
+ return false;
2122
2076
  }
2123
- parameterNames.delete('content');
2124
- // <- Note {websiteContent} is used in `preparedContent`
2125
- return parameterNames;
2077
+ /*
2078
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2079
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2080
+ > return false;
2081
+ > }
2082
+ */
2083
+ return true;
2126
2084
  }
2127
2085
  /**
2128
- * TODO: [🔣] If script require contentLanguage
2086
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2087
+ * TODO: [🐠] Maybe base this on `makeValidator`
2088
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2089
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2090
+ * - [🏍] ? Is context in each template
2091
+ * - [♨] Are samples prepared
2092
+ * - [♨] Are templates prepared
2129
2093
  */
2130
2094
 
2131
2095
  /**
@@ -2145,27 +2109,6 @@ function serializeError(error) {
2145
2109
  };
2146
2110
  }
2147
2111
 
2148
- /**
2149
- * Function isValidJsonString will tell you if the string is valid JSON or not
2150
- *
2151
- * @public exported from `@promptbook/utils`
2152
- */
2153
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2154
- try {
2155
- JSON.parse(value);
2156
- return true;
2157
- }
2158
- catch (error) {
2159
- if (!(error instanceof Error)) {
2160
- throw error;
2161
- }
2162
- if (error.message.includes('Unexpected token')) {
2163
- return false;
2164
- }
2165
- return false;
2166
- }
2167
- }
2168
-
2169
2112
  /**
2170
2113
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2171
2114
  *
@@ -2192,9 +2135,10 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2192
2135
  });
2193
2136
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2194
2137
  get: function () {
2195
- return this.llmExecutionTools
2196
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2197
- .join('\n');
2138
+ return this.llmExecutionTools.map(function (_a, index) {
2139
+ var title = _a.title;
2140
+ return "".concat(index + 1, ") `").concat(title, "`");
2141
+ }).join('\n');
2198
2142
  },
2199
2143
  enumerable: false,
2200
2144
  configurable: true
@@ -2392,9 +2336,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2392
2336
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2393
2337
  }
2394
2338
  else {
2395
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.llmExecutionTools
2396
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2397
- .join('\n')), "\n\n "); }));
2339
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\"\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.description), "\n\n "); }));
2398
2340
  }
2399
2341
  }
2400
2342
  });
@@ -2460,95 +2402,700 @@ function joinLlmExecutionTools() {
2460
2402
  */
2461
2403
 
2462
2404
  /**
2463
- * Extracts all code blocks from markdown.
2405
+ * Takes an item or an array of items and returns an array of items
2464
2406
  *
2465
- * Note: There are multiple simmilar function:
2466
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2467
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2468
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2469
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2407
+ * 1) Any item except array and undefined returns array with that one item (also null)
2408
+ * 2) Undefined returns empty array
2409
+ * 3) Array returns itself
2470
2410
  *
2471
- * @param markdown any valid markdown
2472
- * @returns code blocks with language and content
2473
- * @throws {ParseError} if block is not closed properly
2474
- * @public exported from `@promptbook/markdown-utils`
2411
+ * @private internal utility
2475
2412
  */
2476
- function extractAllBlocksFromMarkdown(markdown) {
2477
- var e_1, _a;
2478
- var codeBlocks = [];
2479
- var lines = markdown.split('\n');
2480
- // Note: [0] Ensure that the last block notated by gt > will be closed
2481
- lines.push('');
2482
- var currentCodeBlock = null;
2483
- try {
2484
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2485
- var line = lines_1_1.value;
2486
- if (line.startsWith('> ') || line === '>') {
2487
- if (currentCodeBlock === null) {
2488
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2489
- } /* not else */
2490
- if (currentCodeBlock.blockNotation === '>') {
2491
- if (currentCodeBlock.content !== '') {
2492
- currentCodeBlock.content += '\n';
2493
- }
2494
- currentCodeBlock.content += line.slice(2);
2495
- }
2496
- }
2497
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2498
- codeBlocks.push(currentCodeBlock);
2499
- currentCodeBlock = null;
2500
- }
2501
- /* not else */
2502
- if (line.startsWith('```')) {
2503
- var language = line.slice(3).trim() || null;
2504
- if (currentCodeBlock === null) {
2505
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2506
- }
2507
- else {
2508
- if (language !== null) {
2509
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2510
- }
2511
- codeBlocks.push(currentCodeBlock);
2512
- currentCodeBlock = null;
2513
- }
2514
- }
2515
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2516
- if (currentCodeBlock.content !== '') {
2517
- currentCodeBlock.content += '\n';
2518
- }
2519
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2520
- }
2521
- }
2522
- }
2523
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2524
- finally {
2525
- try {
2526
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2527
- }
2528
- finally { if (e_1) throw e_1.error; }
2413
+ function arrayableToArray(input) {
2414
+ if (input === undefined) {
2415
+ return [];
2529
2416
  }
2530
- if (currentCodeBlock !== null) {
2531
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2417
+ if (input instanceof Array) {
2418
+ return input;
2532
2419
  }
2533
- return codeBlocks;
2420
+ return [input];
2534
2421
  }
2535
- /**
2536
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2537
- */
2538
2422
 
2539
2423
  /**
2540
- * Extracts extracts exactly one valid JSON code block
2541
- *
2542
- * - When given string is a valid JSON as it is, it just returns it
2543
- * - When there is no JSON code block the function throws a `ParseError`
2544
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2545
- *
2546
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2547
- * Note: There are multiple simmilar function:
2548
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2549
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2550
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2551
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2424
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2425
+ *
2426
+ * @param script from which to extract the variables
2427
+ * @returns the list of variable names
2428
+ * @throws {ParseError} if the script is invalid
2429
+ * @public exported from `@promptbook/utils`
2430
+ */
2431
+ function extractVariables(script) {
2432
+ var variables = new Set();
2433
+ script = "(()=>{".concat(script, "})()");
2434
+ try {
2435
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2436
+ try {
2437
+ eval(script);
2438
+ }
2439
+ catch (error) {
2440
+ if (!(error instanceof ReferenceError)) {
2441
+ throw error;
2442
+ }
2443
+ var undefinedName = error.message.split(' ')[0];
2444
+ /*
2445
+ Note: Parsing the error
2446
+ [PipelineUrlError: thing is not defined]
2447
+ */
2448
+ if (!undefinedName) {
2449
+ throw error;
2450
+ }
2451
+ if (script.includes(undefinedName + '(')) {
2452
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2453
+ }
2454
+ else {
2455
+ variables.add(undefinedName);
2456
+ script = "const ".concat(undefinedName, " = '';") + script;
2457
+ }
2458
+ }
2459
+ }
2460
+ catch (error) {
2461
+ if (!(error instanceof Error)) {
2462
+ throw error;
2463
+ }
2464
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2465
+ }
2466
+ return variables;
2467
+ }
2468
+ /**
2469
+ * TODO: [🔣] Support for multiple languages - python, java,...
2470
+ */
2471
+
2472
+ /**
2473
+ * Parses the template and returns the set of all used parameters
2474
+ *
2475
+ * @param template the template with used parameters
2476
+ * @returns the set of parameter names
2477
+ * @throws {ParseError} if the script is invalid
2478
+ * @public exported from `@promptbook/utils`
2479
+ */
2480
+ function extractParameterNamesFromTemplate(template) {
2481
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2482
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2483
+ var parameterNames = new Set();
2484
+ try {
2485
+ 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()) {
2486
+ var parameterName = _f.value;
2487
+ parameterNames.add(parameterName);
2488
+ }
2489
+ }
2490
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2491
+ finally {
2492
+ try {
2493
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2494
+ }
2495
+ finally { if (e_1) throw e_1.error; }
2496
+ }
2497
+ if (templateType === 'SCRIPT_TEMPLATE') {
2498
+ try {
2499
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2500
+ var parameterName = _h.value;
2501
+ parameterNames.add(parameterName);
2502
+ }
2503
+ }
2504
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2505
+ finally {
2506
+ try {
2507
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2508
+ }
2509
+ finally { if (e_2) throw e_2.error; }
2510
+ }
2511
+ }
2512
+ try {
2513
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2514
+ var jokerName = _k.value;
2515
+ parameterNames.add(jokerName);
2516
+ }
2517
+ }
2518
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2519
+ finally {
2520
+ try {
2521
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2522
+ }
2523
+ finally { if (e_3) throw e_3.error; }
2524
+ }
2525
+ parameterNames.delete('content');
2526
+ // <- Note {websiteContent} is used in `preparedContent`
2527
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2528
+ if (foreach !== undefined) {
2529
+ try {
2530
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2531
+ var subparameterName = _m.value;
2532
+ if (parameterNames.has(subparameterName)) {
2533
+ parameterNames.delete(subparameterName);
2534
+ parameterNames.add(foreach.parameterName);
2535
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2536
+ }
2537
+ }
2538
+ }
2539
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2540
+ finally {
2541
+ try {
2542
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2543
+ }
2544
+ finally { if (e_4) throw e_4.error; }
2545
+ }
2546
+ }
2547
+ return parameterNames;
2548
+ }
2549
+ /**
2550
+ * TODO: [🔣] If script require contentLanguage
2551
+ */
2552
+
2553
+ /**
2554
+ * Create difference set of two sets.
2555
+ *
2556
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2557
+ * @public exported from `@promptbook/utils`
2558
+ */
2559
+ function difference(a, b, isEqual) {
2560
+ var e_1, _a;
2561
+ if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2562
+ var diff = new Set();
2563
+ var _loop_1 = function (itemA) {
2564
+ if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2565
+ diff.add(itemA);
2566
+ }
2567
+ };
2568
+ try {
2569
+ for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2570
+ var itemA = _c.value;
2571
+ _loop_1(itemA);
2572
+ }
2573
+ }
2574
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2575
+ finally {
2576
+ try {
2577
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2578
+ }
2579
+ finally { if (e_1) throw e_1.error; }
2580
+ }
2581
+ return diff;
2582
+ }
2583
+ /**
2584
+ * TODO: [🧠][💯] Maybe also implement symmetricDifference
2585
+ */
2586
+
2587
+ /**
2588
+ * Creates a new set with all elements that are present in either set
2589
+ *
2590
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2591
+ * @public exported from `@promptbook/utils`
2592
+ */
2593
+ function union() {
2594
+ var e_1, _a, e_2, _b;
2595
+ var sets = [];
2596
+ for (var _i = 0; _i < arguments.length; _i++) {
2597
+ sets[_i] = arguments[_i];
2598
+ }
2599
+ var union = new Set();
2600
+ try {
2601
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2602
+ var set = sets_1_1.value;
2603
+ try {
2604
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2605
+ var item = _d.value;
2606
+ union.add(item);
2607
+ }
2608
+ }
2609
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2610
+ finally {
2611
+ try {
2612
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2613
+ }
2614
+ finally { if (e_2) throw e_2.error; }
2615
+ }
2616
+ }
2617
+ }
2618
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2619
+ finally {
2620
+ try {
2621
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2622
+ }
2623
+ finally { if (e_1) throw e_1.error; }
2624
+ }
2625
+ return union;
2626
+ }
2627
+
2628
+ /**
2629
+ * Just marks a place of place where should be something implemented
2630
+ * No side effects.
2631
+ *
2632
+ * Note: It can be usefull suppressing eslint errors of unused variables
2633
+ *
2634
+ * @param value any values
2635
+ * @returns void
2636
+ * @private within the repository
2637
+ */
2638
+ function TODO_USE() {
2639
+ var value = [];
2640
+ for (var _i = 0; _i < arguments.length; _i++) {
2641
+ value[_i] = arguments[_i];
2642
+ }
2643
+ }
2644
+
2645
+ /**
2646
+ * @@@
2647
+ *
2648
+ * @public exported from `@promptbook/core`
2649
+ */
2650
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2651
+ header: true,
2652
+ // encoding: 'utf8',
2653
+ });
2654
+
2655
+ /**
2656
+ * Definition for CSV spreadsheet
2657
+ *
2658
+ * @public exported from `@promptbook/core`
2659
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2660
+ */
2661
+ var CsvFormatDefinition = {
2662
+ formatName: 'CSV',
2663
+ aliases: ['SPREADSHEET', 'TABLE'],
2664
+ isValid: function (value, settings, schema) {
2665
+ // TODO: !!!!!! Implement CSV validation
2666
+ TODO_USE(value /* <- TODO: Use value here */);
2667
+ TODO_USE(settings /* <- TODO: Use settings here */);
2668
+ TODO_USE(schema /* <- TODO: Use schema here */);
2669
+ return true;
2670
+ },
2671
+ canBeValid: function (partialValue, settings, schema) {
2672
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2673
+ TODO_USE(settings /* <- TODO: Use settings here */);
2674
+ TODO_USE(schema /* <- TODO: Use schema here */);
2675
+ return true;
2676
+ },
2677
+ heal: function (value, settings, schema) {
2678
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2679
+ TODO_USE(settings /* <- TODO: Use settings here */);
2680
+ TODO_USE(schema /* <- TODO: Use schema here */);
2681
+ throw new Error('Not implemented');
2682
+ },
2683
+ subvalueDefinitions: [
2684
+ {
2685
+ subvalueName: 'ROW',
2686
+ mapValues: function (value, settings, mapCallback) {
2687
+ return __awaiter(this, void 0, void 0, function () {
2688
+ var csv, mappedData;
2689
+ var _this = this;
2690
+ return __generator(this, function (_a) {
2691
+ switch (_a.label) {
2692
+ case 0:
2693
+ csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2694
+ if (csv.errors.length !== 0) {
2695
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2696
+ spaceTrim$1(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2697
+ }
2698
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2699
+ var _a;
2700
+ var _b;
2701
+ return __generator(this, function (_c) {
2702
+ switch (_c.label) {
2703
+ case 0:
2704
+ _a = [__assign({}, row)];
2705
+ _b = {};
2706
+ // <- TODO: !!!!!! Dynamic new column name and position
2707
+ // <- TODO: !!!!!! Check name collisions
2708
+ return [4 /*yield*/, mapCallback(row, index)];
2709
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2710
+ // <- TODO: !!!!!! Dynamic new column name and position
2711
+ // <- TODO: !!!!!! Check name collisions
2712
+ _c.sent(), _b)])))];
2713
+ }
2714
+ });
2715
+ }); }))];
2716
+ case 1:
2717
+ mappedData = _a.sent();
2718
+ return [2 /*return*/, unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2719
+ }
2720
+ });
2721
+ });
2722
+ },
2723
+ },
2724
+ {
2725
+ subvalueName: 'CELL',
2726
+ mapValues: function (value, settings, mapCallback) {
2727
+ return __awaiter(this, void 0, void 0, function () {
2728
+ var csv, mappedData;
2729
+ var _this = this;
2730
+ return __generator(this, function (_a) {
2731
+ switch (_a.label) {
2732
+ case 0:
2733
+ csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2734
+ if (csv.errors.length !== 0) {
2735
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2736
+ spaceTrim$1(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2737
+ }
2738
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2739
+ var _this = this;
2740
+ return __generator(this, function (_a) {
2741
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2742
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2743
+ return __awaiter(_this, void 0, void 0, function () {
2744
+ var index;
2745
+ var _c;
2746
+ return __generator(this, function (_d) {
2747
+ index = rowIndex * Object.keys(row).length + columnIndex;
2748
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2749
+ });
2750
+ });
2751
+ }))];
2752
+ });
2753
+ }); }))];
2754
+ case 1:
2755
+ mappedData = _a.sent();
2756
+ return [2 /*return*/, unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2757
+ }
2758
+ });
2759
+ });
2760
+ },
2761
+ },
2762
+ ],
2763
+ };
2764
+ /**
2765
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2766
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2767
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2768
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2769
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2770
+ */
2771
+
2772
+ /**
2773
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2774
+ *
2775
+ * @public exported from `@promptbook/utils`
2776
+ */
2777
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2778
+ try {
2779
+ JSON.parse(value);
2780
+ return true;
2781
+ }
2782
+ catch (error) {
2783
+ if (!(error instanceof Error)) {
2784
+ throw error;
2785
+ }
2786
+ if (error.message.includes('Unexpected token')) {
2787
+ return false;
2788
+ }
2789
+ return false;
2790
+ }
2791
+ }
2792
+
2793
+ /**
2794
+ * Definition for JSON format
2795
+ *
2796
+ * @private still in development [🏢]
2797
+ */
2798
+ var JsonFormatDefinition = {
2799
+ formatName: 'JSON',
2800
+ mimeType: 'application/json',
2801
+ isValid: function (value, settings, schema) {
2802
+ TODO_USE(schema /* <- TODO: Use schema here */);
2803
+ TODO_USE(settings /* <- TODO: Use settings here */);
2804
+ return isValidJsonString(value);
2805
+ },
2806
+ canBeValid: function (partialValue, settings, schema) {
2807
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2808
+ TODO_USE(settings /* <- TODO: Use settings here */);
2809
+ TODO_USE(schema /* <- TODO: Use schema here */);
2810
+ return true;
2811
+ },
2812
+ heal: function (value, settings, schema) {
2813
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2814
+ TODO_USE(settings /* <- TODO: Use settings here */);
2815
+ TODO_USE(schema /* <- TODO: Use schema here */);
2816
+ throw new Error('Not implemented');
2817
+ },
2818
+ subvalueDefinitions: [],
2819
+ };
2820
+ /**
2821
+ * TODO: [🧠] Maybe propper instance of object
2822
+ * TODO: [0] Make string_serialized_json
2823
+ * TODO: [1] Make type for JSON Settings and Schema
2824
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2825
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2826
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2827
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2828
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2829
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2830
+ */
2831
+
2832
+ /**
2833
+ * Definition for any text - this will be always valid
2834
+ *
2835
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
2836
+ *
2837
+ * @public exported from `@promptbook/core`
2838
+ */
2839
+ var TextFormatDefinition = {
2840
+ formatName: 'TEXT',
2841
+ isValid: function (value) {
2842
+ return typeof value === 'string';
2843
+ },
2844
+ canBeValid: function (partialValue) {
2845
+ return typeof partialValue === 'string';
2846
+ },
2847
+ heal: function () {
2848
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
2849
+ },
2850
+ subvalueDefinitions: [
2851
+ {
2852
+ subvalueName: 'LINE',
2853
+ mapValues: function (value, settings, mapCallback) {
2854
+ return __awaiter(this, void 0, void 0, function () {
2855
+ var lines, mappedLines;
2856
+ return __generator(this, function (_a) {
2857
+ switch (_a.label) {
2858
+ case 0:
2859
+ lines = value.split('\n');
2860
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
2861
+ // TODO: [🧠] Maybe option to skip empty line
2862
+ /* not await */ return mapCallback({
2863
+ lineContent: lineContent,
2864
+ // TODO: [🧠] Maybe also put here `lineNumber`
2865
+ }, lineNumber);
2866
+ }))];
2867
+ case 1:
2868
+ mappedLines = _a.sent();
2869
+ return [2 /*return*/, mappedLines.join('\n')];
2870
+ }
2871
+ });
2872
+ });
2873
+ },
2874
+ },
2875
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2876
+ ],
2877
+ };
2878
+ /**
2879
+ * TODO: [1] Make type for XML Text and Schema
2880
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2881
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
2882
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
2883
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
2884
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
2885
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
2886
+ */
2887
+
2888
+ /**
2889
+ * Definition for XML format
2890
+ *
2891
+ * @private still in development [🏢]
2892
+ */
2893
+ var XmlFormatDefinition = {
2894
+ formatName: 'XML',
2895
+ mimeType: 'application/xml',
2896
+ isValid: function (value, settings, schema) {
2897
+ TODO_USE(value /* <- TODO: Use value here */);
2898
+ TODO_USE(settings /* <- TODO: Use settings here */);
2899
+ TODO_USE(schema /* <- TODO: Use schema here */);
2900
+ return true;
2901
+ },
2902
+ canBeValid: function (partialValue, settings, schema) {
2903
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2904
+ TODO_USE(settings /* <- TODO: Use settings here */);
2905
+ TODO_USE(schema /* <- TODO: Use schema here */);
2906
+ return true;
2907
+ },
2908
+ heal: function (value, settings, schema) {
2909
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2910
+ TODO_USE(settings /* <- TODO: Use settings here */);
2911
+ TODO_USE(schema /* <- TODO: Use schema here */);
2912
+ throw new Error('Not implemented');
2913
+ },
2914
+ subvalueDefinitions: [],
2915
+ };
2916
+ /**
2917
+ * TODO: [🧠] Maybe propper instance of object
2918
+ * TODO: [0] Make string_serialized_xml
2919
+ * TODO: [1] Make type for XML Settings and Schema
2920
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
2921
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
2922
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
2923
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
2924
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
2925
+ * TODO: [🏢] Allow to expect something inside XML and other formats
2926
+ */
2927
+
2928
+ /**
2929
+ * Definitions for all formats supported by Promptbook
2930
+ *
2931
+ * @private internal index of `...` <- TODO [🏢]
2932
+ */
2933
+ var FORMAT_DEFINITIONS = [
2934
+ JsonFormatDefinition,
2935
+ XmlFormatDefinition,
2936
+ TextFormatDefinition,
2937
+ CsvFormatDefinition,
2938
+ ];
2939
+
2940
+ /**
2941
+ * Maps available parameters to expected parameters
2942
+ *
2943
+ * The strategy is:
2944
+ * 1) @@@
2945
+ * 2) @@@
2946
+ *
2947
+ * @throws {PipelineExecutionError} @@@
2948
+ * @private within the repository used in `createPipelineExecutor`
2949
+ */
2950
+ function mapAvailableToExpectedParameters(options) {
2951
+ var e_1, _a;
2952
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
2953
+ var availableParametersNames = new Set(Object.keys(availableParameters));
2954
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
2955
+ var mappedParameters = {};
2956
+ try {
2957
+ // Phase 1️⃣: Matching mapping
2958
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
2959
+ var parameterName = _c.value;
2960
+ // Situation: Parameter is available and expected
2961
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
2962
+ mappedParameters[parameterName] = availableParameters[parameterName];
2963
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
2964
+ availableParametersNames.delete(parameterName);
2965
+ expectedParameterNames.delete(parameterName);
2966
+ }
2967
+ // Situation: Parameter is available but NOT expected
2968
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
2969
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
2970
+ }
2971
+ // Situation: Parameter is NOT available BUT expected
2972
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
2973
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
2974
+ }
2975
+ }
2976
+ }
2977
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2978
+ finally {
2979
+ try {
2980
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2981
+ }
2982
+ finally { if (e_1) throw e_1.error; }
2983
+ }
2984
+ if (expectedParameterNames.size === 0) {
2985
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
2986
+ Object.freeze(mappedParameters);
2987
+ return mappedParameters;
2988
+ }
2989
+ // Phase 2️⃣: Non-matching mapping
2990
+ if (expectedParameterNames.size !== availableParametersNames.size) {
2991
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
2992
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
2993
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
2994
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
2995
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
2996
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
2997
+ .join('\n')), "\n\n "); }));
2998
+ }
2999
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3000
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3001
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3002
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3003
+ }
3004
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3005
+ Object.freeze(mappedParameters);
3006
+ return mappedParameters;
3007
+ }
3008
+
3009
+ /**
3010
+ * Extracts all code blocks from markdown.
3011
+ *
3012
+ * Note: There are multiple simmilar function:
3013
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3014
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3015
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3016
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3017
+ *
3018
+ * @param markdown any valid markdown
3019
+ * @returns code blocks with language and content
3020
+ * @throws {ParseError} if block is not closed properly
3021
+ * @public exported from `@promptbook/markdown-utils`
3022
+ */
3023
+ function extractAllBlocksFromMarkdown(markdown) {
3024
+ var e_1, _a;
3025
+ var codeBlocks = [];
3026
+ var lines = markdown.split('\n');
3027
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3028
+ lines.push('');
3029
+ var currentCodeBlock = null;
3030
+ try {
3031
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3032
+ var line = lines_1_1.value;
3033
+ if (line.startsWith('> ') || line === '>') {
3034
+ if (currentCodeBlock === null) {
3035
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3036
+ } /* not else */
3037
+ if (currentCodeBlock.blockNotation === '>') {
3038
+ if (currentCodeBlock.content !== '') {
3039
+ currentCodeBlock.content += '\n';
3040
+ }
3041
+ currentCodeBlock.content += line.slice(2);
3042
+ }
3043
+ }
3044
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3045
+ codeBlocks.push(currentCodeBlock);
3046
+ currentCodeBlock = null;
3047
+ }
3048
+ /* not else */
3049
+ if (line.startsWith('```')) {
3050
+ var language = line.slice(3).trim() || null;
3051
+ if (currentCodeBlock === null) {
3052
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3053
+ }
3054
+ else {
3055
+ if (language !== null) {
3056
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3057
+ }
3058
+ codeBlocks.push(currentCodeBlock);
3059
+ currentCodeBlock = null;
3060
+ }
3061
+ }
3062
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3063
+ if (currentCodeBlock.content !== '') {
3064
+ currentCodeBlock.content += '\n';
3065
+ }
3066
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3067
+ }
3068
+ }
3069
+ }
3070
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3071
+ finally {
3072
+ try {
3073
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3074
+ }
3075
+ finally { if (e_1) throw e_1.error; }
3076
+ }
3077
+ if (currentCodeBlock !== null) {
3078
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3079
+ }
3080
+ return codeBlocks;
3081
+ }
3082
+ /**
3083
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3084
+ */
3085
+
3086
+ /**
3087
+ * Extracts extracts exactly one valid JSON code block
3088
+ *
3089
+ * - When given string is a valid JSON as it is, it just returns it
3090
+ * - When there is no JSON code block the function throws a `ParseError`
3091
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3092
+ *
3093
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3094
+ * Note: There are multiple simmilar function:
3095
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3096
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3097
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3098
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2552
3099
  *
2553
3100
  * @public exported from `@promptbook/markdown-utils`
2554
3101
  * @throws {ParseError} if there is no valid JSON block in the markdown
@@ -2575,57 +3122,6 @@ function extractJsonBlock(markdown) {
2575
3122
  * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2576
3123
  */
2577
3124
 
2578
- /**
2579
- * Determine if the pipeline is fully prepared
2580
- *
2581
- * @public exported from `@promptbook/core`
2582
- */
2583
- function isPipelinePrepared(pipeline) {
2584
- // Note: Ignoring `pipeline.preparations` @@@
2585
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2586
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2587
- return false;
2588
- }
2589
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2590
- return false;
2591
- }
2592
- /*
2593
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2594
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2595
- > return false;
2596
- > }
2597
- */
2598
- return true;
2599
- }
2600
- /**
2601
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2602
- * TODO: [🐠] Maybe base this on `makeValidator`
2603
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2604
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2605
- * - [🏍] ? Is context in each template
2606
- * - [♨] Are samples prepared
2607
- * - [♨] Are templates prepared
2608
- */
2609
-
2610
- /**
2611
- * Takes an item or an array of items and returns an array of items
2612
- *
2613
- * 1) Any item except array and undefined returns array with that one item (also null)
2614
- * 2) Undefined returns empty array
2615
- * 3) Array returns itself
2616
- *
2617
- * @private internal utility
2618
- */
2619
- function arrayableToArray(input) {
2620
- if (input === undefined) {
2621
- return [];
2622
- }
2623
- if (input instanceof Array) {
2624
- return input;
2625
- }
2626
- return [input];
2627
- }
2628
-
2629
3125
  /**
2630
3126
  * Just says that the variable is not used but should be kept
2631
3127
  * No side effects.
@@ -2647,23 +3143,6 @@ function keepUnused() {
2647
3143
  }
2648
3144
  }
2649
3145
 
2650
- /**
2651
- * Just marks a place of place where should be something implemented
2652
- * No side effects.
2653
- *
2654
- * Note: It can be usefull suppressing eslint errors of unused variables
2655
- *
2656
- * @param value any values
2657
- * @returns void
2658
- * @private within the repository
2659
- */
2660
- function TODO_USE() {
2661
- var value = [];
2662
- for (var _i = 0; _i < arguments.length; _i++) {
2663
- value[_i] = arguments[_i];
2664
- }
2665
- }
2666
-
2667
3146
  /**
2668
3147
  * Replaces parameters in template with values from parameters object
2669
3148
  *
@@ -2720,102 +3199,27 @@ function replaceParameters(template, parameters) {
2720
3199
  if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2721
3200
  parameterValue = parameterValue
2722
3201
  .split('\n')
2723
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2724
- .join('\n');
2725
- }
2726
- replacedTemplate =
2727
- replacedTemplate.substring(0, match.index + precol.length) +
2728
- parameterValue +
2729
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2730
- };
2731
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2732
- .exec(replacedTemplate))) {
2733
- _loop_1();
2734
- }
2735
- // [💫] Check if there are parameters that are not closed properly
2736
- if (/{\w+$/.test(replacedTemplate)) {
2737
- throw new PipelineExecutionError('Parameter is not closed');
2738
- }
2739
- // [💫] Check if there are parameters that are not opened properly
2740
- if (/^\w+}/.test(replacedTemplate)) {
2741
- throw new PipelineExecutionError('Parameter is not opened');
2742
- }
2743
- return replacedTemplate;
2744
- }
2745
-
2746
- /**
2747
- * Create difference set of two sets.
2748
- *
2749
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2750
- * @public exported from `@promptbook/utils`
2751
- */
2752
- function difference(a, b, isEqual) {
2753
- var e_1, _a;
2754
- if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2755
- var diff = new Set();
2756
- var _loop_1 = function (itemA) {
2757
- if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2758
- diff.add(itemA);
2759
- }
2760
- };
2761
- try {
2762
- for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2763
- var itemA = _c.value;
2764
- _loop_1(itemA);
2765
- }
2766
- }
2767
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2768
- finally {
2769
- try {
2770
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2771
- }
2772
- finally { if (e_1) throw e_1.error; }
2773
- }
2774
- return diff;
2775
- }
2776
- /**
2777
- * TODO: [🧠][💯] Maybe also implement symmetricDifference
2778
- */
2779
-
2780
- /**
2781
- * Creates a new set with all elements that are present in either set
2782
- *
2783
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2784
- * @public exported from `@promptbook/utils`
2785
- */
2786
- function union() {
2787
- var e_1, _a, e_2, _b;
2788
- var sets = [];
2789
- for (var _i = 0; _i < arguments.length; _i++) {
2790
- sets[_i] = arguments[_i];
2791
- }
2792
- var union = new Set();
2793
- try {
2794
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2795
- var set = sets_1_1.value;
2796
- try {
2797
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2798
- var item = _d.value;
2799
- union.add(item);
2800
- }
2801
- }
2802
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2803
- finally {
2804
- try {
2805
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2806
- }
2807
- finally { if (e_2) throw e_2.error; }
2808
- }
2809
- }
2810
- }
2811
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2812
- finally {
2813
- try {
2814
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
3202
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3203
+ .join('\n');
2815
3204
  }
2816
- finally { if (e_1) throw e_1.error; }
3205
+ replacedTemplate =
3206
+ replacedTemplate.substring(0, match.index + precol.length) +
3207
+ parameterValue +
3208
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3209
+ };
3210
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3211
+ .exec(replacedTemplate))) {
3212
+ _loop_1();
2817
3213
  }
2818
- return union;
3214
+ // [💫] Check if there are parameters that are not closed properly
3215
+ if (/{\w+$/.test(replacedTemplate)) {
3216
+ throw new PipelineExecutionError('Parameter is not closed');
3217
+ }
3218
+ // [💫] Check if there are parameters that are not opened properly
3219
+ if (/^\w+}/.test(replacedTemplate)) {
3220
+ throw new PipelineExecutionError('Parameter is not opened');
3221
+ }
3222
+ return replacedTemplate;
2819
3223
  }
2820
3224
 
2821
3225
  /**
@@ -2907,6 +3311,9 @@ var CountUtils = {
2907
3311
  LINES: countLines,
2908
3312
  PAGES: countPages,
2909
3313
  };
3314
+ /**
3315
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3316
+ */
2910
3317
 
2911
3318
  /**
2912
3319
  * Function checkExpectations will check if the expectations on given value are met
@@ -2943,597 +3350,748 @@ function checkExpectations(expectations, value) {
2943
3350
  }
2944
3351
  /**
2945
3352
  * TODO: [💝] Unite object for expecting amount and format
3353
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3354
+ * Note: [💝] and [🤠] are interconnected together
2946
3355
  */
2947
3356
 
2948
3357
  /**
2949
- * Creates executor function from pipeline and execution tools.
3358
+ * @@@
2950
3359
  *
2951
- * @returns The executor function
2952
- * @throws {PipelineLogicError} on logical error in the pipeline
2953
- * @public exported from `@promptbook/core`
3360
+ * @private internal utility of `createPipelineExecutor`
2954
3361
  */
2955
- function createPipelineExecutor(options) {
2956
- var _this = this;
2957
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
2958
- 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;
2959
- validatePipeline(pipeline);
2960
- var pipelineIdentification = (function () {
2961
- // Note: This is a 😐 implementation of [🚞]
2962
- var _ = [];
2963
- if (pipeline.sourceFile !== undefined) {
2964
- _.push("File: ".concat(pipeline.sourceFile));
2965
- }
2966
- if (pipeline.pipelineUrl !== undefined) {
2967
- _.push("Url: ".concat(pipeline.pipelineUrl));
2968
- }
2969
- return _.join('\n');
2970
- })();
2971
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
2972
- var preparedPipeline;
2973
- if (isPipelinePrepared(pipeline)) {
2974
- preparedPipeline = pipeline;
2975
- }
2976
- else if (isNotPreparedWarningSupressed !== true) {
2977
- console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
2978
- }
2979
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
2980
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
2981
- function getContextForTemplate(template) {
2982
- return __awaiter(this, void 0, void 0, function () {
2983
- return __generator(this, function (_a) {
2984
- TODO_USE(template);
2985
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
2986
- });
2987
- });
2988
- }
2989
- function getKnowledgeForTemplate(template) {
2990
- return __awaiter(this, void 0, void 0, function () {
2991
- return __generator(this, function (_a) {
2992
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
2993
- TODO_USE(template);
2994
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
2995
- var content = _a.content;
2996
- return "- ".concat(content);
2997
- }).join('\n')];
2998
- });
2999
- });
3000
- }
3001
- function getSamplesForTemplate(template) {
3002
- return __awaiter(this, void 0, void 0, function () {
3003
- return __generator(this, function (_a) {
3004
- // TODO: [♨] Implement Better - use real index and keyword search
3005
- TODO_USE(template);
3006
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3007
- });
3008
- });
3009
- }
3010
- function getReservedParametersForTemplate(template) {
3011
- return __awaiter(this, void 0, void 0, function () {
3012
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3013
- var e_3, _a;
3014
- return __generator(this, function (_b) {
3015
- switch (_b.label) {
3016
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3017
- case 1:
3018
- context = _b.sent();
3019
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3020
- case 2:
3021
- knowledge = _b.sent();
3022
- return [4 /*yield*/, getSamplesForTemplate(template)];
3023
- case 3:
3024
- samples = _b.sent();
3025
- currentDate = new Date().toISOString();
3026
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3027
- reservedParameters = {
3028
- content: RESERVED_PARAMETER_RESTRICTED,
3029
- context: context,
3030
- knowledge: knowledge,
3031
- samples: samples,
3032
- currentDate: currentDate,
3033
- modelName: modelName,
3034
- };
3035
- _loop_3 = function (parameterName) {
3036
- if (reservedParameters[parameterName] === undefined) {
3037
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3038
- }
3039
- };
3040
- try {
3041
- // Note: Doublecheck that ALL reserved parameters are defined:
3042
- 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()) {
3043
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3044
- _loop_3(parameterName);
3045
- }
3046
- }
3047
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3048
- finally {
3049
- try {
3050
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3051
- }
3052
- finally { if (e_3) throw e_3.error; }
3053
- }
3054
- return [2 /*return*/, reservedParameters];
3055
- }
3056
- });
3057
- });
3058
- }
3059
- function executeSingleTemplate(currentTemplate) {
3060
- return __awaiter(this, void 0, void 0, function () {
3061
- 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;
3062
- var e_4, _f, _g;
3063
- return __generator(this, function (_h) {
3064
- switch (_h.label) {
3065
- case 0:
3066
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3067
- title = currentTemplate.title;
3068
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3069
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3070
- progress_1 = {
3071
- name: name,
3072
- title: title,
3073
- isStarted: false,
3074
- isDone: false,
3075
- templateType: currentTemplate.templateType,
3076
- parameterName: currentTemplate.resultingParameterName,
3077
- parameterValue: null,
3078
- // <- [3]
3079
- };
3080
- if (isReturned) {
3081
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3082
- .split('\n')
3083
- .map(function (line) { return "> ".concat(line); })
3084
- .join('\n')), "\n "); }));
3085
- }
3086
- return [4 /*yield*/, onProgress(progress_1)];
3087
- case 1:
3088
- _h.sent();
3089
- _h.label = 2;
3090
- case 2:
3091
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3092
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3093
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3094
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3095
- .map(function (name) { return "{".concat(name, "}"); })
3096
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3097
- .map(function (name) { return "{".concat(name, "}"); })
3098
- .join(', '), "\n\n "); }));
3099
- }
3100
- _b = (_a = Object).freeze;
3101
- _c = [{}];
3102
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3103
- case 3:
3104
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3105
- definedParameterNames = new Set(Object.keys(definedParameters));
3106
- parameters = {};
3107
- _loop_4 = function (parameterName) {
3108
- // Situation: Parameter is defined and used
3109
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3110
- parameters[parameterName] = definedParameters[parameterName];
3111
- }
3112
- // Situation: Parameter is defined but NOT used
3113
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3114
- // Situation: Parameter is NOT defined BUT used
3115
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3116
- // Houston, we have a problem
3117
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3118
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3119
- }
3120
- };
3121
- try {
3122
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3123
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3124
- parameterName = _e.value;
3125
- _loop_4(parameterName);
3126
- }
3127
- }
3128
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3129
- finally {
3130
- try {
3131
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3132
- }
3133
- finally { if (e_4) throw e_4.error; }
3134
- }
3135
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3136
- Object.freeze(parameters);
3137
- result = null;
3138
- resultString = null;
3139
- expectError = null;
3140
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3141
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3142
- preparedContent = (currentTemplate.preparedContent || '{content}')
3143
- .split('{content}')
3144
- .join(currentTemplate.content);
3145
- _loop_5 = function (attempt) {
3146
- 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;
3147
- var e_5, _s, e_7, _t, e_6, _u;
3148
- return __generator(this, function (_v) {
3149
- switch (_v.label) {
3150
- case 0:
3151
- isJokerAttempt = attempt < 0;
3152
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3153
- if (isJokerAttempt && !jokerParameterName) {
3154
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3155
- }
3156
- result = null;
3157
- resultString = null;
3158
- expectError = null;
3159
- if (isJokerAttempt) {
3160
- if (parameters[jokerParameterName] === undefined) {
3161
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3162
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3163
- }
3164
- else {
3165
- resultString = parameters[jokerParameterName];
3166
- }
3167
- }
3168
- _v.label = 1;
3169
- case 1:
3170
- _v.trys.push([1, 44, 45, 46]);
3171
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3172
- _j = currentTemplate.templateType;
3173
- switch (_j) {
3174
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3175
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3176
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3177
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3178
- }
3179
- return [3 /*break*/, 25];
3180
- case 2:
3181
- resultString = replaceParameters(preparedContent, parameters);
3182
- return [3 /*break*/, 26];
3183
- case 3:
3184
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3185
- prompt = {
3186
- title: currentTemplate.title,
3187
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3188
- ? preparedPipeline.pipelineUrl
3189
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3190
- parameters: parameters,
3191
- content: preparedContent,
3192
- modelRequirements: modelRequirements,
3193
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3194
- var name = _a.name;
3195
- return name === currentTemplate.personaName;
3196
- }) || {})), currentTemplate.expectations),
3197
- format: currentTemplate.format,
3198
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3199
- }; // <- TODO: Not very good type guard
3200
- _k = modelRequirements.modelVariant;
3201
- switch (_k) {
3202
- case 'CHAT': return [3 /*break*/, 4];
3203
- case 'COMPLETION': return [3 /*break*/, 6];
3204
- case 'EMBEDDING': return [3 /*break*/, 8];
3205
- }
3206
- return [3 /*break*/, 10];
3207
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3208
- case 5:
3209
- chatResult = _v.sent();
3210
- // TODO: [🍬] Destroy chatThread
3211
- result = chatResult;
3212
- resultString = chatResult.content;
3213
- return [3 /*break*/, 11];
3214
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3215
- case 7:
3216
- completionResult = _v.sent();
3217
- result = completionResult;
3218
- resultString = completionResult.content;
3219
- return [3 /*break*/, 11];
3220
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3221
- case 9:
3222
- embeddingResult = _v.sent();
3223
- result = embeddingResult;
3224
- resultString = embeddingResult.content.join(',');
3225
- return [3 /*break*/, 11];
3226
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3227
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3228
- case 11: return [3 /*break*/, 26];
3229
- case 12:
3230
- if (arrayableToArray(tools.script).length === 0) {
3231
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3232
- }
3233
- if (!currentTemplate.contentLanguage) {
3234
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3235
- }
3236
- // TODO: DRY [1]
3237
- scriptPipelineExecutionErrors = [];
3238
- _v.label = 13;
3239
- case 13:
3240
- _v.trys.push([13, 20, 21, 22]);
3241
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3242
- _v.label = 14;
3243
- case 14:
3244
- if (!!_m.done) return [3 /*break*/, 19];
3245
- scriptTools = _m.value;
3246
- _v.label = 15;
3247
- case 15:
3248
- _v.trys.push([15, 17, , 18]);
3249
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3250
- scriptLanguage: currentTemplate.contentLanguage,
3251
- script: preparedContent,
3252
- parameters: parameters,
3253
- }))];
3254
- case 16:
3255
- resultString = _v.sent();
3256
- return [3 /*break*/, 19];
3257
- case 17:
3258
- error_2 = _v.sent();
3259
- if (!(error_2 instanceof Error)) {
3260
- throw error_2;
3261
- }
3262
- if (error_2 instanceof UnexpectedError) {
3263
- throw error_2;
3264
- }
3265
- scriptPipelineExecutionErrors.push(error_2);
3266
- return [3 /*break*/, 18];
3267
- case 18:
3268
- _m = _l.next();
3269
- return [3 /*break*/, 14];
3270
- case 19: return [3 /*break*/, 22];
3271
- case 20:
3272
- e_5_1 = _v.sent();
3273
- e_5 = { error: e_5_1 };
3274
- return [3 /*break*/, 22];
3275
- case 21:
3276
- try {
3277
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3278
- }
3279
- finally { if (e_5) throw e_5.error; }
3280
- return [7 /*endfinally*/];
3281
- case 22:
3282
- if (resultString !== null) {
3283
- return [3 /*break*/, 26];
3284
- }
3285
- if (scriptPipelineExecutionErrors.length === 1) {
3286
- throw scriptPipelineExecutionErrors[0];
3287
- }
3288
- else {
3289
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3290
- .map(function (error) { return '- ' + error.message; })
3291
- .join('\n\n')), "\n "); }));
3292
- }
3293
- case 23:
3294
- if (tools.userInterface === undefined) {
3295
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3296
- }
3297
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3298
- promptTitle: currentTemplate.title,
3299
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3300
- defaultValue: replaceParameters(preparedContent, parameters),
3301
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3302
- placeholder: undefined,
3303
- priority: priority,
3304
- }))];
3305
- case 24:
3306
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3307
- resultString = _v.sent();
3308
- return [3 /*break*/, 26];
3309
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3310
- case 26:
3311
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3312
- _v.label = 27;
3313
- case 27:
3314
- _v.trys.push([27, 41, 42, 43]);
3315
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3316
- _v.label = 28;
3317
- case 28:
3318
- if (!!_p.done) return [3 /*break*/, 40];
3319
- functionName = _p.value;
3320
- // TODO: DRY [1]
3321
- scriptPipelineExecutionErrors = [];
3322
- postprocessingError = null;
3323
- _v.label = 29;
3324
- case 29:
3325
- _v.trys.push([29, 36, 37, 38]);
3326
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3327
- _v.label = 30;
3328
- case 30:
3329
- if (!!_r.done) return [3 /*break*/, 35];
3330
- scriptTools = _r.value;
3331
- _v.label = 31;
3332
- case 31:
3333
- _v.trys.push([31, 33, , 34]);
3334
- return [4 /*yield*/, scriptTools.execute({
3335
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3336
- script: "".concat(functionName, "(resultString)"),
3337
- parameters: {
3338
- resultString: resultString || '',
3339
- // Note: No ...parametersForTemplate, because working with result only
3340
- },
3341
- })];
3342
- case 32:
3343
- resultString = _v.sent();
3344
- postprocessingError = null;
3345
- return [3 /*break*/, 35];
3346
- case 33:
3347
- error_3 = _v.sent();
3348
- if (!(error_3 instanceof Error)) {
3349
- throw error_3;
3350
- }
3351
- if (error_3 instanceof UnexpectedError) {
3352
- throw error_3;
3353
- }
3354
- postprocessingError = error_3;
3355
- scriptPipelineExecutionErrors.push(error_3);
3356
- return [3 /*break*/, 34];
3357
- case 34:
3358
- _r = _q.next();
3359
- return [3 /*break*/, 30];
3360
- case 35: return [3 /*break*/, 38];
3361
- case 36:
3362
- e_6_1 = _v.sent();
3363
- e_6 = { error: e_6_1 };
3364
- return [3 /*break*/, 38];
3365
- case 37:
3366
- try {
3367
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3368
- }
3369
- finally { if (e_6) throw e_6.error; }
3370
- return [7 /*endfinally*/];
3371
- case 38:
3372
- if (postprocessingError) {
3373
- throw postprocessingError;
3374
- }
3375
- _v.label = 39;
3376
- case 39:
3377
- _p = _o.next();
3378
- return [3 /*break*/, 28];
3379
- case 40: return [3 /*break*/, 43];
3380
- case 41:
3381
- e_7_1 = _v.sent();
3382
- e_7 = { error: e_7_1 };
3383
- return [3 /*break*/, 43];
3384
- case 42:
3385
- try {
3386
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3387
- }
3388
- finally { if (e_7) throw e_7.error; }
3389
- return [7 /*endfinally*/];
3390
- case 43:
3391
- // TODO: [💝] Unite object for expecting amount and format
3392
- if (currentTemplate.format) {
3393
- if (currentTemplate.format === 'JSON') {
3394
- if (!isValidJsonString(resultString || '')) {
3395
- // TODO: [🏢] Do more universally via `FormatDefinition`
3396
- try {
3397
- resultString = extractJsonBlock(resultString || '');
3398
- }
3399
- catch (error) {
3400
- keepUnused(error);
3401
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3402
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3403
- }
3404
- }
3362
+ function executeAttempts(options) {
3363
+ return __awaiter(this, void 0, void 0, function () {
3364
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3365
+ return __generator(this, function (_a) {
3366
+ switch (_a.label) {
3367
+ case 0:
3368
+ 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;
3369
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3370
+ $ongoingTemplateResult = {
3371
+ $result: null,
3372
+ $resultString: null,
3373
+ $expectError: null,
3374
+ $scriptPipelineExecutionErrors: [],
3375
+ };
3376
+ _loop_1 = function (attempt) {
3377
+ var isJokerAttempt, jokerParameterName, _b, modelRequirements, _c, _d, _e, _f, _g, scriptTools, _h, error_1, e_1_1, _j, _k, _l, functionName, postprocessingError, _m, _o, scriptTools, _p, error_2, e_2_1, e_3_1, error_3;
3378
+ var e_1, _q, e_3, _r, e_2, _s;
3379
+ return __generator(this, function (_t) {
3380
+ switch (_t.label) {
3381
+ case 0:
3382
+ isJokerAttempt = attempt < 0;
3383
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3384
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3385
+ if (isJokerAttempt && !jokerParameterName) {
3386
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3387
+ }
3388
+ $ongoingTemplateResult.$result = null;
3389
+ $ongoingTemplateResult.$resultString = null;
3390
+ $ongoingTemplateResult.$expectError = null;
3391
+ if (isJokerAttempt) {
3392
+ if (parameters[jokerParameterName] === undefined) {
3393
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3394
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3395
+ }
3396
+ else {
3397
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3398
+ }
3399
+ }
3400
+ _t.label = 1;
3401
+ case 1:
3402
+ _t.trys.push([1, 43, 44, 45]);
3403
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3404
+ _b = template.templateType;
3405
+ switch (_b) {
3406
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3407
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3408
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3409
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3410
+ }
3411
+ return [3 /*break*/, 24];
3412
+ case 2:
3413
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3414
+ return [3 /*break*/, 25];
3415
+ case 3:
3416
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3417
+ $ongoingTemplateResult.$prompt = {
3418
+ title: template.title,
3419
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3420
+ ? preparedPipeline.pipelineUrl
3421
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3422
+ parameters: parameters,
3423
+ content: preparedContent,
3424
+ modelRequirements: modelRequirements,
3425
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3426
+ var name = _a.name;
3427
+ return name === template.personaName;
3428
+ }) ||
3429
+ {})), template.expectations),
3430
+ format: template.format,
3431
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3432
+ }; // <- TODO: Not very good type guard
3433
+ _c = modelRequirements.modelVariant;
3434
+ switch (_c) {
3435
+ case 'CHAT': return [3 /*break*/, 4];
3436
+ case 'COMPLETION': return [3 /*break*/, 6];
3437
+ case 'EMBEDDING': return [3 /*break*/, 8];
3438
+ }
3439
+ return [3 /*break*/, 9];
3440
+ case 4:
3441
+ _d = $ongoingTemplateResult;
3442
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3443
+ case 5:
3444
+ _d.$chatResult = _t.sent();
3445
+ // TODO: [🍬] Destroy chatThread
3446
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3447
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3448
+ return [3 /*break*/, 10];
3449
+ case 6:
3450
+ _e = $ongoingTemplateResult;
3451
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3452
+ case 7:
3453
+ _e.$completionResult = _t.sent();
3454
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3455
+ $ongoingTemplateResult.$resultString =
3456
+ $ongoingTemplateResult.$completionResult.content;
3457
+ return [3 /*break*/, 10];
3458
+ case 8: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Embedding model can not be used in pipeline\n\n This should be catched during parsing\n\n ".concat(block(pipelineIdentification), "\n\n "); }));
3459
+ case 9: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3460
+ case 10: return [3 /*break*/, 25];
3461
+ case 11:
3462
+ if (arrayableToArray(tools.script).length === 0) {
3463
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3464
+ }
3465
+ if (!template.contentLanguage) {
3466
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3467
+ }
3468
+ _t.label = 12;
3469
+ case 12:
3470
+ _t.trys.push([12, 19, 20, 21]);
3471
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3472
+ _t.label = 13;
3473
+ case 13:
3474
+ if (!!_g.done) return [3 /*break*/, 18];
3475
+ scriptTools = _g.value;
3476
+ _t.label = 14;
3477
+ case 14:
3478
+ _t.trys.push([14, 16, , 17]);
3479
+ _h = $ongoingTemplateResult;
3480
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3481
+ scriptLanguage: template.contentLanguage,
3482
+ script: preparedContent,
3483
+ parameters: parameters,
3484
+ }))];
3485
+ case 15:
3486
+ _h.$resultString = _t.sent();
3487
+ return [3 /*break*/, 18];
3488
+ case 16:
3489
+ error_1 = _t.sent();
3490
+ if (!(error_1 instanceof Error)) {
3491
+ throw error_1;
3492
+ }
3493
+ if (error_1 instanceof UnexpectedError) {
3494
+ throw error_1;
3495
+ }
3496
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3497
+ return [3 /*break*/, 17];
3498
+ case 17:
3499
+ _g = _f.next();
3500
+ return [3 /*break*/, 13];
3501
+ case 18: return [3 /*break*/, 21];
3502
+ case 19:
3503
+ e_1_1 = _t.sent();
3504
+ e_1 = { error: e_1_1 };
3505
+ return [3 /*break*/, 21];
3506
+ case 20:
3507
+ try {
3508
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3509
+ }
3510
+ finally { if (e_1) throw e_1.error; }
3511
+ return [7 /*endfinally*/];
3512
+ case 21:
3513
+ if ($ongoingTemplateResult.$resultString !== null) {
3514
+ return [3 /*break*/, 25];
3515
+ }
3516
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3517
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3518
+ }
3519
+ else {
3520
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3521
+ .map(function (error) { return '- ' + error.message; })
3522
+ .join('\n\n')), "\n "); }));
3523
+ }
3524
+ case 22:
3525
+ if (tools.userInterface === undefined) {
3526
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3527
+ }
3528
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3529
+ _j = $ongoingTemplateResult;
3530
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3531
+ promptTitle: template.title,
3532
+ promptMessage: replaceParameters(template.description || '', parameters),
3533
+ defaultValue: replaceParameters(preparedContent, parameters),
3534
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3535
+ placeholder: undefined,
3536
+ priority: priority,
3537
+ }))];
3538
+ case 23:
3539
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3540
+ _j.$resultString = _t.sent();
3541
+ return [3 /*break*/, 25];
3542
+ case 24: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3543
+ case 25:
3544
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3545
+ _t.label = 26;
3546
+ case 26:
3547
+ _t.trys.push([26, 40, 41, 42]);
3548
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3549
+ _t.label = 27;
3550
+ case 27:
3551
+ if (!!_l.done) return [3 /*break*/, 39];
3552
+ functionName = _l.value;
3553
+ postprocessingError = null;
3554
+ _t.label = 28;
3555
+ case 28:
3556
+ _t.trys.push([28, 35, 36, 37]);
3557
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3558
+ _t.label = 29;
3559
+ case 29:
3560
+ if (!!_o.done) return [3 /*break*/, 34];
3561
+ scriptTools = _o.value;
3562
+ _t.label = 30;
3563
+ case 30:
3564
+ _t.trys.push([30, 32, , 33]);
3565
+ _p = $ongoingTemplateResult;
3566
+ return [4 /*yield*/, scriptTools.execute({
3567
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3568
+ script: "".concat(functionName, "(resultString)"),
3569
+ parameters: {
3570
+ resultString: $ongoingTemplateResult.$resultString || '',
3571
+ // Note: No ...parametersForTemplate, because working with result only
3572
+ },
3573
+ })];
3574
+ case 31:
3575
+ _p.$resultString = _t.sent();
3576
+ postprocessingError = null;
3577
+ return [3 /*break*/, 34];
3578
+ case 32:
3579
+ error_2 = _t.sent();
3580
+ if (!(error_2 instanceof Error)) {
3581
+ throw error_2;
3582
+ }
3583
+ if (error_2 instanceof UnexpectedError) {
3584
+ throw error_2;
3585
+ }
3586
+ postprocessingError = error_2;
3587
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3588
+ return [3 /*break*/, 33];
3589
+ case 33:
3590
+ _o = _m.next();
3591
+ return [3 /*break*/, 29];
3592
+ case 34: return [3 /*break*/, 37];
3593
+ case 35:
3594
+ e_2_1 = _t.sent();
3595
+ e_2 = { error: e_2_1 };
3596
+ return [3 /*break*/, 37];
3597
+ case 36:
3598
+ try {
3599
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3600
+ }
3601
+ finally { if (e_2) throw e_2.error; }
3602
+ return [7 /*endfinally*/];
3603
+ case 37:
3604
+ if (postprocessingError) {
3605
+ throw postprocessingError;
3606
+ }
3607
+ _t.label = 38;
3608
+ case 38:
3609
+ _l = _k.next();
3610
+ return [3 /*break*/, 27];
3611
+ case 39: return [3 /*break*/, 42];
3612
+ case 40:
3613
+ e_3_1 = _t.sent();
3614
+ e_3 = { error: e_3_1 };
3615
+ return [3 /*break*/, 42];
3616
+ case 41:
3617
+ try {
3618
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3619
+ }
3620
+ finally { if (e_3) throw e_3.error; }
3621
+ return [7 /*endfinally*/];
3622
+ case 42:
3623
+ // TODO: [💝] Unite object for expecting amount and format
3624
+ if (template.format) {
3625
+ if (template.format === 'JSON') {
3626
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3627
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3628
+ try {
3629
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3405
3630
  }
3406
- else {
3407
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3631
+ catch (error) {
3632
+ keepUnused(error);
3633
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3634
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3408
3635
  }
3409
3636
  }
3410
- // TODO: [💝] Unite object for expecting amount and format
3411
- if (currentTemplate.expectations) {
3412
- checkExpectations(currentTemplate.expectations, resultString || '');
3413
- }
3414
- return [2 /*return*/, "break-attempts"];
3415
- case 44:
3416
- error_4 = _v.sent();
3417
- if (!(error_4 instanceof ExpectError)) {
3418
- throw error_4;
3419
- }
3420
- expectError = error_4;
3421
- return [3 /*break*/, 46];
3422
- case 45:
3423
- if (!isJokerAttempt &&
3424
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3425
- prompt
3426
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3427
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3428
- ) {
3429
- // TODO: [🧠] Maybe put other templateTypes into report
3430
- executionReport.promptExecutions.push({
3431
- prompt: __assign({}, prompt),
3432
- result: result || undefined,
3433
- error: expectError === null ? undefined : serializeError(expectError),
3434
- });
3435
- }
3436
- return [7 /*endfinally*/];
3437
- case 46:
3438
- if (expectError !== null && attempt === maxAttempts - 1) {
3439
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3440
- .split('\n')
3441
- .map(function (line) { return "> ".concat(line); })
3442
- .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) || '')
3637
+ }
3638
+ else {
3639
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3640
+ }
3641
+ }
3642
+ // TODO: [💝] Unite object for expecting amount and format
3643
+ if (template.expectations) {
3644
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3645
+ }
3646
+ return [2 /*return*/, "break-attempts"];
3647
+ case 43:
3648
+ error_3 = _t.sent();
3649
+ if (!(error_3 instanceof ExpectError)) {
3650
+ throw error_3;
3651
+ }
3652
+ $ongoingTemplateResult.$expectError = error_3;
3653
+ return [3 /*break*/, 45];
3654
+ case 44:
3655
+ if (!isJokerAttempt &&
3656
+ template.templateType === 'PROMPT_TEMPLATE' &&
3657
+ $ongoingTemplateResult.$prompt
3658
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3659
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3660
+ ) {
3661
+ // TODO: [🧠] Maybe put other templateTypes into report
3662
+ $executionReport.promptExecutions.push({
3663
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3664
+ result: $ongoingTemplateResult.$result || undefined,
3665
+ error: $ongoingTemplateResult.$expectError === null
3666
+ ? undefined
3667
+ : serializeError($ongoingTemplateResult.$expectError),
3668
+ });
3669
+ }
3670
+ return [7 /*endfinally*/];
3671
+ case 45:
3672
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3673
+ throw new PipelineExecutionError(spaceTrim(function (block) {
3674
+ var _a, _b, _c;
3675
+ 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) || '')
3676
+ .split('\n')
3677
+ .map(function (line) { return "> ".concat(line); })
3678
+ .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) || '')
3679
+ .split('\n')
3680
+ .map(function (line) { return "> ".concat(line); })
3681
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3682
+ ? 'null'
3683
+ : $ongoingTemplateResult.$resultString
3443
3684
  .split('\n')
3444
3685
  .map(function (line) { return "> ".concat(line); })
3445
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3446
- ? 'null'
3447
- : resultString
3448
- .split('\n')
3449
- .map(function (line) { return "> ".concat(line); })
3450
- .join('\n')), "\n ---\n "); }));
3451
- }
3452
- return [2 /*return*/];
3686
+ .join('\n')), "\n ---\n ");
3687
+ }));
3453
3688
  }
3454
- });
3455
- };
3456
- attempt = -jokerParameterNames.length;
3457
- _h.label = 4;
3458
- case 4:
3459
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3460
- return [5 /*yield**/, _loop_5(attempt)];
3461
- case 5:
3462
- state_2 = _h.sent();
3463
- switch (state_2) {
3464
- case "break-attempts": return [3 /*break*/, 7];
3465
- }
3466
- _h.label = 6;
3467
- case 6:
3468
- attempt++;
3469
- return [3 /*break*/, 4];
3470
- case 7:
3471
- if (resultString === null) {
3472
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3689
+ return [2 /*return*/];
3473
3690
  }
3474
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3475
- progress_2 = {
3476
- name: name,
3477
- title: title,
3478
- isStarted: true,
3479
- isDone: true,
3480
- templateType: currentTemplate.templateType,
3481
- parameterName: currentTemplate.resultingParameterName,
3482
- parameterValue: resultString,
3483
- // <- [3]
3484
- };
3485
- if (isReturned) {
3486
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3487
- .split('\n')
3488
- .map(function (line) { return "> ".concat(line); })
3489
- .join('\n')), "\n\n "); }));
3490
- }
3491
- return [4 /*yield*/, onProgress(progress_2)];
3492
- case 8:
3493
- _h.sent();
3494
- _h.label = 9;
3495
- case 9:
3496
- 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)));
3497
- return [2 /*return*/];
3691
+ });
3692
+ };
3693
+ attempt = -jokerParameterNames.length;
3694
+ _a.label = 1;
3695
+ case 1:
3696
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3697
+ return [5 /*yield**/, _loop_1(attempt)];
3698
+ case 2:
3699
+ state_1 = _a.sent();
3700
+ switch (state_1) {
3701
+ case "break-attempts": return [3 /*break*/, 4];
3702
+ }
3703
+ _a.label = 3;
3704
+ case 3:
3705
+ attempt++;
3706
+ return [3 /*break*/, 1];
3707
+ case 4:
3708
+ if ($ongoingTemplateResult.$resultString === null) {
3709
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3710
+ }
3711
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3712
+ }
3713
+ });
3714
+ });
3715
+ }
3716
+ /**
3717
+ * TODO: Break into smaller functions
3718
+ */
3719
+
3720
+ /**
3721
+ * @@@
3722
+ *
3723
+ * @private internal utility of `createPipelineExecutor`
3724
+ */
3725
+ function executeFormatCells(options) {
3726
+ return __awaiter(this, void 0, void 0, function () {
3727
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
3728
+ var _this = this;
3729
+ return __generator(this, function (_a) {
3730
+ switch (_a.label) {
3731
+ case 0:
3732
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3733
+ if (template.foreach === undefined) {
3734
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3735
+ }
3736
+ if (jokerParameterNames.length !== 0) {
3737
+ throw new UnexpectedError(spaceTrim$1(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 "); }));
3738
+ }
3739
+ parameterValue = parameters[template.foreach.parameterName] || '';
3740
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3741
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3742
+ });
3743
+ if (formatDefinition === undefined) {
3744
+ throw new UnexpectedError(
3745
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3746
+ spaceTrim$1(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; })
3747
+ .map(function (formatName) { return "- ".concat(formatName); })
3748
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3749
+ }
3750
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3751
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
3752
+ });
3753
+ if (subvalueDefinition === undefined) {
3754
+ throw new UnexpectedError(
3755
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3756
+ spaceTrim$1(function (block) { return "\n Unsupported subformat name \"".concat(template.foreach.subformatName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
3757
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3758
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3759
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3760
+ }
3761
+ if (formatDefinition.formatName === 'CSV') {
3762
+ formatSettings = settings.csvSettings;
3763
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
3764
+ }
3765
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3766
+ var mappedParameters, allSubparameters, subresultString;
3767
+ return __generator(this, function (_a) {
3768
+ switch (_a.label) {
3769
+ case 0:
3770
+ // TODO: !!!!!!! Limit to N concurrent executions
3771
+ // TODO: !!!!!!! Report progress
3772
+ try {
3773
+ mappedParameters = mapAvailableToExpectedParameters({
3774
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3775
+ availableParameters: subparameters,
3776
+ });
3777
+ }
3778
+ catch (error) {
3779
+ if (!(error instanceof PipelineExecutionError)) {
3780
+ throw error;
3781
+ }
3782
+ throw new PipelineExecutionError(spaceTrim$1(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 "); }));
3783
+ }
3784
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3785
+ // 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
3786
+ Object.freeze(allSubparameters);
3787
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3788
+ case 1:
3789
+ subresultString = _a.sent();
3790
+ return [2 /*return*/, subresultString];
3791
+ }
3792
+ });
3793
+ }); })];
3794
+ case 1:
3795
+ resultString = _a.sent();
3796
+ return [2 /*return*/, resultString];
3797
+ }
3798
+ });
3799
+ });
3800
+ }
3801
+ /**
3802
+ * TODO: !!!!!! Make pipelineIdentification more precise
3803
+ * TODO: !!!!!! How FOREACH execution looks in the report
3804
+ */
3805
+
3806
+ /**
3807
+ * @@@
3808
+ *
3809
+ * @private internal utility of `createPipelineExecutor`
3810
+ */
3811
+ function getContextForTemplate(template) {
3812
+ return __awaiter(this, void 0, void 0, function () {
3813
+ return __generator(this, function (_a) {
3814
+ TODO_USE(template);
3815
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3816
+ });
3817
+ });
3818
+ }
3819
+
3820
+ /**
3821
+ * @@@
3822
+ *
3823
+ * @private internal utility of `createPipelineExecutor`
3824
+ */
3825
+ function getKnowledgeForTemplate(options) {
3826
+ return __awaiter(this, void 0, void 0, function () {
3827
+ var preparedPipeline, template;
3828
+ return __generator(this, function (_a) {
3829
+ preparedPipeline = options.preparedPipeline, template = options.template;
3830
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3831
+ TODO_USE(template);
3832
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3833
+ var content = _a.content;
3834
+ return "- ".concat(content);
3835
+ }).join('\n')];
3836
+ });
3837
+ });
3838
+ }
3839
+
3840
+ /**
3841
+ * @@@
3842
+ *
3843
+ * @private internal utility of `createPipelineExecutor`
3844
+ */
3845
+ function getSamplesForTemplate(template) {
3846
+ return __awaiter(this, void 0, void 0, function () {
3847
+ return __generator(this, function (_a) {
3848
+ // TODO: [♨] Implement Better - use real index and keyword search
3849
+ TODO_USE(template);
3850
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3851
+ });
3852
+ });
3853
+ }
3854
+
3855
+ /**
3856
+ * @@@
3857
+ *
3858
+ * @private internal utility of `createPipelineExecutor`
3859
+ */
3860
+ function getReservedParametersForTemplate(options) {
3861
+ return __awaiter(this, void 0, void 0, function () {
3862
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3863
+ var e_1, _a;
3864
+ return __generator(this, function (_b) {
3865
+ switch (_b.label) {
3866
+ case 0:
3867
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
3868
+ return [4 /*yield*/, getContextForTemplate(template)];
3869
+ case 1:
3870
+ context = _b.sent();
3871
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
3872
+ case 2:
3873
+ knowledge = _b.sent();
3874
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3875
+ case 3:
3876
+ samples = _b.sent();
3877
+ currentDate = new Date().toISOString();
3878
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3879
+ reservedParameters = {
3880
+ content: RESERVED_PARAMETER_RESTRICTED,
3881
+ context: context,
3882
+ knowledge: knowledge,
3883
+ samples: samples,
3884
+ currentDate: currentDate,
3885
+ modelName: modelName,
3886
+ };
3887
+ _loop_1 = function (parameterName) {
3888
+ if (reservedParameters[parameterName] === undefined) {
3889
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3890
+ }
3891
+ };
3892
+ try {
3893
+ // Note: Doublecheck that ALL reserved parameters are defined:
3894
+ 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()) {
3895
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3896
+ _loop_1(parameterName);
3897
+ }
3498
3898
  }
3499
- });
3500
- });
3501
- }
3502
- function filterJustOutputParameters() {
3503
- var e_8, _a;
3504
- var outputParameters = {};
3505
- var _loop_6 = function (parameter) {
3506
- if (parametersToPass[parameter.name] === undefined) {
3507
- // [4]
3508
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3509
- return "continue";
3510
- }
3511
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3512
- };
3513
- try {
3514
- // Note: Filter ONLY output parameters
3515
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3516
- var isOutput = _a.isOutput;
3517
- return isOutput;
3518
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3519
- var parameter = _c.value;
3520
- _loop_6(parameter);
3521
- }
3899
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3900
+ finally {
3901
+ try {
3902
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3903
+ }
3904
+ finally { if (e_1) throw e_1.error; }
3905
+ }
3906
+ return [2 /*return*/, reservedParameters];
3522
3907
  }
3523
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3524
- finally {
3525
- try {
3526
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3527
- }
3528
- finally { if (e_8) throw e_8.error; }
3908
+ });
3909
+ });
3910
+ }
3911
+
3912
+ /**
3913
+ * @@@
3914
+ *
3915
+ * @private internal utility of `createPipelineExecutor`
3916
+ */
3917
+ function executeTemplate(options) {
3918
+ return __awaiter(this, void 0, void 0, function () {
3919
+ 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;
3920
+ var e_1, _f, _g;
3921
+ return __generator(this, function (_h) {
3922
+ switch (_h.label) {
3923
+ case 0:
3924
+ 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;
3925
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3926
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3927
+ title = currentTemplate.title;
3928
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3929
+ return [4 /*yield*/, onProgress({
3930
+ name: name,
3931
+ title: title,
3932
+ isStarted: false,
3933
+ isDone: false,
3934
+ templateType: currentTemplate.templateType,
3935
+ parameterName: currentTemplate.resultingParameterName,
3936
+ parameterValue: null,
3937
+ // <- [🍸]
3938
+ })];
3939
+ case 1:
3940
+ _h.sent();
3941
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3942
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3943
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
3944
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3945
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
3946
+ .map(function (name) { return "{".concat(name, "}"); })
3947
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3948
+ .map(function (name) { return "{".concat(name, "}"); })
3949
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3950
+ }
3951
+ _b = (_a = Object).freeze;
3952
+ _c = [{}];
3953
+ return [4 /*yield*/, getReservedParametersForTemplate({
3954
+ preparedPipeline: preparedPipeline,
3955
+ template: currentTemplate,
3956
+ pipelineIdentification: pipelineIdentification,
3957
+ })];
3958
+ case 2:
3959
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3960
+ definedParameterNames = new Set(Object.keys(definedParameters));
3961
+ parameters = {};
3962
+ _loop_1 = function (parameterName) {
3963
+ // Situation: Parameter is defined and used
3964
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3965
+ parameters[parameterName] = definedParameters[parameterName];
3966
+ }
3967
+ // Situation: Parameter is defined but NOT used
3968
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3969
+ // Situation: Parameter is NOT defined BUT used
3970
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3971
+ // Houston, we have a problem
3972
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3973
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3974
+ }
3975
+ };
3976
+ try {
3977
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3978
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
3979
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3980
+ parameterName = _e.value;
3981
+ _loop_1(parameterName);
3982
+ }
3983
+ }
3984
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3985
+ finally {
3986
+ try {
3987
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3988
+ }
3989
+ finally { if (e_1) throw e_1.error; }
3990
+ }
3991
+ // 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
3992
+ Object.freeze(parameters);
3993
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3994
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3995
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3996
+ .split('{content}')
3997
+ .join(currentTemplate.content);
3998
+ return [4 /*yield*/, executeFormatCells({
3999
+ jokerParameterNames: jokerParameterNames,
4000
+ priority: priority,
4001
+ maxAttempts: maxAttempts,
4002
+ preparedContent: preparedContent,
4003
+ parameters: parameters,
4004
+ template: currentTemplate,
4005
+ preparedPipeline: preparedPipeline,
4006
+ tools: tools,
4007
+ llmTools: llmTools,
4008
+ settings: settings,
4009
+ $executionReport: $executionReport,
4010
+ pipelineIdentification: pipelineIdentification,
4011
+ })];
4012
+ case 3:
4013
+ resultString = _h.sent();
4014
+ return [4 /*yield*/, onProgress({
4015
+ name: name,
4016
+ title: title,
4017
+ isStarted: true,
4018
+ isDone: true,
4019
+ templateType: currentTemplate.templateType,
4020
+ parameterName: currentTemplate.resultingParameterName,
4021
+ parameterValue: resultString,
4022
+ // <- [🍸]
4023
+ })];
4024
+ case 4:
4025
+ _h.sent();
4026
+ return [2 /*return*/, Object.freeze((_g = {},
4027
+ _g[currentTemplate.resultingParameterName] =
4028
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4029
+ resultString,
4030
+ _g))];
3529
4031
  }
3530
- return outputParameters;
4032
+ });
4033
+ });
4034
+ }
4035
+ /**
4036
+ * TODO: [🤹‍♂️]
4037
+ */
4038
+
4039
+ /**
4040
+ * @@@
4041
+ *
4042
+ * @private internal utility of `createPipelineExecutor`
4043
+ */
4044
+ function filterJustOutputParameters(options) {
4045
+ var e_1, _a;
4046
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4047
+ var outputParameters = {};
4048
+ var _loop_1 = function (parameter) {
4049
+ if (parametersToPass[parameter.name] === undefined) {
4050
+ // [4]
4051
+ $warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
4052
+ return "continue";
4053
+ }
4054
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4055
+ };
4056
+ try {
4057
+ // Note: Filter ONLY output parameters
4058
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4059
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4060
+ var isOutput = _a.isOutput;
4061
+ return isOutput;
4062
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4063
+ var parameter = _c.value;
4064
+ _loop_1(parameter);
4065
+ }
4066
+ }
4067
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4068
+ finally {
4069
+ try {
4070
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3531
4071
  }
3532
- 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;
4072
+ finally { if (e_1) throw e_1.error; }
4073
+ }
4074
+ return outputParameters;
4075
+ }
4076
+
4077
+ /**
4078
+ * @@@
4079
+ *
4080
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4081
+ *
4082
+ * @private internal utility of `createPipelineExecutor`
4083
+ */
4084
+ function executePipeline(options) {
4085
+ return __awaiter(this, void 0, void 0, function () {
4086
+ 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;
3533
4087
  var e_1, _e, e_2, _f;
3534
4088
  return __generator(this, function (_g) {
3535
4089
  switch (_g.label) {
3536
4090
  case 0:
4091
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4092
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4093
+ preparedPipeline = options.preparedPipeline;
4094
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3537
4095
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3538
4096
  return [4 /*yield*/, preparePipeline(pipeline, {
3539
4097
  llmTools: llmTools,
@@ -3542,6 +4100,7 @@ function createPipelineExecutor(options) {
3542
4100
  })];
3543
4101
  case 1:
3544
4102
  preparedPipeline = _g.sent();
4103
+ setPreparedPipeline(preparedPipeline);
3545
4104
  _g.label = 2;
3546
4105
  case 2:
3547
4106
  errors = [];
@@ -3611,7 +4170,7 @@ function createPipelineExecutor(options) {
3611
4170
  return name === parameterName;
3612
4171
  });
3613
4172
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3614
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4173
+ warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3615
4174
  return [3 /*break*/, 4];
3616
4175
  case 1:
3617
4176
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3623,10 +4182,10 @@ function createPipelineExecutor(options) {
3623
4182
  // Note: Wait a short time to prevent race conditions
3624
4183
  _h.sent();
3625
4184
  _h.label = 3;
3626
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4185
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3627
4186
  isSuccessful: false,
3628
4187
  errors: __spreadArray([
3629
- new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4188
+ new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3630
4189
  ], __read(errors), false).map(serializeError),
3631
4190
  warnings: warnings.map(serializeError),
3632
4191
  executionReport: executionReport,
@@ -3690,7 +4249,7 @@ function createPipelineExecutor(options) {
3690
4249
  case 0:
3691
4250
  if (loopLimit-- < 0) {
3692
4251
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3693
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4252
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3694
4253
  }
3695
4254
  currentTemplate = unresovedTemplates_1.find(function (template) {
3696
4255
  return template.dependentParameterNames.every(function (name) {
@@ -3700,29 +4259,52 @@ function createPipelineExecutor(options) {
3700
4259
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3701
4260
  throw new UnexpectedError(
3702
4261
  // TODO: [🐎] DRY
3703
- spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4262
+ spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3704
4263
  .map(function (_a) {
3705
4264
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3706
4265
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3707
4266
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3708
4267
  .join(' and '));
3709
4268
  })
3710
- .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 "); }));
4269
+ .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 "); }));
3711
4270
  case 1:
3712
4271
  if (!!currentTemplate) return [3 /*break*/, 3];
3713
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4272
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3714
4273
  case 2:
3715
- /* [5] */ _j.sent();
4274
+ /* [🤹‍♂️] */ _j.sent();
3716
4275
  return [3 /*break*/, 4];
3717
4276
  case 3:
3718
4277
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3719
- work_1 = executeSingleTemplate(currentTemplate)
3720
- .then(function () {
4278
+ work_1 = executeTemplate({
4279
+ currentTemplate: currentTemplate,
4280
+ preparedPipeline: preparedPipeline,
4281
+ parametersToPass: parametersToPass,
4282
+ tools: tools,
4283
+ llmTools: llmTools,
4284
+ onProgress: function (progress) {
4285
+ if (isReturned) {
4286
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4287
+ .split('\n')
4288
+ .map(function (line) { return "> ".concat(line); })
4289
+ .join('\n')), "\n "); }));
4290
+ }
4291
+ if (onProgress) {
4292
+ onProgress(progress);
4293
+ }
4294
+ },
4295
+ settings: settings,
4296
+ $executionReport: executionReport,
4297
+ pipelineIdentification: pipelineIdentification,
4298
+ })
4299
+ .then(function (newParametersToPass) {
4300
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3721
4301
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3722
4302
  })
3723
4303
  .then(function () {
3724
4304
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3725
4305
  });
4306
+ // <- Note: Errors are catched here [3]
4307
+ // 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
3726
4308
  resolving_1.push(work_1);
3727
4309
  _j.label = 4;
3728
4310
  case 4: return [2 /*return*/];
@@ -3749,7 +4331,12 @@ function createPipelineExecutor(options) {
3749
4331
  var result = _a.result;
3750
4332
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3751
4333
  })), false));
3752
- outputParameters_1 = filterJustOutputParameters();
4334
+ outputParameters_1 = filterJustOutputParameters({
4335
+ preparedPipeline: preparedPipeline,
4336
+ parametersToPass: parametersToPass,
4337
+ $warnings: warnings,
4338
+ pipelineIdentification: pipelineIdentification,
4339
+ });
3753
4340
  isReturned = true;
3754
4341
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3755
4342
  // Note: Wait a short time to prevent race conditions
@@ -3772,7 +4359,12 @@ function createPipelineExecutor(options) {
3772
4359
  var result = _a.result;
3773
4360
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3774
4361
  })), false));
3775
- outputParameters = filterJustOutputParameters();
4362
+ outputParameters = filterJustOutputParameters({
4363
+ preparedPipeline: preparedPipeline,
4364
+ parametersToPass: parametersToPass,
4365
+ $warnings: warnings,
4366
+ pipelineIdentification: pipelineIdentification,
4367
+ });
3776
4368
  isReturned = true;
3777
4369
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3778
4370
  // Note: Wait a short time to prevent race conditions
@@ -3792,22 +4384,63 @@ function createPipelineExecutor(options) {
3792
4384
  })];
3793
4385
  }
3794
4386
  });
3795
- }); };
3796
- return pipelineExecutor;
4387
+ });
3797
4388
  }
4389
+
3798
4390
  /**
3799
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3800
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3801
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3802
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3803
- * TODO: [♈] Probbably move expectations from templates to parameters
3804
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3805
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3806
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3807
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3808
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3809
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4391
+ * Creates executor function from pipeline and execution tools.
4392
+ *
4393
+ * @returns The executor function
4394
+ * @throws {PipelineLogicError} on logical error in the pipeline
4395
+ * @public exported from `@promptbook/core`
3810
4396
  */
4397
+ function createPipelineExecutor(options) {
4398
+ var _this = this;
4399
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4400
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.csvSettings, csvSettings = _d === void 0 ? DEFAULT_CSV_SETTINGS : _d, _e = settings.isVerbose, isVerbose = _e === void 0 ? IS_VERBOSE : _e, _f = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _f === void 0 ? false : _f;
4401
+ validatePipeline(pipeline);
4402
+ var pipelineIdentification = (function () {
4403
+ // Note: This is a 😐 implementation of [🚞]
4404
+ var _ = [];
4405
+ if (pipeline.sourceFile !== undefined) {
4406
+ _.push("File: ".concat(pipeline.sourceFile));
4407
+ }
4408
+ if (pipeline.pipelineUrl !== undefined) {
4409
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4410
+ }
4411
+ return _.join('\n');
4412
+ })();
4413
+ var preparedPipeline;
4414
+ if (isPipelinePrepared(pipeline)) {
4415
+ preparedPipeline = pipeline;
4416
+ }
4417
+ else if (isNotPreparedWarningSupressed !== true) {
4418
+ console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4419
+ }
4420
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4421
+ return __generator(this, function (_a) {
4422
+ return [2 /*return*/, executePipeline({
4423
+ pipeline: pipeline,
4424
+ preparedPipeline: preparedPipeline,
4425
+ setPreparedPipeline: function (newPreparedPipeline) {
4426
+ preparedPipeline = newPreparedPipeline;
4427
+ },
4428
+ inputParameters: inputParameters,
4429
+ tools: tools,
4430
+ onProgress: onProgress,
4431
+ pipelineIdentification: pipelineIdentification,
4432
+ settings: {
4433
+ maxExecutionAttempts: maxExecutionAttempts,
4434
+ maxParallelCount: maxParallelCount,
4435
+ csvSettings: csvSettings,
4436
+ isVerbose: isVerbose,
4437
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4438
+ },
4439
+ })];
4440
+ });
4441
+ }); };
4442
+ return pipelineExecutor;
4443
+ }
3811
4444
 
3812
4445
  /**
3813
4446
  * @@@
@@ -3859,7 +4492,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
3859
4492
  outputParameters = result.outputParameters;
3860
4493
  knowledgePiecesRaw = outputParameters.knowledgePieces;
3861
4494
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
3862
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4495
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
3863
4496
  if (isVerbose) {
3864
4497
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
3865
4498
  }
@@ -3917,8 +4550,13 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
3917
4550
  case 6: return [3 /*break*/, 8];
3918
4551
  case 7:
3919
4552
  error_1 = _c.sent();
4553
+ // Note: Here is expected error:
4554
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4555
+ if (!(error_1 instanceof PipelineExecutionError)) {
4556
+ throw error_1;
4557
+ }
3920
4558
  // TODO: [🟥] Detect browser / node and make it colorfull
3921
- console.error(error_1);
4559
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
3922
4560
  return [3 /*break*/, 8];
3923
4561
  case 8: return [2 /*return*/, {
3924
4562
  name: name,
@@ -3939,7 +4577,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
3939
4577
  });
3940
4578
  }
3941
4579
  /**
3942
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4580
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
3943
4581
  * TODO: [🪂] Do it in parallel 11:11
3944
4582
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
3945
4583
  */
@@ -3963,7 +4601,7 @@ function prepareKnowledgePieces(knowledgeSources, options) {
3963
4601
  var partialPieces, pieces;
3964
4602
  return __generator(this, function (_a) {
3965
4603
  switch (_a.label) {
3966
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4604
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
3967
4605
  options)];
3968
4606
  case 1:
3969
4607
  partialPieces = _a.sent();
@@ -4155,7 +4793,7 @@ function preparePersona(personaDescription, options) {
4155
4793
  });
4156
4794
  }
4157
4795
  /**
4158
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4796
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4159
4797
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4160
4798
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4161
4799
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4204,7 +4842,7 @@ function prepareTemplates(pipeline, options) {
4204
4842
  case 0:
4205
4843
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4206
4844
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4207
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
4845
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4208
4846
  TODO_USE(parameters);
4209
4847
  templatesPrepared = new Array(
4210
4848
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4236,7 +4874,7 @@ function prepareTemplates(pipeline, options) {
4236
4874
  /**
4237
4875
  * TODO: [🧠] Add context to each template (if missing)
4238
4876
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4239
- * TODO: [♨] !!! Prepare index the samples and maybe templates
4877
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4240
4878
  * TODO: Write tests for `preparePipeline`
4241
4879
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4242
4880
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4408,7 +5046,7 @@ var knowledgeCommandParser = {
4408
5046
  if (sourceContent === '') {
4409
5047
  throw new ParseError("Source is not defined");
4410
5048
  }
4411
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5049
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4412
5050
  if (sourceContent.startsWith('http://')) {
4413
5051
  throw new ParseError("Source is not secure");
4414
5052
  }
@@ -4611,7 +5249,7 @@ var templateCommandParser = {
4611
5249
  if (command.templateType === 'KNOWLEDGE') {
4612
5250
  knowledgeCommandParser.$applyToPipelineJson({
4613
5251
  type: 'KNOWLEDGE',
4614
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5252
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4615
5253
  }, $pipelineJson);
4616
5254
  $templateJson.isTemplate = false;
4617
5255
  return;
@@ -4961,6 +5599,171 @@ function normalizeTo_SCREAMING_CASE(text) {
4961
5599
  * TODO: [🌺] Use some intermediate util splitWords
4962
5600
  */
4963
5601
 
5602
+ /**
5603
+ * @@@
5604
+ *
5605
+ * @param text @@@
5606
+ * @param _isFirstLetterCapital @@@
5607
+ * @returns @@@
5608
+ * @example 'helloWorld'
5609
+ * @example 'iLovePromptbook'
5610
+ * @public exported from `@promptbook/utils`
5611
+ */
5612
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5613
+ var e_1, _a;
5614
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5615
+ var charType;
5616
+ var lastCharType = null;
5617
+ var normalizedName = '';
5618
+ try {
5619
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5620
+ var char = text_1_1.value;
5621
+ var normalizedChar = void 0;
5622
+ if (/^[a-z]$/.test(char)) {
5623
+ charType = 'LOWERCASE';
5624
+ normalizedChar = char;
5625
+ }
5626
+ else if (/^[A-Z]$/.test(char)) {
5627
+ charType = 'UPPERCASE';
5628
+ normalizedChar = char.toLowerCase();
5629
+ }
5630
+ else if (/^[0-9]$/.test(char)) {
5631
+ charType = 'NUMBER';
5632
+ normalizedChar = char;
5633
+ }
5634
+ else {
5635
+ charType = 'OTHER';
5636
+ normalizedChar = '';
5637
+ }
5638
+ if (!lastCharType) {
5639
+ if (_isFirstLetterCapital) {
5640
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5641
+ }
5642
+ }
5643
+ else if (charType !== lastCharType &&
5644
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5645
+ !(lastCharType === 'NUMBER') &&
5646
+ !(charType === 'NUMBER')) {
5647
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5648
+ }
5649
+ normalizedName += normalizedChar;
5650
+ lastCharType = charType;
5651
+ }
5652
+ }
5653
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5654
+ finally {
5655
+ try {
5656
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5657
+ }
5658
+ finally { if (e_1) throw e_1.error; }
5659
+ }
5660
+ return normalizedName;
5661
+ }
5662
+ /**
5663
+ * TODO: [🌺] Use some intermediate util splitWords
5664
+ */
5665
+
5666
+ /**
5667
+ * Removes quotes from a string
5668
+ *
5669
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5670
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5671
+ * Note: There are two simmilar functions:
5672
+ * - `removeQuotes` which removes only bounding quotes
5673
+ * - `unwrapResult` which removes whole introduce sentence
5674
+ *
5675
+ * @param text optionally quoted text
5676
+ * @returns text without quotes
5677
+ * @public exported from `@promptbook/utils`
5678
+ */
5679
+ function removeQuotes(text) {
5680
+ if (text.startsWith('"') && text.endsWith('"')) {
5681
+ return text.slice(1, -1);
5682
+ }
5683
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5684
+ return text.slice(1, -1);
5685
+ }
5686
+ return text;
5687
+ }
5688
+
5689
+ /**
5690
+ * Function `validateParameterName` will @@@
5691
+ *
5692
+ * @param parameterName @@@
5693
+ * @returns @@@
5694
+ * @throws {ParseError} @@@
5695
+ * @private within the repository
5696
+ */
5697
+ function validateParameterName(parameterName) {
5698
+ var e_1, _a;
5699
+ var rawParameterName = parameterName;
5700
+ try {
5701
+ for (var _b = __values([
5702
+ ['`', '`'],
5703
+ ['{', '}'],
5704
+ ['[', ']'],
5705
+ ['(', ')'],
5706
+ ['<', '>'],
5707
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5708
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5709
+ if (parameterName.substring(0, 1) === start &&
5710
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5711
+ // <- TODO: More universal that 1 character
5712
+ ) {
5713
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5714
+ // <- TODO: More universal that 1 character
5715
+ }
5716
+ }
5717
+ }
5718
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5719
+ finally {
5720
+ try {
5721
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5722
+ }
5723
+ finally { if (e_1) throw e_1.error; }
5724
+ }
5725
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5726
+ try {
5727
+ /*
5728
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5729
+ if (parameterName.includes(' ')) {
5730
+ throw new ParseError(`Parameter name cannot contain spaces`);
5731
+ }
5732
+ */
5733
+ if (parameterName.includes('.')) {
5734
+ throw new ParseError("Parameter name cannot contain dots");
5735
+ }
5736
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5737
+ throw new ParseError("Parameter name cannot contain slashes");
5738
+ }
5739
+ if (parameterName.includes('(') ||
5740
+ parameterName.includes(')') ||
5741
+ parameterName.includes('{') ||
5742
+ parameterName.includes('}') ||
5743
+ parameterName.includes('[') ||
5744
+ parameterName.includes(']')) {
5745
+ throw new ParseError("Parameter name cannot contain braces");
5746
+ }
5747
+ parameterName = removeDiacritics(parameterName);
5748
+ parameterName = removeEmojis(parameterName);
5749
+ parameterName = removeQuotes(parameterName);
5750
+ parameterName = normalizeTo_camelCase(parameterName);
5751
+ if (parameterName === '') {
5752
+ throw new ParseError("Parameter name cannot be empty");
5753
+ }
5754
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5755
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5756
+ }
5757
+ }
5758
+ catch (error) {
5759
+ if (!(error instanceof ParseError)) {
5760
+ throw error;
5761
+ }
5762
+ throw new ParseError(spaceTrim$1(function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
5763
+ }
5764
+ return parameterName;
5765
+ }
5766
+
4964
5767
  /**
4965
5768
  * Parses the foreach command
4966
5769
  *
@@ -4990,67 +5793,61 @@ var foreachCommandParser = {
4990
5793
  /**
4991
5794
  * Link to discussion
4992
5795
  */
4993
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5796
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
4994
5797
  /**
4995
5798
  * Example usages of the FOREACH command
4996
5799
  */
4997
5800
  examples: [
4998
- 'FOREACH List Line -> `{customer}`',
4999
- 'FOR List Line -> `{customer}`',
5000
- 'EACH List Line -> `{customer}`',
5001
- // <- TODO: [🍭] !!!!!! More
5801
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5802
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5803
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
5002
5804
  ],
5003
5805
  /**
5004
5806
  * Parses the FOREACH command
5005
5807
  */
5006
5808
  parse: function (input) {
5007
- var args = input.args, rawArgs = input.rawArgs;
5809
+ var args = input.args;
5008
5810
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5009
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5010
- var assignSign = args[2];
5011
- var parameter = args[3];
5012
- if (![
5013
- 'LIST',
5014
- 'CSV',
5015
- // <- TODO: [🏢] Unhardcode formats
5016
- ].includes(formatName)) {
5017
- console.info({ args: args, formatName: formatName });
5018
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5811
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5812
+ var parameterNameArg = args[2] || '';
5813
+ var assignSign = args[3];
5814
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5815
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5816
+ });
5817
+ if (formatDefinition === undefined) {
5818
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
5819
+ .map(function (formatName) { return "- ".concat(formatName); })
5820
+ .join('\n')), "\n "); }));
5019
5821
  // <- TODO: [🏢] List all supported format names
5020
5822
  }
5021
- if (![
5022
- 'LINE',
5023
- 'ROW',
5024
- 'COLUMN',
5025
- 'CELL',
5026
- // <- TODO: [🏢] Unhardcode format cekks
5027
- ].includes(cellName)) {
5028
- console.info({ args: args, cellName: cellName });
5029
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5030
- // <- TODO: [🏢] List all supported cell names for the format
5823
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5824
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5825
+ });
5826
+ if (subvalueDefinition === undefined) {
5827
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unsupported subformat name \"".concat(subformatName, "\" for format \"").concat(formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
5828
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5829
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5830
+ .join('\n')), "\n "); }));
5831
+ // <- TODO: [🏢] List all supported subformat names for the format
5031
5832
  }
5032
5833
  if (assignSign !== '->') {
5033
- console.info({ args: args, assignSign: assignSign });
5034
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5035
- }
5036
- var parameterNames = extractParameterNames(parameter || rawArgs);
5037
- if (parameterNames.size !== 1) {
5038
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5039
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5040
- }
5041
- var parameterName = parameterNames.values().next().value;
5042
- if (typeof parameterName !== 'string'
5043
- // <- TODO: !!!!!! Replace with propper parameter name validation
5044
- ) {
5045
- console.info({ args: args, parameterName: parameterName });
5046
- throw new Error("Invalid parameter name");
5047
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
5834
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5835
+ }
5836
+ var parameterName = validateParameterName(parameterNameArg);
5837
+ var subparameterNames = args
5838
+ .slice(4)
5839
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5840
+ .filter(function (parameterName) { return parameterName !== ''; })
5841
+ .map(validateParameterName);
5842
+ if (subparameterNames.length === 0) {
5843
+ throw new ParseError("FOREACH command must have at least one subparameter");
5048
5844
  }
5049
5845
  return {
5050
5846
  type: 'FOREACH',
5051
5847
  formatName: formatName,
5052
- cellName: cellName,
5848
+ subformatName: subformatName,
5053
5849
  parameterName: parameterName,
5850
+ subparameterNames: subparameterNames,
5054
5851
  };
5055
5852
  },
5056
5853
  /**
@@ -5059,8 +5856,12 @@ var foreachCommandParser = {
5059
5856
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5060
5857
  */
5061
5858
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5062
- keepUnused(command, $templateJson, $pipelineJson);
5063
- // <- TODO: [🍭] !!!!!! Implement
5859
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
5860
+ // TODO: [🍭] Detect double use
5861
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
5862
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
5863
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5864
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5064
5865
  },
5065
5866
  /**
5066
5867
  * Converts the FOREACH command back to string
@@ -5069,8 +5870,7 @@ var foreachCommandParser = {
5069
5870
  */
5070
5871
  stringify: function (command) {
5071
5872
  keepUnused(command);
5072
- return "";
5073
- // <- TODO: [🍭] !!!!!! Implement
5873
+ return "---"; // <- TODO: [🛋] Implement
5074
5874
  },
5075
5875
  /**
5076
5876
  * Reads the FOREACH command from the `TemplateJson`
@@ -5079,13 +5879,11 @@ var foreachCommandParser = {
5079
5879
  */
5080
5880
  takeFromTemplateJson: function ($templateJson) {
5081
5881
  keepUnused($templateJson);
5082
- return [];
5083
- // <- TODO: [🍭] !!!!!! Implement
5882
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5084
5883
  },
5085
5884
  };
5086
5885
  /**
5087
- * TODO: !!!!!! Comment console logs
5088
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5886
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5089
5887
  */
5090
5888
 
5091
5889
  /**
@@ -5195,11 +5993,11 @@ var jokerCommandParser = {
5195
5993
  */
5196
5994
  parse: function (input) {
5197
5995
  var args = input.args;
5198
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5199
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5200
- throw new ParseError("Invalid joker");
5996
+ if (args.length !== 1) {
5997
+ throw new ParseError("JOKE command expects exactly one parameter name");
5201
5998
  }
5202
- var parameterName = parametersMatch.groups.parameterName;
5999
+ var parameterNameArg = args[0] || '';
6000
+ var parameterName = validateParameterName(parameterNameArg);
5203
6001
  return {
5204
6002
  type: 'JOKER',
5205
6003
  parameterName: parameterName,
@@ -5274,6 +6072,9 @@ var modelCommandParser = {
5274
6072
  */
5275
6073
  parse: function (input) {
5276
6074
  var args = input.args, normalized = input.normalized;
6075
+ var availableVariantsMessage = spaceTrim$1(function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6076
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6077
+ }).join('\n')), "\n "); });
5277
6078
  // TODO: Make this more elegant and dynamically
5278
6079
  if (normalized.startsWith('MODEL_VARIANT')) {
5279
6080
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5289,17 +6090,13 @@ var modelCommandParser = {
5289
6090
  key: 'modelVariant',
5290
6091
  value: 'COMPLETION',
5291
6092
  };
6093
+ // <- Note: [🤖]
5292
6094
  }
5293
6095
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5294
- return {
5295
- type: 'MODEL',
5296
- key: 'modelVariant',
5297
- value: 'EMBEDDING',
5298
- };
5299
- // <- Note: [🤖]
6096
+ spaceTrim$1(function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5300
6097
  }
5301
6098
  else {
5302
- throw new ParseError(spaceTrim$1(function (block) { return "\n Unknown model variant in command:\n\n Supported variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) { return "- ".concat(variantName); }).join('\n')), "\n "); }));
6099
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5303
6100
  }
5304
6101
  }
5305
6102
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5324,6 +6121,7 @@ var modelCommandParser = {
5324
6121
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5325
6122
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5326
6123
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6124
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5327
6125
  }
5328
6126
  else {
5329
6127
  throw new ParseError(spaceTrim$1("\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 ")));
@@ -5423,14 +6221,13 @@ var parameterCommandParser = {
5423
6221
  * Parses the PARAMETER command
5424
6222
  */
5425
6223
  parse: function (input) {
5426
- var normalized = input.normalized, raw = input.raw;
5427
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5428
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5429
- throw new ParseError("Invalid parameter");
5430
- }
5431
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5432
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5433
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6224
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6225
+ var parameterNameRaw = args.shift() || '';
6226
+ var parameterDescriptionRaw = args.join(' ');
6227
+ // <- TODO: When [🥶] fixed, change to:
6228
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6229
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6230
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameterNameRaw, "} can not contain another parameter in description\n\n The description:\n ").concat(block(parameterDescriptionRaw), "\n "); }));
5434
6231
  }
5435
6232
  var isInput = normalized.startsWith('INPUT');
5436
6233
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5438,11 +6235,12 @@ var parameterCommandParser = {
5438
6235
  isInput = false;
5439
6236
  isOutput = false;
5440
6237
  }
5441
- // TODO: !!!!!! Add parameter name validation
6238
+ var parameterName = validateParameterName(parameterNameRaw);
6239
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5442
6240
  return {
5443
6241
  type: 'PARAMETER',
5444
6242
  parameterName: parameterName,
5445
- parameterDescription: parameterDescription.trim() || null,
6243
+ parameterDescription: parameterDescription,
5446
6244
  isInput: isInput,
5447
6245
  isOutput: isOutput,
5448
6246
  };
@@ -5767,6 +6565,7 @@ var promptbookVersionCommandParser = {
5767
6565
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
5768
6566
  */
5769
6567
  $applyToPipelineJson: function (command, $pipelineJson) {
6568
+ // TODO: Warn if the version is overridden
5770
6569
  $pipelineJson.promptbookVersion = command.promptbookVersion;
5771
6570
  },
5772
6571
  /**
@@ -6249,7 +7048,9 @@ function parseCommand(raw, usagePlace) {
6249
7048
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6250
7049
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6251
7050
  var args = items.slice(commandNameSegmentsCount + 1);
6252
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7051
+ var rawArgs = raw
7052
+ .substring(commandNameRaw.length)
7053
+ .trim();
6253
7054
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6254
7055
  if (command !== null) {
6255
7056
  return command;
@@ -6260,7 +7061,9 @@ function parseCommand(raw, usagePlace) {
6260
7061
  {
6261
7062
  var commandNameRaw = items.slice(-1).join('_');
6262
7063
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6263
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7064
+ var rawArgs = raw
7065
+ .substring(0, raw.length - commandNameRaw.length)
7066
+ .trim();
6264
7067
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6265
7068
  if (command !== null) {
6266
7069
  return command;
@@ -6400,7 +7203,7 @@ function extractAllListItemsFromMarkdown(markdown) {
6400
7203
  function extractOneBlockFromMarkdown(markdown) {
6401
7204
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6402
7205
  if (codeBlocks.length !== 1) {
6403
- throw new ParseError(spaceTrim$1(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 "); }));
7206
+ throw new ParseError(spaceTrim$1(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 "); }));
6404
7207
  }
6405
7208
  return codeBlocks[0];
6406
7209
  }
@@ -6587,7 +7390,7 @@ function pipelineStringToJsonSync(pipelineString) {
6587
7390
  var $pipelineJson = {
6588
7391
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6589
7392
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6590
- promptbookVersion: PROMPTBOOK_VERSION,
7393
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6591
7394
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6592
7395
  parameters: [],
6593
7396
  templates: [],
@@ -6878,7 +7681,7 @@ function pipelineStringToJsonSync(pipelineString) {
6878
7681
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
6879
7682
  }
6880
7683
  /**
6881
- * TODO: !!!! Warn if used only sync version
7684
+ * TODO:[main] !!!! Warn if used only sync version
6882
7685
  * TODO: [🚞] Report here line/column of error
6883
7686
  * TODO: Use spaceTrim more effectively
6884
7687
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7661,7 +8464,7 @@ function isSerializableAsJson(value) {
7661
8464
  }
7662
8465
  }
7663
8466
  /**
7664
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8467
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7665
8468
  * TODO: [🧠][💺] Can be done this on type-level?
7666
8469
  */
7667
8470