@promptbook/node 0.69.0-2 → 0.69.0-21

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 (75) hide show
  1. package/README.md +21 -58
  2. package/esm/index.es.js +1855 -1069
  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 +10 -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 +1 -1
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +6 -5
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +1 -1
  14. package/esm/typings/src/config.d.ts +11 -4
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -3
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +6 -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/embeddingVectorToString.d.ts +1 -1
  34. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  35. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  36. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  37. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +31 -0
  38. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  39. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  40. package/esm/typings/src/formats/index.d.ts +1 -1
  41. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  42. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  43. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  44. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  45. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  48. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  50. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  51. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  52. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  53. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -1
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/execution-report/executionReportJsonToString.d.ts +2 -1
  57. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  58. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  59. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  60. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  61. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  62. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  63. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  64. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  65. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  67. package/package.json +18 -13
  68. package/umd/index.umd.js +1858 -1073
  69. package/umd/index.umd.js.map +1 -1
  70. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  71. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  72. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  73. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  74. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  75. /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-1';
39
- // TODO: !!!! List here all the versions and annotate + put into script
38
+ var PROMPTBOOK_VERSION = '0.69.0-20';
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,6 +442,17 @@
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
  *
@@ -524,7 +536,7 @@
524
536
  commands.push("PIPELINE URL ".concat(pipelineUrl));
525
537
  }
526
538
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
527
- // 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
528
540
  pipelineString = prettifyMarkdown(pipelineString);
529
541
  try {
530
542
  for (var _g = __values(parameters.filter(function (_a) {
@@ -672,12 +684,12 @@
672
684
  pipelineString += '```' + contentLanguage;
673
685
  pipelineString += '\n';
674
686
  pipelineString += spaceTrim__default["default"](content);
675
- // <- TODO: !!! Escape
687
+ // <- TODO:[main] !!! Escape
676
688
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
677
689
  pipelineString += '\n';
678
690
  pipelineString += '```';
679
691
  pipelineString += '\n\n';
680
- 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
681
693
  }
682
694
  }
683
695
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -904,7 +916,7 @@
904
916
  });
905
917
  }
906
918
 
907
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-1",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-1",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-1",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-1",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"}];
908
920
 
909
921
  /**
910
922
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -979,7 +991,7 @@
979
991
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
980
992
  return false;
981
993
  }
982
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
994
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
983
995
  return true;
984
996
  }
985
997
 
@@ -1148,19 +1160,19 @@
1148
1160
  // <- Note: [🚲]
1149
1161
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1150
1162
  }
1151
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1163
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1152
1164
  // <- Note: [🚲]
1153
1165
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1154
1166
  }
1155
1167
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1156
1168
  if (!Array.isArray(pipeline.parameters)) {
1157
1169
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1158
- 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 "); }));
1159
1171
  }
1160
1172
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1161
1173
  if (!Array.isArray(pipeline.templates)) {
1162
1174
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1163
- 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 "); }));
1164
1176
  }
1165
1177
  var _loop_1 = function (parameter) {
1166
1178
  if (parameter.isInput && parameter.isOutput) {
@@ -1331,6 +1343,7 @@
1331
1343
  }
1332
1344
  }
1333
1345
  /**
1346
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1334
1347
  * TODO: [🧠] Work with promptbookVersion
1335
1348
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1336
1349
  * > /**
@@ -1342,11 +1355,11 @@
1342
1355
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1343
1356
  */
1344
1357
  /**
1345
- * TODO: [🐣] !!!! Validate that all samples match expectations
1346
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1347
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1348
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1349
- * 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
1350
1363
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1351
1364
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1352
1365
  */
@@ -2068,121 +2081,35 @@
2068
2081
  */
2069
2082
 
2070
2083
  /**
2071
- * Parses the given script and returns the list of all used variables that are not defined in the script
2072
- *
2073
- * @param script from which to extract the variables
2074
- * @returns the list of variable names
2075
- * @throws {ParseError} if the script is invalid
2076
- * @public exported from `@promptbook/utils`
2077
- */
2078
- function extractVariables(script) {
2079
- var variables = new Set();
2080
- script = "(()=>{".concat(script, "})()");
2081
- try {
2082
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2083
- try {
2084
- eval(script);
2085
- }
2086
- catch (error) {
2087
- if (!(error instanceof ReferenceError)) {
2088
- throw error;
2089
- }
2090
- var undefinedName = error.message.split(' ')[0];
2091
- /*
2092
- Note: Parsing the error
2093
- [PipelineUrlError: thing is not defined]
2094
- */
2095
- if (!undefinedName) {
2096
- throw error;
2097
- }
2098
- if (script.includes(undefinedName + '(')) {
2099
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2100
- }
2101
- else {
2102
- variables.add(undefinedName);
2103
- script = "const ".concat(undefinedName, " = '';") + script;
2104
- }
2105
- }
2106
- }
2107
- catch (error) {
2108
- if (!(error instanceof Error)) {
2109
- throw error;
2110
- }
2111
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2112
- }
2113
- return variables;
2114
- }
2115
- /**
2116
- * TODO: [🔣] Support for multiple languages - python, java,...
2117
- */
2118
-
2119
- /**
2120
- * Parses the template and returns the set of all used parameters
2084
+ * Determine if the pipeline is fully prepared
2121
2085
  *
2122
- * @param template the template with used parameters
2123
- * @returns the set of parameter names
2124
- * @throws {ParseError} if the script is invalid
2125
- * @public exported from `@promptbook/utils`
2086
+ * @public exported from `@promptbook/core`
2126
2087
  */
2127
- function extractParameterNamesFromTemplate(template) {
2128
- var e_1, _a, e_2, _b, e_3, _c;
2129
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2130
- var parameterNames = new Set();
2131
- try {
2132
- 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()) {
2133
- var parameterName = _e.value;
2134
- parameterNames.add(parameterName);
2135
- }
2136
- }
2137
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2138
- finally {
2139
- try {
2140
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2141
- }
2142
- finally { if (e_1) throw e_1.error; }
2143
- }
2144
- if (templateType === 'SCRIPT_TEMPLATE') {
2145
- try {
2146
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2147
- var parameterName = _g.value;
2148
- parameterNames.add(parameterName);
2149
- }
2150
- }
2151
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2152
- finally {
2153
- try {
2154
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2155
- }
2156
- finally { if (e_2) throw e_2.error; }
2157
- }
2158
- }
2159
- try {
2160
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2161
- var jokerName = _j.value;
2162
- parameterNames.add(jokerName);
2163
- }
2164
- }
2165
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2166
- finally {
2167
- try {
2168
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2169
- }
2170
- finally { if (e_3) throw e_3.error; }
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;
2171
2093
  }
2172
- parameterNames.delete('content');
2173
- // <- Note {websiteContent} is used in `preparedContent`
2174
- // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2175
- if (foreach !== undefined) {
2176
- if (parameterNames.has(foreach.subparameterName)) {
2177
- parameterNames.delete(foreach.subparameterName);
2178
- parameterNames.add(foreach.parameterName);
2179
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2180
- }
2094
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2095
+ return false;
2181
2096
  }
2182
- 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;
2183
2104
  }
2184
2105
  /**
2185
- * 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
2186
2113
  */
2187
2114
 
2188
2115
  /**
@@ -2202,27 +2129,6 @@
2202
2129
  };
2203
2130
  }
2204
2131
 
2205
- /**
2206
- * Function isValidJsonString will tell you if the string is valid JSON or not
2207
- *
2208
- * @public exported from `@promptbook/utils`
2209
- */
2210
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2211
- try {
2212
- JSON.parse(value);
2213
- return true;
2214
- }
2215
- catch (error) {
2216
- if (!(error instanceof Error)) {
2217
- throw error;
2218
- }
2219
- if (error.message.includes('Unexpected token')) {
2220
- return false;
2221
- }
2222
- return false;
2223
- }
2224
- }
2225
-
2226
2132
  /**
2227
2133
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2228
2134
  *
@@ -2249,9 +2155,10 @@
2249
2155
  });
2250
2156
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2251
2157
  get: function () {
2252
- return this.llmExecutionTools
2253
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2254
- .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');
2255
2162
  },
2256
2163
  enumerable: false,
2257
2164
  configurable: true
@@ -2449,9 +2356,7 @@
2449
2356
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2450
2357
  }
2451
2358
  else {
2452
- 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
2453
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2454
- .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 "); }));
2455
2360
  }
2456
2361
  }
2457
2362
  });
@@ -2517,75 +2422,680 @@
2517
2422
  */
