@promptbook/node 0.70.0-0 → 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/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.hexEncoder, global.sha256, global.posix, global.dotenv));
5
- })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, hexEncoder, sha256, posix, dotenv) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.hexEncoder, global.sha256, global.posix, global.dotenv));
5
+ })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, papaparse, hexEncoder, sha256, posix, dotenv) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -35,8 +35,8 @@
35
35
  /**
36
36
  * The version of the Promptbook library
37
37
  */
38
- var PROMPTBOOK_VERSION = '0.69.0-0';
39
- // TODO: !!!! List here all the versions and annotate + put into script
38
+ var PROMPTBOOK_VERSION = '0.70.0-1';
39
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
40
40
 
41
41
  /*! *****************************************************************************
42
42
  Copyright (c) Microsoft Corporation.
@@ -346,7 +346,7 @@
346
346
  }
347
347
  /**
348
348
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
349
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
349
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
350
350
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
351
351
  */
352
352
 
@@ -388,13 +388,13 @@
388
388
  *
389
389
  * @public exported from `@promptbook/core`
390
390
  */
391
- var MAX_PARALLEL_COUNT = 5;
391
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
392
392
  /**
393
393
  * The maximum number of attempts to execute LLM task before giving up
394
394
  *
395
395
  * @public exported from `@promptbook/core`
396
396
  */
397
- var MAX_EXECUTION_ATTEMPTS = 3;
397
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
398
398
  /**
399
399
  * The maximum length of the (generated) filename
400
400
  *
@@ -425,6 +425,7 @@
425
425
  'samples',
426
426
  'modelName',
427
427
  'currentDate',
428
+ // <- TODO: !!!!! list here all command names
428
429
  // <- TODO: Add more like 'date', 'modelName',...
429
430
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
430
431
  ]);
@@ -441,12 +442,32 @@
441
442
  */
442
443
  var RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
443
444
  // <- TODO: [🧜‍♂️]
445
+ /**
446
+ * @@@
447
+ *
448
+ * @public exported from `@promptbook/core`
449
+ */
450
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
451
+ delimiter: ',',
452
+ quoteChar: '"',
453
+ newline: '\n',
454
+ skipEmptyLines: true,
455
+ });
444
456
  /**
445
457
  * @@@
446
458
  *
447
459
  * @public exported from `@promptbook/core`
448
460
  */
449
461
  var IS_VERBOSE = false;
462
+ /**
463
+ * @@@
464
+ *
465
+ * @private within the repository
466
+ */
467
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
468
+ /**/
469
+ // Note: In normal situations, we check the pipeline logic:
470
+ true);
450
471
  /**
451
472
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
452
473
  */
@@ -515,7 +536,7 @@
515
536
  commands.push("PIPELINE URL ".concat(pipelineUrl));
516
537
  }
517
538
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
518
- // TODO: !!! This increase size of the bundle and is probbably not necessary
539
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
519
540
  pipelineString = prettifyMarkdown(pipelineString);
520
541
  try {
521
542
  for (var _g = __values(parameters.filter(function (_a) {
@@ -663,12 +684,12 @@
663
684
  pipelineString += '```' + contentLanguage;
664
685
  pipelineString += '\n';
665
686
  pipelineString += spaceTrim__default["default"](content);
666
- // <- TODO: !!! Escape
687
+ // <- TODO:[main] !!! Escape
667
688
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
668
689
  pipelineString += '\n';
669
690
  pipelineString += '```';
670
691
  pipelineString += '\n\n';
671
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
692
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
672
693
  }
673
694
  }
674
695
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -895,7 +916,7 @@
895
916
  });
896
917
  }
897
918
 
898
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
919
+ 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"}];
899
920
 
900
921
  /**
901
922
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -970,7 +991,7 @@
970
991
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
971
992
  return false;
972
993
  }
973
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
994
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
974
995
  return true;
975
996
  }
976
997
 
@@ -1102,6 +1123,26 @@
1102
1123
  * @public exported from `@promptbook/core`
1103
1124
  */
1104
1125
  function validatePipeline(pipeline) {
1126
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1127
+ validatePipelineCore(pipeline);
1128
+ }
1129
+ else {
1130
+ try {
1131
+ validatePipelineCore(pipeline);
1132
+ }
1133
+ catch (error) {
1134
+ if (!(error instanceof PipelineLogicError)) {
1135
+ throw error;
1136
+ }
1137
+ console.error(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1138
+ }
1139
+ }
1140
+ return pipeline;
1141
+ }
1142
+ /**
1143
+ * @private internal function for `validatePipeline`
1144
+ */
1145
+ function validatePipelineCore(pipeline) {
1105
1146
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1106
1147
  var e_1, _a, e_2, _b, e_3, _c;
1107
1148
  var pipelineIdentification = (function () {
@@ -1119,19 +1160,19 @@
1119
1160
  // <- Note: [🚲]
1120
1161
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1121
1162
  }
1122
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1163
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1123
1164
  // <- Note: [🚲]
1124
1165
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1125
1166
  }
1126
1167
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1127
1168
  if (!Array.isArray(pipeline.parameters)) {
1128
1169
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1129
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1170
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1130
1171
  }
1131
1172
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1132
1173
  if (!Array.isArray(pipeline.templates)) {
1133
1174
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1134
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1175
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1135
1176
  }
1136
1177
  var _loop_1 = function (parameter) {
1137
1178
  if (parameter.isInput && parameter.isOutput) {
@@ -1300,9 +1341,9 @@
1300
1341
  while (unresovedTemplates.length > 0) {
1301
1342
  _loop_3();
1302
1343
  }
1303
- return pipeline;
1304
1344
  }
1305
1345
  /**
1346
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1306
1347
  * TODO: [🧠] Work with promptbookVersion
1307
1348
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1308
1349
  * > /**
@@ -1314,11 +1355,11 @@
1314
1355
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1315
1356
  */
1316
1357
  /**
1317
- * TODO: [🐣] !!!! Validate that all samples match expectations
1318
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1319
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1320
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1321
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1358
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1359
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1360
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1361
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1362
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1322
1363
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1323
1364
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1324
1365
  */
@@ -2040,113 +2081,35 @@
2040
2081
  */
2041
2082
 
2042
2083
  /**
2043
- * Parses the given script and returns the list of all used variables that are not defined in the script
2044
- *
2045
- * @param script from which to extract the variables
2046
- * @returns the list of variable names
2047
- * @throws {ParseError} if the script is invalid
2048
- * @public exported from `@promptbook/utils`
2049
- */
2050
- function extractVariables(script) {
2051
- var variables = new Set();
2052
- script = "(()=>{".concat(script, "})()");
2053
- try {
2054
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2055
- try {
2056
- eval(script);
2057
- }
2058
- catch (error) {
2059
- if (!(error instanceof ReferenceError)) {
2060
- throw error;
2061
- }
2062
- var undefinedName = error.message.split(' ')[0];
2063
- /*
2064
- Note: Parsing the error
2065
- [PipelineUrlError: thing is not defined]
2066
- */
2067
- if (!undefinedName) {
2068
- throw error;
2069
- }
2070
- if (script.includes(undefinedName + '(')) {
2071
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2072
- }
2073
- else {
2074
- variables.add(undefinedName);
2075
- script = "const ".concat(undefinedName, " = '';") + script;
2076
- }
2077
- }
2078
- }
2079
- catch (error) {
2080
- if (!(error instanceof Error)) {
2081
- throw error;
2082
- }
2083
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2084
- }
2085
- return variables;
2086
- }
2087
- /**
2088
- * TODO: [🔣] Support for multiple languages - python, java,...
2089
- */
2090
-
2091
- /**
2092
- * Parses the template and returns the set of all used parameters
2084
+ * Determine if the pipeline is fully prepared
2093
2085
  *
2094
- * @param template the template with used parameters
2095
- * @returns the set of parameter names
2096
- * @throws {ParseError} if the script is invalid
2097
- * @public exported from `@promptbook/utils`
2086
+ * @public exported from `@promptbook/core`
2098
2087
  */
2099
- function extractParameterNamesFromTemplate(template) {
2100
- var e_1, _a, e_2, _b, e_3, _c;
2101
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2102
- var parameterNames = new Set();
2103
- try {
2104
- 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()) {
2105
- var parameterName = _e.value;
2106
- parameterNames.add(parameterName);
2107
- }
2108
- }
2109
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2110
- finally {
2111
- try {
2112
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2113
- }
2114
- finally { if (e_1) throw e_1.error; }
2115
- }
2116
- if (templateType === 'SCRIPT_TEMPLATE') {
2117
- try {
2118
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2119
- var parameterName = _g.value;
2120
- parameterNames.add(parameterName);
2121
- }
2122
- }
2123
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2124
- finally {
2125
- try {
2126
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2127
- }
2128
- finally { if (e_2) throw e_2.error; }
2129
- }
2130
- }
2131
- try {
2132
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2133
- var jokerName = _j.value;
2134
- parameterNames.add(jokerName);
2135
- }
2088
+ function isPipelinePrepared(pipeline) {
2089
+ // Note: Ignoring `pipeline.preparations` @@@
2090
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2091
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2092
+ return false;
2136
2093
  }
2137
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2138
- finally {
2139
- try {
2140
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2141
- }
2142
- finally { if (e_3) throw e_3.error; }
2094
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2095
+ return false;
2143
2096
  }
2144
- parameterNames.delete('content');
2145
- // <- Note {websiteContent} is used in `preparedContent`
2146
- return parameterNames;
2097
+ /*
2098
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2099
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2100
+ > return false;
2101
+ > }
2102
+ */
2103
+ return true;
2147
2104
  }
2148
2105
  /**
2149
- * TODO: [🔣] If script require contentLanguage
2106
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2107
+ * TODO: [🐠] Maybe base this on `makeValidator`
2108
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2109
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2110
+ * - [🏍] ? Is context in each template
2111
+ * - [♨] Are samples prepared
2112
+ * - [♨] Are templates prepared
2150
2113
  */
2151
2114
 
2152
2115
  /**
@@ -2166,27 +2129,6 @@
2166
2129
  };
2167
2130
  }
2168
2131
 
2169
- /**
2170
- * Function isValidJsonString will tell you if the string is valid JSON or not
2171
- *
2172
- * @public exported from `@promptbook/utils`
2173
- */
2174
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2175
- try {
2176
- JSON.parse(value);
2177
- return true;
2178
- }
2179
- catch (error) {
2180
- if (!(error instanceof Error)) {
2181
- throw error;
2182
- }
2183
- if (error.message.includes('Unexpected token')) {
2184
- return false;
2185
- }
2186
- return false;
2187
- }
2188
- }
2189
-
2190
2132
  /**
2191
2133
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2192
2134
  *
@@ -2213,9 +2155,10 @@
2213
2155
  });
2214
2156
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2215
2157
  get: function () {
2216
- return this.llmExecutionTools
2217
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2218
- .join('\n');
2158
+ return this.llmExecutionTools.map(function (_a, index) {
2159
+ var title = _a.title;
2160
+ return "".concat(index + 1, ") `").concat(title, "`");
2161
+ }).join('\n');
2219
2162
  },
2220
2163
  enumerable: false,
2221
2164
  configurable: true
@@ -2413,9 +2356,7 @@
2413
2356
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2414
2357
  }
2415
2358
  else {
2416
- throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.llmExecutionTools
2417
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2418
- .join('\n')), "\n\n "); }));
2359
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\"\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.description), "\n\n "); }));
2419
2360
  }
2420
2361
  }
2421
2362
  });
@@ -2481,95 +2422,700 @@
2481
2422
  */
2482
2423
 
2483
2424
  /**
2484
- * Extracts all code blocks from markdown.
2425
+ * Takes an item or an array of items and returns an array of items
2485
2426
  *
2486
- * Note: There are multiple simmilar function:
2487
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2488
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2489
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2490
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2427
+ * 1) Any item except array and undefined returns array with that one item (also null)
2428
+ * 2) Undefined returns empty array
2429
+ * 3) Array returns itself
2491
2430
  *
2492
- * @param markdown any valid markdown
2493
- * @returns code blocks with language and content
2494
- * @throws {ParseError} if block is not closed properly
2495
- * @public exported from `@promptbook/markdown-utils`
2431
+ * @private internal utility
2496
2432
  */
2497
- function extractAllBlocksFromMarkdown(markdown) {
2498
- var e_1, _a;
2499
- var codeBlocks = [];
2500
- var lines = markdown.split('\n');
2501
- // Note: [0] Ensure that the last block notated by gt > will be closed
2502
- lines.push('');
2503
- var currentCodeBlock = null;
2504
- try {
2505
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2506
- var line = lines_1_1.value;
2507
- if (line.startsWith('> ') || line === '>') {
2508
- if (currentCodeBlock === null) {
2509
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2510
- } /* not else */
2511
- if (currentCodeBlock.blockNotation === '>') {
2512
- if (currentCodeBlock.content !== '') {
2513
- currentCodeBlock.content += '\n';
2514
- }
2515
- currentCodeBlock.content += line.slice(2);
2516
- }
2517
- }
2518
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2519
- codeBlocks.push(currentCodeBlock);
2520
- currentCodeBlock = null;
2521
- }
2522
- /* not else */
2523
- if (line.startsWith('```')) {
2524
- var language = line.slice(3).trim() || null;
2525
- if (currentCodeBlock === null) {
2526
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2527
- }
2528
- else {
2529
- if (language !== null) {
2530
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2531
- }
2532
- codeBlocks.push(currentCodeBlock);
2533
- currentCodeBlock = null;
2534
- }
2535
- }
2536
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2537
- if (currentCodeBlock.content !== '') {
2538
- currentCodeBlock.content += '\n';
2539
- }
2540
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2541
- }
2542
- }
2543
- }
2544
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2545
- finally {
2546
- try {
2547
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2548
- }
2549
- finally { if (e_1) throw e_1.error; }
2433
+ function arrayableToArray(input) {
2434
+ if (input === undefined) {
2435
+ return [];
2550
2436
  }
2551
- if (currentCodeBlock !== null) {
2552
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2437
+ if (input instanceof Array) {
2438
+ return input;
2553
2439
  }
2554
- return codeBlocks;
2440
+ return [input];
2555
2441
  }
2556
- /**
2557
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2558
- */
2559
2442
 
2560
2443
  /**
2561
- * Extracts extracts exactly one valid JSON code block
2562
- *
2563
- * - When given string is a valid JSON as it is, it just returns it
2564
- * - When there is no JSON code block the function throws a `ParseError`
2565
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2566
- *
2567
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2568
- * Note: There are multiple simmilar function:
2569
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2570
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2571
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2572
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2444
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2445
+ *
2446
+ * @param script from which to extract the variables
2447
+ * @returns the list of variable names
2448
+ * @throws {ParseError} if the script is invalid
2449
+ * @public exported from `@promptbook/utils`
2450
+ */
2451
+ function extractVariables(script) {
2452
+ var variables = new Set();
2453
+ script = "(()=>{".concat(script, "})()");
2454
+ try {
2455
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2456
+ try {
2457
+ eval(script);
2458
+ }
2459
+ catch (error) {
2460
+ if (!(error instanceof ReferenceError)) {
2461
+ throw error;
2462
+ }
2463
+ var undefinedName = error.message.split(' ')[0];
2464
+ /*
2465
+ Note: Parsing the error
2466
+ [PipelineUrlError: thing is not defined]
2467
+ */
2468
+ if (!undefinedName) {
2469
+ throw error;
2470
+ }
2471
+ if (script.includes(undefinedName + '(')) {
2472
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2473
+ }
2474
+ else {
2475
+ variables.add(undefinedName);
2476
+ script = "const ".concat(undefinedName, " = '';") + script;
2477
+ }
2478
+ }
2479
+ }
2480
+ catch (error) {
2481
+ if (!(error instanceof Error)) {
2482
+ throw error;
2483
+ }
2484
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2485
+ }
2486
+ return variables;
2487
+ }
2488
+ /**
2489
+ * TODO: [🔣] Support for multiple languages - python, java,...
2490
+ */
2491
+
2492
+ /**
2493
+ * Parses the template and returns the set of all used parameters
2494
+ *
2495
+ * @param template the template with used parameters
2496
+ * @returns the set of parameter names
2497
+ * @throws {ParseError} if the script is invalid
2498
+ * @public exported from `@promptbook/utils`
2499
+ */
2500
+ function extractParameterNamesFromTemplate(template) {
2501
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2502
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2503
+ var parameterNames = new Set();
2504
+ try {
2505
+ 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()) {
2506
+ var parameterName = _f.value;
2507
+ parameterNames.add(parameterName);
2508
+ }
2509
+ }
2510
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2511
+ finally {
2512
+ try {
2513
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2514
+ }
2515
+ finally { if (e_1) throw e_1.error; }
2516
+ }
2517
+ if (templateType === 'SCRIPT_TEMPLATE') {
2518
+ try {
2519
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2520
+ var parameterName = _h.value;
2521
+ parameterNames.add(parameterName);
2522
+ }
2523
+ }
2524
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2525
+ finally {
2526
+ try {
2527
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2528
+ }
2529
+ finally { if (e_2) throw e_2.error; }
2530
+ }
2531
+ }
2532
+ try {
2533
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2534
+ var jokerName = _k.value;
2535
+ parameterNames.add(jokerName);
2536
+ }
2537
+ }
2538
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2539
+ finally {
2540
+ try {
2541
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2542
+ }
2543
+ finally { if (e_3) throw e_3.error; }
2544
+ }
2545
+ parameterNames.delete('content');
2546
+ // <- Note {websiteContent} is used in `preparedContent`
2547
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2548
+ if (foreach !== undefined) {
2549
+ try {
2550
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2551
+ var subparameterName = _m.value;
2552
+ if (parameterNames.has(subparameterName)) {
2553
+ parameterNames.delete(subparameterName);
2554
+ parameterNames.add(foreach.parameterName);
2555
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2556
+ }
2557
+ }
2558
+ }
2559
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2560
+ finally {
2561
+ try {
2562
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2563
+ }
2564
+ finally { if (e_4) throw e_4.error; }
2565
+ }
2566
+ }
2567
+ return parameterNames;
2568
+ }
2569
+ /**
2570
+ * TODO: [🔣] If script require contentLanguage
2571
+ */
2572
+
2573
+ /**
2574
+ * Create difference set of two sets.
2575
+ *
2576
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2577
+ * @public exported from `@promptbook/utils`
2578
+ */
2579
+ function difference(a, b, isEqual) {
2580
+ var e_1, _a;
2581
+ if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2582
+ var diff = new Set();
2583
+ var _loop_1 = function (itemA) {
2584
+ if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2585
+ diff.add(itemA);
2586
+ }
2587
+ };
2588
+ try {
2589
+ for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2590
+ var itemA = _c.value;
2591
+ _loop_1(itemA);
2592
+ }
2593
+ }
2594
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2595
+ finally {
2596
+ try {
2597
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2598
+ }
2599
+ finally { if (e_1) throw e_1.error; }
2600
+ }
2601
+ return diff;
2602
+ }
2603
+ /**
2604
+ * TODO: [🧠][💯] Maybe also implement symmetricDifference
2605
+ */
2606
+
2607
+ /**
2608
+ * Creates a new set with all elements that are present in either set
2609
+ *
2610
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2611
+ * @public exported from `@promptbook/utils`
2612
+ */
2613
+ function union() {
2614
+ var e_1, _a, e_2, _b;
2615
+ var sets = [];
2616
+ for (var _i = 0; _i < arguments.length; _i++) {
2617
+ sets[_i] = arguments[_i];
2618
+ }
2619
+ var union = new Set();
2620
+ try {
2621
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2622
+ var set = sets_1_1.value;
2623
+ try {
2624
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2625
+ var item = _d.value;
2626
+ union.add(item);
2627
+ }
2628
+ }
2629
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2630
+ finally {
2631
+ try {
2632
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2633
+ }
2634
+ finally { if (e_2) throw e_2.error; }
2635
+ }
2636
+ }
2637
+ }
2638
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2639
+ finally {
2640
+ try {
2641
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2642
+ }
2643
+ finally { if (e_1) throw e_1.error; }
2644
+ }
2645
+ return union;
2646
+ }
2647
+
2648
+ /**
2649
+ * Just marks a place of place where should be something implemented
2650
+ * No side effects.
2651
+ *
2652
+ * Note: It can be usefull suppressing eslint errors of unused variables
2653
+ *
2654
+ * @param value any values
2655
+ * @returns void
2656
+ * @private within the repository
2657
+ */
2658
+ function TODO_USE() {
2659
+ var value = [];
2660
+ for (var _i = 0; _i < arguments.length; _i++) {
2661
+ value[_i] = arguments[_i];
2662
+ }
2663
+ }
2664
+
2665
+ /**
2666
+ * @@@
2667
+ *
2668
+ * @public exported from `@promptbook/core`
2669
+ */
2670
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2671
+ header: true,
2672
+ // encoding: 'utf8',
2673
+ });
2674
+
2675
+ /**
2676
+ * Definition for CSV spreadsheet
2677
+ *
2678
+ * @public exported from `@promptbook/core`
2679
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2680
+ */
2681
+ var CsvFormatDefinition = {
2682
+ formatName: 'CSV',
2683
+ aliases: ['SPREADSHEET', 'TABLE'],
2684
+ isValid: function (value, settings, schema) {
2685
+ // TODO: !!!!!! Implement CSV validation
2686
+ TODO_USE(value /* <- TODO: Use value here */);
2687
+ TODO_USE(settings /* <- TODO: Use settings here */);
2688
+ TODO_USE(schema /* <- TODO: Use schema here */);
2689
+ return true;
2690
+ },
2691
+ canBeValid: function (partialValue, settings, schema) {
2692
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2693
+ TODO_USE(settings /* <- TODO: Use settings here */);
2694
+ TODO_USE(schema /* <- TODO: Use schema here */);
2695
+ return true;
2696
+ },
2697
+ heal: function (value, settings, schema) {
2698
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2699
+ TODO_USE(settings /* <- TODO: Use settings here */);
2700
+ TODO_USE(schema /* <- TODO: Use schema here */);
2701
+ throw new Error('Not implemented');
2702
+ },
2703
+ subvalueDefinitions: [
2704
+ {
2705
+ subvalueName: 'ROW',
2706
+ mapValues: function (value, settings, mapCallback) {
2707
+ return __awaiter(this, void 0, void 0, function () {
2708
+ var csv, mappedData;
2709
+ var _this = this;
2710
+ return __generator(this, function (_a) {
2711
+ switch (_a.label) {
2712
+ case 0:
2713
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2714
+ if (csv.errors.length !== 0) {
2715
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2716
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2717
+ }
2718
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2719
+ var _a;
2720
+ var _b;
2721
+ return __generator(this, function (_c) {
2722
+ switch (_c.label) {
2723
+ case 0:
2724
+ _a = [__assign({}, row)];
2725
+ _b = {};
2726
+ // <- TODO: !!!!!! Dynamic new column name and position
2727
+ // <- TODO: !!!!!! Check name collisions
2728
+ return [4 /*yield*/, mapCallback(row, index)];
2729
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2730
+ // <- TODO: !!!!!! Dynamic new column name and position
2731
+ // <- TODO: !!!!!! Check name collisions
2732
+ _c.sent(), _b)])))];
2733
+ }
2734
+ });
2735
+ }); }))];
2736
+ case 1:
2737
+ mappedData = _a.sent();
2738
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2739
+ }
2740
+ });
2741
+ });
2742
+ },
2743
+ },
2744
+ {
2745
+ subvalueName: 'CELL',
2746
+ mapValues: function (value, settings, mapCallback) {
2747
+ return __awaiter(this, void 0, void 0, function () {
2748
+ var csv, mappedData;
2749
+ var _this = this;
2750
+ return __generator(this, function (_a) {
2751
+ switch (_a.label) {
2752
+ case 0:
2753
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2754
+ if (csv.errors.length !== 0) {
2755
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2756
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2757
+ }
2758
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2759
+ var _this = this;
2760
+ return __generator(this, function (_a) {
2761
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2762
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2763
+ return __awaiter(_this, void 0, void 0, function () {
2764
+ var index;
2765
+ var _c;
2766
+ return __generator(this, function (_d) {
2767
+ index = rowIndex * Object.keys(row).length + columnIndex;
2768
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2769
+ });
2770
+ });
2771
+ }))];
2772
+ });
2773
+ }); }))];
2774
+ case 1:
2775
+ mappedData = _a.sent();
2776
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2777
+ }
2778
+ });
2779
+ });
2780
+ },
2781
+ },
2782
+ ],
2783
+ };
2784
+ /**
2785
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2786
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2787
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2788
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2789
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2790
+ */
2791
+
2792
+ /**
2793
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2794
+ *
2795
+ * @public exported from `@promptbook/utils`
2796
+ */
2797
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2798
+ try {
2799
+ JSON.parse(value);
2800
+ return true;
2801
+ }
2802
+ catch (error) {
2803
+ if (!(error instanceof Error)) {
2804
+ throw error;
2805
+ }
2806
+ if (error.message.includes('Unexpected token')) {
2807
+ return false;
2808
+ }
2809
+ return false;
2810
+ }
2811
+ }
2812
+
2813
+ /**
2814
+ * Definition for JSON format
2815
+ *
2816
+ * @private still in development [🏢]
2817
+ */
2818
+ var JsonFormatDefinition = {
2819
+ formatName: 'JSON',
2820
+ mimeType: 'application/json',
2821
+ isValid: function (value, settings, schema) {
2822
+ TODO_USE(schema /* <- TODO: Use schema here */);
2823
+ TODO_USE(settings /* <- TODO: Use settings here */);
2824
+ return isValidJsonString(value);
2825
+ },
2826
+ canBeValid: function (partialValue, settings, schema) {
2827
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2828
+ TODO_USE(settings /* <- TODO: Use settings here */);
2829
+ TODO_USE(schema /* <- TODO: Use schema here */);
2830
+ return true;
2831
+ },
2832
+ heal: function (value, settings, schema) {
2833
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2834
+ TODO_USE(settings /* <- TODO: Use settings here */);
2835
+ TODO_USE(schema /* <- TODO: Use schema here */);
2836
+ throw new Error('Not implemented');
2837
+ },
2838
+ subvalueDefinitions: [],
2839
+ };
2840
+ /**
2841
+ * TODO: [🧠] Maybe propper instance of object
2842
+ * TODO: [0] Make string_serialized_json
2843
+ * TODO: [1] Make type for JSON Settings and Schema
2844
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2845
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2846
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2847
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2848
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2849
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2850
+ */
2851
+
2852
+ /**
2853
+ * Definition for any text - this will be always valid
2854
+ *
2855
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
2856
+ *
2857
+ * @public exported from `@promptbook/core`
2858
+ */
2859
+ var TextFormatDefinition = {
2860
+ formatName: 'TEXT',
2861
+ isValid: function (value) {
2862
+ return typeof value === 'string';
2863
+ },
2864
+ canBeValid: function (partialValue) {
2865
+ return typeof partialValue === 'string';
2866
+ },
2867
+ heal: function () {
2868
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
2869
+ },
2870
+ subvalueDefinitions: [
2871
+ {
2872
+ subvalueName: 'LINE',
2873
+ mapValues: function (value, settings, mapCallback) {
2874
+ return __awaiter(this, void 0, void 0, function () {
2875
+ var lines, mappedLines;
2876
+ return __generator(this, function (_a) {
2877
+ switch (_a.label) {
2878
+ case 0:
2879
+ lines = value.split('\n');
2880
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
2881
+ // TODO: [🧠] Maybe option to skip empty line
2882
+ /* not await */ return mapCallback({
2883
+ lineContent: lineContent,
2884
+ // TODO: [🧠] Maybe also put here `lineNumber`
2885
+ }, lineNumber);
2886
+ }))];
2887
+ case 1:
2888
+ mappedLines = _a.sent();
2889
+ return [2 /*return*/, mappedLines.join('\n')];
2890
+ }
2891
+ });
2892
+ });
2893
+ },
2894
+ },
2895
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2896
+ ],
2897
+ };
2898
+ /**
2899
+ * TODO: [1] Make type for XML Text and Schema
2900
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2901
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
2902
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
2903
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
2904
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
2905
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
2906
+ */
2907
+
2908
+ /**
2909
+ * Definition for XML format
2910
+ *
2911
+ * @private still in development [🏢]
2912
+ */
2913
+ var XmlFormatDefinition = {
2914
+ formatName: 'XML',
2915
+ mimeType: 'application/xml',
2916
+ isValid: function (value, settings, schema) {
2917
+ TODO_USE(value /* <- TODO: Use value here */);
2918
+ TODO_USE(settings /* <- TODO: Use settings here */);
2919
+ TODO_USE(schema /* <- TODO: Use schema here */);
2920
+ return true;
2921
+ },
2922
+ canBeValid: function (partialValue, settings, schema) {
2923
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2924
+ TODO_USE(settings /* <- TODO: Use settings here */);
2925
+ TODO_USE(schema /* <- TODO: Use schema here */);
2926
+ return true;
2927
+ },
2928
+ heal: function (value, settings, schema) {
2929
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2930
+ TODO_USE(settings /* <- TODO: Use settings here */);
2931
+ TODO_USE(schema /* <- TODO: Use schema here */);
2932
+ throw new Error('Not implemented');
2933
+ },
2934
+ subvalueDefinitions: [],
2935
+ };
2936
+ /**
2937
+ * TODO: [🧠] Maybe propper instance of object
2938
+ * TODO: [0] Make string_serialized_xml
2939
+ * TODO: [1] Make type for XML Settings and Schema
2940
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
2941
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
2942
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
2943
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
2944
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
2945
+ * TODO: [🏢] Allow to expect something inside XML and other formats
2946
+ */
2947
+
2948
+ /**
2949
+ * Definitions for all formats supported by Promptbook
2950
+ *
2951
+ * @private internal index of `...` <- TODO [🏢]
2952
+ */
2953
+ var FORMAT_DEFINITIONS = [
2954
+ JsonFormatDefinition,
2955
+ XmlFormatDefinition,
2956
+ TextFormatDefinition,
2957
+ CsvFormatDefinition,
2958
+ ];
2959
+
2960
+ /**
2961
+ * Maps available parameters to expected parameters
2962
+ *
2963
+ * The strategy is:
2964
+ * 1) @@@
2965
+ * 2) @@@
2966
+ *
2967
+ * @throws {PipelineExecutionError} @@@
2968
+ * @private within the repository used in `createPipelineExecutor`
2969
+ */
2970
+ function mapAvailableToExpectedParameters(options) {
2971
+ var e_1, _a;
2972
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
2973
+ var availableParametersNames = new Set(Object.keys(availableParameters));
2974
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
2975
+ var mappedParameters = {};
2976
+ try {
2977
+ // Phase 1️⃣: Matching mapping
2978
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
2979
+ var parameterName = _c.value;
2980
+ // Situation: Parameter is available and expected
2981
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
2982
+ mappedParameters[parameterName] = availableParameters[parameterName];
2983
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
2984
+ availableParametersNames.delete(parameterName);
2985
+ expectedParameterNames.delete(parameterName);
2986
+ }
2987
+ // Situation: Parameter is available but NOT expected
2988
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
2989
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
2990
+ }
2991
+ // Situation: Parameter is NOT available BUT expected
2992
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
2993
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
2994
+ }
2995
+ }
2996
+ }
2997
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2998
+ finally {
2999
+ try {
3000
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3001
+ }
3002
+ finally { if (e_1) throw e_1.error; }
3003
+ }
3004
+ if (expectedParameterNames.size === 0) {
3005
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3006
+ Object.freeze(mappedParameters);
3007
+ return mappedParameters;
3008
+ }
3009
+ // Phase 2️⃣: Non-matching mapping
3010
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3011
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3012
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3013
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3014
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3015
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3016
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3017
+ .join('\n')), "\n\n "); }));
3018
+ }
3019
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3020
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3021
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3022
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3023
+ }
3024
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3025
+ Object.freeze(mappedParameters);
3026
+ return mappedParameters;
3027
+ }
3028
+
3029
+ /**
3030
+ * Extracts all code blocks from markdown.
3031
+ *
3032
+ * Note: There are multiple simmilar function:
3033
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3034
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3035
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3036
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3037
+ *
3038
+ * @param markdown any valid markdown
3039
+ * @returns code blocks with language and content
3040
+ * @throws {ParseError} if block is not closed properly
3041
+ * @public exported from `@promptbook/markdown-utils`
3042
+ */
3043
+ function extractAllBlocksFromMarkdown(markdown) {
3044
+ var e_1, _a;
3045
+ var codeBlocks = [];
3046
+ var lines = markdown.split('\n');
3047
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3048
+ lines.push('');
3049
+ var currentCodeBlock = null;
3050
+ try {
3051
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3052
+ var line = lines_1_1.value;
3053
+ if (line.startsWith('> ') || line === '>') {
3054
+ if (currentCodeBlock === null) {
3055
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3056
+ } /* not else */
3057
+ if (currentCodeBlock.blockNotation === '>') {
3058
+ if (currentCodeBlock.content !== '') {
3059
+ currentCodeBlock.content += '\n';
3060
+ }
3061
+ currentCodeBlock.content += line.slice(2);
3062
+ }
3063
+ }
3064
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3065
+ codeBlocks.push(currentCodeBlock);
3066
+ currentCodeBlock = null;
3067
+ }
3068
+ /* not else */
3069
+ if (line.startsWith('```')) {
3070
+ var language = line.slice(3).trim() || null;
3071
+ if (currentCodeBlock === null) {
3072
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3073
+ }
3074
+ else {
3075
+ if (language !== null) {
3076
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3077
+ }
3078
+ codeBlocks.push(currentCodeBlock);
3079
+ currentCodeBlock = null;
3080
+ }
3081
+ }
3082
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3083
+ if (currentCodeBlock.content !== '') {
3084
+ currentCodeBlock.content += '\n';
3085
+ }
3086
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3087
+ }
3088
+ }
3089
+ }
3090
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3091
+ finally {
3092
+ try {
3093
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3094
+ }
3095
+ finally { if (e_1) throw e_1.error; }
3096
+ }
3097
+ if (currentCodeBlock !== null) {
3098
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3099
+ }
3100
+ return codeBlocks;
3101
+ }
3102
+ /**
3103
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3104
+ */
3105
+
3106
+ /**
3107
+ * Extracts extracts exactly one valid JSON code block
3108
+ *
3109
+ * - When given string is a valid JSON as it is, it just returns it
3110
+ * - When there is no JSON code block the function throws a `ParseError`
3111
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3112
+ *
3113
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3114
+ * Note: There are multiple simmilar function:
3115
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3116
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3117
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3118
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2573
3119
  *
2574
3120
  * @public exported from `@promptbook/markdown-utils`
2575
3121
  * @throws {ParseError} if there is no valid JSON block in the markdown
@@ -2596,57 +3142,6 @@
2596
3142
  * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2597
3143
  */