2518
2423
 
2519
2424
  /**
2520
- * Extracts all code blocks from markdown.
2425
+ * Takes an item or an array of items and returns an array of items
2521
2426
  *
2522
- * Note: There are multiple simmilar function:
2523
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2524
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2525
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2526
- * - `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
2527
2430
  *
2528
- * @param markdown any valid markdown
2529
- * @returns code blocks with language and content
2530
- * @throws {ParseError} if block is not closed properly
2531
- * @public exported from `@promptbook/markdown-utils`
2431
+ * @private internal utility
2532
2432
  */
2533
- function extractAllBlocksFromMarkdown(markdown) {
2534
- var e_1, _a;
2535
- var codeBlocks = [];
2536
- var lines = markdown.split('\n');
2537
- // Note: [0] Ensure that the last block notated by gt > will be closed
2538
- lines.push('');
2539
- var currentCodeBlock = null;
2433
+ function arrayableToArray(input) {
2434
+ if (input === undefined) {
2435
+ return [];
2436
+ }
2437
+ if (input instanceof Array) {
2438
+ return input;
2439
+ }
2440
+ return [input];
2441
+ }
2442
+
2443
+ /**
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, "})()");
2540
2454
  try {
2541
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2542
- var line = lines_1_1.value;
2543
- if (line.startsWith('> ') || line === '>') {
2544
- if (currentCodeBlock === null) {
2545
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2546
- } /* not else */
2547
- if (currentCodeBlock.blockNotation === '>') {
2548
- if (currentCodeBlock.content !== '') {
2549
- currentCodeBlock.content += '\n';
2550
- }
2551
- currentCodeBlock.content += line.slice(2);
2552
- }
2553
- }
2554
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2555
- codeBlocks.push(currentCodeBlock);
2556
- currentCodeBlock = null;
2455
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2456
+ try {
2457
+ eval(script);
2557
2458
  }
2558
- /* not else */
2559
- if (line.startsWith('```')) {
2560
- var language = line.slice(3).trim() || null;
2561
- if (currentCodeBlock === null) {
2562
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2459
+ catch (error) {
2460
+ if (!(error instanceof ReferenceError)) {
2461
+ throw error;
2563
2462
  }
2564
- else {
2565
- if (language !== null) {
2566
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2567
- }
2568
- codeBlocks.push(currentCodeBlock);
2569
- currentCodeBlock = null;
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;
2570
2470
  }
2571
- }
2572
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2573
- if (currentCodeBlock.content !== '') {
2574
- currentCodeBlock.content += '\n';
2471
+ if (script.includes(undefinedName + '(')) {
2472
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2473
+ }
2474
+ else {
2475
+ variables.add(undefinedName);
2476
+ script = "const ".concat(undefinedName, " = '';") + script;
2575
2477
  }
2576
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2577
2478
  }
2578
- }
2579
2479
  }
2580
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2581
- finally {
2582
- try {
2583
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2480
+ catch (error) {
2481
+ if (!(error instanceof Error)) {
2482
+ throw error;
2584
2483
  }
2585
- finally { if (e_1) throw e_1.error; }
2586
- }
2587
- if (currentCodeBlock !== null) {
2588
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
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.inputSubparameterNames), _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, outputParameterName, 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, _b;
2720
+ var _c;
2721
+ return __generator(this, function (_d) {
2722
+ switch (_d.label) {
2723
+ case 0:
2724
+ if (row[outputParameterName]) {
2725
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2726
+ "Can not overwrite existing column \"".concat(outputParameterName, "\" in CSV row"));
2727
+ }
2728
+ _a = [__assign({}, row)];
2729
+ _c = {};
2730
+ _b = outputParameterName;
2731
+ return [4 /*yield*/, mapCallback(row, index)];
2732
+ case 1: return [2 /*return*/, __assign.apply(void 0, _a.concat([(_c[_b] = _d.sent(), _c)]))];
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, outputParameterName, 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, outputParameterName, 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"));
2589
3099
  }
2590
3100
  return codeBlocks;
2591
3101
  }
@@ -2632,57 +3142,6 @@
2632
3142
  * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2633
3143
  */
2634
3144
 
2635
- /**
2636
- * Determine if the pipeline is fully prepared
2637
- *
2638
- * @public exported from `@promptbook/core`
2639
- */
2640
- function isPipelinePrepared(pipeline) {
2641
- // Note: Ignoring `pipeline.preparations` @@@
2642
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2643
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2644
- return false;
2645
- }
2646
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2647
- return false;
2648
- }
2649
- /*
2650
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2651
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2652
- > return false;
2653
- > }
2654
- */
2655
- return true;
2656
- }
2657
- /**
2658
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2659
- * TODO: [🐠] Maybe base this on `makeValidator`
2660
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2661
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2662
- * - [🏍] ? Is context in each template
2663
- * - [♨] Are samples prepared
2664
- * - [♨] Are templates prepared
2665
- */
2666
-
2667
- /**
2668
- * Takes an item or an array of items and returns an array of items
2669
- *
2670
- * 1) Any item except array and undefined returns array with that one item (also null)
2671
- * 2) Undefined returns empty array
2672
- * 3) Array returns itself
2673
- *
2674
- * @private internal utility
2675
- */
2676
- function arrayableToArray(input) {
2677
- if (input === undefined) {
2678
- return [];
2679
- }
2680
- if (input instanceof Array) {
2681
- return input;
2682
- }
2683
- return [input];
2684
- }
2685
-
2686
3145
  /**
2687
3146
  * Just says that the variable is not used but should be kept
2688
3147
  * No side effects.
@@ -2704,23 +3163,6 @@
2704
3163
  }
2705
3164
  }
2706
3165
 
2707
- /**
2708
- * Just marks a place of place where should be something implemented
2709
- * No side effects.
2710
- *
2711
- * Note: It can be usefull suppressing eslint errors of unused variables
2712
- *
2713
- * @param value any values
2714
- * @returns void
2715
- * @private within the repository
2716
- */
2717
- function TODO_USE() {
2718
- var value = [];
2719
- for (var _i = 0; _i < arguments.length; _i++) {
2720
- value[_i] = arguments[_i];
2721
- }
2722
- }
2723
-
2724
3166
  /**
2725
3167
  * Replaces parameters in template with values from parameters object
2726
3168
  *
@@ -2780,99 +3222,24 @@
2780
3222
  .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2781
3223
  .join('\n');
2782
3224
  }
2783
- replacedTemplate =
2784
- replacedTemplate.substring(0, match.index + precol.length) +
2785
- parameterValue +
2786
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2787
- };
2788
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2789
- .exec(replacedTemplate))) {
2790
- _loop_1();
2791
- }
2792
- // [💫] Check if there are parameters that are not closed properly
2793
- if (/{\w+$/.test(replacedTemplate)) {
2794
- throw new PipelineExecutionError('Parameter is not closed');
2795
- }
2796
- // [💫] Check if there are parameters that are not opened properly
2797
- if (/^\w+}/.test(replacedTemplate)) {
2798
- throw new PipelineExecutionError('Parameter is not opened');
2799
- }
2800
- return replacedTemplate;
2801
- }
2802
-
2803
- /**
2804
- * Create difference set of two sets.
2805
- *
2806
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2807
- * @public exported from `@promptbook/utils`
2808
- */
2809
- function difference(a, b, isEqual) {
2810
- var e_1, _a;
2811
- if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2812
- var diff = new Set();
2813
- var _loop_1 = function (itemA) {
2814
- if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2815
- diff.add(itemA);
2816
- }
2817
- };
2818
- try {
2819
- for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2820
- var itemA = _c.value;
2821
- _loop_1(itemA);
2822
- }
2823
- }
2824
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2825
- finally {
2826
- try {
2827
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2828
- }
2829
- finally { if (e_1) throw e_1.error; }
2830
- }
2831
- return diff;
2832
- }
2833
- /**
2834
- * TODO: [🧠][💯] Maybe also implement symmetricDifference
2835
- */
2836
-
2837
- /**
2838
- * Creates a new set with all elements that are present in either set
2839
- *
2840
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2841
- * @public exported from `@promptbook/utils`
2842
- */
2843
- function union() {
2844
- var e_1, _a, e_2, _b;
2845
- var sets = [];
2846
- for (var _i = 0; _i < arguments.length; _i++) {
2847
- sets[_i] = arguments[_i];
2848
- }
2849
- var union = new Set();
2850
- try {
2851
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2852
- var set = sets_1_1.value;
2853
- try {
2854
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2855
- var item = _d.value;
2856
- union.add(item);
2857
- }
2858
- }
2859
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2860
- finally {
2861
- try {
2862
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2863
- }
2864
- finally { if (e_2) throw e_2.error; }
2865
- }
2866
- }
2867
- }
2868
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2869
- finally {
2870
- try {
2871
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2872
- }
2873
- 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();
2874
3233
  }
2875
- 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;
2876
3243
  }
2877
3244
 
2878
3245
  /**
@@ -2964,6 +3331,9 @@
2964
3331
  LINES: countLines,
2965
3332
  PAGES: countPages,
2966
3333
  };
3334
+ /**
3335
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3336
+ */
2967
3337
 
2968
3338
  /**
2969
3339
  * Function checkExpectations will check if the expectations on given value are met
@@ -3000,611 +3370,748 @@
3000
3370
  }
3001
3371
  /**
3002
3372
  * TODO: [💝] Unite object for expecting amount and format
3373
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3374
+ * Note: [💝] and [🤠] are interconnected together
3003
3375
  */
3004
3376
 
3005
3377
  /**
3006
- * Creates executor function from pipeline and execution tools.
3378
+ * @@@
3007
3379
  *
3008
- * @returns The executor function
3009
- * @throws {PipelineLogicError} on logical error in the pipeline
3010
- * @public exported from `@promptbook/core`
3380
+ * @private internal utility of `createPipelineExecutor`
3011
3381
  */
3012
- function createPipelineExecutor(options) {
3013
- var _this = this;
3014
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3015
- 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;
3016
- validatePipeline(pipeline);
3017
- var pipelineIdentification = (function () {
3018
- // Note: This is a 😐 implementation of [🚞]
3019
- var _ = [];
3020
- if (pipeline.sourceFile !== undefined) {
3021
- _.push("File: ".concat(pipeline.sourceFile));
3022
- }
3023
- if (pipeline.pipelineUrl !== undefined) {
3024
- _.push("Url: ".concat(pipeline.pipelineUrl));
3025
- }
3026
- return _.join('\n');
3027
- })();
3028
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3029
- var preparedPipeline;
3030
- if (isPipelinePrepared(pipeline)) {
3031
- preparedPipeline = pipeline;
3032
- }
3033
- else if (isNotPreparedWarningSupressed !== true) {
3034
- 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 "); }));
3035
- }
3036
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3037
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3038
- function getContextForTemplate(template) {
3039
- return __awaiter(this, void 0, void 0, function () {
3040
- return __generator(this, function (_a) {
3041
- TODO_USE(template);
3042
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3043
- });
3044
- });
3045
- }
3046
- function getKnowledgeForTemplate(template) {
3047
- return __awaiter(this, void 0, void 0, function () {
3048
- return __generator(this, function (_a) {
3049
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3050
- TODO_USE(template);
3051
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3052
- var content = _a.content;
3053
- return "- ".concat(content);
3054
- }).join('\n')];
3055
- });
3056
- });
3057
- }
3058
- function getSamplesForTemplate(template) {
3059
- return __awaiter(this, void 0, void 0, function () {
3060
- return __generator(this, function (_a) {
3061
- // TODO: [♨] Implement Better - use real index and keyword search
3062
- TODO_USE(template);
3063
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3064
- });
3065
- });
3066
- }
3067
- function getReservedParametersForTemplate(template) {
3068
- return __awaiter(this, void 0, void 0, function () {
3069
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3070
- var e_3, _a;
3071
- return __generator(this, function (_b) {
3072
- switch (_b.label) {
3073
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3074
- case 1:
3075
- context = _b.sent();
3076
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3077
- case 2:
3078
- knowledge = _b.sent();
3079
- return [4 /*yield*/, getSamplesForTemplate(template)];
3080
- case 3:
3081
- samples = _b.sent();
3082
- currentDate = new Date().toISOString();
3083
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3084
- reservedParameters = {
3085
- content: RESERVED_PARAMETER_RESTRICTED,
3086
- context: context,
3087
- knowledge: knowledge,
3088
- samples: samples,
3089
- currentDate: currentDate,
3090
- modelName: modelName,
3091
- };
3092
- _loop_3 = function (parameterName) {
3093
- if (reservedParameters[parameterName] === undefined) {
3094
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3095
- }
3096
- };
3097
- try {
3098
- // Note: Doublecheck that ALL reserved parameters are defined:
3099
- 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()) {
3100
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3101
- _loop_3(parameterName);
3102
- }
3103
- }
3104
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3105
- finally {
3106
- try {
3107
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3108
- }
3109
- finally { if (e_3) throw e_3.error; }
3110
- }
3111
- return [2 /*return*/, reservedParameters];
3112
- }
3113
- });
3114
- });
3115
- }
3116
- function executeSingleTemplate(currentTemplate) {
3117
- return __awaiter(this, void 0, void 0, function () {
3118
- 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;
3119
- var e_4, _f, _g;
3120
- return __generator(this, function (_h) {
3121
- switch (_h.label) {
3122
- case 0:
3123
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3124
- title = currentTemplate.title;
3125
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3126
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3127
- progress_1 = {
3128
- name: name,
3129
- title: title,
3130
- isStarted: false,
3131
- isDone: false,
3132
- templateType: currentTemplate.templateType,
3133
- parameterName: currentTemplate.resultingParameterName,
3134
- parameterValue: null,
3135
- // <- [3]
3136
- };
3137
- if (isReturned) {
3138
- 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)
3139
- .split('\n')
3140
- .map(function (line) { return "> ".concat(line); })
3141
- .join('\n')), "\n "); }));
3142
- }
3143
- return [4 /*yield*/, onProgress(progress_1)];
3144
- case 1:
3145
- _h.sent();
3146
- _h.label = 2;
3147
- case 2:
3148
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3149
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3150
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3151
- 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)
3152
- .map(function (name) { return "{".concat(name, "}"); })
3153
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3154
- .map(function (name) { return "{".concat(name, "}"); })
3155
- .join(', '), "\n\n "); }));
3156
- }
3157
- _b = (_a = Object).freeze;
3158
- _c = [{}];
3159
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3160
- case 3:
3161
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3162
- definedParameterNames = new Set(Object.keys(definedParameters));
3163
- parameters = {};
3164
- _loop_4 = function (parameterName) {
3165
- // Situation: Parameter is defined and used
3166
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3167
- parameters[parameterName] = definedParameters[parameterName];
3168
- }
3169
- // Situation: Parameter is defined but NOT used
3170
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3171
- // Situation: Parameter is NOT defined BUT used
3172
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3173
- // Houston, we have a problem
3174
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3175
- 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 "); }));
3176
- }
3177
- };
3178
- try {
3179
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3180
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3181
- parameterName = _e.value;
3182
- _loop_4(parameterName);
3183
- }
3184
- }
3185
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3186
- finally {
3187
- try {
3188
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3189
- }
3190
- finally { if (e_4) throw e_4.error; }
3191
- }
3192
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3193
- Object.freeze(parameters);
3194
- result = null;
3195
- resultString = null;
3196
- expectError = null;
3197
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3198
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3199
- preparedContent = (currentTemplate.preparedContent || '{content}')
3200
- .split('{content}')
3201
- .join(currentTemplate.content);
3202
- _loop_5 = function (attempt) {
3203
- 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;
3204
- var e_5, _s, e_7, _t, e_6, _u;
3205
- return __generator(this, function (_v) {
3206
- switch (_v.label) {
3207
- case 0:
3208
- isJokerAttempt = attempt < 0;
3209
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3210
- // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3211
- if (isJokerAttempt && !jokerParameterName) {
3212
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3213
- }
3214
- result = null;
3215
- resultString = null;
3216
- expectError = null;
3217
- if (isJokerAttempt) {
3218
- if (parameters[jokerParameterName] === undefined) {
3219
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3220
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3221
- }
3222
- else {
3223
- resultString = parameters[jokerParameterName];
3224
- }
3225
- }
3226
- _v.label = 1;
3227
- case 1:
3228
- _v.trys.push([1, 44, 45, 46]);
3229
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3230
- _j = currentTemplate.templateType;
3231
- switch (_j) {
3232
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3233
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3234
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3235
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3236
- }
3237
- return [3 /*break*/, 25];
3238
- case 2:
3239
- resultString = replaceParameters(preparedContent, parameters);
3240
- return [3 /*break*/, 26];
3241
- case 3:
3242
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3243
- prompt = {
3244
- title: currentTemplate.title,
3245
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3246
- ? preparedPipeline.pipelineUrl
3247
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3248
- parameters: parameters,
3249
- content: preparedContent,
3250
- modelRequirements: modelRequirements,
3251
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3252
- var name = _a.name;
3253
- return name === currentTemplate.personaName;
3254
- }) || {})), currentTemplate.expectations),
3255
- format: currentTemplate.format,
3256
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3257
- }; // <- TODO: Not very good type guard
3258
- _k = modelRequirements.modelVariant;
3259
- switch (_k) {
3260
- case 'CHAT': return [3 /*break*/, 4];
3261
- case 'COMPLETION': return [3 /*break*/, 6];
3262
- case 'EMBEDDING': return [3 /*break*/, 8];
3263
- }
3264
- return [3 /*break*/, 10];
3265
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3266
- case 5:
3267
- chatResult = _v.sent();
3268
- // TODO: [🍬] Destroy chatThread
3269
- result = chatResult;
3270
- resultString = chatResult.content;
3271
- return [3 /*break*/, 11];
3272
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3273
- case 7:
3274
- completionResult = _v.sent();
3275
- result = completionResult;
3276
- resultString = completionResult.content;
3277
- return [3 /*break*/, 11];
3278
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3279
- case 9:
3280
- embeddingResult = _v.sent();
3281
- result = embeddingResult;
3282
- resultString = embeddingResult.content.join(',');
3283
- return [3 /*break*/, 11];
3284
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3285
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3286
- case 11: return [3 /*break*/, 26];
3287
- case 12:
3288
- if (arrayableToArray(tools.script).length === 0) {
3289
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3290
- }
3291
- if (!currentTemplate.contentLanguage) {
3292
- 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 "); }));
3293
- }
3294
- // TODO: DRY [1]
3295
- scriptPipelineExecutionErrors = [];
3296
- _v.label = 13;
3297
- case 13:
3298
- _v.trys.push([13, 20, 21, 22]);
3299
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3300
- _v.label = 14;
3301
- case 14:
3302
- if (!!_m.done) return [3 /*break*/, 19];
3303
- scriptTools = _m.value;
3304
- _v.label = 15;
3305
- case 15:
3306
- _v.trys.push([15, 17, , 18]);
3307
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3308
- scriptLanguage: currentTemplate.contentLanguage,
3309
- script: preparedContent,
3310
- parameters: parameters,
3311
- }))];
3312
- case 16:
3313
- resultString = _v.sent();
3314
- return [3 /*break*/, 19];
3315
- case 17:
3316
- error_2 = _v.sent();
3317
- if (!(error_2 instanceof Error)) {
3318
- throw error_2;
3319
- }
3320
- if (error_2 instanceof UnexpectedError) {
3321
- throw error_2;
3322
- }
3323
- scriptPipelineExecutionErrors.push(error_2);
3324
- return [3 /*break*/, 18];
3325
- case 18:
3326
- _m = _l.next();
3327
- return [3 /*break*/, 14];
3328
- case 19: return [3 /*break*/, 22];
3329
- case 20:
3330
- e_5_1 = _v.sent();
3331
- e_5 = { error: e_5_1 };
3332
- return [3 /*break*/, 22];
3333
- case 21:
3334
- try {
3335
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3336
- }
3337
- finally { if (e_5) throw e_5.error; }
3338
- return [7 /*endfinally*/];
3339
- case 22:
3340
- if (resultString !== null) {
3341
- return [3 /*break*/, 26];
3342
- }
3343
- if (scriptPipelineExecutionErrors.length === 1) {
3344
- throw scriptPipelineExecutionErrors[0];
3345
- }
3346
- else {
3347
- 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
3348
- .map(function (error) { return '- ' + error.message; })
3349
- .join('\n\n')), "\n "); }));
3350
- }
3351
- case 23:
3352
- if (tools.userInterface === undefined) {
3353
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3354
- }
3355
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3356
- promptTitle: currentTemplate.title,
3357
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3358
- defaultValue: replaceParameters(preparedContent, parameters),
3359
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3360
- placeholder: undefined,
3361
- priority: priority,
3362
- }))];
3363
- case 24:
3364
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3365
- resultString = _v.sent();
3366
- return [3 /*break*/, 26];
3367
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3368
- case 26:
3369
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3370
- _v.label = 27;
3371
- case 27:
3372
- _v.trys.push([27, 41, 42, 43]);
3373
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3374
- _v.label = 28;
3375
- case 28:
3376
- if (!!_p.done) return [3 /*break*/, 40];
3377
- functionName = _p.value;
3378
- // TODO: DRY [1]
3379
- scriptPipelineExecutionErrors = [];
3380
- postprocessingError = null;
3381
- _v.label = 29;
3382
- case 29:
3383
- _v.trys.push([29, 36, 37, 38]);
3384
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3385
- _v.label = 30;
3386
- case 30:
3387
- if (!!_r.done) return [3 /*break*/, 35];
3388
- scriptTools = _r.value;
3389
- _v.label = 31;
3390
- case 31:
3391
- _v.trys.push([31, 33, , 34]);
3392
- return [4 /*yield*/, scriptTools.execute({
3393
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3394
- script: "".concat(functionName, "(resultString)"),
3395
- parameters: {
3396
- resultString: resultString || '',
3397
- // Note: No ...parametersForTemplate, because working with result only
3398
- },
3399
- })];
3400
- case 32:
3401
- resultString = _v.sent();
3402
- postprocessingError = null;
3403
- return [3 /*break*/, 35];
3404
- case 33:
3405
- error_3 = _v.sent();
3406
- if (!(error_3 instanceof Error)) {
3407
- throw error_3;
3408
- }
3409
- if (error_3 instanceof UnexpectedError) {
3410
- throw error_3;
3411
- }
3412
- postprocessingError = error_3;
3413
- scriptPipelineExecutionErrors.push(error_3);
3414
- return [3 /*break*/, 34];
3415
- case 34:
3416
- _r = _q.next();
3417
- return [3 /*break*/, 30];
3418
- case 35: return [3 /*break*/, 38];
3419
- case 36:
3420
- e_6_1 = _v.sent();
3421
- e_6 = { error: e_6_1 };
3422
- return [3 /*break*/, 38];
3423
- case 37:
3424
- try {
3425
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3426
- }
3427
- finally { if (e_6) throw e_6.error; }
3428
- return [7 /*endfinally*/];
3429
- case 38:
3430
- if (postprocessingError) {
3431
- throw postprocessingError;
3432
- }
3433
- _v.label = 39;
3434
- case 39:
3435
- _p = _o.next();
3436
- return [3 /*break*/, 28];
3437
- case 40: return [3 /*break*/, 43];
3438
- case 41:
3439
- e_7_1 = _v.sent();
3440
- e_7 = { error: e_7_1 };
3441
- return [3 /*break*/, 43];
3442
- case 42:
3443
- try {
3444
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3445
- }
3446
- finally { if (e_7) throw e_7.error; }
3447
- return [7 /*endfinally*/];
3448
- case 43:
3449
- // TODO: [💝] Unite object for expecting amount and format
3450
- if (currentTemplate.format) {
3451
- if (currentTemplate.format === 'JSON') {
3452
- if (!isValidJsonString(resultString || '')) {
3453
- // TODO: [🏢] Do more universally via `FormatDefinition`
3454
- try {
3455
- resultString = extractJsonBlock(resultString || '');
3456
- }
3457
- catch (error) {
3458
- keepUnused(error);
3459
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3460
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3461
- }
3462
- }
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 || '');
3463
3650
  }