2598
3144
 
2599
- /**
2600
- * Determine if the pipeline is fully prepared
2601
- *
2602
- * @public exported from `@promptbook/core`
2603
- */
2604
- function isPipelinePrepared(pipeline) {
2605
- // Note: Ignoring `pipeline.preparations` @@@
2606
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2607
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2608
- return false;
2609
- }
2610
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2611
- return false;
2612
- }
2613
- /*
2614
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2615
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2616
- > return false;
2617
- > }
2618
- */
2619
- return true;
2620
- }
2621
- /**
2622
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2623
- * TODO: [🐠] Maybe base this on `makeValidator`
2624
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2625
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2626
- * - [🏍] ? Is context in each template
2627
- * - [♨] Are samples prepared
2628
- * - [♨] Are templates prepared
2629
- */
2630
-
2631
- /**
2632
- * Takes an item or an array of items and returns an array of items
2633
- *
2634
- * 1) Any item except array and undefined returns array with that one item (also null)
2635
- * 2) Undefined returns empty array
2636
- * 3) Array returns itself
2637
- *
2638
- * @private internal utility
2639
- */
2640
- function arrayableToArray(input) {
2641
- if (input === undefined) {
2642
- return [];
2643
- }
2644
- if (input instanceof Array) {
2645
- return input;
2646
- }
2647
- return [input];
2648
- }
2649
-
2650
3145
  /**
2651
3146
  * Just says that the variable is not used but should be kept
2652
3147
  * No side effects.
@@ -2668,23 +3163,6 @@
2668
3163
  }
2669
3164
  }
2670
3165
 
2671
- /**
2672
- * Just marks a place of place where should be something implemented
2673
- * No side effects.
2674
- *
2675
- * Note: It can be usefull suppressing eslint errors of unused variables
2676
- *
2677
- * @param value any values
2678
- * @returns void
2679
- * @private within the repository
2680
- */
2681
- function TODO_USE() {
2682
- var value = [];
2683
- for (var _i = 0; _i < arguments.length; _i++) {
2684
- value[_i] = arguments[_i];
2685
- }
2686
- }
2687
-
2688
3166
  /**
2689
3167
  * Replaces parameters in template with values from parameters object
2690
3168
  *
@@ -2741,102 +3219,27 @@
2741
3219
  if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2742
3220
  parameterValue = parameterValue
2743
3221
  .split('\n')
2744
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2745
- .join('\n');
2746
- }
2747
- replacedTemplate =
2748
- replacedTemplate.substring(0, match.index + precol.length) +
2749
- parameterValue +
2750
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2751
- };
2752
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2753
- .exec(replacedTemplate))) {
2754
- _loop_1();
2755
- }
2756
- // [💫] Check if there are parameters that are not closed properly
2757
- if (/{\w+$/.test(replacedTemplate)) {
2758
- throw new PipelineExecutionError('Parameter is not closed');
2759
- }
2760
- // [💫] Check if there are parameters that are not opened properly
2761
- if (/^\w+}/.test(replacedTemplate)) {
2762
- throw new PipelineExecutionError('Parameter is not opened');
2763
- }
2764
- return replacedTemplate;
2765
- }
2766
-
2767
- /**
2768
- * Create difference set of two sets.
2769
- *
2770
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2771
- * @public exported from `@promptbook/utils`
2772
- */
2773
- function difference(a, b, isEqual) {
2774
- var e_1, _a;
2775
- if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2776
- var diff = new Set();
2777
- var _loop_1 = function (itemA) {
2778
- if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2779
- diff.add(itemA);
2780
- }
2781
- };
2782
- try {
2783
- for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2784
- var itemA = _c.value;
2785
- _loop_1(itemA);
2786
- }
2787
- }
2788
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2789
- finally {
2790
- try {
2791
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2792
- }
2793
- finally { if (e_1) throw e_1.error; }
2794
- }
2795
- return diff;
2796
- }
2797
- /**
2798
- * TODO: [🧠][💯] Maybe also implement symmetricDifference
2799
- */
2800
-
2801
- /**
2802
- * Creates a new set with all elements that are present in either set
2803
- *
2804
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2805
- * @public exported from `@promptbook/utils`
2806
- */
2807
- function union() {
2808
- var e_1, _a, e_2, _b;
2809
- var sets = [];
2810
- for (var _i = 0; _i < arguments.length; _i++) {
2811
- sets[_i] = arguments[_i];
2812
- }
2813
- var union = new Set();
2814
- try {
2815
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2816
- var set = sets_1_1.value;
2817
- try {
2818
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2819
- var item = _d.value;
2820
- union.add(item);
2821
- }
2822
- }
2823
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2824
- finally {
2825
- try {
2826
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2827
- }
2828
- finally { if (e_2) throw e_2.error; }
2829
- }
2830
- }
2831
- }
2832
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2833
- finally {
2834
- try {
2835
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
3222
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3223
+ .join('\n');
2836
3224
  }
2837
- finally { if (e_1) throw e_1.error; }
3225
+ replacedTemplate =
3226
+ replacedTemplate.substring(0, match.index + precol.length) +
3227
+ parameterValue +
3228
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3229
+ };
3230
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3231
+ .exec(replacedTemplate))) {
3232
+ _loop_1();
2838
3233
  }
2839
- return union;
3234
+ // [💫] Check if there are parameters that are not closed properly
3235
+ if (/{\w+$/.test(replacedTemplate)) {
3236
+ throw new PipelineExecutionError('Parameter is not closed');
3237
+ }
3238
+ // [💫] Check if there are parameters that are not opened properly
3239
+ if (/^\w+}/.test(replacedTemplate)) {
3240
+ throw new PipelineExecutionError('Parameter is not opened');
3241
+ }
3242
+ return replacedTemplate;
2840
3243
  }
2841
3244
 
2842
3245
  /**
@@ -2928,6 +3331,9 @@
2928
3331
  LINES: countLines,
2929
3332
  PAGES: countPages,
2930
3333
  };
3334
+ /**
3335
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3336
+ */
2931
3337
 