3464
- else {
3465
- 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 "); }));
3466
3655
  }
3467
3656
  }
3468
- // TODO: [💝] Unite object for expecting amount and format
3469
- if (currentTemplate.expectations) {
3470
- checkExpectations(currentTemplate.expectations, resultString || '');
3471
- }
3472
- return [2 /*return*/, "break-attempts"];
3473
- case 44:
3474
- error_4 = _v.sent();
3475
- if (!(error_4 instanceof ExpectError)) {
3476
- throw error_4;
3477
- }
3478
- expectError = error_4;
3479
- return [3 /*break*/, 46];
3480
- case 45:
3481
- if (!isJokerAttempt &&
3482
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3483
- prompt
3484
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3485
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3486
- ) {
3487
- // TODO: [🧠] Maybe put other templateTypes into report
3488
- executionReport.promptExecutions.push({
3489
- prompt: __assign({}, prompt),
3490
- result: result || undefined,
3491
- error: expectError === null ? undefined : serializeError(expectError),
3492
- });
3493
- }
3494
- return [7 /*endfinally*/];
3495
- case 46:
3496
- if (expectError !== null && attempt === maxAttempts - 1) {
3497
- 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
3498
- .split('\n')
3499
- .map(function (line) { return "> ".concat(line); })
3500
- .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
3501
3704
  .split('\n')
3502
3705
  .map(function (line) { return "> ".concat(line); })
3503
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3504
- ? 'null'
3505
- : resultString
3506
- .split('\n')
3507
- .map(function (line) { return "> ".concat(line); })
3508
- .join('\n')), "\n ---\n "); }));
3509
- }
3510
- return [2 /*return*/];
3706
+ .join('\n')), "\n ---\n ");
3707
+ }));
3511
3708
  }
3512
- });
3513
- };
3514
- attempt = -jokerParameterNames.length;
3515
- _h.label = 4;
3516
- case 4:
3517
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3518
- return [5 /*yield**/, _loop_5(attempt)];
3519
- case 5:
3520
- state_2 = _h.sent();
3521
- switch (state_2) {
3522
- case "break-attempts": return [3 /*break*/, 7];
3523
- }
3524
- _h.label = 6;
3525
- case 6:
3526
- attempt++;
3527
- return [3 /*break*/, 4];
3528
- case 7:
3529
- //------------------------------------
3530
- /*
3531
-
3532
-
3533
-
3534
-
3535
-
3536
-
3537
-
3538
-
3539
-
3540
- */
3541
- //------------------------------------
3542
- if (resultString === null) {
3543
- 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*/];
3544
3710
  }
3545
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3546
- progress_2 = {
3547
- name: name,
3548
- title: title,
3549
- isStarted: true,
3550
- isDone: true,
3551
- templateType: currentTemplate.templateType,
3552
- parameterName: currentTemplate.resultingParameterName,
3553
- parameterValue: resultString,
3554
- // <- [3]
3555
- };
3556
- if (isReturned) {
3557
- 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)
3558
- .split('\n')
3559
- .map(function (line) { return "> ".concat(line); })
3560
- .join('\n')), "\n\n "); }));
3561
- }
3562
- return [4 /*yield*/, onProgress(progress_2)];
3563
- case 8:
3564
- _h.sent();
3565
- _h.label = 9;
3566
- case 9:
3567
- 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)));
3568
- 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, template.foreach.outputSubparameterName, 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.inputSubparameterNames.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 Subparameter index: ").concat(index, "\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: spaceTrim__default["default"](function (block) { return "\n ".concat(block(pipelineIdentification), "\n Subparameter index: ").concat(index, "\n "); }) }))];
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
+ }
3569
3918
  }
3570
- });
3571
- });
3572
- }
3573
- function filterJustOutputParameters() {
3574
- var e_8, _a;
3575
- var outputParameters = {};
3576
- var _loop_6 = function (parameter) {
3577
- if (parametersToPass[parameter.name] === undefined) {
3578
- // [4]
3579
- 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 "); })));
3580
- return "continue";
3581
- }
3582
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3583
- };
3584
- try {
3585
- // Note: Filter ONLY output parameters
3586
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3587
- var isOutput = _a.isOutput;
3588
- return isOutput;
3589
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3590
- var parameter = _c.value;
3591
- _loop_6(parameter);
3592
- }
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];
3593
3927
  }
3594
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3595
- finally {
3596
- try {
3597
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3598
- }
3599
- 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))];
3600
4051
  }
3601
- 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);
3602
4091
  }
3603
- 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;
3604
4107
  var e_1, _e, e_2, _f;
3605
4108
  return __generator(this, function (_g) {
3606
4109
  switch (_g.label) {
3607
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));
3608
4115
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3609
4116
  return [4 /*yield*/, preparePipeline(pipeline, {
3610
4117
  llmTools: llmTools,
@@ -3613,6 +4120,7 @@
3613
4120
  })];
3614
4121
  case 1:
3615
4122
  preparedPipeline = _g.sent();
4123
+ setPreparedPipeline(preparedPipeline);
3616
4124
  _g.label = 2;
3617
4125
  case 2:
3618
4126
  errors = [];
@@ -3682,7 +4190,7 @@
3682
4190
  return name === parameterName;
3683
4191
  });
3684
4192
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3685
- 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 "); })));
3686
4194
  return [3 /*break*/, 4];
3687
4195
  case 1:
3688
4196
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3694,10 +4202,10 @@
3694
4202
  // Note: Wait a short time to prevent race conditions
3695
4203
  _h.sent();
3696
4204
  _h.label = 3;
3697
- 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 "); }), {
3698
4206
  isSuccessful: false,
3699
4207
  errors: __spreadArray([
3700
- 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 "); }))
3701
4209
  ], __read(errors), false).map(serializeError),
3702
4210
  warnings: warnings.map(serializeError),
3703
4211
  executionReport: executionReport,
@@ -3761,7 +4269,7 @@
3761
4269
  case 0:
3762
4270
  if (loopLimit-- < 0) {
3763
4271
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3764
- 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 "); }));
3765
4273
  }
3766
4274
  currentTemplate = unresovedTemplates_1.find(function (template) {
3767
4275
  return template.dependentParameterNames.every(function (name) {
@@ -3771,29 +4279,52 @@
3771
4279
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3772
4280
  throw new UnexpectedError(
3773
4281
  // TODO: [🐎] DRY
3774
- 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
3775
4283
  .map(function (_a) {
3776
4284
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3777
4285
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3778
4286
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3779
4287
  .join(' and '));
3780
4288
  })
3781
- .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 "); }));
3782
4290
  case 1:
3783
4291
  if (!!currentTemplate) return [3 /*break*/, 3];
3784
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4292
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3785
4293
  case 2:
3786
- /* [5] */ _j.sent();
4294
+ /* [🤹‍♂️] */ _j.sent();
3787
4295
  return [3 /*break*/, 4];
3788
4296
  case 3:
3789
4297
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3790
- work_1 = executeSingleTemplate(currentTemplate)
3791
- .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: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Template name: ").concat(currentTemplate.name, "\n Template title: ").concat(currentTemplate.title, "\n "); }),
4318
+ })
4319
+ .then(function (newParametersToPass) {
4320
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3792
4321
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3793
4322
  })
3794
4323
  .then(function () {
3795
4324
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3796
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
3797
4328
  resolving_1.push(work_1);
3798
4329
  _j.label = 4;
3799
4330
  case 4: return [2 /*return*/];
@@ -3820,7 +4351,12 @@
3820
4351
  var result = _a.result;
3821
4352
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3822
4353
  })), false));