2932
3338
  /**
2933
3339
  * Function checkExpectations will check if the expectations on given value are met
@@ -2964,597 +3370,748 @@
2964
3370
  }
2965
3371
  /**
2966
3372
  * TODO: [💝] Unite object for expecting amount and format
3373
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3374
+ * Note: [💝] and [🤠] are interconnected together
2967
3375
  */
2968
3376
 
2969
3377
  /**
2970
- * Creates executor function from pipeline and execution tools.
3378
+ * @@@
2971
3379
  *
2972
- * @returns The executor function
2973
- * @throws {PipelineLogicError} on logical error in the pipeline
2974
- * @public exported from `@promptbook/core`
3380
+ * @private internal utility of `createPipelineExecutor`
2975
3381
  */
2976
- function createPipelineExecutor(options) {
2977
- var _this = this;
2978
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
2979
- 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;
2980
- validatePipeline(pipeline);
2981
- var pipelineIdentification = (function () {
2982
- // Note: This is a 😐 implementation of [🚞]
2983
- var _ = [];
2984
- if (pipeline.sourceFile !== undefined) {
2985
- _.push("File: ".concat(pipeline.sourceFile));
2986
- }
2987
- if (pipeline.pipelineUrl !== undefined) {
2988
- _.push("Url: ".concat(pipeline.pipelineUrl));
2989
- }
2990
- return _.join('\n');
2991
- })();
2992
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
2993
- var preparedPipeline;
2994
- if (isPipelinePrepared(pipeline)) {
2995
- preparedPipeline = pipeline;
2996
- }
2997
- else if (isNotPreparedWarningSupressed !== true) {
2998
- console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
2999
- }
3000
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3001
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3002
- function getContextForTemplate(template) {
3003
- return __awaiter(this, void 0, void 0, function () {
3004
- return __generator(this, function (_a) {
3005
- TODO_USE(template);
3006
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3007
- });
3008
- });
3009
- }
3010
- function getKnowledgeForTemplate(template) {
3011
- return __awaiter(this, void 0, void 0, function () {
3012
- return __generator(this, function (_a) {
3013
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3014
- TODO_USE(template);
3015
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3016
- var content = _a.content;
3017
- return "- ".concat(content);
3018
- }).join('\n')];
3019
- });
3020
- });
3021
- }
3022
- function getSamplesForTemplate(template) {
3023
- return __awaiter(this, void 0, void 0, function () {
3024
- return __generator(this, function (_a) {
3025
- // TODO: [♨] Implement Better - use real index and keyword search
3026
- TODO_USE(template);
3027
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3028
- });
3029
- });
3030
- }
3031
- function getReservedParametersForTemplate(template) {
3032
- return __awaiter(this, void 0, void 0, function () {
3033
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3034
- var e_3, _a;
3035
- return __generator(this, function (_b) {
3036
- switch (_b.label) {
3037
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3038
- case 1:
3039
- context = _b.sent();
3040
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3041
- case 2:
3042
- knowledge = _b.sent();
3043
- return [4 /*yield*/, getSamplesForTemplate(template)];
3044
- case 3:
3045
- samples = _b.sent();
3046
- currentDate = new Date().toISOString();
3047
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3048
- reservedParameters = {
3049
- content: RESERVED_PARAMETER_RESTRICTED,
3050
- context: context,
3051
- knowledge: knowledge,
3052
- samples: samples,
3053
- currentDate: currentDate,
3054
- modelName: modelName,
3055
- };
3056
- _loop_3 = function (parameterName) {
3057
- if (reservedParameters[parameterName] === undefined) {
3058
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3059
- }
3060
- };
3061
- try {
3062
- // Note: Doublecheck that ALL reserved parameters are defined:
3063
- 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()) {
3064
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3065
- _loop_3(parameterName);
3066
- }
3067
- }
3068
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3069
- finally {
3070
- try {
3071
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3072
- }
3073
- finally { if (e_3) throw e_3.error; }
3074
- }
3075
- return [2 /*return*/, reservedParameters];
3076
- }
3077
- });
3078
- });
3079
- }
3080
- function executeSingleTemplate(currentTemplate) {
3081
- return __awaiter(this, void 0, void 0, function () {
3082
- 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;
3083
- var e_4, _f, _g;
3084
- return __generator(this, function (_h) {
3085
- switch (_h.label) {
3086
- case 0:
3087
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3088
- title = currentTemplate.title;
3089
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3090
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3091
- progress_1 = {
3092
- name: name,
3093
- title: title,
3094
- isStarted: false,
3095
- isDone: false,
3096
- templateType: currentTemplate.templateType,
3097
- parameterName: currentTemplate.resultingParameterName,
3098
- parameterValue: null,
3099
- // <- [3]
3100
- };
3101
- if (isReturned) {
3102
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3103
- .split('\n')
3104
- .map(function (line) { return "> ".concat(line); })
3105
- .join('\n')), "\n "); }));
3106
- }
3107
- return [4 /*yield*/, onProgress(progress_1)];
3108
- case 1:
3109
- _h.sent();
3110
- _h.label = 2;
3111
- case 2:
3112
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3113
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3114
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3115
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3116
- .map(function (name) { return "{".concat(name, "}"); })
3117
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3118
- .map(function (name) { return "{".concat(name, "}"); })
3119
- .join(', '), "\n\n "); }));
3120
- }
3121
- _b = (_a = Object).freeze;
3122
- _c = [{}];
3123
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3124
- case 3:
3125
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3126
- definedParameterNames = new Set(Object.keys(definedParameters));
3127
- parameters = {};
3128
- _loop_4 = function (parameterName) {
3129
- // Situation: Parameter is defined and used
3130
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3131
- parameters[parameterName] = definedParameters[parameterName];
3132
- }
3133
- // Situation: Parameter is defined but NOT used
3134
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3135
- // Situation: Parameter is NOT defined BUT used
3136
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3137
- // Houston, we have a problem
3138
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3139
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3140
- }
3141
- };
3142
- try {
3143
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3144
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3145
- parameterName = _e.value;
3146
- _loop_4(parameterName);
3147
- }
3148
- }
3149
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3150
- finally {
3151
- try {
3152
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3153
- }
3154
- finally { if (e_4) throw e_4.error; }
3155
- }
3156
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3157
- Object.freeze(parameters);
3158
- result = null;
3159
- resultString = null;
3160
- expectError = null;
3161
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3162
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3163
- preparedContent = (currentTemplate.preparedContent || '{content}')
3164
- .split('{content}')
3165
- .join(currentTemplate.content);
3166
- _loop_5 = function (attempt) {
3167
- 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;
3168
- var e_5, _s, e_7, _t, e_6, _u;
3169
- return __generator(this, function (_v) {
3170
- switch (_v.label) {
3171
- case 0:
3172
- isJokerAttempt = attempt < 0;
3173
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3174
- if (isJokerAttempt && !jokerParameterName) {
3175
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3176
- }
3177
- result = null;
3178
- resultString = null;
3179
- expectError = null;
3180
- if (isJokerAttempt) {
3181
- if (parameters[jokerParameterName] === undefined) {
3182
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3183
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3184
- }
3185
- else {
3186
- resultString = parameters[jokerParameterName];
3187
- }
3188
- }
3189
- _v.label = 1;
3190
- case 1:
3191
- _v.trys.push([1, 44, 45, 46]);
3192
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3193
- _j = currentTemplate.templateType;
3194
- switch (_j) {
3195
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3196
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3197
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3198
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3199
- }
3200
- return [3 /*break*/, 25];
3201
- case 2:
3202
- resultString = replaceParameters(preparedContent, parameters);
3203
- return [3 /*break*/, 26];
3204
- case 3:
3205
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3206
- prompt = {
3207
- title: currentTemplate.title,
3208
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3209
- ? preparedPipeline.pipelineUrl
3210
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3211
- parameters: parameters,
3212
- content: preparedContent,
3213
- modelRequirements: modelRequirements,
3214
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3215
- var name = _a.name;
3216
- return name === currentTemplate.personaName;
3217
- }) || {})), currentTemplate.expectations),
3218
- format: currentTemplate.format,
3219
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3220
- }; // <- TODO: Not very good type guard
3221
- _k = modelRequirements.modelVariant;
3222
- switch (_k) {
3223
- case 'CHAT': return [3 /*break*/, 4];
3224
- case 'COMPLETION': return [3 /*break*/, 6];
3225
- case 'EMBEDDING': return [3 /*break*/, 8];
3226
- }
3227
- return [3 /*break*/, 10];
3228
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3229
- case 5:
3230
- chatResult = _v.sent();
3231
- // TODO: [🍬] Destroy chatThread
3232
- result = chatResult;
3233
- resultString = chatResult.content;
3234
- return [3 /*break*/, 11];
3235
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3236
- case 7:
3237
- completionResult = _v.sent();
3238
- result = completionResult;
3239
- resultString = completionResult.content;
3240
- return [3 /*break*/, 11];
3241
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3242
- case 9:
3243
- embeddingResult = _v.sent();
3244
- result = embeddingResult;
3245
- resultString = embeddingResult.content.join(',');
3246
- return [3 /*break*/, 11];
3247
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3248
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3249
- case 11: return [3 /*break*/, 26];
3250
- case 12:
3251
- if (arrayableToArray(tools.script).length === 0) {
3252
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3253
- }
3254
- if (!currentTemplate.contentLanguage) {
3255
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3256
- }
3257
- // TODO: DRY [1]
3258
- scriptPipelineExecutionErrors = [];
3259
- _v.label = 13;
3260
- case 13:
3261
- _v.trys.push([13, 20, 21, 22]);
3262
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3263
- _v.label = 14;
3264
- case 14:
3265
- if (!!_m.done) return [3 /*break*/, 19];
3266
- scriptTools = _m.value;
3267
- _v.label = 15;
3268
- case 15:
3269
- _v.trys.push([15, 17, , 18]);
3270
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3271
- scriptLanguage: currentTemplate.contentLanguage,
3272
- script: preparedContent,
3273
- parameters: parameters,
3274
- }))];
3275
- case 16:
3276
- resultString = _v.sent();
3277
- return [3 /*break*/, 19];
3278
- case 17:
3279
- error_2 = _v.sent();
3280
- if (!(error_2 instanceof Error)) {
3281
- throw error_2;
3282
- }
3283
- if (error_2 instanceof UnexpectedError) {
3284
- throw error_2;
3285
- }
3286
- scriptPipelineExecutionErrors.push(error_2);
3287
- return [3 /*break*/, 18];
3288
- case 18:
3289
- _m = _l.next();
3290
- return [3 /*break*/, 14];
3291
- case 19: return [3 /*break*/, 22];
3292
- case 20:
3293
- e_5_1 = _v.sent();
3294
- e_5 = { error: e_5_1 };
3295
- return [3 /*break*/, 22];
3296
- case 21:
3297
- try {
3298
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3299
- }
3300
- finally { if (e_5) throw e_5.error; }
3301
- return [7 /*endfinally*/];
3302
- case 22:
3303
- if (resultString !== null) {
3304
- return [3 /*break*/, 26];
3305
- }
3306
- if (scriptPipelineExecutionErrors.length === 1) {
3307
- throw scriptPipelineExecutionErrors[0];
3308
- }
3309
- else {
3310
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3311
- .map(function (error) { return '- ' + error.message; })
3312
- .join('\n\n')), "\n "); }));
3313
- }
3314
- case 23:
3315
- if (tools.userInterface === undefined) {
3316
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3317
- }
3318
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3319
- promptTitle: currentTemplate.title,
3320
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3321
- defaultValue: replaceParameters(preparedContent, parameters),
3322
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3323
- placeholder: undefined,
3324
- priority: priority,
3325
- }))];
3326
- case 24:
3327
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3328
- resultString = _v.sent();
3329
- return [3 /*break*/, 26];
3330
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3331
- case 26:
3332
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3333
- _v.label = 27;
3334
- case 27:
3335
- _v.trys.push([27, 41, 42, 43]);
3336
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3337
- _v.label = 28;
3338
- case 28:
3339
- if (!!_p.done) return [3 /*break*/, 40];
3340
- functionName = _p.value;
3341
- // TODO: DRY [1]
3342
- scriptPipelineExecutionErrors = [];
3343
- postprocessingError = null;
3344
- _v.label = 29;
3345
- case 29:
3346
- _v.trys.push([29, 36, 37, 38]);
3347
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3348
- _v.label = 30;
3349
- case 30:
3350
- if (!!_r.done) return [3 /*break*/, 35];
3351
- scriptTools = _r.value;
3352
- _v.label = 31;
3353
- case 31:
3354
- _v.trys.push([31, 33, , 34]);
3355
- return [4 /*yield*/, scriptTools.execute({
3356
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3357
- script: "".concat(functionName, "(resultString)"),
3358
- parameters: {
3359
- resultString: resultString || '',
3360
- // Note: No ...parametersForTemplate, because working with result only
3361
- },
3362
- })];
3363
- case 32:
3364
- resultString = _v.sent();
3365
- postprocessingError = null;
3366
- return [3 /*break*/, 35];
3367
- case 33:
3368
- error_3 = _v.sent();
3369
- if (!(error_3 instanceof Error)) {
3370
- throw error_3;
3371
- }
3372
- if (error_3 instanceof UnexpectedError) {
3373
- throw error_3;
3374
- }
3375
- postprocessingError = error_3;
3376
- scriptPipelineExecutionErrors.push(error_3);
3377
- return [3 /*break*/, 34];
3378
- case 34:
3379
- _r = _q.next();
3380
- return [3 /*break*/, 30];
3381
- case 35: return [3 /*break*/, 38];
3382
- case 36:
3383
- e_6_1 = _v.sent();
3384
- e_6 = { error: e_6_1 };
3385
- return [3 /*break*/, 38];
3386
- case 37:
3387
- try {
3388
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3389
- }
3390
- finally { if (e_6) throw e_6.error; }
3391
- return [7 /*endfinally*/];
3392
- case 38:
3393
- if (postprocessingError) {
3394
- throw postprocessingError;
3395
- }
3396
- _v.label = 39;
3397
- case 39:
3398
- _p = _o.next();
3399
- return [3 /*break*/, 28];
3400
- case 40: return [3 /*break*/, 43];
3401
- case 41:
3402
- e_7_1 = _v.sent();
3403
- e_7 = { error: e_7_1 };
3404
- return [3 /*break*/, 43];
3405
- case 42:
3406
- try {
3407
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3408
- }
3409
- finally { if (e_7) throw e_7.error; }
3410
- return [7 /*endfinally*/];
3411
- case 43:
3412
- // TODO: [💝] Unite object for expecting amount and format
3413
- if (currentTemplate.format) {
3414
- if (currentTemplate.format === 'JSON') {
3415
- if (!isValidJsonString(resultString || '')) {
3416
- // TODO: [🏢] Do more universally via `FormatDefinition`
3417
- try {
3418
- resultString = extractJsonBlock(resultString || '');
3419
- }
3420
- catch (error) {
3421
- keepUnused(error);
3422
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3423
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3424
- }
3425
- }
3382
+ function executeAttempts(options) {
3383
+ return __awaiter(this, void 0, void 0, function () {
3384
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3385
+ return __generator(this, function (_a) {
3386
+ switch (_a.label) {
3387
+ case 0:
3388
+ 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;
3389
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3390
+ $ongoingTemplateResult = {
3391
+ $result: null,
3392
+ $resultString: null,
3393
+ $expectError: null,
3394
+ $scriptPipelineExecutionErrors: [],
3395
+ };
3396
+ _loop_1 = function (attempt) {
3397
+ 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;
3398
+ var e_1, _q, e_3, _r, e_2, _s;
3399
+ return __generator(this, function (_t) {
3400
+ switch (_t.label) {
3401
+ case 0:
3402
+ isJokerAttempt = attempt < 0;
3403
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3404
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3405
+ if (isJokerAttempt && !jokerParameterName) {
3406
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3407
+ }
3408
+ $ongoingTemplateResult.$result = null;
3409
+ $ongoingTemplateResult.$resultString = null;
3410
+ $ongoingTemplateResult.$expectError = null;
3411
+ if (isJokerAttempt) {
3412
+ if (parameters[jokerParameterName] === undefined) {
3413
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3414
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3415
+ }
3416
+ else {
3417
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3418
+ }
3419
+ }
3420
+ _t.label = 1;
3421
+ case 1:
3422
+ _t.trys.push([1, 43, 44, 45]);
3423
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3424
+ _b = template.templateType;
3425
+ switch (_b) {
3426
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3427
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3428
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3429
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3430
+ }
3431
+ return [3 /*break*/, 24];
3432
+ case 2:
3433
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3434
+ return [3 /*break*/, 25];
3435
+ case 3:
3436
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3437
+ $ongoingTemplateResult.$prompt = {
3438
+ title: template.title,
3439
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3440
+ ? preparedPipeline.pipelineUrl
3441
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3442
+ parameters: parameters,
3443
+ content: preparedContent,
3444
+ modelRequirements: modelRequirements,
3445
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3446
+ var name = _a.name;
3447
+ return name === template.personaName;
3448
+ }) ||
3449
+ {})), template.expectations),
3450
+ format: template.format,
3451
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3452
+ }; // <- TODO: Not very good type guard
3453
+ _c = modelRequirements.modelVariant;
3454
+ switch (_c) {
3455
+ case 'CHAT': return [3 /*break*/, 4];
3456
+ case 'COMPLETION': return [3 /*break*/, 6];
3457
+ case 'EMBEDDING': return [3 /*break*/, 8];
3458
+ }
3459
+ return [3 /*break*/, 9];
3460
+ case 4:
3461
+ _d = $ongoingTemplateResult;
3462
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3463
+ case 5:
3464
+ _d.$chatResult = _t.sent();
3465
+ // TODO: [🍬] Destroy chatThread
3466
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3467
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3468
+ return [3 /*break*/, 10];
3469
+ case 6:
3470
+ _e = $ongoingTemplateResult;
3471
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3472
+ case 7:
3473
+ _e.$completionResult = _t.sent();
3474
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3475
+ $ongoingTemplateResult.$resultString =
3476
+ $ongoingTemplateResult.$completionResult.content;
3477
+ return [3 /*break*/, 10];
3478
+ case 8: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Embedding model can not be used in pipeline\n\n This should be catched during parsing\n\n ".concat(block(pipelineIdentification), "\n\n "); }));
3479
+ case 9: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3480
+ case 10: return [3 /*break*/, 25];
3481
+ case 11:
3482
+ if (arrayableToArray(tools.script).length === 0) {
3483
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3484
+ }
3485
+ if (!template.contentLanguage) {
3486
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3487
+ }
3488
+ _t.label = 12;
3489
+ case 12:
3490
+ _t.trys.push([12, 19, 20, 21]);
3491
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3492
+ _t.label = 13;
3493
+ case 13:
3494
+ if (!!_g.done) return [3 /*break*/, 18];
3495
+ scriptTools = _g.value;
3496
+ _t.label = 14;
3497
+ case 14:
3498
+ _t.trys.push([14, 16, , 17]);
3499
+ _h = $ongoingTemplateResult;
3500
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3501
+ scriptLanguage: template.contentLanguage,
3502
+ script: preparedContent,
3503
+ parameters: parameters,
3504
+ }))];
3505
+ case 15:
3506
+ _h.$resultString = _t.sent();
3507
+ return [3 /*break*/, 18];
3508
+ case 16:
3509
+ error_1 = _t.sent();
3510
+ if (!(error_1 instanceof Error)) {
3511
+ throw error_1;
3512
+ }
3513
+ if (error_1 instanceof UnexpectedError) {
3514
+ throw error_1;
3515
+ }
3516
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3517
+ return [3 /*break*/, 17];
3518
+ case 17:
3519
+ _g = _f.next();
3520
+ return [3 /*break*/, 13];
3521
+ case 18: return [3 /*break*/, 21];
3522
+ case 19:
3523
+ e_1_1 = _t.sent();
3524
+ e_1 = { error: e_1_1 };
3525
+ return [3 /*break*/, 21];
3526
+ case 20:
3527
+ try {
3528
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3529
+ }
3530
+ finally { if (e_1) throw e_1.error; }
3531
+ return [7 /*endfinally*/];
3532
+ case 21:
3533
+ if ($ongoingTemplateResult.$resultString !== null) {
3534
+ return [3 /*break*/, 25];
3535
+ }
3536
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3537
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3538
+ }
3539
+ else {
3540
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3541
+ .map(function (error) { return '- ' + error.message; })
3542
+ .join('\n\n')), "\n "); }));
3543
+ }
3544
+ case 22:
3545
+ if (tools.userInterface === undefined) {
3546
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3547
+ }
3548
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3549
+ _j = $ongoingTemplateResult;
3550
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3551
+ promptTitle: template.title,
3552
+ promptMessage: replaceParameters(template.description || '', parameters),
3553
+ defaultValue: replaceParameters(preparedContent, parameters),
3554
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3555
+ placeholder: undefined,
3556
+ priority: priority,
3557
+ }))];
3558
+ case 23:
3559
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3560
+ _j.$resultString = _t.sent();
3561
+ return [3 /*break*/, 25];
3562
+ case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3563
+ case 25:
3564
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3565
+ _t.label = 26;
3566
+ case 26:
3567
+ _t.trys.push([26, 40, 41, 42]);
3568
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3569
+ _t.label = 27;
3570
+ case 27:
3571
+ if (!!_l.done) return [3 /*break*/, 39];
3572
+ functionName = _l.value;
3573
+ postprocessingError = null;
3574
+ _t.label = 28;
3575
+ case 28:
3576
+ _t.trys.push([28, 35, 36, 37]);
3577
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3578
+ _t.label = 29;
3579
+ case 29:
3580
+ if (!!_o.done) return [3 /*break*/, 34];
3581
+ scriptTools = _o.value;
3582
+ _t.label = 30;
3583
+ case 30:
3584
+ _t.trys.push([30, 32, , 33]);
3585
+ _p = $ongoingTemplateResult;
3586
+ return [4 /*yield*/, scriptTools.execute({
3587
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3588
+ script: "".concat(functionName, "(resultString)"),
3589
+ parameters: {
3590
+ resultString: $ongoingTemplateResult.$resultString || '',
3591
+ // Note: No ...parametersForTemplate, because working with result only
3592
+ },
3593
+ })];
3594
+ case 31:
3595
+ _p.$resultString = _t.sent();
3596
+ postprocessingError = null;
3597
+ return [3 /*break*/, 34];
3598
+ case 32:
3599
+ error_2 = _t.sent();
3600
+ if (!(error_2 instanceof Error)) {
3601
+ throw error_2;
3602
+ }
3603
+ if (error_2 instanceof UnexpectedError) {
3604
+ throw error_2;
3605
+ }
3606
+ postprocessingError = error_2;
3607
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3608
+ return [3 /*break*/, 33];
3609
+ case 33:
3610
+ _o = _m.next();
3611
+ return [3 /*break*/, 29];
3612
+ case 34: return [3 /*break*/, 37];
3613
+ case 35:
3614
+ e_2_1 = _t.sent();
3615
+ e_2 = { error: e_2_1 };
3616
+ return [3 /*break*/, 37];
3617
+ case 36:
3618
+ try {
3619
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3620
+ }
3621
+ finally { if (e_2) throw e_2.error; }
3622
+ return [7 /*endfinally*/];
3623
+ case 37:
3624
+ if (postprocessingError) {
3625
+ throw postprocessingError;
3626
+ }
3627
+ _t.label = 38;
3628
+ case 38:
3629
+ _l = _k.next();
3630
+ return [3 /*break*/, 27];
3631
+ case 39: return [3 /*break*/, 42];
3632
+ case 40:
3633
+ e_3_1 = _t.sent();
3634
+ e_3 = { error: e_3_1 };
3635
+ return [3 /*break*/, 42];
3636
+ case 41:
3637
+ try {
3638
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3639
+ }
3640
+ finally { if (e_3) throw e_3.error; }
3641
+ return [7 /*endfinally*/];
3642
+ case 42:
3643
+ // TODO: [💝] Unite object for expecting amount and format
3644
+ if (template.format) {
3645
+ if (template.format === 'JSON') {
3646
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3647
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3648
+ try {
3649
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3426
3650
  }
3427
- else {
3428
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3651
+ catch (error) {
3652
+ keepUnused(error);
3653
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3654
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3429
3655
  }
3430
3656
  }
3431
- // TODO: [💝] Unite object for expecting amount and format
3432
- if (currentTemplate.expectations) {
3433
- checkExpectations(currentTemplate.expectations, resultString || '');
3434
- }
3435
- return [2 /*return*/, "break-attempts"];
3436
- case 44:
3437
- error_4 = _v.sent();
3438
- if (!(error_4 instanceof ExpectError)) {
3439
- throw error_4;
3440
- }
3441
- expectError = error_4;
3442
- return [3 /*break*/, 46];
3443
- case 45:
3444
- if (!isJokerAttempt &&
3445
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3446
- prompt
3447
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3448
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3449
- ) {
3450
- // TODO: [🧠] Maybe put other templateTypes into report
3451
- executionReport.promptExecutions.push({
3452
- prompt: __assign({}, prompt),
3453
- result: result || undefined,
3454
- error: expectError === null ? undefined : serializeError(expectError),
3455
- });
3456
- }
3457
- return [7 /*endfinally*/];
3458
- case 46:
3459
- if (expectError !== null && attempt === maxAttempts - 1) {
3460
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3461
- .split('\n')
3462
- .map(function (line) { return "> ".concat(line); })
3463
- .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) || '')
3657
+ }
3658
+ else {
3659
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3660
+ }
3661
+ }
3662
+ // TODO: [💝] Unite object for expecting amount and format
3663
+ if (template.expectations) {
3664
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3665
+ }
3666
+ return [2 /*return*/, "break-attempts"];
3667
+ case 43:
3668
+ error_3 = _t.sent();
3669
+ if (!(error_3 instanceof ExpectError)) {
3670
+ throw error_3;
3671
+ }
3672
+ $ongoingTemplateResult.$expectError = error_3;
3673
+ return [3 /*break*/, 45];
3674
+ case 44:
3675
+ if (!isJokerAttempt &&
3676
+ template.templateType === 'PROMPT_TEMPLATE' &&
3677
+ $ongoingTemplateResult.$prompt
3678
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3679
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3680
+ ) {
3681
+ // TODO: [🧠] Maybe put other templateTypes into report
3682
+ $executionReport.promptExecutions.push({
3683
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3684
+ result: $ongoingTemplateResult.$result || undefined,
3685
+ error: $ongoingTemplateResult.$expectError === null
3686
+ ? undefined
3687
+ : serializeError($ongoingTemplateResult.$expectError),
3688
+ });
3689
+ }
3690
+ return [7 /*endfinally*/];
3691
+ case 45:
3692
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3693
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3694
+ var _a, _b, _c;
3695
+ 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) || '')
3696
+ .split('\n')
3697
+ .map(function (line) { return "> ".concat(line); })
3698
+ .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) || '')
3699
+ .split('\n')
3700
+ .map(function (line) { return "> ".concat(line); })
3701
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3702
+ ? 'null'
3703
+ : $ongoingTemplateResult.$resultString
3464
3704
  .split('\n')