3823
- outputParameters_1 = filterJustOutputParameters();
4354
+ outputParameters_1 = filterJustOutputParameters({
4355
+ preparedPipeline: preparedPipeline,
4356
+ parametersToPass: parametersToPass,
4357
+ $warnings: warnings,
4358
+ pipelineIdentification: pipelineIdentification,
4359
+ });
3824
4360
  isReturned = true;
3825
4361
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3826
4362
  // Note: Wait a short time to prevent race conditions
@@ -3843,7 +4379,12 @@
3843
4379
  var result = _a.result;
3844
4380
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3845
4381
  })), false));
3846
- outputParameters = filterJustOutputParameters();
4382
+ outputParameters = filterJustOutputParameters({
4383
+ preparedPipeline: preparedPipeline,
4384
+ parametersToPass: parametersToPass,
4385
+ $warnings: warnings,
4386
+ pipelineIdentification: pipelineIdentification,
4387
+ });
3847
4388
  isReturned = true;
3848
4389
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3849
4390
  // Note: Wait a short time to prevent race conditions
@@ -3863,22 +4404,65 @@
3863
4404
  })];
3864
4405
  }
3865
4406
  });
3866
- }); };
3867
- return pipelineExecutor;
4407
+ });
3868
4408
  }
4409
+
3869
4410
  /**
3870
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3871
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3872
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3873
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3874
- * TODO: [♈] Probbably move expectations from templates to parameters
3875
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3876
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3877
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3878
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3879
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3880
- * 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`
3881
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 runCount = 0;
4441
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4442
+ return __generator(this, function (_a) {
4443
+ runCount++;
4444
+ return [2 /*return*/, /* not await */ executePipeline({
4445
+ pipeline: pipeline,
4446
+ preparedPipeline: preparedPipeline,
4447
+ setPreparedPipeline: function (newPreparedPipeline) {
4448
+ preparedPipeline = newPreparedPipeline;
4449
+ },
4450
+ inputParameters: inputParameters,
4451
+ tools: tools,
4452
+ onProgress: onProgress,
4453
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n ").concat(runCount === 1 ? '' : "Run #".concat(runCount), "\n "); }),
4454
+ settings: {
4455
+ maxExecutionAttempts: maxExecutionAttempts,
4456
+ maxParallelCount: maxParallelCount,
4457
+ csvSettings: csvSettings,
4458
+ isVerbose: isVerbose,
4459
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4460
+ },
4461
+ })];
4462
+ });
4463
+ }); };
4464
+ return pipelineExecutor;
4465
+ }
3882
4466
 
3883
4467
  /**
3884
4468
  * @@@
@@ -3930,7 +4514,7 @@
3930
4514
  outputParameters = result.outputParameters;
3931
4515
  knowledgePiecesRaw = outputParameters.knowledgePieces;
3932
4516
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
3933
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4517
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
3934
4518
  if (isVerbose) {
3935
4519
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
3936
4520
  }
@@ -3988,8 +4572,13 @@
3988
4572
  case 6: return [3 /*break*/, 8];
3989
4573
  case 7:
3990
4574
  error_1 = _c.sent();
4575
+ // Note: Here is expected error:
4576
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4577
+ if (!(error_1 instanceof PipelineExecutionError)) {
4578
+ throw error_1;
4579
+ }
3991
4580
  // TODO: [🟥] Detect browser / node and make it colorfull
3992
- console.error(error_1);
4581
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
3993
4582
  return [3 /*break*/, 8];
3994
4583
  case 8: return [2 /*return*/, {
3995
4584
  name: name,
@@ -4010,7 +4599,7 @@
4010
4599
  });
4011
4600
  }
4012
4601
  /**
4013
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4602
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4014
4603
  * TODO: [🪂] Do it in parallel 11:11
4015
4604
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4016
4605
  */
@@ -4034,7 +4623,7 @@
4034
4623
  var partialPieces, pieces;
4035
4624
  return __generator(this, function (_a) {
4036
4625
  switch (_a.label) {
4037
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4626
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝][main] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4038
4627
  options)];
4039
4628
  case 1:
4040
4629
  partialPieces = _a.sent();
@@ -4226,7 +4815,7 @@
4226
4815
  });
4227
4816
  }
4228
4817
  /**
4229
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4818
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4230
4819
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4231
4820
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4232
4821
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4275,7 +4864,7 @@
4275
4864
  case 0:
4276
4865
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4277
4866
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4278
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
4867
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4279
4868
  TODO_USE(parameters);
4280
4869
  templatesPrepared = new Array(
4281
4870
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4307,7 +4896,7 @@
4307
4896
  /**
4308
4897
  * TODO: [🧠] Add context to each template (if missing)
4309
4898
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4310
- * TODO: [♨] !!! Prepare index the samples and maybe templates
4899
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4311
4900
  * TODO: Write tests for `preparePipeline`
4312
4901
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4313
4902
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4479,7 +5068,7 @@
4479
5068
  if (sourceContent === '') {
4480
5069
  throw new ParseError("Source is not defined");
4481
5070
  }
4482
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5071
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4483
5072
  if (sourceContent.startsWith('http://')) {
4484
5073
  throw new ParseError("Source is not secure");
4485
5074
  }
@@ -4682,7 +5271,7 @@
4682
5271
  if (command.templateType === 'KNOWLEDGE') {
4683
5272
  knowledgeCommandParser.$applyToPipelineJson({
4684
5273
  type: 'KNOWLEDGE',
4685
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5274
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4686
5275
  }, $pipelineJson);
4687
5276
  $templateJson.isTemplate = false;
4688
5277
  return;
@@ -5032,6 +5621,171 @@
5032
5621
  * TODO: [🌺] Use some intermediate util splitWords
5033
5622
  */
5034
5623
 
5624
+ /**
5625
+ * @@@
5626
+ *
5627
+ * @param text @@@
5628
+ * @param _isFirstLetterCapital @@@
5629
+ * @returns @@@
5630
+ * @example 'helloWorld'
5631
+ * @example 'iLovePromptbook'
5632
+ * @public exported from `@promptbook/utils`
5633
+ */
5634
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5635
+ var e_1, _a;
5636
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5637
+ var charType;
5638
+ var lastCharType = null;
5639
+ var normalizedName = '';
5640
+ try {
5641
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5642
+ var char = text_1_1.value;
5643
+ var normalizedChar = void 0;
5644
+ if (/^[a-z]$/.test(char)) {
5645
+ charType = 'LOWERCASE';
5646
+ normalizedChar = char;
5647
+ }
5648
+ else if (/^[A-Z]$/.test(char)) {
5649
+ charType = 'UPPERCASE';
5650
+ normalizedChar = char.toLowerCase();
5651
+ }
5652
+ else if (/^[0-9]$/.test(char)) {
5653
+ charType = 'NUMBER';
5654
+ normalizedChar = char;
5655
+ }
5656
+ else {
5657
+ charType = 'OTHER';
5658
+ normalizedChar = '';
5659
+ }
5660
+ if (!lastCharType) {
5661
+ if (_isFirstLetterCapital) {
5662
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5663
+ }
5664
+ }
5665
+ else if (charType !== lastCharType &&
5666
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5667
+ !(lastCharType === 'NUMBER') &&
5668
+ !(charType === 'NUMBER')) {
5669
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5670
+ }
5671
+ normalizedName += normalizedChar;
5672
+ lastCharType = charType;
5673
+ }
5674
+ }
5675
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5676
+ finally {
5677
+ try {
5678
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5679
+ }
5680
+ finally { if (e_1) throw e_1.error; }
5681
+ }
5682
+ return normalizedName;
5683
+ }
5684
+ /**
5685
+ * TODO: [🌺] Use some intermediate util splitWords
5686
+ */
5687
+
5688
+ /**
5689
+ * Removes quotes from a string
5690
+ *
5691
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5692
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5693
+ * Note: There are two simmilar functions:
5694
+ * - `removeQuotes` which removes only bounding quotes
5695
+ * - `unwrapResult` which removes whole introduce sentence
5696
+ *
5697
+ * @param text optionally quoted text
5698
+ * @returns text without quotes
5699
+ * @public exported from `@promptbook/utils`
5700
+ */
5701
+ function removeQuotes(text) {
5702
+ if (text.startsWith('"') && text.endsWith('"')) {
5703
+ return text.slice(1, -1);
5704
+ }
5705
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5706
+ return text.slice(1, -1);
5707
+ }
5708
+ return text;
5709
+ }
5710
+
5711
+ /**
5712
+ * Function `validateParameterName` will @@@
5713
+ *
5714
+ * @param parameterName @@@
5715
+ * @returns @@@
5716
+ * @throws {ParseError} @@@
5717
+ * @private within the repository
5718
+ */
5719
+ function validateParameterName(parameterName) {
5720
+ var e_1, _a;
5721
+ var rawParameterName = parameterName;
5722
+ try {
5723
+ for (var _b = __values([
5724
+ ['`', '`'],
5725
+ ['{', '}'],
5726
+ ['[', ']'],
5727
+ ['(', ')'],
5728
+ ['<', '>'],
5729
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5730
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5731
+ if (parameterName.substring(0, 1) === start &&
5732
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5733
+ // <- TODO: More universal that 1 character
5734
+ ) {
5735
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5736
+ // <- TODO: More universal that 1 character
5737
+ }
5738
+ }
5739
+ }
5740
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5741
+ finally {
5742
+ try {
5743
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5744
+ }
5745
+ finally { if (e_1) throw e_1.error; }
5746
+ }
5747
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5748
+ try {
5749
+ /*
5750
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5751
+ if (parameterName.includes(' ')) {
5752
+ throw new ParseError(`Parameter name cannot contain spaces`);
5753
+ }
5754
+ */
5755
+ if (parameterName.includes('.')) {
5756
+ throw new ParseError("Parameter name cannot contain dots");
5757
+ }
5758
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5759
+ throw new ParseError("Parameter name cannot contain slashes");
5760
+ }
5761
+ if (parameterName.includes('(') ||
5762
+ parameterName.includes(')') ||
5763
+ parameterName.includes('{') ||
5764
+ parameterName.includes('}') ||
5765
+ parameterName.includes('[') ||
5766
+ parameterName.includes(']')) {
5767
+ throw new ParseError("Parameter name cannot contain braces");
5768
+ }
5769
+ parameterName = removeDiacritics(parameterName);
5770
+ parameterName = removeEmojis(parameterName);
5771
+ parameterName = removeQuotes(parameterName);
5772
+ parameterName = normalizeTo_camelCase(parameterName);
5773
+ if (parameterName === '') {
5774
+ throw new ParseError("Parameter name cannot be empty");
5775
+ }
5776
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5777
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5778
+ }
5779
+ }
5780
+ catch (error) {
5781
+ if (!(error instanceof ParseError)) {
5782
+ throw error;
5783
+ }
5784
+ 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 "); }));
5785
+ }
5786
+ return parameterName;
5787
+ }
5788
+
5035
5789
  /**
5036
5790
  * Parses the foreach command
5037
5791
  *
@@ -5061,15 +5815,16 @@
5061
5815
  /**
5062
5816
  * Link to discussion
5063
5817
  */
5064
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5818
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5065
5819
  /**
5066
5820
  * Example usages of the FOREACH command
5067
5821
  */
5068
5822
  examples: [
5069
- 'FOREACH List Line `{customers}` -> `{customer}`',
5070
- 'FOR List Line `{customers}` -> `{customer}`',
5071
- 'EACH List Line `{customers}` -> `{customer}`',
5072
- // <- TODO: [🍭] !!!!!! More
5823
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5824
+ 'FOREACH Csv Cell `{customers}` -> `{cell}`',
5825
+ 'FOREACH Csv Row `{customers}` -> `{firstName}`, `{lastName}`, `+{email}`',
5826
+ 'FOR Text Line `{customers}` -> `{customer}`',
5827
+ 'EACH Text Line `{customers}` -> `{customer}`',
5073
5828
  ],
5074
5829
  /**
5075
5830
  * Parses the FOREACH command
@@ -5077,55 +5832,75 @@
5077
5832
  parse: function (input) {
5078
5833
  var args = input.args;
5079
5834
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5080
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5081
- var parameterNameWrapped = args[2];
5835
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5836
+ var parameterNameArg = args[2] || '';
5082
5837
  var assignSign = args[3];
5083
- var subparameterNameWrapped = args[4];
5084
- if (![
5085
- 'LIST',
5086
- 'CSV',
5087
- // <- TODO: [🏢] Unhardcode formats
5088
- ].includes(formatName)) {
5089
- console.info({ args: args, formatName: formatName });
5090
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5838
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5839
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5840
+ });
5841
+ if (formatDefinition === undefined) {
5842
+ 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; })
5843
+ .map(function (formatName) { return "- ".concat(formatName); })
5844
+ .join('\n')), "\n "); }));
5091
5845
  // <- TODO: [🏢] List all supported format names
5092
5846
  }
5093
- if (![
5094
- 'LINE',
5095
- 'ROW',
5096
- 'COLUMN',
5097
- 'CELL',
5098
- // <- TODO: [🏢] Unhardcode format cells
5099
- ].includes(cellName)) {
5100
- console.info({ args: args, cellName: cellName });
5101
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5102
- // <- TODO: [🏢] List all supported cell names for the format
5847
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5848
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5849
+ });
5850
+ if (subvalueDefinition === undefined) {
5851
+ 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
5852
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5853
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5854
+ .join('\n')), "\n "); }));
5855
+ // <- TODO: [🏢] List all supported subformat names for the format
5103
5856
  }
5104
5857
  if (assignSign !== '->') {
5105
- console.info({ args: args, assignSign: assignSign });
5106
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5107
- }
5108
- // TODO: !!!!!! Replace with propper parameter name validation
5109
- if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5110
- (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5111
- console.info({ args: args, parameterNameWrapped: parameterNameWrapped }, parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1), parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length));
5112
- throw new Error("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5113
- }
5114
- var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5115
- // TODO: !!!!!! Replace with propper parameter name validation
5116
- if ((subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(0, 1)) !== '{' ||
5117
- (subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(subparameterNameWrapped.length - 1, subparameterNameWrapped.length)) !==
5118
- '}') {
5119
- console.info({ args: args, subparameterNameWrapped: subparameterNameWrapped });
5120
- throw new Error("!!!!!! 2 Here will be error (with rules and precise error) from validateParameterName");
5121
- }
5122
- var subparameterName = subparameterNameWrapped.substring(1, subparameterNameWrapped.length - 1);
5858
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5859
+ }
5860
+ var parameterName = validateParameterName(parameterNameArg);
5861
+ var outputSubparameterName = null;
5862
+ // TODO: [4] DRY
5863
+ var inputSubparameterNames = args
5864
+ .slice(4)
5865
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5866
+ .filter(function (parameterName) { return !parameterName.includes('+'); })
5867
+ .filter(function (parameterName) { return parameterName !== ''; })
5868
+ .map(validateParameterName);
5869
+ // TODO: [4] DRY
5870
+ var outputSubparameterNames = args
5871
+ .slice(4)
5872
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5873
+ .filter(function (parameterName) { return parameterName.includes('+'); })
5874
+ .map(function (parameterName) { return parameterName.split('+').join(''); })
5875
+ .map(validateParameterName);
5876
+ if (outputSubparameterNames.length === 1) {
5877
+ outputSubparameterName = outputSubparameterNames[0];
5878
+ }
5879
+ else if (outputSubparameterNames.length > 1) {
5880
+ throw new ParseError("FOREACH command can not have more than one output subparameter");
5881
+ }
5882
+ if (inputSubparameterNames.length === 0) {
5883
+ throw new ParseError("FOREACH command must have at least one input subparameter");
5884
+ }
5885
+ if (outputSubparameterName === null) {
5886
+ // TODO: Following code should be unhardcoded from here and moved to the format definition
5887
+ if (formatName === 'CSV' && subformatName === 'CELL') {
5888
+ outputSubparameterName = 'newCell';
5889
+ }
5890
+ else if (formatName === 'TEXT' && subformatName === 'LINE') {
5891
+ outputSubparameterName = 'newLine';
5892
+ }
5893
+ else {
5894
+ throw new ParseError(spaceTrim__default["default"]("\n FOREACH ".concat(formatName, " ").concat(subformatName, " must specify output subparameter\n\n Correct example:\n - FOREACH ").concat(formatName, " ").concat(subformatName, " {").concat(parameterName, "} -> {inputSubparameterName1}, {inputSubparameterName2}, +{outputSubparameterName}\n\n ")));
5895
+ }
5896
+ }
5123
5897
  return {
5124
5898
  type: 'FOREACH',
5125
5899
  formatName: formatName,
5126
- cellName: cellName,
5900
+ subformatName: subformatName,
5127
5901
  parameterName: parameterName,
5128
- subparameterName: subparameterName,
5902
+ inputSubparameterNames: inputSubparameterNames,
5903
+ outputSubparameterName: outputSubparameterName,
5129
5904
  };
5130
5905
  },
5131
5906
  /**
@@ -5134,9 +5909,17 @@
5134
5909
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5135
5910
  */