3465
3705
  .map(function (line) { return "> ".concat(line); })
3466
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3467
- ? 'null'
3468
- : resultString
3469
- .split('\n')
3470
- .map(function (line) { return "> ".concat(line); })
3471
- .join('\n')), "\n ---\n "); }));
3472
- }
3473
- return [2 /*return*/];
3706
+ .join('\n')), "\n ---\n ");
3707
+ }));
3474
3708
  }
3475
- });
3476
- };
3477
- attempt = -jokerParameterNames.length;
3478
- _h.label = 4;
3479
- case 4:
3480
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3481
- return [5 /*yield**/, _loop_5(attempt)];
3482
- case 5:
3483
- state_2 = _h.sent();
3484
- switch (state_2) {
3485
- case "break-attempts": return [3 /*break*/, 7];
3486
- }
3487
- _h.label = 6;
3488
- case 6:
3489
- attempt++;
3490
- return [3 /*break*/, 4];
3491
- case 7:
3492
- if (resultString === null) {
3493
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3709
+ return [2 /*return*/];
3494
3710
  }
3495
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3496
- progress_2 = {
3497
- name: name,
3498
- title: title,
3499
- isStarted: true,
3500
- isDone: true,
3501
- templateType: currentTemplate.templateType,
3502
- parameterName: currentTemplate.resultingParameterName,
3503
- parameterValue: resultString,
3504
- // <- [3]
3505
- };
3506
- if (isReturned) {
3507
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3508
- .split('\n')
3509
- .map(function (line) { return "> ".concat(line); })
3510
- .join('\n')), "\n\n "); }));
3511
- }
3512
- return [4 /*yield*/, onProgress(progress_2)];
3513
- case 8:
3514
- _h.sent();
3515
- _h.label = 9;
3516
- case 9:
3517
- 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)));
3518
- return [2 /*return*/];
3711
+ });
3712
+ };
3713
+ attempt = -jokerParameterNames.length;
3714
+ _a.label = 1;
3715
+ case 1:
3716
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3717
+ return [5 /*yield**/, _loop_1(attempt)];
3718
+ case 2:
3719
+ state_1 = _a.sent();
3720
+ switch (state_1) {
3721
+ case "break-attempts": return [3 /*break*/, 4];
3722
+ }
3723
+ _a.label = 3;
3724
+ case 3:
3725
+ attempt++;
3726
+ return [3 /*break*/, 1];
3727
+ case 4:
3728
+ if ($ongoingTemplateResult.$resultString === null) {
3729
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3730
+ }
3731
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3732
+ }
3733
+ });
3734
+ });
3735
+ }
3736
+ /**
3737
+ * TODO: Break into smaller functions
3738
+ */
3739
+
3740
+ /**
3741
+ * @@@
3742
+ *
3743
+ * @private internal utility of `createPipelineExecutor`
3744
+ */
3745
+ function executeFormatCells(options) {
3746
+ return __awaiter(this, void 0, void 0, function () {
3747
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
3748
+ var _this = this;
3749
+ return __generator(this, function (_a) {
3750
+ switch (_a.label) {
3751
+ case 0:
3752
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3753
+ if (template.foreach === undefined) {
3754
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3755
+ }
3756
+ if (jokerParameterNames.length !== 0) {
3757
+ throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n JOKER parameters are not supported together with FOREACH command\n\n [\uD83E\uDDDE\u200D\u2640\uFE0F] This should be prevented in `validatePipeline`\n\n ".concat(block(pipelineIdentification), "\n "); }));
3758
+ }
3759
+ parameterValue = parameters[template.foreach.parameterName] || '';
3760
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3761
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3762
+ });
3763
+ if (formatDefinition === undefined) {
3764
+ throw new UnexpectedError(
3765
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3766
+ spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(template.foreach.formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
3767
+ .map(function (formatName) { return "- ".concat(formatName); })
3768
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3769
+ }
3770
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3771
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
3772
+ });
3773
+ if (subvalueDefinition === undefined) {
3774
+ throw new UnexpectedError(
3775
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3776
+ spaceTrim__default["default"](function (block) { return "\n Unsupported subformat name \"".concat(template.foreach.subformatName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
3777
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3778
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3779
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3780
+ }
3781
+ if (formatDefinition.formatName === 'CSV') {
3782
+ formatSettings = settings.csvSettings;
3783
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
3784
+ }
3785
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3786
+ var mappedParameters, allSubparameters, subresultString;
3787
+ return __generator(this, function (_a) {
3788
+ switch (_a.label) {
3789
+ case 0:
3790
+ // TODO: !!!!!!! Limit to N concurrent executions
3791
+ // TODO: !!!!!!! Report progress
3792
+ try {
3793
+ mappedParameters = mapAvailableToExpectedParameters({
3794
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3795
+ availableParameters: subparameters,
3796
+ });
3797
+ }
3798
+ catch (error) {
3799
+ if (!(error instanceof PipelineExecutionError)) {
3800
+ throw error;
3801
+ }
3802
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n ".concat(error.message, "\n\n This is error in FOREACH command\n You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command\n\n ").concat(block(pipelineIdentification), "\n "); }));
3803
+ }
3804
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3805
+ // 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
3806
+ Object.freeze(allSubparameters);
3807
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3808
+ case 1:
3809
+ subresultString = _a.sent();
3810
+ return [2 /*return*/, subresultString];
3811
+ }
3812
+ });
3813
+ }); })];
3814
+ case 1:
3815
+ resultString = _a.sent();
3816
+ return [2 /*return*/, resultString];
3817
+ }
3818
+ });
3819
+ });
3820
+ }
3821
+ /**
3822
+ * TODO: !!!!!! Make pipelineIdentification more precise
3823
+ * TODO: !!!!!! How FOREACH execution looks in the report
3824
+ */
3825
+
3826
+ /**
3827
+ * @@@
3828
+ *
3829
+ * @private internal utility of `createPipelineExecutor`
3830
+ */
3831
+ function getContextForTemplate(template) {
3832
+ return __awaiter(this, void 0, void 0, function () {
3833
+ return __generator(this, function (_a) {
3834
+ TODO_USE(template);
3835
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3836
+ });
3837
+ });
3838
+ }
3839
+
3840
+ /**
3841
+ * @@@
3842
+ *
3843
+ * @private internal utility of `createPipelineExecutor`
3844
+ */
3845
+ function getKnowledgeForTemplate(options) {
3846
+ return __awaiter(this, void 0, void 0, function () {
3847
+ var preparedPipeline, template;
3848
+ return __generator(this, function (_a) {
3849
+ preparedPipeline = options.preparedPipeline, template = options.template;
3850
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3851
+ TODO_USE(template);
3852
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3853
+ var content = _a.content;
3854
+ return "- ".concat(content);
3855
+ }).join('\n')];
3856
+ });
3857
+ });
3858
+ }
3859
+
3860
+ /**
3861
+ * @@@
3862
+ *
3863
+ * @private internal utility of `createPipelineExecutor`
3864
+ */
3865
+ function getSamplesForTemplate(template) {
3866
+ return __awaiter(this, void 0, void 0, function () {
3867
+ return __generator(this, function (_a) {
3868
+ // TODO: [♨] Implement Better - use real index and keyword search
3869
+ TODO_USE(template);
3870
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3871
+ });
3872
+ });
3873
+ }
3874
+
3875
+ /**
3876
+ * @@@
3877
+ *
3878
+ * @private internal utility of `createPipelineExecutor`
3879
+ */
3880
+ function getReservedParametersForTemplate(options) {
3881
+ return __awaiter(this, void 0, void 0, function () {
3882
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3883
+ var e_1, _a;
3884
+ return __generator(this, function (_b) {
3885
+ switch (_b.label) {
3886
+ case 0:
3887
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
3888
+ return [4 /*yield*/, getContextForTemplate(template)];
3889
+ case 1:
3890
+ context = _b.sent();
3891
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
3892
+ case 2:
3893
+ knowledge = _b.sent();
3894
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3895
+ case 3:
3896
+ samples = _b.sent();
3897
+ currentDate = new Date().toISOString();
3898
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3899
+ reservedParameters = {
3900
+ content: RESERVED_PARAMETER_RESTRICTED,
3901
+ context: context,
3902
+ knowledge: knowledge,
3903
+ samples: samples,
3904
+ currentDate: currentDate,
3905
+ modelName: modelName,
3906
+ };
3907
+ _loop_1 = function (parameterName) {
3908
+ if (reservedParameters[parameterName] === undefined) {
3909
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3910
+ }
3911
+ };
3912
+ try {
3913
+ // Note: Doublecheck that ALL reserved parameters are defined:
3914
+ 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()) {
3915
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3916
+ _loop_1(parameterName);
3917
+ }
3519
3918
  }
3520
- });
3521
- });
3522
- }
3523
- function filterJustOutputParameters() {
3524
- var e_8, _a;
3525
- var outputParameters = {};
3526
- var _loop_6 = function (parameter) {
3527
- if (parametersToPass[parameter.name] === undefined) {
3528
- // [4]
3529
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3530
- return "continue";
3531
- }
3532
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3533
- };
3534
- try {
3535
- // Note: Filter ONLY output parameters
3536
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3537
- var isOutput = _a.isOutput;
3538
- return isOutput;
3539
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3540
- var parameter = _c.value;
3541
- _loop_6(parameter);
3542
- }
3919
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3920
+ finally {
3921
+ try {
3922
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3923
+ }
3924
+ finally { if (e_1) throw e_1.error; }
3925
+ }
3926
+ return [2 /*return*/, reservedParameters];
3543
3927
  }