5136
5911
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5137
- var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5138
- $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5139
- keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
5912
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, inputSubparameterNames = command.inputSubparameterNames, outputSubparameterName = command.outputSubparameterName;
5913
+ // TODO: [🍭] Detect double use
5914
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
5915
+ $templateJson.foreach = {
5916
+ formatName: formatName,
5917
+ subformatName: subformatName,
5918
+ parameterName: parameterName,
5919
+ inputSubparameterNames: inputSubparameterNames,
5920
+ outputSubparameterName: outputSubparameterName,
5921
+ };
5922
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5140
5923
  // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5141
5924
  },
5142
5925
  /**
@@ -5159,8 +5942,7 @@
5159
5942
  },
5160
5943
  };
5161
5944
  /**
5162
- * TODO: !!!!!! Comment console logs
5163
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5945
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5164
5946
  */
5165
5947
 
5166
5948
  /**
@@ -5270,12 +6052,11 @@
5270
6052
  */
5271
6053
  parse: function (input) {
5272
6054
  var args = input.args;
5273
- // TODO: !!!!!! Replace with propper parameter name validation
5274
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5275
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5276
- throw new ParseError("Invalid joker");
6055
+ if (args.length !== 1) {
6056
+ throw new ParseError("JOKE command expects exactly one parameter name");
5277
6057
  }
5278
- var parameterName = parametersMatch.groups.parameterName;
6058
+ var parameterNameArg = args[0] || '';
6059
+ var parameterName = validateParameterName(parameterNameArg);
5279
6060
  return {
5280
6061
  type: 'JOKER',
5281
6062
  parameterName: parameterName,
@@ -5350,6 +6131,9 @@
5350
6131
  */
5351
6132
  parse: function (input) {
5352
6133
  var args = input.args, normalized = input.normalized;
6134
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6135
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6136
+ }).join('\n')), "\n "); });
5353
6137
  // TODO: Make this more elegant and dynamically
5354
6138
  if (normalized.startsWith('MODEL_VARIANT')) {
5355
6139
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5365,17 +6149,13 @@
5365
6149
  key: 'modelVariant',
5366
6150
  value: 'COMPLETION',
5367
6151
  };
6152
+ // <- Note: [🤖]
5368
6153
  }
5369
6154
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5370
- return {
5371
- type: 'MODEL',
5372
- key: 'modelVariant',
5373
- value: 'EMBEDDING',
5374
- };
5375
- // <- Note: [🤖]
6155
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5376
6156
  }
5377
6157
  else {
5378
- 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 "); }));
6158
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5379
6159
  }
5380
6160
  }
5381
6161
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5500,14 +6280,13 @@
5500
6280
  * Parses the PARAMETER command
5501
6281
  */
5502
6282
  parse: function (input) {
5503
- var normalized = input.normalized, raw = input.raw;
5504
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5505
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5506
- throw new ParseError("Invalid parameter");
5507
- }
5508
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5509
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5510
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6283
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6284
+ var parameterNameRaw = args.shift() || '';
6285
+ var parameterDescriptionRaw = args.join(' ');
6286
+ // <- TODO: When [🥶] fixed, change to:
6287
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6288
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6289
+ 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 "); }));
5511
6290
  }
5512
6291
  var isInput = normalized.startsWith('INPUT');
5513
6292
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5515,11 +6294,12 @@
5515
6294
  isInput = false;
5516
6295
  isOutput = false;
5517
6296
  }
5518
- // TODO: !!!!!! Add parameter name validation
6297
+ var parameterName = validateParameterName(parameterNameRaw);
6298
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5519
6299
  return {
5520
6300
  type: 'PARAMETER',
5521
6301
  parameterName: parameterName,
5522
- parameterDescription: parameterDescription.trim() || null,
6302
+ parameterDescription: parameterDescription,
5523
6303
  isInput: isInput,
5524
6304
  isOutput: isOutput,
5525
6305
  };
@@ -5844,6 +6624,7 @@
5844
6624
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
5845
6625
  */
5846
6626
  $applyToPipelineJson: function (command, $pipelineJson) {
6627
+ // TODO: Warn if the version is overridden
5847
6628
  $pipelineJson.promptbookVersion = command.promptbookVersion;
5848
6629
  },
5849
6630
  /**
@@ -6326,7 +7107,9 @@
6326
7107
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6327
7108
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6328
7109
  var args = items.slice(commandNameSegmentsCount + 1);
6329
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7110
+ var rawArgs = raw
7111
+ .substring(commandNameRaw.length)
7112
+ .trim();
6330
7113
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6331
7114
  if (command !== null) {
6332
7115
  return command;
@@ -6337,7 +7120,9 @@
6337
7120
  {
6338
7121
  var commandNameRaw = items.slice(-1).join('_');
6339
7122
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6340
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7123
+ var rawArgs = raw
7124
+ .substring(0, raw.length - commandNameRaw.length)
7125
+ .trim();
6341
7126
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6342
7127
  if (command !== null) {
6343
7128
  return command;
@@ -6477,7 +7262,7 @@
6477
7262
  function extractOneBlockFromMarkdown(markdown) {
6478
7263
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6479
7264
  if (codeBlocks.length !== 1) {
6480
- 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 "); }));
7265
+ 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 "); }));
6481
7266
  }
6482
7267
  return codeBlocks[0];
6483
7268
  }
@@ -6664,7 +7449,7 @@
6664
7449
  var $pipelineJson = {
6665
7450
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6666
7451
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6667
- promptbookVersion: PROMPTBOOK_VERSION,
7452
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6668
7453
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6669
7454
  parameters: [],
6670
7455
  templates: [],
@@ -6955,7 +7740,7 @@
6955
7740
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
6956
7741
  }
6957
7742
  /**
6958
- * TODO: !!!! Warn if used only sync version
7743
+ * TODO:[main] !!!! Warn if used only sync version
6959
7744
  * TODO: [🚞] Report here line/column of error
6960
7745
  * TODO: Use spaceTrim more effectively
6961
7746
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7738,7 +8523,7 @@
7738
8523
  }
7739
8524
  }
7740
8525
  /**
7741
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8526
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7742
8527
  * TODO: [🧠][💺] Can be done this on type-level?
7743
8528
  */
7744
8529