3544
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3545
- finally {
3546
- try {
3547
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3548
- }
3549
- finally { if (e_8) throw e_8.error; }
3928
+ });
3929
+ });
3930
+ }
3931
+
3932
+ /**
3933
+ * @@@
3934
+ *
3935
+ * @private internal utility of `createPipelineExecutor`
3936
+ */
3937
+ function executeTemplate(options) {
3938
+ return __awaiter(this, void 0, void 0, function () {
3939
+ 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;
3940
+ var e_1, _f, _g;
3941
+ return __generator(this, function (_h) {
3942
+ switch (_h.label) {
3943
+ case 0:
3944
+ 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;
3945
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3946
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3947
+ title = currentTemplate.title;
3948
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3949
+ return [4 /*yield*/, onProgress({
3950
+ name: name,
3951
+ title: title,
3952
+ isStarted: false,
3953
+ isDone: false,
3954
+ templateType: currentTemplate.templateType,
3955
+ parameterName: currentTemplate.resultingParameterName,
3956
+ parameterValue: null,
3957
+ // <- [🍸]
3958
+ })];
3959
+ case 1:
3960
+ _h.sent();
3961
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3962
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3963
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
3964
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3965
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
3966
+ .map(function (name) { return "{".concat(name, "}"); })
3967
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3968
+ .map(function (name) { return "{".concat(name, "}"); })
3969
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3970
+ }
3971
+ _b = (_a = Object).freeze;
3972
+ _c = [{}];
3973
+ return [4 /*yield*/, getReservedParametersForTemplate({
3974
+ preparedPipeline: preparedPipeline,
3975
+ template: currentTemplate,
3976
+ pipelineIdentification: pipelineIdentification,
3977
+ })];
3978
+ case 2:
3979
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3980
+ definedParameterNames = new Set(Object.keys(definedParameters));
3981
+ parameters = {};
3982
+ _loop_1 = function (parameterName) {
3983
+ // Situation: Parameter is defined and used
3984
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3985
+ parameters[parameterName] = definedParameters[parameterName];
3986
+ }
3987
+ // Situation: Parameter is defined but NOT used
3988
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3989
+ // Situation: Parameter is NOT defined BUT used
3990
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3991
+ // Houston, we have a problem
3992
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3993
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3994
+ }
3995
+ };
3996
+ try {
3997
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3998
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
3999
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4000
+ parameterName = _e.value;
4001
+ _loop_1(parameterName);
4002
+ }
4003
+ }
4004
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4005
+ finally {
4006
+ try {
4007
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4008
+ }
4009
+ finally { if (e_1) throw e_1.error; }
4010
+ }
4011
+ // 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
4012
+ Object.freeze(parameters);
4013
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4014
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4015
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4016
+ .split('{content}')
4017
+ .join(currentTemplate.content);
4018
+ return [4 /*yield*/, executeFormatCells({
4019
+ jokerParameterNames: jokerParameterNames,
4020
+ priority: priority,
4021
+ maxAttempts: maxAttempts,
4022
+ preparedContent: preparedContent,
4023
+ parameters: parameters,
4024
+ template: currentTemplate,
4025
+ preparedPipeline: preparedPipeline,
4026
+ tools: tools,
4027
+ llmTools: llmTools,
4028
+ settings: settings,
4029
+ $executionReport: $executionReport,
4030
+ pipelineIdentification: pipelineIdentification,
4031
+ })];
4032
+ case 3:
4033
+ resultString = _h.sent();
4034
+ return [4 /*yield*/, onProgress({
4035
+ name: name,
4036
+ title: title,
4037
+ isStarted: true,
4038
+ isDone: true,
4039
+ templateType: currentTemplate.templateType,
4040
+ parameterName: currentTemplate.resultingParameterName,
4041
+ parameterValue: resultString,
4042
+ // <- [🍸]
4043
+ })];
4044
+ case 4:
4045
+ _h.sent();
4046
+ return [2 /*return*/, Object.freeze((_g = {},
4047
+ _g[currentTemplate.resultingParameterName] =
4048
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4049
+ resultString,
4050
+ _g))];
3550
4051
  }
3551
- return outputParameters;
4052
+ });
4053
+ });
4054
+ }
4055
+ /**
4056
+ * TODO: [🤹‍♂️]
4057
+ */
4058
+
4059
+ /**
4060
+ * @@@
4061
+ *
4062
+ * @private internal utility of `createPipelineExecutor`
4063
+ */
4064
+ function filterJustOutputParameters(options) {
4065
+ var e_1, _a;
4066
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4067
+ var outputParameters = {};
4068
+ var _loop_1 = function (parameter) {
4069
+ if (parametersToPass[parameter.name] === undefined) {
4070
+ // [4]
4071
+ $warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
4072
+ return "continue";
4073
+ }
4074
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4075
+ };
4076
+ try {
4077
+ // Note: Filter ONLY output parameters
4078
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4079
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4080
+ var isOutput = _a.isOutput;
4081
+ return isOutput;
4082
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4083
+ var parameter = _c.value;
4084
+ _loop_1(parameter);
4085
+ }
4086
+ }
4087
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4088
+ finally {
4089
+ try {
4090
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3552
4091
  }
3553
- 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;
4092
+ finally { if (e_1) throw e_1.error; }
4093
+ }
4094
+ return outputParameters;
4095
+ }
4096
+
4097
+ /**
4098
+ * @@@
4099
+ *
4100
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4101
+ *
4102
+ * @private internal utility of `createPipelineExecutor`
4103
+ */
4104
+ function executePipeline(options) {
4105
+ return __awaiter(this, void 0, void 0, function () {
4106
+ 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;
3554
4107
  var e_1, _e, e_2, _f;
3555
4108
  return __generator(this, function (_g) {
3556
4109
  switch (_g.label) {
3557
4110
  case 0:
4111
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4112
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4113
+ preparedPipeline = options.preparedPipeline;
4114
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3558
4115
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3559
4116
  return [4 /*yield*/, preparePipeline(pipeline, {
3560
4117
  llmTools: llmTools,
@@ -3563,6 +4120,7 @@
3563
4120
  })];
3564
4121
  case 1:
3565
4122
  preparedPipeline = _g.sent();
4123
+ setPreparedPipeline(preparedPipeline);
3566
4124
  _g.label = 2;
3567
4125
  case 2:
3568
4126
  errors = [];
@@ -3632,7 +4190,7 @@
3632
4190
  return name === parameterName;
3633
4191
  });
3634
4192
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3635
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4193
+ warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3636
4194
  return [3 /*break*/, 4];
3637
4195
  case 1:
3638
4196
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3644,10 +4202,10 @@
3644
4202
  // Note: Wait a short time to prevent race conditions
3645
4203
  _h.sent();
3646
4204
  _h.label = 3;
3647
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4205
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3648
4206
  isSuccessful: false,
3649
4207
  errors: __spreadArray([
3650
- new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4208
+ new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3651
4209
  ], __read(errors), false).map(serializeError),
3652
4210
  warnings: warnings.map(serializeError),
3653
4211
  executionReport: executionReport,
@@ -3711,7 +4269,7 @@
3711
4269
  case 0:
3712
4270
  if (loopLimit-- < 0) {
3713
4271
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3714
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4272
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3715
4273
  }
3716
4274
  currentTemplate = unresovedTemplates_1.find(function (template) {
3717
4275
  return template.dependentParameterNames.every(function (name) {
@@ -3721,29 +4279,52 @@
3721
4279
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3722
4280
  throw new UnexpectedError(
3723
4281
  // TODO: [🐎] DRY
3724
- spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4282
+ spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3725
4283
  .map(function (_a) {
3726
4284
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3727
4285
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3728
4286
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3729
4287
  .join(' and '));
3730
4288
  })
3731
- .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 "); }));
4289
+ .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 "); }));
3732
4290
  case 1:
3733
4291
  if (!!currentTemplate) return [3 /*break*/, 3];
3734
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4292
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3735
4293
  case 2:
3736
- /* [5] */ _j.sent();
4294
+ /* [🤹‍♂️] */ _j.sent();
3737
4295
  return [3 /*break*/, 4];
3738
4296
  case 3:
3739
4297
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3740
- work_1 = executeSingleTemplate(currentTemplate)
3741
- .then(function () {
4298
+ work_1 = executeTemplate({
4299
+ currentTemplate: currentTemplate,
4300
+ preparedPipeline: preparedPipeline,
4301
+ parametersToPass: parametersToPass,
4302
+ tools: tools,
4303
+ llmTools: llmTools,
4304
+ onProgress: function (progress) {
4305
+ if (isReturned) {
4306
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4307
+ .split('\n')
4308
+ .map(function (line) { return "> ".concat(line); })
4309
+ .join('\n')), "\n "); }));
4310
+ }
4311
+ if (onProgress) {
4312
+ onProgress(progress);
4313
+ }
4314
+ },
4315
+ settings: settings,
4316
+ $executionReport: executionReport,
4317
+ pipelineIdentification: pipelineIdentification,
4318
+ })
4319
+ .then(function (newParametersToPass) {
4320
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3742
4321
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3743
4322
  })
3744
4323
  .then(function () {
3745
4324
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3746
4325
  });
4326
+ // <- Note: Errors are catched here [3]
4327
+ // 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
3747
4328
  resolving_1.push(work_1);
3748
4329
  _j.label = 4;
3749
4330
  case 4: return [2 /*return*/];
@@ -3770,7 +4351,12 @@
3770
4351
  var result = _a.result;
3771
4352
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3772
4353
  })), false));
3773
- outputParameters_1 = filterJustOutputParameters();
4354
+ outputParameters_1 = filterJustOutputParameters({
4355
+ preparedPipeline: preparedPipeline,
4356
+ parametersToPass: parametersToPass,
4357
+ $warnings: warnings,
4358
+ pipelineIdentification: pipelineIdentification,
4359
+ });
3774
4360
  isReturned = true;
3775
4361
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3776
4362
  // Note: Wait a short time to prevent race conditions
@@ -3793,7 +4379,12 @@
3793
4379
  var result = _a.result;
3794
4380
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3795
4381
  })), false));
3796
- outputParameters = filterJustOutputParameters();
4382
+ outputParameters = filterJustOutputParameters({
4383
+ preparedPipeline: preparedPipeline,
4384
+ parametersToPass: parametersToPass,
4385
+ $warnings: warnings,
4386
+ pipelineIdentification: pipelineIdentification,
4387
+ });
3797
4388
  isReturned = true;
3798
4389
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3799
4390
  // Note: Wait a short time to prevent race conditions
@@ -3813,22 +4404,63 @@
3813
4404
  })];
3814
4405
  }
3815
4406
  });
3816
- }); };
3817
- return pipelineExecutor;
4407
+ });
3818
4408
  }
4409
+
3819
4410
  /**
3820
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3821
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3822
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3823
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3824
- * TODO: [♈] Probbably move expectations from templates to parameters
3825
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3826
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3827
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3828
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3829
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3830
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4411
+ * Creates executor function from pipeline and execution tools.
4412
+ *
4413
+ * @returns The executor function
4414
+ * @throws {PipelineLogicError} on logical error in the pipeline
4415
+ * @public exported from `@promptbook/core`
3831
4416
  */
4417
+ function createPipelineExecutor(options) {
4418
+ var _this = this;
4419
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4420
+ 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;
4421
+ validatePipeline(pipeline);
4422
+ var pipelineIdentification = (function () {
4423
+ // Note: This is a 😐 implementation of [🚞]
4424
+ var _ = [];
4425
+ if (pipeline.sourceFile !== undefined) {
4426
+ _.push("File: ".concat(pipeline.sourceFile));
4427
+ }
4428
+ if (pipeline.pipelineUrl !== undefined) {
4429
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4430
+ }
4431
+ return _.join('\n');
4432
+ })();
4433
+ var preparedPipeline;
4434
+ if (isPipelinePrepared(pipeline)) {
4435
+ preparedPipeline = pipeline;
4436
+ }
4437
+ else if (isNotPreparedWarningSupressed !== true) {
4438
+ console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4439
+ }
4440
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4441
+ return __generator(this, function (_a) {
4442
+ return [2 /*return*/, executePipeline({
4443
+ pipeline: pipeline,
4444
+ preparedPipeline: preparedPipeline,
4445
+ setPreparedPipeline: function (newPreparedPipeline) {
4446
+ preparedPipeline = newPreparedPipeline;
4447
+ },
4448
+ inputParameters: inputParameters,
4449
+ tools: tools,
4450
+ onProgress: onProgress,
4451
+ pipelineIdentification: pipelineIdentification,
4452
+ settings: {
4453
+ maxExecutionAttempts: maxExecutionAttempts,
4454
+ maxParallelCount: maxParallelCount,
4455
+ csvSettings: csvSettings,
4456
+ isVerbose: isVerbose,
4457
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4458
+ },
4459
+ })];
4460
+ });
4461
+ }); };
4462
+ return pipelineExecutor;
4463
+ }
3832
4464
 
3833
4465
  /**
3834
4466
  * @@@
@@ -3880,7 +4512,7 @@
3880
4512
  outputParameters = result.outputParameters;
3881
4513
  knowledgePiecesRaw = outputParameters.knowledgePieces;
3882
4514
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
3883
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4515
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
3884
4516
  if (isVerbose) {
3885
4517
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
3886
4518
  }
@@ -3938,8 +4570,13 @@
3938
4570
  case 6: return [3 /*break*/, 8];
3939
4571
  case 7:
3940
4572
  error_1 = _c.sent();
4573
+ // Note: Here is expected error:
4574
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4575
+ if (!(error_1 instanceof PipelineExecutionError)) {
4576
+ throw error_1;
4577
+ }
3941
4578
  // TODO: [🟥] Detect browser / node and make it colorfull
3942
- console.error(error_1);
4579
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
3943
4580
  return [3 /*break*/, 8];
3944
4581
  case 8: return [2 /*return*/, {
3945
4582
  name: name,
@@ -3960,7 +4597,7 @@
3960
4597
  });
3961
4598
  }
3962
4599
  /**
3963
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4600
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
3964
4601
  * TODO: [🪂] Do it in parallel 11:11
3965
4602
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
3966
4603
  */
@@ -3984,7 +4621,7 @@
3984
4621
  var partialPieces, pieces;
3985
4622
  return __generator(this, function (_a) {
3986
4623
  switch (_a.label) {
3987
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4624
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
3988
4625
  options)];
3989
4626
  case 1:
3990
4627
  partialPieces = _a.sent();
@@ -4176,7 +4813,7 @@
4176
4813
  });
4177
4814
  }
4178
4815
  /**
4179
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4816
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4180
4817
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4181
4818
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4182
4819
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4225,7 +4862,7 @@
4225
4862
  case 0:
4226
4863
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4227
4864
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4228
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
4865
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4229
4866
  TODO_USE(parameters);
4230
4867
  templatesPrepared = new Array(
4231
4868
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4257,7 +4894,7 @@
4257
4894
  /**
4258
4895
  * TODO: [🧠] Add context to each template (if missing)
4259
4896
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4260
- * TODO: [♨] !!! Prepare index the samples and maybe templates
4897
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4261
4898
  * TODO: Write tests for `preparePipeline`
4262
4899
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4263
4900
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4429,7 +5066,7 @@
4429
5066
  if (sourceContent === '') {
4430
5067
  throw new ParseError("Source is not defined");
4431
5068
  }
4432
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5069
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4433
5070
  if (sourceContent.startsWith('http://')) {
4434
5071
  throw new ParseError("Source is not secure");
4435
5072
  }
@@ -4632,7 +5269,7 @@
4632
5269
  if (command.templateType === 'KNOWLEDGE') {
4633
5270
  knowledgeCommandParser.$applyToPipelineJson({
4634
5271
  type: 'KNOWLEDGE',
4635
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5272
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4636
5273
  }, $pipelineJson);
4637
5274
  $templateJson.isTemplate = false;
4638
5275
  return;
@@ -4982,6 +5619,171 @@
4982
5619
  * TODO: [🌺] Use some intermediate util splitWords
4983
5620
  */
4984
5621
 
5622
+ /**
5623
+ * @@@
5624
+ *
5625
+ * @param text @@@
5626
+ * @param _isFirstLetterCapital @@@
5627
+ * @returns @@@
5628
+ * @example 'helloWorld'
5629
+ * @example 'iLovePromptbook'
5630
+ * @public exported from `@promptbook/utils`
5631
+ */
5632
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5633
+ var e_1, _a;
5634
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5635
+ var charType;
5636
+ var lastCharType = null;
5637
+ var normalizedName = '';
5638
+ try {
5639
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5640
+ var char = text_1_1.value;
5641
+ var normalizedChar = void 0;
5642
+ if (/^[a-z]$/.test(char)) {
5643
+ charType = 'LOWERCASE';
5644
+ normalizedChar = char;
5645
+ }
5646
+ else if (/^[A-Z]$/.test(char)) {
5647
+ charType = 'UPPERCASE';
5648
+ normalizedChar = char.toLowerCase();
5649
+ }
5650
+ else if (/^[0-9]$/.test(char)) {
5651
+ charType = 'NUMBER';
5652
+ normalizedChar = char;
5653
+ }
5654
+ else {
5655
+ charType = 'OTHER';
5656
+ normalizedChar = '';
5657
+ }
5658
+ if (!lastCharType) {
5659
+ if (_isFirstLetterCapital) {
5660
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5661
+ }
5662
+ }
5663
+ else if (charType !== lastCharType &&
5664
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5665
+ !(lastCharType === 'NUMBER') &&
5666
+ !(charType === 'NUMBER')) {
5667
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5668
+ }
5669
+ normalizedName += normalizedChar;
5670
+ lastCharType = charType;
5671
+ }
5672
+ }
5673
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5674
+ finally {
5675
+ try {
5676
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5677
+ }
5678
+ finally { if (e_1) throw e_1.error; }
5679
+ }
5680
+ return normalizedName;
5681
+ }
5682
+ /**
5683
+ * TODO: [🌺] Use some intermediate util splitWords
5684
+ */
5685
+
5686
+ /**
5687
+ * Removes quotes from a string
5688
+ *
5689
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5690
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5691
+ * Note: There are two simmilar functions:
5692
+ * - `removeQuotes` which removes only bounding quotes
5693
+ * - `unwrapResult` which removes whole introduce sentence
5694
+ *
5695
+ * @param text optionally quoted text
5696
+ * @returns text without quotes
5697
+ * @public exported from `@promptbook/utils`
5698
+ */
5699
+ function removeQuotes(text) {
5700
+ if (text.startsWith('"') && text.endsWith('"')) {
5701
+ return text.slice(1, -1);
5702
+ }
5703
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5704
+ return text.slice(1, -1);
5705
+ }
5706
+ return text;
5707
+ }
5708
+
5709
+ /**
5710
+ * Function `validateParameterName` will @@@
5711
+ *
5712
+ * @param parameterName @@@
5713
+ * @returns @@@
5714
+ * @throws {ParseError} @@@
5715
+ * @private within the repository
5716
+ */
5717
+ function validateParameterName(parameterName) {
5718
+ var e_1, _a;
5719
+ var rawParameterName = parameterName;
5720
+ try {
5721
+ for (var _b = __values([
5722
+ ['`', '`'],
5723
+ ['{', '}'],
5724
+ ['[', ']'],
5725
+ ['(', ')'],
5726
+ ['<', '>'],
5727
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5728
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5729
+ if (parameterName.substring(0, 1) === start &&
5730
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5731
+ // <- TODO: More universal that 1 character
5732
+ ) {
5733
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5734
+ // <- TODO: More universal that 1 character
5735
+ }
5736
+ }
5737
+ }
5738
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5739
+ finally {
5740
+ try {
5741
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5742
+ }
5743
+ finally { if (e_1) throw e_1.error; }
5744
+ }
5745
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5746
+ try {
5747
+ /*
5748
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5749
+ if (parameterName.includes(' ')) {
5750
+ throw new ParseError(`Parameter name cannot contain spaces`);
5751
+ }
5752
+ */
5753
+ if (parameterName.includes('.')) {
5754
+ throw new ParseError("Parameter name cannot contain dots");
5755
+ }
5756
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5757
+ throw new ParseError("Parameter name cannot contain slashes");
5758
+ }
5759
+ if (parameterName.includes('(') ||
5760
+ parameterName.includes(')') ||
5761
+ parameterName.includes('{') ||
5762
+ parameterName.includes('}') ||
5763
+ parameterName.includes('[') ||
5764
+ parameterName.includes(']')) {
5765
+ throw new ParseError("Parameter name cannot contain braces");
5766
+ }
5767
+ parameterName = removeDiacritics(parameterName);
5768
+ parameterName = removeEmojis(parameterName);
5769
+ parameterName = removeQuotes(parameterName);
5770
+ parameterName = normalizeTo_camelCase(parameterName);
5771
+ if (parameterName === '') {
5772
+ throw new ParseError("Parameter name cannot be empty");
5773
+ }
5774
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5775
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5776
+ }
5777
+ }
5778
+ catch (error) {
5779
+ if (!(error instanceof ParseError)) {
5780
+ throw error;
5781
+ }
5782
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
5783
+ }
5784
+ return parameterName;
5785
+ }
5786
+
4985
5787
  /**
4986
5788
  * Parses the foreach command
4987
5789
  *
@@ -5011,67 +5813,61 @@
5011
5813
  /**
5012
5814
  * Link to discussion
5013
5815
  */
5014
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5816
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5015
5817
  /**
5016
5818
  * Example usages of the FOREACH command
5017
5819
  */
5018
5820
  examples: [
5019
- 'FOREACH List Line -> `{customer}`',
5020
- 'FOR List Line -> `{customer}`',
5021
- 'EACH List Line -> `{customer}`',
5022
- // <- TODO: [🍭] !!!!!! More
5821
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5822
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5823
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
5023
5824
  ],
5024
5825
  /**
5025
5826
  * Parses the FOREACH command
5026
5827
  */
5027
5828
  parse: function (input) {
5028
- var args = input.args, rawArgs = input.rawArgs;
5829
+ var args = input.args;
5029
5830
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5030
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5031
- var assignSign = args[2];
5032
- var parameter = args[3];
5033
- if (![
5034
- 'LIST',
5035
- 'CSV',
5036
- // <- TODO: [🏢] Unhardcode formats
5037
- ].includes(formatName)) {
5038
- console.info({ args: args, formatName: formatName });
5039
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5831
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5832
+ var parameterNameArg = args[2] || '';
5833
+ var assignSign = args[3];
5834
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5835
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5836
+ });
5837
+ if (formatDefinition === undefined) {
5838
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
5839
+ .map(function (formatName) { return "- ".concat(formatName); })
5840
+ .join('\n')), "\n "); }));
5040
5841
  // <- TODO: [🏢] List all supported format names
5041
5842
  }
5042
- if (![
5043
- 'LINE',
5044
- 'ROW',
5045
- 'COLUMN',
5046
- 'CELL',
5047
- // <- TODO: [🏢] Unhardcode format cekks
5048
- ].includes(cellName)) {
5049
- console.info({ args: args, cellName: cellName });
5050
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5051
- // <- TODO: [🏢] List all supported cell names for the format
5843
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5844
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5845
+ });
5846
+ if (subvalueDefinition === undefined) {
5847
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported subformat name \"".concat(subformatName, "\" for format \"").concat(formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
5848
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5849
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5850
+ .join('\n')), "\n "); }));
5851
+ // <- TODO: [🏢] List all supported subformat names for the format
5052
5852
  }
5053
5853
  if (assignSign !== '->') {
5054
- console.info({ args: args, assignSign: assignSign });
5055
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5056
- }
5057
- var parameterNames = extractParameterNames(parameter || rawArgs);
5058
- if (parameterNames.size !== 1) {
5059
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5060
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5061
- }
5062
- var parameterName = parameterNames.values().next().value;
5063
- if (typeof parameterName !== 'string'
5064
- // <- TODO: !!!!!! Replace with propper parameter name validation
5065
- ) {
5066
- console.info({ args: args, parameterName: parameterName });
5067
- throw new Error("Invalid parameter name");
5068
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
5854
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5855
+ }
5856
+ var parameterName = validateParameterName(parameterNameArg);
5857
+ var subparameterNames = args
5858
+ .slice(4)
5859
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5860
+ .filter(function (parameterName) { return parameterName !== ''; })
5861
+ .map(validateParameterName);
5862
+ if (subparameterNames.length === 0) {
5863
+ throw new ParseError("FOREACH command must have at least one subparameter");
5069
5864
  }
5070
5865
  return {
5071
5866
  type: 'FOREACH',
5072
5867
  formatName: formatName,
5073
- cellName: cellName,
5868
+ subformatName: subformatName,
5074
5869
  parameterName: parameterName,
5870
+ subparameterNames: subparameterNames,
5075
5871
  };
5076
5872
  },
5077
5873
  /**
@@ -5080,8 +5876,12 @@
5080
5876
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5081
5877
  */
5082
5878
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5083
- keepUnused(command, $templateJson, $pipelineJson);
5084
- // <- TODO: [🍭] !!!!!! Implement
5879
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
5880
+ // TODO: [🍭] Detect double use
5881
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
5882
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
5883
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5884
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5085
5885
  },
5086
5886
  /**
5087
5887
  * Converts the FOREACH command back to string
@@ -5090,8 +5890,7 @@
5090
5890
  */
5091
5891
  stringify: function (command) {
5092
5892
  keepUnused(command);
5093
- return "";
5094
- // <- TODO: [🍭] !!!!!! Implement
5893
+ return "---"; // <- TODO: [🛋] Implement
5095
5894
  },
5096
5895
  /**
5097
5896
  * Reads the FOREACH command from the `TemplateJson`
@@ -5100,13 +5899,11 @@
5100
5899
  */
5101
5900
  takeFromTemplateJson: function ($templateJson) {
5102
5901
  keepUnused($templateJson);
5103
- return [];
5104
- // <- TODO: [🍭] !!!!!! Implement
5902
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5105
5903
  },
5106
5904
  };
5107
5905
  /**
5108
- * TODO: !!!!!! Comment console logs
5109
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5906
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5110
5907
  */
5111
5908
 
5112
5909
  /**
@@ -5216,11 +6013,11 @@
5216
6013
  */
5217
6014
  parse: function (input) {
5218
6015
  var args = input.args;
5219
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5220
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5221
- throw new ParseError("Invalid joker");
6016
+ if (args.length !== 1) {
6017
+ throw new ParseError("JOKE command expects exactly one parameter name");
5222
6018
  }
5223
- var parameterName = parametersMatch.groups.parameterName;
6019
+ var parameterNameArg = args[0] || '';
6020
+ var parameterName = validateParameterName(parameterNameArg);
5224
6021
  return {
5225
6022
  type: 'JOKER',
5226
6023
  parameterName: parameterName,
@@ -5295,6 +6092,9 @@
5295
6092
  */
5296
6093
  parse: function (input) {
5297
6094
  var args = input.args, normalized = input.normalized;
6095
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6096
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6097
+ }).join('\n')), "\n "); });
5298
6098
  // TODO: Make this more elegant and dynamically
5299
6099
  if (normalized.startsWith('MODEL_VARIANT')) {
5300
6100
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5310,17 +6110,13 @@
5310
6110
  key: 'modelVariant',
5311
6111
  value: 'COMPLETION',
5312
6112
  };
6113
+ // <- Note: [🤖]
5313
6114
  }
5314
6115
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5315
- return {
5316
- type: 'MODEL',
5317
- key: 'modelVariant',
5318
- value: 'EMBEDDING',
5319
- };
5320
- // <- Note: [🤖]
6116
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5321
6117
  }
5322
6118
  else {
5323
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n Supported variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) { return "- ".concat(variantName); }).join('\n')), "\n "); }));
6119
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5324
6120
  }
5325
6121
  }
5326
6122
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5345,6 +6141,7 @@
5345
6141
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5346
6142
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5347
6143
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6144
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5348
6145
  }
5349
6146
  else {
5350
6147
  throw new ParseError(spaceTrim__default["default"]("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -5444,14 +6241,13 @@
5444
6241
  * Parses the PARAMETER command
5445
6242
  */
5446
6243
  parse: function (input) {
5447
- var normalized = input.normalized, raw = input.raw;
5448
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5449
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5450
- throw new ParseError("Invalid parameter");
5451
- }
5452
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5453
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5454
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6244
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6245
+ var parameterNameRaw = args.shift() || '';
6246
+ var parameterDescriptionRaw = args.join(' ');
6247
+ // <- TODO: When [🥶] fixed, change to:
6248
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6249
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6250
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Parameter {".concat(parameterNameRaw, "} can not contain another parameter in description\n\n The description:\n ").concat(block(parameterDescriptionRaw), "\n "); }));
5455
6251
  }
5456
6252
  var isInput = normalized.startsWith('INPUT');
5457
6253
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5459,11 +6255,12 @@
5459
6255
  isInput = false;
5460
6256
  isOutput = false;
5461
6257
  }
5462
- // TODO: !!!!!! Add parameter name validation
6258
+ var parameterName = validateParameterName(parameterNameRaw);
6259
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5463
6260
  return {
5464
6261
  type: 'PARAMETER',
5465
6262
  parameterName: parameterName,
5466
- parameterDescription: parameterDescription.trim() || null,
6263
+ parameterDescription: parameterDescription,
5467
6264
  isInput: isInput,
5468
6265
  isOutput: isOutput,
5469
6266
  };
@@ -5788,6 +6585,7 @@
5788
6585
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
5789
6586
  */
5790
6587
  $applyToPipelineJson: function (command, $pipelineJson) {
6588
+ // TODO: Warn if the version is overridden
5791
6589
  $pipelineJson.promptbookVersion = command.promptbookVersion;
5792
6590
  },
5793
6591
  /**
@@ -6270,7 +7068,9 @@
6270
7068
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6271
7069
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6272
7070
  var args = items.slice(commandNameSegmentsCount + 1);
6273
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7071
+ var rawArgs = raw
7072
+ .substring(commandNameRaw.length)
7073
+ .trim();
6274
7074
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6275
7075
  if (command !== null) {
6276
7076
  return command;
@@ -6281,7 +7081,9 @@
6281
7081
  {
6282
7082
  var commandNameRaw = items.slice(-1).join('_');
6283
7083
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6284
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7084
+ var rawArgs = raw
7085
+ .substring(0, raw.length - commandNameRaw.length)
7086
+ .trim();
6285
7087
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6286
7088
  if (command !== null) {
6287
7089
  return command;
@@ -6421,7 +7223,7 @@
6421
7223
  function extractOneBlockFromMarkdown(markdown) {
6422
7224
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6423
7225
  if (codeBlocks.length !== 1) {
6424
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7226
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6425
7227
  }
6426
7228
  return codeBlocks[0];
6427
7229
  }
@@ -6608,7 +7410,7 @@
6608
7410
  var $pipelineJson = {
6609
7411
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6610
7412
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6611
- promptbookVersion: PROMPTBOOK_VERSION,
7413
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6612
7414
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6613
7415
  parameters: [],
6614
7416
  templates: [],
@@ -6899,7 +7701,7 @@
6899
7701
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
6900
7702
  }
6901
7703
  /**
6902
- * TODO: !!!! Warn if used only sync version
7704
+ * TODO:[main] !!!! Warn if used only sync version
6903
7705
  * TODO: [🚞] Report here line/column of error
6904
7706
  * TODO: Use spaceTrim more effectively
6905
7707
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7682,7 +8484,7 @@
7682
8484
  }
7683
8485
  }
7684
8486
  /**
7685
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8487
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7686
8488
  * TODO: [🧠][💺] Can be done this on type-level?
7687
8489
  */
7688
8490