@promptbook/cli 0.70.0-0 → 0.71.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +23 -60
  2. package/esm/index.es.js +2030 -1220
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/promptbook-collection/index.d.ts +0 -3
  5. package/esm/typings/src/_packages/core.index.d.ts +9 -1
  6. package/esm/typings/src/_packages/types.index.d.ts +12 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  8. package/esm/typings/src/cli/cli-commands/make.d.ts +1 -1
  9. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +1 -1
  10. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +3 -7
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +23 -0
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  14. package/esm/typings/src/config.d.ts +16 -3
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +10 -5
  19. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +9 -8
  20. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +45 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +40 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +19 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  31. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  32. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  33. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  34. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  35. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  36. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  37. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  38. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  39. package/esm/typings/src/formats/index.d.ts +1 -1
  40. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  41. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  42. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  43. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  44. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  45. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  48. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  50. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  51. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  52. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  53. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +9 -2
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  57. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  58. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  59. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  60. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  61. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  62. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  63. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  64. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  65. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  67. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  68. package/package.json +17 -12
  69. package/umd/index.umd.js +2033 -1224
  70. package/umd/index.umd.js.map +1 -1
  71. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  72. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  73. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  74. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  75. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  76. /package/esm/typings/src/{personas/preparePersona.test.d.ts → utils/validators/parameterName/validateParameterName.test.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -6,6 +6,7 @@ import { stat, access, constants, readdir, readFile, writeFile, mkdir, unlink }
6
6
  import { join as join$1, dirname } from 'path';
7
7
  import { format } from 'prettier';
8
8
  import parserHtml from 'prettier/parser-html';
9
+ import { unparse, parse } from 'papaparse';
9
10
  import hexEncoder from 'crypto-js/enc-hex';
10
11
  import sha256 from 'crypto-js/sha256';
11
12
  import { join } from 'path/posix';
@@ -20,8 +21,8 @@ import OpenAI from 'openai';
20
21
  /**
21
22
  * The version of the Promptbook library
22
23
  */
23
- var PROMPTBOOK_VERSION = '0.69.0-0';
24
- // TODO: !!!! List here all the versions and annotate + put into script
24
+ var PROMPTBOOK_VERSION = '0.70.0-1';
25
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
25
26
 
26
27
  /*! *****************************************************************************
27
28
  Copyright (c) Microsoft Corporation.
@@ -356,7 +357,7 @@ function checkSerializableAsJson(name, value) {
356
357
  }
357
358
  /**
358
359
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
359
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
360
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
360
361
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
361
362
  */
362
363
 
@@ -430,13 +431,13 @@ var IMMEDIATE_TIME = 10;
430
431
  *
431
432
  * @public exported from `@promptbook/core`
432
433
  */
433
- var MAX_PARALLEL_COUNT = 5;
434
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
434
435
  /**
435
436
  * The maximum number of attempts to execute LLM task before giving up
436
437
  *
437
438
  * @public exported from `@promptbook/core`
438
439
  */
439
- var MAX_EXECUTION_ATTEMPTS = 3;
440
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
440
441
  /**
441
442
  * The maximum length of the (generated) filename
442
443
  *
@@ -473,6 +474,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
473
474
  'samples',
474
475
  'modelName',
475
476
  'currentDate',
477
+ // <- TODO: !!!!! list here all command names
476
478
  // <- TODO: Add more like 'date', 'modelName',...
477
479
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
478
480
  ]);
@@ -501,12 +503,32 @@ var DEFAULT_REMOTE_URL = 'https://api.pavolhejny.com/';
501
503
  */
502
504
  var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
503
505
  // <- TODO: [🧜‍♂️]
506
+ /**
507
+ * @@@
508
+ *
509
+ * @public exported from `@promptbook/core`
510
+ */
511
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
512
+ delimiter: ',',
513
+ quoteChar: '"',
514
+ newline: '\n',
515
+ skipEmptyLines: true,
516
+ });
504
517
  /**
505
518
  * @@@
506
519
  *
507
520
  * @public exported from `@promptbook/core`
508
521
  */
509
522
  var IS_VERBOSE = false;
523
+ /**
524
+ * @@@
525
+ *
526
+ * @private within the repository
527
+ */
528
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
529
+ /**/
530
+ // Note: In normal situations, we check the pipeline logic:
531
+ true);
510
532
  /**
511
533
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
512
534
  */
@@ -660,7 +682,7 @@ function pipelineJsonToString(pipelineJson) {
660
682
  commands.push("PIPELINE URL ".concat(pipelineUrl));
661
683
  }
662
684
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
663
- // TODO: !!! This increase size of the bundle and is probbably not necessary
685
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
664
686
  pipelineString = prettifyMarkdown(pipelineString);
665
687
  try {
666
688
  for (var _g = __values(parameters.filter(function (_a) {
@@ -808,12 +830,12 @@ function pipelineJsonToString(pipelineJson) {
808
830
  pipelineString += '```' + contentLanguage;
809
831
  pipelineString += '\n';
810
832
  pipelineString += spaceTrim$1(content);
811
- // <- TODO: !!! Escape
833
+ // <- TODO:[main] !!! Escape
812
834
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
813
835
  pipelineString += '\n';
814
836
  pipelineString += '```';
815
837
  pipelineString += '\n\n';
816
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
838
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
817
839
  }
818
840
  }
819
841
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -1040,7 +1062,7 @@ function forEachAsync(array, options, callbackfunction) {
1040
1062
  });
1041
1063
  }
1042
1064
 
1043
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1065
+ 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"}];
1044
1066
 
1045
1067
  /**
1046
1068
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1115,7 +1137,7 @@ function isValidPromptbookVersion(version) {
1115
1137
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
1116
1138
  return false;
1117
1139
  }
1118
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1140
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1119
1141
  return true;
1120
1142
  }
1121
1143
 
@@ -1247,6 +1269,26 @@ function isValidPipelineUrl(url) {
1247
1269
  * @public exported from `@promptbook/core`
1248
1270
  */
1249
1271
  function validatePipeline(pipeline) {
1272
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1273
+ validatePipelineCore(pipeline);
1274
+ }
1275
+ else {
1276
+ try {
1277
+ validatePipelineCore(pipeline);
1278
+ }
1279
+ catch (error) {
1280
+ if (!(error instanceof PipelineLogicError)) {
1281
+ throw error;
1282
+ }
1283
+ console.error(spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1284
+ }
1285
+ }
1286
+ return pipeline;
1287
+ }
1288
+ /**
1289
+ * @private internal function for `validatePipeline`
1290
+ */
1291
+ function validatePipelineCore(pipeline) {
1250
1292
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1251
1293
  var e_1, _a, e_2, _b, e_3, _c;
1252
1294
  var pipelineIdentification = (function () {
@@ -1264,19 +1306,19 @@ function validatePipeline(pipeline) {
1264
1306
  // <- Note: [🚲]
1265
1307
  throw new PipelineLogicError(spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1266
1308
  }
1267
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1309
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1268
1310
  // <- Note: [🚲]
1269
1311
  throw new PipelineLogicError(spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1270
1312
  }
1271
1313
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1272
1314
  if (!Array.isArray(pipeline.parameters)) {
1273
1315
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1274
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1316
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1275
1317
  }
1276
1318
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1277
1319
  if (!Array.isArray(pipeline.templates)) {
1278
1320
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1279
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1321
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1280
1322
  }
1281
1323
  var _loop_1 = function (parameter) {
1282
1324
  if (parameter.isInput && parameter.isOutput) {
@@ -1445,9 +1487,9 @@ function validatePipeline(pipeline) {
1445
1487
  while (unresovedTemplates.length > 0) {
1446
1488
  _loop_3();
1447
1489
  }
1448
- return pipeline;
1449
1490
  }
1450
1491
  /**
1492
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1451
1493
  * TODO: [🧠] Work with promptbookVersion
1452
1494
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1453
1495
  * > /**
@@ -1459,11 +1501,11 @@ function validatePipeline(pipeline) {
1459
1501
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1460
1502
  */
1461
1503
  /**
1462
- * TODO: [🐣] !!!! Validate that all samples match expectations
1463
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1464
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1465
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1466
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1504
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1505
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1506
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1507
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1508
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1467
1509
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1468
1510
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1469
1511
  */
@@ -2169,113 +2211,35 @@ function assertsExecutionSuccessful(executionResult) {
2169
2211
  */
2170
2212
 
2171
2213
  /**
2172
- * Parses the given script and returns the list of all used variables that are not defined in the script
2173
- *
2174
- * @param script from which to extract the variables
2175
- * @returns the list of variable names
2176
- * @throws {ParseError} if the script is invalid
2177
- * @public exported from `@promptbook/utils`
2178
- */
2179
- function extractVariables(script) {
2180
- var variables = new Set();
2181
- script = "(()=>{".concat(script, "})()");
2182
- try {
2183
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2184
- try {
2185
- eval(script);
2186
- }
2187
- catch (error) {
2188
- if (!(error instanceof ReferenceError)) {
2189
- throw error;
2190
- }
2191
- var undefinedName = error.message.split(' ')[0];
2192
- /*
2193
- Note: Parsing the error
2194
- [PipelineUrlError: thing is not defined]
2195
- */
2196
- if (!undefinedName) {
2197
- throw error;
2198
- }
2199
- if (script.includes(undefinedName + '(')) {
2200
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2201
- }
2202
- else {
2203
- variables.add(undefinedName);
2204
- script = "const ".concat(undefinedName, " = '';") + script;
2205
- }
2206
- }
2207
- }
2208
- catch (error) {
2209
- if (!(error instanceof Error)) {
2210
- throw error;
2211
- }
2212
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2213
- }
2214
- return variables;
2215
- }
2216
- /**
2217
- * TODO: [🔣] Support for multiple languages - python, java,...
2218
- */
2219
-
2220
- /**
2221
- * Parses the template and returns the set of all used parameters
2214
+ * Determine if the pipeline is fully prepared
2222
2215
  *
2223
- * @param template the template with used parameters
2224
- * @returns the set of parameter names
2225
- * @throws {ParseError} if the script is invalid
2226
- * @public exported from `@promptbook/utils`
2216
+ * @public exported from `@promptbook/core`
2227
2217
  */
2228
- function extractParameterNamesFromTemplate(template) {
2229
- var e_1, _a, e_2, _b, e_3, _c;
2230
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2231
- var parameterNames = new Set();
2232
- try {
2233
- 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()) {
2234
- var parameterName = _e.value;
2235
- parameterNames.add(parameterName);
2236
- }
2237
- }
2238
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2239
- finally {
2240
- try {
2241
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2242
- }
2243
- finally { if (e_1) throw e_1.error; }
2244
- }
2245
- if (templateType === 'SCRIPT_TEMPLATE') {
2246
- try {
2247
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2248
- var parameterName = _g.value;
2249
- parameterNames.add(parameterName);
2250
- }
2251
- }
2252
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2253
- finally {
2254
- try {
2255
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2256
- }
2257
- finally { if (e_2) throw e_2.error; }
2258
- }
2259
- }
2260
- try {
2261
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2262
- var jokerName = _j.value;
2263
- parameterNames.add(jokerName);
2264
- }
2218
+ function isPipelinePrepared(pipeline) {
2219
+ // Note: Ignoring `pipeline.preparations` @@@
2220
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2221
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2222
+ return false;
2265
2223
  }
2266
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2267
- finally {
2268
- try {
2269
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2270
- }
2271
- finally { if (e_3) throw e_3.error; }
2224
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2225
+ return false;
2272
2226
  }
2273
- parameterNames.delete('content');
2274
- // <- Note {websiteContent} is used in `preparedContent`
2275
- return parameterNames;
2227
+ /*
2228
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2229
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2230
+ > return false;
2231
+ > }
2232
+ */
2233
+ return true;
2276
2234
  }
2277
2235
  /**
2278
- * TODO: [🔣] If script require contentLanguage
2236
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2237
+ * TODO: [🐠] Maybe base this on `makeValidator`
2238
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2239
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2240
+ * - [🏍] ? Is context in each template
2241
+ * - [♨] Are samples prepared
2242
+ * - [♨] Are templates prepared
2279
2243
  */
2280
2244
 
2281
2245
  /**
@@ -2295,27 +2259,6 @@ function serializeError(error) {
2295
2259
  };
2296
2260
  }
2297
2261
 
2298
- /**
2299
- * Function isValidJsonString will tell you if the string is valid JSON or not
2300
- *
2301
- * @public exported from `@promptbook/utils`
2302
- */
2303
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2304
- try {
2305
- JSON.parse(value);
2306
- return true;
2307
- }
2308
- catch (error) {
2309
- if (!(error instanceof Error)) {
2310
- throw error;
2311
- }
2312
- if (error.message.includes('Unexpected token')) {
2313
- return false;
2314
- }
2315
- return false;
2316
- }
2317
- }
2318
-
2319
2262
  /**
2320
2263
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2321
2264
  *
@@ -2342,9 +2285,10 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2342
2285
  });
2343
2286
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2344
2287
  get: function () {
2345
- return this.llmExecutionTools
2346
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2347
- .join('\n');
2288
+ return this.llmExecutionTools.map(function (_a, index) {
2289
+ var title = _a.title;
2290
+ return "".concat(index + 1, ") `").concat(title, "`");
2291
+ }).join('\n');
2348
2292
  },
2349
2293
  enumerable: false,
2350
2294
  configurable: true
@@ -2542,9 +2486,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2542
2486
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2543
2487
  }
2544
2488
  else {
2545
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.llmExecutionTools
2546
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2547
- .join('\n')), "\n\n "); }));
2489
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\"\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.description), "\n\n "); }));
2548
2490
  }
2549
2491
  }
2550
2492
  });
@@ -2610,288 +2552,153 @@ function joinLlmExecutionTools() {
2610
2552
  */
2611
2553
 
2612
2554
  /**
2613
- * Extracts all code blocks from markdown.
2555
+ * Takes an item or an array of items and returns an array of items
2614
2556
  *
2615
- * Note: There are multiple simmilar function:
2616
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2617
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2618
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2619
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2557
+ * 1) Any item except array and undefined returns array with that one item (also null)
2558
+ * 2) Undefined returns empty array
2559
+ * 3) Array returns itself
2620
2560
  *
2621
- * @param markdown any valid markdown
2622
- * @returns code blocks with language and content
2623
- * @throws {ParseError} if block is not closed properly
2624
- * @public exported from `@promptbook/markdown-utils`
2561
+ * @private internal utility
2625
2562
  */
2626
- function extractAllBlocksFromMarkdown(markdown) {
2627
- var e_1, _a;
2628
- var codeBlocks = [];
2629
- var lines = markdown.split('\n');
2630
- // Note: [0] Ensure that the last block notated by gt > will be closed
2631
- lines.push('');
2632
- var currentCodeBlock = null;
2633
- try {
2634
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2635
- var line = lines_1_1.value;
2636
- if (line.startsWith('> ') || line === '>') {
2637
- if (currentCodeBlock === null) {
2638
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2639
- } /* not else */
2640
- if (currentCodeBlock.blockNotation === '>') {
2641
- if (currentCodeBlock.content !== '') {
2642
- currentCodeBlock.content += '\n';
2643
- }
2644
- currentCodeBlock.content += line.slice(2);
2645
- }
2646
- }
2647
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2648
- codeBlocks.push(currentCodeBlock);
2649
- currentCodeBlock = null;
2650
- }
2651
- /* not else */
2652
- if (line.startsWith('```')) {
2653
- var language = line.slice(3).trim() || null;
2654
- if (currentCodeBlock === null) {
2655
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2656
- }
2657
- else {
2658
- if (language !== null) {
2659
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2660
- }
2661
- codeBlocks.push(currentCodeBlock);
2662
- currentCodeBlock = null;
2663
- }
2664
- }
2665
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2666
- if (currentCodeBlock.content !== '') {
2667
- currentCodeBlock.content += '\n';
2668
- }
2669
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2670
- }
2671
- }
2672
- }
2673
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2674
- finally {
2675
- try {
2676
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2677
- }
2678
- finally { if (e_1) throw e_1.error; }
2563
+ function arrayableToArray(input) {
2564
+ if (input === undefined) {
2565
+ return [];
2679
2566
  }
2680
- if (currentCodeBlock !== null) {
2681
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2567
+ if (input instanceof Array) {
2568
+ return input;
2682
2569
  }
2683
- return codeBlocks;
2570
+ return [input];
2684
2571
  }
2685
- /**
2686
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2687
- */
2688
2572
 
2689
2573
  /**
2690
- * Extracts extracts exactly one valid JSON code block
2691
- *
2692
- * - When given string is a valid JSON as it is, it just returns it
2693
- * - When there is no JSON code block the function throws a `ParseError`
2694
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2695
- *
2696
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2697
- * Note: There are multiple simmilar function:
2698
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2699
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2700
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2701
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2574
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2702
2575
  *
2703
- * @public exported from `@promptbook/markdown-utils`
2704
- * @throws {ParseError} if there is no valid JSON block in the markdown
2705
- */
2706
- function extractJsonBlock(markdown) {
2707
- if (isValidJsonString(markdown)) {
2708
- return markdown;
2709
- }
2710
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2711
- var jsonBlocks = codeBlocks.filter(function (_a) {
2712
- var content = _a.content;
2713
- return isValidJsonString(content);
2714
- });
2715
- if (jsonBlocks.length === 0) {
2716
- throw new Error('There is no valid JSON block in the markdown');
2717
- }
2718
- if (jsonBlocks.length > 1) {
2719
- throw new Error('There are multiple JSON code blocks in the markdown');
2720
- }
2721
- return jsonBlocks[0].content;
2722
- }
2723
- /**
2724
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2725
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2726
- */
2727
-
2728
- /**
2729
- * Determine if the pipeline is fully prepared
2730
- *
2731
- * @public exported from `@promptbook/core`
2732
- */
2733
- function isPipelinePrepared(pipeline) {
2734
- // Note: Ignoring `pipeline.preparations` @@@
2735
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2736
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2737
- return false;
2738
- }
2739
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2740
- return false;
2741
- }
2742
- /*
2743
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2744
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2745
- > return false;
2746
- > }
2747
- */
2748
- return true;
2749
- }
2750
- /**
2751
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2752
- * TODO: [🐠] Maybe base this on `makeValidator`
2753
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2754
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2755
- * - [🏍] ? Is context in each template
2756
- * - [♨] Are samples prepared
2757
- * - [♨] Are templates prepared
2758
- */
2759
-
2760
- /**
2761
- * Takes an item or an array of items and returns an array of items
2762
- *
2763
- * 1) Any item except array and undefined returns array with that one item (also null)
2764
- * 2) Undefined returns empty array
2765
- * 3) Array returns itself
2766
- *
2767
- * @private internal utility
2576
+ * @param script from which to extract the variables
2577
+ * @returns the list of variable names
2578
+ * @throws {ParseError} if the script is invalid
2579
+ * @public exported from `@promptbook/utils`
2768
2580
  */
2769
- function arrayableToArray(input) {
2770
- if (input === undefined) {
2771
- return [];
2772
- }
2773
- if (input instanceof Array) {
2774
- return input;
2581
+ function extractVariables(script) {
2582
+ var variables = new Set();
2583
+ script = "(()=>{".concat(script, "})()");
2584
+ try {
2585
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2586
+ try {
2587
+ eval(script);
2588
+ }
2589
+ catch (error) {
2590
+ if (!(error instanceof ReferenceError)) {
2591
+ throw error;
2592
+ }
2593
+ var undefinedName = error.message.split(' ')[0];
2594
+ /*
2595
+ Note: Parsing the error
2596
+ [PipelineUrlError: thing is not defined]
2597
+ */
2598
+ if (!undefinedName) {
2599
+ throw error;
2600
+ }
2601
+ if (script.includes(undefinedName + '(')) {
2602
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2603
+ }
2604
+ else {
2605
+ variables.add(undefinedName);
2606
+ script = "const ".concat(undefinedName, " = '';") + script;
2607
+ }
2608
+ }
2775
2609
  }
2776
- return [input];
2777
- }
2778
-
2779
- /**
2780
- * Just says that the variable is not used but should be kept
2781
- * No side effects.
2782
- *
2783
- * Note: It can be usefull for:
2784
- *
2785
- * 1) Suppressing eager optimization of unused imports
2786
- * 2) Suppressing eslint errors of unused variables in the tests
2787
- * 3) Keeping the type of the variable for type testing
2788
- *
2789
- * @param value any values
2790
- * @returns void
2791
- * @private within the repository
2792
- */
2793
- function keepUnused() {
2794
- var valuesToKeep = [];
2795
- for (var _i = 0; _i < arguments.length; _i++) {
2796
- valuesToKeep[_i] = arguments[_i];
2610
+ catch (error) {
2611
+ if (!(error instanceof Error)) {
2612
+ throw error;
2613
+ }
2614
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2797
2615
  }
2616
+ return variables;
2798
2617
  }
2799
-
2800
2618
  /**
2801
- * Just marks a place of place where should be something implemented
2802
- * No side effects.
2803
- *
2804
- * Note: It can be usefull suppressing eslint errors of unused variables
2805
- *
2806
- * @param value any values
2807
- * @returns void
2808
- * @private within the repository
2619
+ * TODO: [🔣] Support for multiple languages - python, java,...
2809
2620
  */
2810
- function TODO_USE() {
2811
- var value = [];
2812
- for (var _i = 0; _i < arguments.length; _i++) {
2813
- value[_i] = arguments[_i];
2814
- }
2815
- }
2816
2621
 
2817
2622
  /**
2818
- * Replaces parameters in template with values from parameters object
2623
+ * Parses the template and returns the set of all used parameters
2819
2624
  *
2820
- * @param template the template with parameters in {curly} braces
2821
- * @param parameters the object with parameters
2822
- * @returns the template with replaced parameters
2823
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2625
+ * @param template the template with used parameters
2626
+ * @returns the set of parameter names
2627
+ * @throws {ParseError} if the script is invalid
2824
2628
  * @public exported from `@promptbook/utils`
2825
2629
  */
2826
- function replaceParameters(template, parameters) {
2827
- var e_1, _a;
2630
+ function extractParameterNamesFromTemplate(template) {
2631
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2632
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2633
+ var parameterNames = new Set();
2828
2634
  try {
2829
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2830
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2831
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2832
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2833
- }
2834
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2835
- // TODO: [🍵]
2836
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2837
- }
2635
+ 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()) {
2636
+ var parameterName = _f.value;
2637
+ parameterNames.add(parameterName);
2838
2638
  }
2839
2639
  }
2840
2640
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2841
2641
  finally {
2842
2642
  try {
2843
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2643
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2844
2644
  }
2845
2645
  finally { if (e_1) throw e_1.error; }
2846
2646
  }
2847
- var replacedTemplate = template;
2848
- var match;
2849
- var loopLimit = LOOP_LIMIT;
2850
- var _loop_1 = function () {
2851
- if (loopLimit-- < 0) {
2852
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2647
+ if (templateType === 'SCRIPT_TEMPLATE') {
2648
+ try {
2649
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2650
+ var parameterName = _h.value;
2651
+ parameterNames.add(parameterName);
2652
+ }
2853
2653
  }
2854
- var precol = match.groups.precol;
2855
- var parameterName = match.groups.parameterName;
2856
- if (parameterName === '') {
2857
- return "continue";
2654
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2655
+ finally {
2656
+ try {
2657
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2658
+ }
2659
+ finally { if (e_2) throw e_2.error; }
2858
2660
  }
2859
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2860
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2661
+ }
2662
+ try {
2663
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2664
+ var jokerName = _k.value;
2665
+ parameterNames.add(jokerName);
2861
2666
  }
2862
- if (parameters[parameterName] === undefined) {
2863
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2667
+ }
2668
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2669
+ finally {
2670
+ try {
2671
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2864
2672
  }
2865
- var parameterValue = parameters[parameterName];
2866
- if (parameterValue === undefined) {
2867
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2673
+ finally { if (e_3) throw e_3.error; }
2674
+ }
2675
+ parameterNames.delete('content');
2676
+ // <- Note {websiteContent} is used in `preparedContent`
2677
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2678
+ if (foreach !== undefined) {
2679
+ try {
2680
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2681
+ var subparameterName = _m.value;
2682
+ if (parameterNames.has(subparameterName)) {
2683
+ parameterNames.delete(subparameterName);
2684
+ parameterNames.add(foreach.parameterName);
2685
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2686
+ }
2687
+ }
2868
2688
  }
2869
- parameterValue = parameterValue.toString();
2870
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2871
- parameterValue = parameterValue
2872
- .split('\n')
2873
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2874
- .join('\n');
2689
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2690
+ finally {
2691
+ try {
2692
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2693
+ }
2694
+ finally { if (e_4) throw e_4.error; }
2875
2695
  }
2876
- replacedTemplate =
2877
- replacedTemplate.substring(0, match.index + precol.length) +
2878
- parameterValue +
2879
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2880
- };
2881
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2882
- .exec(replacedTemplate))) {
2883
- _loop_1();
2884
- }
2885
- // [💫] Check if there are parameters that are not closed properly
2886
- if (/{\w+$/.test(replacedTemplate)) {
2887
- throw new PipelineExecutionError('Parameter is not closed');
2888
2696
  }
2889
- // [💫] Check if there are parameters that are not opened properly
2890
- if (/^\w+}/.test(replacedTemplate)) {
2891
- throw new PipelineExecutionError('Parameter is not opened');
2892
- }
2893
- return replacedTemplate;
2697
+ return parameterNames;
2894
2698
  }
2699
+ /**
2700
+ * TODO: [🔣] If script require contentLanguage
2701
+ */
2895
2702
 
2896
2703
  /**
2897
2704
  * Create difference set of two sets.
@@ -2969,16 +2776,613 @@ function union() {
2969
2776
  }
2970
2777
 
2971
2778
  /**
2972
- * Counts number of characters in the text
2779
+ * Just marks a place of place where should be something implemented
2780
+ * No side effects.
2973
2781
  *
2974
- * @public exported from `@promptbook/utils`
2782
+ * Note: It can be usefull suppressing eslint errors of unused variables
2783
+ *
2784
+ * @param value any values
2785
+ * @returns void
2786
+ * @private within the repository
2975
2787
  */
2976
- function countCharacters(text) {
2977
- // Remove null characters
2978
- text = text.replace(/\0/g, '');
2979
- // Replace emojis (and also ZWJ sequence) with hyphens
2980
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2981
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2788
+ function TODO_USE() {
2789
+ var value = [];
2790
+ for (var _i = 0; _i < arguments.length; _i++) {
2791
+ value[_i] = arguments[_i];
2792
+ }
2793
+ }
2794
+
2795
+ /**
2796
+ * @@@
2797
+ *
2798
+ * @public exported from `@promptbook/core`
2799
+ */
2800
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2801
+ header: true,
2802
+ // encoding: 'utf8',
2803
+ });
2804
+
2805
+ /**
2806
+ * Definition for CSV spreadsheet
2807
+ *
2808
+ * @public exported from `@promptbook/core`
2809
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2810
+ */
2811
+ var CsvFormatDefinition = {
2812
+ formatName: 'CSV',
2813
+ aliases: ['SPREADSHEET', 'TABLE'],
2814
+ isValid: function (value, settings, schema) {
2815
+ // TODO: !!!!!! Implement CSV validation
2816
+ TODO_USE(value /* <- TODO: Use value here */);
2817
+ TODO_USE(settings /* <- TODO: Use settings here */);
2818
+ TODO_USE(schema /* <- TODO: Use schema here */);
2819
+ return true;
2820
+ },
2821
+ canBeValid: function (partialValue, settings, schema) {
2822
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2823
+ TODO_USE(settings /* <- TODO: Use settings here */);
2824
+ TODO_USE(schema /* <- TODO: Use schema here */);
2825
+ return true;
2826
+ },
2827
+ heal: function (value, settings, schema) {
2828
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2829
+ TODO_USE(settings /* <- TODO: Use settings here */);
2830
+ TODO_USE(schema /* <- TODO: Use schema here */);
2831
+ throw new Error('Not implemented');
2832
+ },
2833
+ subvalueDefinitions: [
2834
+ {
2835
+ subvalueName: 'ROW',
2836
+ mapValues: function (value, settings, mapCallback) {
2837
+ return __awaiter(this, void 0, void 0, function () {
2838
+ var csv, mappedData;
2839
+ var _this = this;
2840
+ return __generator(this, function (_a) {
2841
+ switch (_a.label) {
2842
+ case 0:
2843
+ csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2844
+ if (csv.errors.length !== 0) {
2845
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2846
+ spaceTrim$1(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2847
+ }
2848
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2849
+ var _a;
2850
+ var _b;
2851
+ return __generator(this, function (_c) {
2852
+ switch (_c.label) {
2853
+ case 0:
2854
+ _a = [__assign({}, row)];
2855
+ _b = {};
2856
+ // <- TODO: !!!!!! Dynamic new column name and position
2857
+ // <- TODO: !!!!!! Check name collisions
2858
+ return [4 /*yield*/, mapCallback(row, index)];
2859
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2860
+ // <- TODO: !!!!!! Dynamic new column name and position
2861
+ // <- TODO: !!!!!! Check name collisions
2862
+ _c.sent(), _b)])))];
2863
+ }
2864
+ });
2865
+ }); }))];
2866
+ case 1:
2867
+ mappedData = _a.sent();
2868
+ return [2 /*return*/, unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2869
+ }
2870
+ });
2871
+ });
2872
+ },
2873
+ },
2874
+ {
2875
+ subvalueName: 'CELL',
2876
+ mapValues: function (value, settings, mapCallback) {
2877
+ return __awaiter(this, void 0, void 0, function () {
2878
+ var csv, mappedData;
2879
+ var _this = this;
2880
+ return __generator(this, function (_a) {
2881
+ switch (_a.label) {
2882
+ case 0:
2883
+ csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2884
+ if (csv.errors.length !== 0) {
2885
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2886
+ spaceTrim$1(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2887
+ }
2888
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2889
+ var _this = this;
2890
+ return __generator(this, function (_a) {
2891
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2892
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2893
+ return __awaiter(_this, void 0, void 0, function () {
2894
+ var index;
2895
+ var _c;
2896
+ return __generator(this, function (_d) {
2897
+ index = rowIndex * Object.keys(row).length + columnIndex;
2898
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2899
+ });
2900
+ });
2901
+ }))];
2902
+ });
2903
+ }); }))];
2904
+ case 1:
2905
+ mappedData = _a.sent();
2906
+ return [2 /*return*/, unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2907
+ }
2908
+ });
2909
+ });
2910
+ },
2911
+ },
2912
+ ],
2913
+ };
2914
+ /**
2915
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2916
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2917
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2918
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2919
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2920
+ */
2921
+
2922
+ /**
2923
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2924
+ *
2925
+ * @public exported from `@promptbook/utils`
2926
+ */
2927
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2928
+ try {
2929
+ JSON.parse(value);
2930
+ return true;
2931
+ }
2932
+ catch (error) {
2933
+ if (!(error instanceof Error)) {
2934
+ throw error;
2935
+ }
2936
+ if (error.message.includes('Unexpected token')) {
2937
+ return false;
2938
+ }
2939
+ return false;
2940
+ }
2941
+ }
2942
+
2943
+ /**
2944
+ * Definition for JSON format
2945
+ *
2946
+ * @private still in development [🏢]
2947
+ */
2948
+ var JsonFormatDefinition = {
2949
+ formatName: 'JSON',
2950
+ mimeType: 'application/json',
2951
+ isValid: function (value, settings, schema) {
2952
+ TODO_USE(schema /* <- TODO: Use schema here */);
2953
+ TODO_USE(settings /* <- TODO: Use settings here */);
2954
+ return isValidJsonString(value);
2955
+ },
2956
+ canBeValid: function (partialValue, settings, schema) {
2957
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2958
+ TODO_USE(settings /* <- TODO: Use settings here */);
2959
+ TODO_USE(schema /* <- TODO: Use schema here */);
2960
+ return true;
2961
+ },
2962
+ heal: function (value, settings, schema) {
2963
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2964
+ TODO_USE(settings /* <- TODO: Use settings here */);
2965
+ TODO_USE(schema /* <- TODO: Use schema here */);
2966
+ throw new Error('Not implemented');
2967
+ },
2968
+ subvalueDefinitions: [],
2969
+ };
2970
+ /**
2971
+ * TODO: [🧠] Maybe propper instance of object
2972
+ * TODO: [0] Make string_serialized_json
2973
+ * TODO: [1] Make type for JSON Settings and Schema
2974
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2975
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2976
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2977
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2978
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2979
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2980
+ */
2981
+
2982
+ /**
2983
+ * Definition for any text - this will be always valid
2984
+ *
2985
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
2986
+ *
2987
+ * @public exported from `@promptbook/core`
2988
+ */
2989
+ var TextFormatDefinition = {
2990
+ formatName: 'TEXT',
2991
+ isValid: function (value) {
2992
+ return typeof value === 'string';
2993
+ },
2994
+ canBeValid: function (partialValue) {
2995
+ return typeof partialValue === 'string';
2996
+ },
2997
+ heal: function () {
2998
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
2999
+ },
3000
+ subvalueDefinitions: [
3001
+ {
3002
+ subvalueName: 'LINE',
3003
+ mapValues: function (value, settings, mapCallback) {
3004
+ return __awaiter(this, void 0, void 0, function () {
3005
+ var lines, mappedLines;
3006
+ return __generator(this, function (_a) {
3007
+ switch (_a.label) {
3008
+ case 0:
3009
+ lines = value.split('\n');
3010
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3011
+ // TODO: [🧠] Maybe option to skip empty line
3012
+ /* not await */ return mapCallback({
3013
+ lineContent: lineContent,
3014
+ // TODO: [🧠] Maybe also put here `lineNumber`
3015
+ }, lineNumber);
3016
+ }))];
3017
+ case 1:
3018
+ mappedLines = _a.sent();
3019
+ return [2 /*return*/, mappedLines.join('\n')];
3020
+ }
3021
+ });
3022
+ });
3023
+ },
3024
+ },
3025
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3026
+ ],
3027
+ };
3028
+ /**
3029
+ * TODO: [1] Make type for XML Text and Schema
3030
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3031
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3032
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3033
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3034
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3035
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3036
+ */
3037
+
3038
+ /**
3039
+ * Definition for XML format
3040
+ *
3041
+ * @private still in development [🏢]
3042
+ */
3043
+ var XmlFormatDefinition = {
3044
+ formatName: 'XML',
3045
+ mimeType: 'application/xml',
3046
+ isValid: function (value, settings, schema) {
3047
+ TODO_USE(value /* <- TODO: Use value here */);
3048
+ TODO_USE(settings /* <- TODO: Use settings here */);
3049
+ TODO_USE(schema /* <- TODO: Use schema here */);
3050
+ return true;
3051
+ },
3052
+ canBeValid: function (partialValue, settings, schema) {
3053
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3054
+ TODO_USE(settings /* <- TODO: Use settings here */);
3055
+ TODO_USE(schema /* <- TODO: Use schema here */);
3056
+ return true;
3057
+ },
3058
+ heal: function (value, settings, schema) {
3059
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3060
+ TODO_USE(settings /* <- TODO: Use settings here */);
3061
+ TODO_USE(schema /* <- TODO: Use schema here */);
3062
+ throw new Error('Not implemented');
3063
+ },
3064
+ subvalueDefinitions: [],
3065
+ };
3066
+ /**
3067
+ * TODO: [🧠] Maybe propper instance of object
3068
+ * TODO: [0] Make string_serialized_xml
3069
+ * TODO: [1] Make type for XML Settings and Schema
3070
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3071
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3072
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3073
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3074
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3075
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3076
+ */
3077
+
3078
+ /**
3079
+ * Definitions for all formats supported by Promptbook
3080
+ *
3081
+ * @private internal index of `...` <- TODO [🏢]
3082
+ */
3083
+ var FORMAT_DEFINITIONS = [
3084
+ JsonFormatDefinition,
3085
+ XmlFormatDefinition,
3086
+ TextFormatDefinition,
3087
+ CsvFormatDefinition,
3088
+ ];
3089
+
3090
+ /**
3091
+ * Maps available parameters to expected parameters
3092
+ *
3093
+ * The strategy is:
3094
+ * 1) @@@
3095
+ * 2) @@@
3096
+ *
3097
+ * @throws {PipelineExecutionError} @@@
3098
+ * @private within the repository used in `createPipelineExecutor`
3099
+ */
3100
+ function mapAvailableToExpectedParameters(options) {
3101
+ var e_1, _a;
3102
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3103
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3104
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3105
+ var mappedParameters = {};
3106
+ try {
3107
+ // Phase 1️⃣: Matching mapping
3108
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3109
+ var parameterName = _c.value;
3110
+ // Situation: Parameter is available and expected
3111
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3112
+ mappedParameters[parameterName] = availableParameters[parameterName];
3113
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3114
+ availableParametersNames.delete(parameterName);
3115
+ expectedParameterNames.delete(parameterName);
3116
+ }
3117
+ // Situation: Parameter is available but NOT expected
3118
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3119
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3120
+ }
3121
+ // Situation: Parameter is NOT available BUT expected
3122
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3123
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3124
+ }
3125
+ }
3126
+ }
3127
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3128
+ finally {
3129
+ try {
3130
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3131
+ }
3132
+ finally { if (e_1) throw e_1.error; }
3133
+ }
3134
+ if (expectedParameterNames.size === 0) {
3135
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3136
+ Object.freeze(mappedParameters);
3137
+ return mappedParameters;
3138
+ }
3139
+ // Phase 2️⃣: Non-matching mapping
3140
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3141
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3142
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3143
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3144
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3145
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3146
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3147
+ .join('\n')), "\n\n "); }));
3148
+ }
3149
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3150
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3151
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3152
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3153
+ }
3154
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3155
+ Object.freeze(mappedParameters);
3156
+ return mappedParameters;
3157
+ }
3158
+
3159
+ /**
3160
+ * Extracts all code blocks from markdown.
3161
+ *
3162
+ * Note: There are multiple simmilar function:
3163
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3164
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3165
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3166
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3167
+ *
3168
+ * @param markdown any valid markdown
3169
+ * @returns code blocks with language and content
3170
+ * @throws {ParseError} if block is not closed properly
3171
+ * @public exported from `@promptbook/markdown-utils`
3172
+ */
3173
+ function extractAllBlocksFromMarkdown(markdown) {
3174
+ var e_1, _a;
3175
+ var codeBlocks = [];
3176
+ var lines = markdown.split('\n');
3177
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3178
+ lines.push('');
3179
+ var currentCodeBlock = null;
3180
+ try {
3181
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3182
+ var line = lines_1_1.value;
3183
+ if (line.startsWith('> ') || line === '>') {
3184
+ if (currentCodeBlock === null) {
3185
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3186
+ } /* not else */
3187
+ if (currentCodeBlock.blockNotation === '>') {
3188
+ if (currentCodeBlock.content !== '') {
3189
+ currentCodeBlock.content += '\n';
3190
+ }
3191
+ currentCodeBlock.content += line.slice(2);
3192
+ }
3193
+ }
3194
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3195
+ codeBlocks.push(currentCodeBlock);
3196
+ currentCodeBlock = null;
3197
+ }
3198
+ /* not else */
3199
+ if (line.startsWith('```')) {
3200
+ var language = line.slice(3).trim() || null;
3201
+ if (currentCodeBlock === null) {
3202
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3203
+ }
3204
+ else {
3205
+ if (language !== null) {
3206
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3207
+ }
3208
+ codeBlocks.push(currentCodeBlock);
3209
+ currentCodeBlock = null;
3210
+ }
3211
+ }
3212
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3213
+ if (currentCodeBlock.content !== '') {
3214
+ currentCodeBlock.content += '\n';
3215
+ }
3216
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3217
+ }
3218
+ }
3219
+ }
3220
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3221
+ finally {
3222
+ try {
3223
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3224
+ }
3225
+ finally { if (e_1) throw e_1.error; }
3226
+ }
3227
+ if (currentCodeBlock !== null) {
3228
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3229
+ }
3230
+ return codeBlocks;
3231
+ }
3232
+ /**
3233
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3234
+ */
3235
+
3236
+ /**
3237
+ * Extracts extracts exactly one valid JSON code block
3238
+ *
3239
+ * - When given string is a valid JSON as it is, it just returns it
3240
+ * - When there is no JSON code block the function throws a `ParseError`
3241
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3242
+ *
3243
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3244
+ * Note: There are multiple simmilar function:
3245
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3246
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3247
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3248
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3249
+ *
3250
+ * @public exported from `@promptbook/markdown-utils`
3251
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3252
+ */
3253
+ function extractJsonBlock(markdown) {
3254
+ if (isValidJsonString(markdown)) {
3255
+ return markdown;
3256
+ }
3257
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3258
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3259
+ var content = _a.content;
3260
+ return isValidJsonString(content);
3261
+ });
3262
+ if (jsonBlocks.length === 0) {
3263
+ throw new Error('There is no valid JSON block in the markdown');
3264
+ }
3265
+ if (jsonBlocks.length > 1) {
3266
+ throw new Error('There are multiple JSON code blocks in the markdown');
3267
+ }
3268
+ return jsonBlocks[0].content;
3269
+ }
3270
+ /**
3271
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3272
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3273
+ */
3274
+
3275
+ /**
3276
+ * Just says that the variable is not used but should be kept
3277
+ * No side effects.
3278
+ *
3279
+ * Note: It can be usefull for:
3280
+ *
3281
+ * 1) Suppressing eager optimization of unused imports
3282
+ * 2) Suppressing eslint errors of unused variables in the tests
3283
+ * 3) Keeping the type of the variable for type testing
3284
+ *
3285
+ * @param value any values
3286
+ * @returns void
3287
+ * @private within the repository
3288
+ */
3289
+ function keepUnused() {
3290
+ var valuesToKeep = [];
3291
+ for (var _i = 0; _i < arguments.length; _i++) {
3292
+ valuesToKeep[_i] = arguments[_i];
3293
+ }
3294
+ }
3295
+
3296
+ /**
3297
+ * Replaces parameters in template with values from parameters object
3298
+ *
3299
+ * @param template the template with parameters in {curly} braces
3300
+ * @param parameters the object with parameters
3301
+ * @returns the template with replaced parameters
3302
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3303
+ * @public exported from `@promptbook/utils`
3304
+ */
3305
+ function replaceParameters(template, parameters) {
3306
+ var e_1, _a;
3307
+ try {
3308
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3309
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3310
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3311
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3312
+ }
3313
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3314
+ // TODO: [🍵]
3315
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3316
+ }
3317
+ }
3318
+ }
3319
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3320
+ finally {
3321
+ try {
3322
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3323
+ }
3324
+ finally { if (e_1) throw e_1.error; }
3325
+ }
3326
+ var replacedTemplate = template;
3327
+ var match;
3328
+ var loopLimit = LOOP_LIMIT;
3329
+ var _loop_1 = function () {
3330
+ if (loopLimit-- < 0) {
3331
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3332
+ }
3333
+ var precol = match.groups.precol;
3334
+ var parameterName = match.groups.parameterName;
3335
+ if (parameterName === '') {
3336
+ return "continue";
3337
+ }
3338
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3339
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3340
+ }
3341
+ if (parameters[parameterName] === undefined) {
3342
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3343
+ }
3344
+ var parameterValue = parameters[parameterName];
3345
+ if (parameterValue === undefined) {
3346
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3347
+ }
3348
+ parameterValue = parameterValue.toString();
3349
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3350
+ parameterValue = parameterValue
3351
+ .split('\n')
3352
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3353
+ .join('\n');
3354
+ }
3355
+ replacedTemplate =
3356
+ replacedTemplate.substring(0, match.index + precol.length) +
3357
+ parameterValue +
3358
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3359
+ };
3360
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3361
+ .exec(replacedTemplate))) {
3362
+ _loop_1();
3363
+ }
3364
+ // [💫] Check if there are parameters that are not closed properly
3365
+ if (/{\w+$/.test(replacedTemplate)) {
3366
+ throw new PipelineExecutionError('Parameter is not closed');
3367
+ }
3368
+ // [💫] Check if there are parameters that are not opened properly
3369
+ if (/^\w+}/.test(replacedTemplate)) {
3370
+ throw new PipelineExecutionError('Parameter is not opened');
3371
+ }
3372
+ return replacedTemplate;
3373
+ }
3374
+
3375
+ /**
3376
+ * Counts number of characters in the text
3377
+ *
3378
+ * @public exported from `@promptbook/utils`
3379
+ */
3380
+ function countCharacters(text) {
3381
+ // Remove null characters
3382
+ text = text.replace(/\0/g, '');
3383
+ // Replace emojis (and also ZWJ sequence) with hyphens
3384
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3385
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2982
3386
  text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
2983
3387
  return text.length;
2984
3388
  }
@@ -3025,62 +3429,789 @@ function splitIntoSentences(text) {
3025
3429
  return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3026
3430
  }
3027
3431
  /**
3028
- * Counts number of sentences in the text
3432
+ * Counts number of sentences in the text
3433
+ *
3434
+ * @public exported from `@promptbook/utils`
3435
+ */
3436
+ function countSentences(text) {
3437
+ return splitIntoSentences(text).length;
3438
+ }
3439
+
3440
+ /**
3441
+ * Counts number of words in the text
3442
+ *
3443
+ * @public exported from `@promptbook/utils`
3444
+ */
3445
+ function countWords(text) {
3446
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3447
+ text = removeDiacritics(text);
3448
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3449
+ }
3450
+
3451
+ /**
3452
+ * Index of all counter functions
3453
+ *
3454
+ * @public exported from `@promptbook/utils`
3455
+ */
3456
+ var CountUtils = {
3457
+ CHARACTERS: countCharacters,
3458
+ WORDS: countWords,
3459
+ SENTENCES: countSentences,
3460
+ PARAGRAPHS: countParagraphs,
3461
+ LINES: countLines,
3462
+ PAGES: countPages,
3463
+ };
3464
+ /**
3465
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3466
+ */
3467
+
3468
+ /**
3469
+ * Function checkExpectations will check if the expectations on given value are met
3470
+ *
3471
+ * Note: There are two simmilar functions:
3472
+ * - `checkExpectations` which throws an error if the expectations are not met
3473
+ * - `isPassingExpectations` which returns a boolean
3474
+ *
3475
+ * @throws {ExpectError} if the expectations are not met
3476
+ * @returns {void} Nothing
3477
+ * @private internal function of `createPipelineExecutor`
3478
+ */
3479
+ function checkExpectations(expectations, value) {
3480
+ var e_1, _a;
3481
+ try {
3482
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3483
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3484
+ var amount = CountUtils[unit.toUpperCase()](value);
3485
+ if (min && amount < min) {
3486
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3487
+ } /* not else */
3488
+ if (max && amount > max) {
3489
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3490
+ }
3491
+ }
3492
+ }
3493
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3494
+ finally {
3495
+ try {
3496
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3497
+ }
3498
+ finally { if (e_1) throw e_1.error; }
3499
+ }
3500
+ }
3501
+ /**
3502
+ * TODO: [💝] Unite object for expecting amount and format
3503
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3504
+ * Note: [💝] and [🤠] are interconnected together
3505
+ */
3506
+
3507
+ /**
3508
+ * @@@
3509
+ *
3510
+ * @private internal utility of `createPipelineExecutor`
3511
+ */
3512
+ function executeAttempts(options) {
3513
+ return __awaiter(this, void 0, void 0, function () {
3514
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3515
+ return __generator(this, function (_a) {
3516
+ switch (_a.label) {
3517
+ case 0:
3518
+ 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;
3519
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3520
+ $ongoingTemplateResult = {
3521
+ $result: null,
3522
+ $resultString: null,
3523
+ $expectError: null,
3524
+ $scriptPipelineExecutionErrors: [],
3525
+ };
3526
+ _loop_1 = function (attempt) {
3527
+ 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;
3528
+ var e_1, _q, e_3, _r, e_2, _s;
3529
+ return __generator(this, function (_t) {
3530
+ switch (_t.label) {
3531
+ case 0:
3532
+ isJokerAttempt = attempt < 0;
3533
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3534
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3535
+ if (isJokerAttempt && !jokerParameterName) {
3536
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3537
+ }
3538
+ $ongoingTemplateResult.$result = null;
3539
+ $ongoingTemplateResult.$resultString = null;
3540
+ $ongoingTemplateResult.$expectError = null;
3541
+ if (isJokerAttempt) {
3542
+ if (parameters[jokerParameterName] === undefined) {
3543
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3544
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3545
+ }
3546
+ else {
3547
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3548
+ }
3549
+ }
3550
+ _t.label = 1;
3551
+ case 1:
3552
+ _t.trys.push([1, 43, 44, 45]);
3553
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3554
+ _b = template.templateType;
3555
+ switch (_b) {
3556
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3557
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3558
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3559
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3560
+ }
3561
+ return [3 /*break*/, 24];
3562
+ case 2:
3563
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3564
+ return [3 /*break*/, 25];
3565
+ case 3:
3566
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3567
+ $ongoingTemplateResult.$prompt = {
3568
+ title: template.title,
3569
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3570
+ ? preparedPipeline.pipelineUrl
3571
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3572
+ parameters: parameters,
3573
+ content: preparedContent,
3574
+ modelRequirements: modelRequirements,
3575
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3576
+ var name = _a.name;
3577
+ return name === template.personaName;
3578
+ }) ||
3579
+ {})), template.expectations),
3580
+ format: template.format,
3581
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3582
+ }; // <- TODO: Not very good type guard
3583
+ _c = modelRequirements.modelVariant;
3584
+ switch (_c) {
3585
+ case 'CHAT': return [3 /*break*/, 4];
3586
+ case 'COMPLETION': return [3 /*break*/, 6];
3587
+ case 'EMBEDDING': return [3 /*break*/, 8];
3588
+ }
3589
+ return [3 /*break*/, 9];
3590
+ case 4:
3591
+ _d = $ongoingTemplateResult;
3592
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3593
+ case 5:
3594
+ _d.$chatResult = _t.sent();
3595
+ // TODO: [🍬] Destroy chatThread
3596
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3597
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3598
+ return [3 /*break*/, 10];
3599
+ case 6:
3600
+ _e = $ongoingTemplateResult;
3601
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3602
+ case 7:
3603
+ _e.$completionResult = _t.sent();
3604
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3605
+ $ongoingTemplateResult.$resultString =
3606
+ $ongoingTemplateResult.$completionResult.content;
3607
+ return [3 /*break*/, 10];
3608
+ case 8: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Embedding model can not be used in pipeline\n\n This should be catched during parsing\n\n ".concat(block(pipelineIdentification), "\n\n "); }));
3609
+ case 9: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3610
+ case 10: return [3 /*break*/, 25];
3611
+ case 11:
3612
+ if (arrayableToArray(tools.script).length === 0) {
3613
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3614
+ }
3615
+ if (!template.contentLanguage) {
3616
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3617
+ }
3618
+ _t.label = 12;
3619
+ case 12:
3620
+ _t.trys.push([12, 19, 20, 21]);
3621
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3622
+ _t.label = 13;
3623
+ case 13:
3624
+ if (!!_g.done) return [3 /*break*/, 18];
3625
+ scriptTools = _g.value;
3626
+ _t.label = 14;
3627
+ case 14:
3628
+ _t.trys.push([14, 16, , 17]);
3629
+ _h = $ongoingTemplateResult;
3630
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3631
+ scriptLanguage: template.contentLanguage,
3632
+ script: preparedContent,
3633
+ parameters: parameters,
3634
+ }))];
3635
+ case 15:
3636
+ _h.$resultString = _t.sent();
3637
+ return [3 /*break*/, 18];
3638
+ case 16:
3639
+ error_1 = _t.sent();
3640
+ if (!(error_1 instanceof Error)) {
3641
+ throw error_1;
3642
+ }
3643
+ if (error_1 instanceof UnexpectedError) {
3644
+ throw error_1;
3645
+ }
3646
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3647
+ return [3 /*break*/, 17];
3648
+ case 17:
3649
+ _g = _f.next();
3650
+ return [3 /*break*/, 13];
3651
+ case 18: return [3 /*break*/, 21];
3652
+ case 19:
3653
+ e_1_1 = _t.sent();
3654
+ e_1 = { error: e_1_1 };
3655
+ return [3 /*break*/, 21];
3656
+ case 20:
3657
+ try {
3658
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3659
+ }
3660
+ finally { if (e_1) throw e_1.error; }
3661
+ return [7 /*endfinally*/];
3662
+ case 21:
3663
+ if ($ongoingTemplateResult.$resultString !== null) {
3664
+ return [3 /*break*/, 25];
3665
+ }
3666
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3667
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3668
+ }
3669
+ else {
3670
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3671
+ .map(function (error) { return '- ' + error.message; })
3672
+ .join('\n\n')), "\n "); }));
3673
+ }
3674
+ case 22:
3675
+ if (tools.userInterface === undefined) {
3676
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3677
+ }
3678
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3679
+ _j = $ongoingTemplateResult;
3680
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3681
+ promptTitle: template.title,
3682
+ promptMessage: replaceParameters(template.description || '', parameters),
3683
+ defaultValue: replaceParameters(preparedContent, parameters),
3684
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3685
+ placeholder: undefined,
3686
+ priority: priority,
3687
+ }))];
3688
+ case 23:
3689
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3690
+ _j.$resultString = _t.sent();
3691
+ return [3 /*break*/, 25];
3692
+ case 24: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3693
+ case 25:
3694
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3695
+ _t.label = 26;
3696
+ case 26:
3697
+ _t.trys.push([26, 40, 41, 42]);
3698
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3699
+ _t.label = 27;
3700
+ case 27:
3701
+ if (!!_l.done) return [3 /*break*/, 39];
3702
+ functionName = _l.value;
3703
+ postprocessingError = null;
3704
+ _t.label = 28;
3705
+ case 28:
3706
+ _t.trys.push([28, 35, 36, 37]);
3707
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3708
+ _t.label = 29;
3709
+ case 29:
3710
+ if (!!_o.done) return [3 /*break*/, 34];
3711
+ scriptTools = _o.value;
3712
+ _t.label = 30;
3713
+ case 30:
3714
+ _t.trys.push([30, 32, , 33]);
3715
+ _p = $ongoingTemplateResult;
3716
+ return [4 /*yield*/, scriptTools.execute({
3717
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3718
+ script: "".concat(functionName, "(resultString)"),
3719
+ parameters: {
3720
+ resultString: $ongoingTemplateResult.$resultString || '',
3721
+ // Note: No ...parametersForTemplate, because working with result only
3722
+ },
3723
+ })];
3724
+ case 31:
3725
+ _p.$resultString = _t.sent();
3726
+ postprocessingError = null;
3727
+ return [3 /*break*/, 34];
3728
+ case 32:
3729
+ error_2 = _t.sent();
3730
+ if (!(error_2 instanceof Error)) {
3731
+ throw error_2;
3732
+ }
3733
+ if (error_2 instanceof UnexpectedError) {
3734
+ throw error_2;
3735
+ }
3736
+ postprocessingError = error_2;
3737
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3738
+ return [3 /*break*/, 33];
3739
+ case 33:
3740
+ _o = _m.next();
3741
+ return [3 /*break*/, 29];
3742
+ case 34: return [3 /*break*/, 37];
3743
+ case 35:
3744
+ e_2_1 = _t.sent();
3745
+ e_2 = { error: e_2_1 };
3746
+ return [3 /*break*/, 37];
3747
+ case 36:
3748
+ try {
3749
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3750
+ }
3751
+ finally { if (e_2) throw e_2.error; }
3752
+ return [7 /*endfinally*/];
3753
+ case 37:
3754
+ if (postprocessingError) {
3755
+ throw postprocessingError;
3756
+ }
3757
+ _t.label = 38;
3758
+ case 38:
3759
+ _l = _k.next();
3760
+ return [3 /*break*/, 27];
3761
+ case 39: return [3 /*break*/, 42];
3762
+ case 40:
3763
+ e_3_1 = _t.sent();
3764
+ e_3 = { error: e_3_1 };
3765
+ return [3 /*break*/, 42];
3766
+ case 41:
3767
+ try {
3768
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3769
+ }
3770
+ finally { if (e_3) throw e_3.error; }
3771
+ return [7 /*endfinally*/];
3772
+ case 42:
3773
+ // TODO: [💝] Unite object for expecting amount and format
3774
+ if (template.format) {
3775
+ if (template.format === 'JSON') {
3776
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3777
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3778
+ try {
3779
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3780
+ }
3781
+ catch (error) {
3782
+ keepUnused(error);
3783
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3784
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3785
+ }
3786
+ }
3787
+ }
3788
+ else {
3789
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3790
+ }
3791
+ }
3792
+ // TODO: [💝] Unite object for expecting amount and format
3793
+ if (template.expectations) {
3794
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3795
+ }
3796
+ return [2 /*return*/, "break-attempts"];
3797
+ case 43:
3798
+ error_3 = _t.sent();
3799
+ if (!(error_3 instanceof ExpectError)) {
3800
+ throw error_3;
3801
+ }
3802
+ $ongoingTemplateResult.$expectError = error_3;
3803
+ return [3 /*break*/, 45];
3804
+ case 44:
3805
+ if (!isJokerAttempt &&
3806
+ template.templateType === 'PROMPT_TEMPLATE' &&
3807
+ $ongoingTemplateResult.$prompt
3808
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3809
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3810
+ ) {
3811
+ // TODO: [🧠] Maybe put other templateTypes into report
3812
+ $executionReport.promptExecutions.push({
3813
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3814
+ result: $ongoingTemplateResult.$result || undefined,
3815
+ error: $ongoingTemplateResult.$expectError === null
3816
+ ? undefined
3817
+ : serializeError($ongoingTemplateResult.$expectError),
3818
+ });
3819
+ }
3820
+ return [7 /*endfinally*/];
3821
+ case 45:
3822
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3823
+ throw new PipelineExecutionError(spaceTrim(function (block) {
3824
+ var _a, _b, _c;
3825
+ 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) || '')
3826
+ .split('\n')
3827
+ .map(function (line) { return "> ".concat(line); })
3828
+ .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) || '')
3829
+ .split('\n')
3830
+ .map(function (line) { return "> ".concat(line); })
3831
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3832
+ ? 'null'
3833
+ : $ongoingTemplateResult.$resultString
3834
+ .split('\n')
3835
+ .map(function (line) { return "> ".concat(line); })
3836
+ .join('\n')), "\n ---\n ");
3837
+ }));
3838
+ }
3839
+ return [2 /*return*/];
3840
+ }
3841
+ });
3842
+ };
3843
+ attempt = -jokerParameterNames.length;
3844
+ _a.label = 1;
3845
+ case 1:
3846
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3847
+ return [5 /*yield**/, _loop_1(attempt)];
3848
+ case 2:
3849
+ state_1 = _a.sent();
3850
+ switch (state_1) {
3851
+ case "break-attempts": return [3 /*break*/, 4];
3852
+ }
3853
+ _a.label = 3;
3854
+ case 3:
3855
+ attempt++;
3856
+ return [3 /*break*/, 1];
3857
+ case 4:
3858
+ if ($ongoingTemplateResult.$resultString === null) {
3859
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3860
+ }
3861
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3862
+ }
3863
+ });
3864
+ });
3865
+ }
3866
+ /**
3867
+ * TODO: Break into smaller functions
3868
+ */
3869
+
3870
+ /**
3871
+ * @@@
3872
+ *
3873
+ * @private internal utility of `createPipelineExecutor`
3874
+ */
3875
+ function executeFormatCells(options) {
3876
+ return __awaiter(this, void 0, void 0, function () {
3877
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
3878
+ var _this = this;
3879
+ return __generator(this, function (_a) {
3880
+ switch (_a.label) {
3881
+ case 0:
3882
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3883
+ if (template.foreach === undefined) {
3884
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3885
+ }
3886
+ if (jokerParameterNames.length !== 0) {
3887
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n JOKER parameters are not supported together with FOREACH command\n\n [\uD83E\uDDDE\u200D\u2640\uFE0F] This should be prevented in `validatePipeline`\n\n ".concat(block(pipelineIdentification), "\n "); }));
3888
+ }
3889
+ parameterValue = parameters[template.foreach.parameterName] || '';
3890
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3891
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3892
+ });
3893
+ if (formatDefinition === undefined) {
3894
+ throw new UnexpectedError(
3895
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3896
+ spaceTrim$1(function (block) { return "\n Unsupported format \"".concat(template.foreach.formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
3897
+ .map(function (formatName) { return "- ".concat(formatName); })
3898
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3899
+ }
3900
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3901
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
3902
+ });
3903
+ if (subvalueDefinition === undefined) {
3904
+ throw new UnexpectedError(
3905
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3906
+ spaceTrim$1(function (block) { return "\n Unsupported subformat name \"".concat(template.foreach.subformatName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
3907
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3908
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3909
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3910
+ }
3911
+ if (formatDefinition.formatName === 'CSV') {
3912
+ formatSettings = settings.csvSettings;
3913
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
3914
+ }
3915
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3916
+ var mappedParameters, allSubparameters, subresultString;
3917
+ return __generator(this, function (_a) {
3918
+ switch (_a.label) {
3919
+ case 0:
3920
+ // TODO: !!!!!!! Limit to N concurrent executions
3921
+ // TODO: !!!!!!! Report progress
3922
+ try {
3923
+ mappedParameters = mapAvailableToExpectedParameters({
3924
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3925
+ availableParameters: subparameters,
3926
+ });
3927
+ }
3928
+ catch (error) {
3929
+ if (!(error instanceof PipelineExecutionError)) {
3930
+ throw error;
3931
+ }
3932
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n ".concat(error.message, "\n\n This is error in FOREACH command\n You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command\n\n ").concat(block(pipelineIdentification), "\n "); }));
3933
+ }
3934
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3935
+ // 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
3936
+ Object.freeze(allSubparameters);
3937
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3938
+ case 1:
3939
+ subresultString = _a.sent();
3940
+ return [2 /*return*/, subresultString];
3941
+ }
3942
+ });
3943
+ }); })];
3944
+ case 1:
3945
+ resultString = _a.sent();
3946
+ return [2 /*return*/, resultString];
3947
+ }
3948
+ });
3949
+ });
3950
+ }
3951
+ /**
3952
+ * TODO: !!!!!! Make pipelineIdentification more precise
3953
+ * TODO: !!!!!! How FOREACH execution looks in the report
3954
+ */
3955
+
3956
+ /**
3957
+ * @@@
3958
+ *
3959
+ * @private internal utility of `createPipelineExecutor`
3960
+ */
3961
+ function getContextForTemplate(template) {
3962
+ return __awaiter(this, void 0, void 0, function () {
3963
+ return __generator(this, function (_a) {
3964
+ TODO_USE(template);
3965
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3966
+ });
3967
+ });
3968
+ }
3969
+
3970
+ /**
3971
+ * @@@
3972
+ *
3973
+ * @private internal utility of `createPipelineExecutor`
3974
+ */
3975
+ function getKnowledgeForTemplate(options) {
3976
+ return __awaiter(this, void 0, void 0, function () {
3977
+ var preparedPipeline, template;
3978
+ return __generator(this, function (_a) {
3979
+ preparedPipeline = options.preparedPipeline, template = options.template;
3980
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3981
+ TODO_USE(template);
3982
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3983
+ var content = _a.content;
3984
+ return "- ".concat(content);
3985
+ }).join('\n')];
3986
+ });
3987
+ });
3988
+ }
3989
+
3990
+ /**
3991
+ * @@@
3992
+ *
3993
+ * @private internal utility of `createPipelineExecutor`
3994
+ */
3995
+ function getSamplesForTemplate(template) {
3996
+ return __awaiter(this, void 0, void 0, function () {
3997
+ return __generator(this, function (_a) {
3998
+ // TODO: [♨] Implement Better - use real index and keyword search
3999
+ TODO_USE(template);
4000
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4001
+ });
4002
+ });
4003
+ }
4004
+
4005
+ /**
4006
+ * @@@
3029
4007
  *
3030
- * @public exported from `@promptbook/utils`
4008
+ * @private internal utility of `createPipelineExecutor`
3031
4009
  */
3032
- function countSentences(text) {
3033
- return splitIntoSentences(text).length;
4010
+ function getReservedParametersForTemplate(options) {
4011
+ return __awaiter(this, void 0, void 0, function () {
4012
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4013
+ var e_1, _a;
4014
+ return __generator(this, function (_b) {
4015
+ switch (_b.label) {
4016
+ case 0:
4017
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4018
+ return [4 /*yield*/, getContextForTemplate(template)];
4019
+ case 1:
4020
+ context = _b.sent();
4021
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4022
+ case 2:
4023
+ knowledge = _b.sent();
4024
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4025
+ case 3:
4026
+ samples = _b.sent();
4027
+ currentDate = new Date().toISOString();
4028
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4029
+ reservedParameters = {
4030
+ content: RESERVED_PARAMETER_RESTRICTED,
4031
+ context: context,
4032
+ knowledge: knowledge,
4033
+ samples: samples,
4034
+ currentDate: currentDate,
4035
+ modelName: modelName,
4036
+ };
4037
+ _loop_1 = function (parameterName) {
4038
+ if (reservedParameters[parameterName] === undefined) {
4039
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4040
+ }
4041
+ };
4042
+ try {
4043
+ // Note: Doublecheck that ALL reserved parameters are defined:
4044
+ 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()) {
4045
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4046
+ _loop_1(parameterName);
4047
+ }
4048
+ }
4049
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4050
+ finally {
4051
+ try {
4052
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4053
+ }
4054
+ finally { if (e_1) throw e_1.error; }
4055
+ }
4056
+ return [2 /*return*/, reservedParameters];
4057
+ }
4058
+ });
4059
+ });
3034
4060
  }
3035
4061
 
3036
4062
  /**
3037
- * Counts number of words in the text
4063
+ * @@@
3038
4064
  *
3039
- * @public exported from `@promptbook/utils`
4065
+ * @private internal utility of `createPipelineExecutor`
3040
4066
  */
3041
- function countWords(text) {
3042
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3043
- text = removeDiacritics(text);
3044
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
4067
+ function executeTemplate(options) {
4068
+ return __awaiter(this, void 0, void 0, function () {
4069
+ 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;
4070
+ var e_1, _f, _g;
4071
+ return __generator(this, function (_h) {
4072
+ switch (_h.label) {
4073
+ case 0:
4074
+ 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;
4075
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4076
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4077
+ title = currentTemplate.title;
4078
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4079
+ return [4 /*yield*/, onProgress({
4080
+ name: name,
4081
+ title: title,
4082
+ isStarted: false,
4083
+ isDone: false,
4084
+ templateType: currentTemplate.templateType,
4085
+ parameterName: currentTemplate.resultingParameterName,
4086
+ parameterValue: null,
4087
+ // <- [🍸]
4088
+ })];
4089
+ case 1:
4090
+ _h.sent();
4091
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4092
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4093
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4094
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4095
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
4096
+ .map(function (name) { return "{".concat(name, "}"); })
4097
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4098
+ .map(function (name) { return "{".concat(name, "}"); })
4099
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4100
+ }
4101
+ _b = (_a = Object).freeze;
4102
+ _c = [{}];
4103
+ return [4 /*yield*/, getReservedParametersForTemplate({
4104
+ preparedPipeline: preparedPipeline,
4105
+ template: currentTemplate,
4106
+ pipelineIdentification: pipelineIdentification,
4107
+ })];
4108
+ case 2:
4109
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4110
+ definedParameterNames = new Set(Object.keys(definedParameters));
4111
+ parameters = {};
4112
+ _loop_1 = function (parameterName) {
4113
+ // Situation: Parameter is defined and used
4114
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4115
+ parameters[parameterName] = definedParameters[parameterName];
4116
+ }
4117
+ // Situation: Parameter is defined but NOT used
4118
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4119
+ // Situation: Parameter is NOT defined BUT used
4120
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4121
+ // Houston, we have a problem
4122
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4123
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4124
+ }
4125
+ };
4126
+ try {
4127
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4128
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4129
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4130
+ parameterName = _e.value;
4131
+ _loop_1(parameterName);
4132
+ }
4133
+ }
4134
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4135
+ finally {
4136
+ try {
4137
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4138
+ }
4139
+ finally { if (e_1) throw e_1.error; }
4140
+ }
4141
+ // 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
4142
+ Object.freeze(parameters);
4143
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4144
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4145
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4146
+ .split('{content}')
4147
+ .join(currentTemplate.content);
4148
+ return [4 /*yield*/, executeFormatCells({
4149
+ jokerParameterNames: jokerParameterNames,
4150
+ priority: priority,
4151
+ maxAttempts: maxAttempts,
4152
+ preparedContent: preparedContent,
4153
+ parameters: parameters,
4154
+ template: currentTemplate,
4155
+ preparedPipeline: preparedPipeline,
4156
+ tools: tools,
4157
+ llmTools: llmTools,
4158
+ settings: settings,
4159
+ $executionReport: $executionReport,
4160
+ pipelineIdentification: pipelineIdentification,
4161
+ })];
4162
+ case 3:
4163
+ resultString = _h.sent();
4164
+ return [4 /*yield*/, onProgress({
4165
+ name: name,
4166
+ title: title,
4167
+ isStarted: true,
4168
+ isDone: true,
4169
+ templateType: currentTemplate.templateType,
4170
+ parameterName: currentTemplate.resultingParameterName,
4171
+ parameterValue: resultString,
4172
+ // <- [🍸]
4173
+ })];
4174
+ case 4:
4175
+ _h.sent();
4176
+ return [2 /*return*/, Object.freeze((_g = {},
4177
+ _g[currentTemplate.resultingParameterName] =
4178
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4179
+ resultString,
4180
+ _g))];
4181
+ }
4182
+ });
4183
+ });
3045
4184
  }
3046
-
3047
4185
  /**
3048
- * Index of all counter functions
3049
- *
3050
- * @public exported from `@promptbook/utils`
4186
+ * TODO: [🤹‍♂️]
3051
4187
  */
3052
- var CountUtils = {
3053
- CHARACTERS: countCharacters,
3054
- WORDS: countWords,
3055
- SENTENCES: countSentences,
3056
- PARAGRAPHS: countParagraphs,
3057
- LINES: countLines,
3058
- PAGES: countPages,
3059
- };
3060
4188
 
3061
4189
  /**
3062
- * Function checkExpectations will check if the expectations on given value are met
3063
- *
3064
- * Note: There are two simmilar functions:
3065
- * - `checkExpectations` which throws an error if the expectations are not met
3066
- * - `isPassingExpectations` which returns a boolean
4190
+ * @@@
3067
4191
  *
3068
- * @throws {ExpectError} if the expectations are not met
3069
- * @returns {void} Nothing
3070
- * @private internal function of `createPipelineExecutor`
4192
+ * @private internal utility of `createPipelineExecutor`
3071
4193
  */
3072
- function checkExpectations(expectations, value) {
4194
+ function filterJustOutputParameters(options) {
3073
4195
  var e_1, _a;
4196
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4197
+ var outputParameters = {};
4198
+ var _loop_1 = function (parameter) {
4199
+ if (parametersToPass[parameter.name] === undefined) {
4200
+ // [4]
4201
+ $warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
4202
+ return "continue";
4203
+ }
4204
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4205
+ };
3074
4206
  try {
3075
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3076
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3077
- var amount = CountUtils[unit.toUpperCase()](value);
3078
- if (min && amount < min) {
3079
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3080
- } /* not else */
3081
- if (max && amount > max) {
3082
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3083
- }
4207
+ // Note: Filter ONLY output parameters
4208
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4209
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4210
+ var isOutput = _a.isOutput;
4211
+ return isOutput;
4212
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4213
+ var parameter = _c.value;
4214
+ _loop_1(parameter);
3084
4215
  }
3085
4216
  }
3086
4217
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3090,600 +4221,27 @@ function checkExpectations(expectations, value) {
3090
4221
  }
3091
4222
  finally { if (e_1) throw e_1.error; }
3092
4223
  }
4224
+ return outputParameters;
3093
4225
  }
3094
- /**
3095
- * TODO: [💝] Unite object for expecting amount and format
3096
- */
3097
4226
 
3098
4227
  /**
3099
- * Creates executor function from pipeline and execution tools.
4228
+ * @@@
3100
4229
  *
3101
- * @returns The executor function
3102
- * @throws {PipelineLogicError} on logical error in the pipeline
3103
- * @public exported from `@promptbook/core`
4230
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4231
+ *
4232
+ * @private internal utility of `createPipelineExecutor`
3104
4233
  */
3105
- function createPipelineExecutor(options) {
3106
- var _this = this;
3107
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3108
- 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;
3109
- validatePipeline(pipeline);
3110
- var pipelineIdentification = (function () {
3111
- // Note: This is a 😐 implementation of [🚞]
3112
- var _ = [];
3113
- if (pipeline.sourceFile !== undefined) {
3114
- _.push("File: ".concat(pipeline.sourceFile));
3115
- }
3116
- if (pipeline.pipelineUrl !== undefined) {
3117
- _.push("Url: ".concat(pipeline.pipelineUrl));
3118
- }
3119
- return _.join('\n');
3120
- })();
3121
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3122
- var preparedPipeline;
3123
- if (isPipelinePrepared(pipeline)) {
3124
- preparedPipeline = pipeline;
3125
- }
3126
- else if (isNotPreparedWarningSupressed !== true) {
3127
- console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3128
- }
3129
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3130
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3131
- function getContextForTemplate(template) {
3132
- return __awaiter(this, void 0, void 0, function () {
3133
- return __generator(this, function (_a) {
3134
- TODO_USE(template);
3135
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3136
- });
3137
- });
3138
- }
3139
- function getKnowledgeForTemplate(template) {
3140
- return __awaiter(this, void 0, void 0, function () {
3141
- return __generator(this, function (_a) {
3142
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3143
- TODO_USE(template);
3144
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3145
- var content = _a.content;
3146
- return "- ".concat(content);
3147
- }).join('\n')];
3148
- });
3149
- });
3150
- }
3151
- function getSamplesForTemplate(template) {
3152
- return __awaiter(this, void 0, void 0, function () {
3153
- return __generator(this, function (_a) {
3154
- // TODO: [♨] Implement Better - use real index and keyword search
3155
- TODO_USE(template);
3156
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3157
- });
3158
- });
3159
- }
3160
- function getReservedParametersForTemplate(template) {
3161
- return __awaiter(this, void 0, void 0, function () {
3162
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3163
- var e_3, _a;
3164
- return __generator(this, function (_b) {
3165
- switch (_b.label) {
3166
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3167
- case 1:
3168
- context = _b.sent();
3169
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3170
- case 2:
3171
- knowledge = _b.sent();
3172
- return [4 /*yield*/, getSamplesForTemplate(template)];
3173
- case 3:
3174
- samples = _b.sent();
3175
- currentDate = new Date().toISOString();
3176
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3177
- reservedParameters = {
3178
- content: RESERVED_PARAMETER_RESTRICTED,
3179
- context: context,
3180
- knowledge: knowledge,
3181
- samples: samples,
3182
- currentDate: currentDate,
3183
- modelName: modelName,
3184
- };
3185
- _loop_3 = function (parameterName) {
3186
- if (reservedParameters[parameterName] === undefined) {
3187
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3188
- }
3189
- };
3190
- try {
3191
- // Note: Doublecheck that ALL reserved parameters are defined:
3192
- 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()) {
3193
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3194
- _loop_3(parameterName);
3195
- }
3196
- }
3197
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3198
- finally {
3199
- try {
3200
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3201
- }
3202
- finally { if (e_3) throw e_3.error; }
3203
- }
3204
- return [2 /*return*/, reservedParameters];
3205
- }
3206
- });
3207
- });
3208
- }
3209
- function executeSingleTemplate(currentTemplate) {
3210
- return __awaiter(this, void 0, void 0, function () {
3211
- 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;
3212
- var e_4, _f, _g;
3213
- return __generator(this, function (_h) {
3214
- switch (_h.label) {
3215
- case 0:
3216
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3217
- title = currentTemplate.title;
3218
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3219
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3220
- progress_1 = {
3221
- name: name,
3222
- title: title,
3223
- isStarted: false,
3224
- isDone: false,
3225
- templateType: currentTemplate.templateType,
3226
- parameterName: currentTemplate.resultingParameterName,
3227
- parameterValue: null,
3228
- // <- [3]
3229
- };
3230
- if (isReturned) {
3231
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3232
- .split('\n')
3233
- .map(function (line) { return "> ".concat(line); })
3234
- .join('\n')), "\n "); }));
3235
- }
3236
- return [4 /*yield*/, onProgress(progress_1)];
3237
- case 1:
3238
- _h.sent();
3239
- _h.label = 2;
3240
- case 2:
3241
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3242
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3243
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3244
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3245
- .map(function (name) { return "{".concat(name, "}"); })
3246
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3247
- .map(function (name) { return "{".concat(name, "}"); })
3248
- .join(', '), "\n\n "); }));
3249
- }
3250
- _b = (_a = Object).freeze;
3251
- _c = [{}];
3252
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3253
- case 3:
3254
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3255
- definedParameterNames = new Set(Object.keys(definedParameters));
3256
- parameters = {};
3257
- _loop_4 = function (parameterName) {
3258
- // Situation: Parameter is defined and used
3259
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3260
- parameters[parameterName] = definedParameters[parameterName];
3261
- }
3262
- // Situation: Parameter is defined but NOT used
3263
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3264
- // Situation: Parameter is NOT defined BUT used
3265
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3266
- // Houston, we have a problem
3267
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3268
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3269
- }
3270
- };
3271
- try {
3272
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3273
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3274
- parameterName = _e.value;
3275
- _loop_4(parameterName);
3276
- }
3277
- }
3278
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3279
- finally {
3280
- try {
3281
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3282
- }
3283
- finally { if (e_4) throw e_4.error; }
3284
- }
3285
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3286
- Object.freeze(parameters);
3287
- result = null;
3288
- resultString = null;
3289
- expectError = null;
3290
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3291
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3292
- preparedContent = (currentTemplate.preparedContent || '{content}')
3293
- .split('{content}')
3294
- .join(currentTemplate.content);
3295
- _loop_5 = function (attempt) {
3296
- 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;
3297
- var e_5, _s, e_7, _t, e_6, _u;
3298
- return __generator(this, function (_v) {
3299
- switch (_v.label) {
3300
- case 0:
3301
- isJokerAttempt = attempt < 0;
3302
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3303
- if (isJokerAttempt && !jokerParameterName) {
3304
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3305
- }
3306
- result = null;
3307
- resultString = null;
3308
- expectError = null;
3309
- if (isJokerAttempt) {
3310
- if (parameters[jokerParameterName] === undefined) {
3311
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3312
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3313
- }
3314
- else {
3315
- resultString = parameters[jokerParameterName];
3316
- }
3317
- }
3318
- _v.label = 1;
3319
- case 1:
3320
- _v.trys.push([1, 44, 45, 46]);
3321
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3322
- _j = currentTemplate.templateType;
3323
- switch (_j) {
3324
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3325
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3326
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3327
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3328
- }
3329
- return [3 /*break*/, 25];
3330
- case 2:
3331
- resultString = replaceParameters(preparedContent, parameters);
3332
- return [3 /*break*/, 26];
3333
- case 3:
3334
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3335
- prompt = {
3336
- title: currentTemplate.title,
3337
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3338
- ? preparedPipeline.pipelineUrl
3339
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3340
- parameters: parameters,
3341
- content: preparedContent,
3342
- modelRequirements: modelRequirements,
3343
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3344
- var name = _a.name;
3345
- return name === currentTemplate.personaName;
3346
- }) || {})), currentTemplate.expectations),
3347
- format: currentTemplate.format,
3348
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3349
- }; // <- TODO: Not very good type guard
3350
- _k = modelRequirements.modelVariant;
3351
- switch (_k) {
3352
- case 'CHAT': return [3 /*break*/, 4];
3353
- case 'COMPLETION': return [3 /*break*/, 6];
3354
- case 'EMBEDDING': return [3 /*break*/, 8];
3355
- }
3356
- return [3 /*break*/, 10];
3357
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3358
- case 5:
3359
- chatResult = _v.sent();
3360
- // TODO: [🍬] Destroy chatThread
3361
- result = chatResult;
3362
- resultString = chatResult.content;
3363
- return [3 /*break*/, 11];
3364
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3365
- case 7:
3366
- completionResult = _v.sent();
3367
- result = completionResult;
3368
- resultString = completionResult.content;
3369
- return [3 /*break*/, 11];
3370
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3371
- case 9:
3372
- embeddingResult = _v.sent();
3373
- result = embeddingResult;
3374
- resultString = embeddingResult.content.join(',');
3375
- return [3 /*break*/, 11];
3376
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3377
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3378
- case 11: return [3 /*break*/, 26];
3379
- case 12:
3380
- if (arrayableToArray(tools.script).length === 0) {
3381
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3382
- }
3383
- if (!currentTemplate.contentLanguage) {
3384
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3385
- }
3386
- // TODO: DRY [1]
3387
- scriptPipelineExecutionErrors = [];
3388
- _v.label = 13;
3389
- case 13:
3390
- _v.trys.push([13, 20, 21, 22]);
3391
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3392
- _v.label = 14;
3393
- case 14:
3394
- if (!!_m.done) return [3 /*break*/, 19];
3395
- scriptTools = _m.value;
3396
- _v.label = 15;
3397
- case 15:
3398
- _v.trys.push([15, 17, , 18]);
3399
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3400
- scriptLanguage: currentTemplate.contentLanguage,
3401
- script: preparedContent,
3402
- parameters: parameters,
3403
- }))];
3404
- case 16:
3405
- resultString = _v.sent();
3406
- return [3 /*break*/, 19];
3407
- case 17:
3408
- error_2 = _v.sent();
3409
- if (!(error_2 instanceof Error)) {
3410
- throw error_2;
3411
- }
3412
- if (error_2 instanceof UnexpectedError) {
3413
- throw error_2;
3414
- }
3415
- scriptPipelineExecutionErrors.push(error_2);
3416
- return [3 /*break*/, 18];
3417
- case 18:
3418
- _m = _l.next();
3419
- return [3 /*break*/, 14];
3420
- case 19: return [3 /*break*/, 22];
3421
- case 20:
3422
- e_5_1 = _v.sent();
3423
- e_5 = { error: e_5_1 };
3424
- return [3 /*break*/, 22];
3425
- case 21:
3426
- try {
3427
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3428
- }
3429
- finally { if (e_5) throw e_5.error; }
3430
- return [7 /*endfinally*/];
3431
- case 22:
3432
- if (resultString !== null) {
3433
- return [3 /*break*/, 26];
3434
- }
3435
- if (scriptPipelineExecutionErrors.length === 1) {
3436
- throw scriptPipelineExecutionErrors[0];
3437
- }
3438
- else {
3439
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3440
- .map(function (error) { return '- ' + error.message; })
3441
- .join('\n\n')), "\n "); }));
3442
- }
3443
- case 23:
3444
- if (tools.userInterface === undefined) {
3445
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3446
- }
3447
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3448
- promptTitle: currentTemplate.title,
3449
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3450
- defaultValue: replaceParameters(preparedContent, parameters),
3451
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3452
- placeholder: undefined,
3453
- priority: priority,
3454
- }))];
3455
- case 24:
3456
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3457
- resultString = _v.sent();
3458
- return [3 /*break*/, 26];
3459
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3460
- case 26:
3461
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3462
- _v.label = 27;
3463
- case 27:
3464
- _v.trys.push([27, 41, 42, 43]);
3465
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3466
- _v.label = 28;
3467
- case 28:
3468
- if (!!_p.done) return [3 /*break*/, 40];
3469
- functionName = _p.value;
3470
- // TODO: DRY [1]
3471
- scriptPipelineExecutionErrors = [];
3472
- postprocessingError = null;
3473
- _v.label = 29;
3474
- case 29:
3475
- _v.trys.push([29, 36, 37, 38]);
3476
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3477
- _v.label = 30;
3478
- case 30:
3479
- if (!!_r.done) return [3 /*break*/, 35];
3480
- scriptTools = _r.value;
3481
- _v.label = 31;
3482
- case 31:
3483
- _v.trys.push([31, 33, , 34]);
3484
- return [4 /*yield*/, scriptTools.execute({
3485
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3486
- script: "".concat(functionName, "(resultString)"),
3487
- parameters: {
3488
- resultString: resultString || '',
3489
- // Note: No ...parametersForTemplate, because working with result only
3490
- },
3491
- })];
3492
- case 32:
3493
- resultString = _v.sent();
3494
- postprocessingError = null;
3495
- return [3 /*break*/, 35];
3496
- case 33:
3497
- error_3 = _v.sent();
3498
- if (!(error_3 instanceof Error)) {
3499
- throw error_3;
3500
- }
3501
- if (error_3 instanceof UnexpectedError) {
3502
- throw error_3;
3503
- }
3504
- postprocessingError = error_3;
3505
- scriptPipelineExecutionErrors.push(error_3);
3506
- return [3 /*break*/, 34];
3507
- case 34:
3508
- _r = _q.next();
3509
- return [3 /*break*/, 30];
3510
- case 35: return [3 /*break*/, 38];
3511
- case 36:
3512
- e_6_1 = _v.sent();
3513
- e_6 = { error: e_6_1 };
3514
- return [3 /*break*/, 38];
3515
- case 37:
3516
- try {
3517
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3518
- }
3519
- finally { if (e_6) throw e_6.error; }
3520
- return [7 /*endfinally*/];
3521
- case 38:
3522
- if (postprocessingError) {
3523
- throw postprocessingError;
3524
- }
3525
- _v.label = 39;
3526
- case 39:
3527
- _p = _o.next();
3528
- return [3 /*break*/, 28];
3529
- case 40: return [3 /*break*/, 43];
3530
- case 41:
3531
- e_7_1 = _v.sent();
3532
- e_7 = { error: e_7_1 };
3533
- return [3 /*break*/, 43];
3534
- case 42:
3535
- try {
3536
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3537
- }
3538
- finally { if (e_7) throw e_7.error; }
3539
- return [7 /*endfinally*/];
3540
- case 43:
3541
- // TODO: [💝] Unite object for expecting amount and format
3542
- if (currentTemplate.format) {
3543
- if (currentTemplate.format === 'JSON') {
3544
- if (!isValidJsonString(resultString || '')) {
3545
- // TODO: [🏢] Do more universally via `FormatDefinition`
3546
- try {
3547
- resultString = extractJsonBlock(resultString || '');
3548
- }
3549
- catch (error) {
3550
- keepUnused(error);
3551
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3552
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3553
- }
3554
- }
3555
- }
3556
- else {
3557
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3558
- }
3559
- }
3560
- // TODO: [💝] Unite object for expecting amount and format
3561
- if (currentTemplate.expectations) {
3562
- checkExpectations(currentTemplate.expectations, resultString || '');
3563
- }
3564
- return [2 /*return*/, "break-attempts"];
3565
- case 44:
3566
- error_4 = _v.sent();
3567
- if (!(error_4 instanceof ExpectError)) {
3568
- throw error_4;
3569
- }
3570
- expectError = error_4;
3571
- return [3 /*break*/, 46];
3572
- case 45:
3573
- if (!isJokerAttempt &&
3574
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3575
- prompt
3576
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3577
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3578
- ) {
3579
- // TODO: [🧠] Maybe put other templateTypes into report
3580
- executionReport.promptExecutions.push({
3581
- prompt: __assign({}, prompt),
3582
- result: result || undefined,
3583
- error: expectError === null ? undefined : serializeError(expectError),
3584
- });
3585
- }
3586
- return [7 /*endfinally*/];
3587
- case 46:
3588
- if (expectError !== null && attempt === maxAttempts - 1) {
3589
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3590
- .split('\n')
3591
- .map(function (line) { return "> ".concat(line); })
3592
- .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) || '')
3593
- .split('\n')
3594
- .map(function (line) { return "> ".concat(line); })
3595
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3596
- ? 'null'
3597
- : resultString
3598
- .split('\n')
3599
- .map(function (line) { return "> ".concat(line); })
3600
- .join('\n')), "\n ---\n "); }));
3601
- }
3602
- return [2 /*return*/];
3603
- }
3604
- });
3605
- };
3606
- attempt = -jokerParameterNames.length;
3607
- _h.label = 4;
3608
- case 4:
3609
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3610
- return [5 /*yield**/, _loop_5(attempt)];
3611
- case 5:
3612
- state_2 = _h.sent();
3613
- switch (state_2) {
3614
- case "break-attempts": return [3 /*break*/, 7];
3615
- }
3616
- _h.label = 6;
3617
- case 6:
3618
- attempt++;
3619
- return [3 /*break*/, 4];
3620
- case 7:
3621
- if (resultString === null) {
3622
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3623
- }
3624
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3625
- progress_2 = {
3626
- name: name,
3627
- title: title,
3628
- isStarted: true,
3629
- isDone: true,
3630
- templateType: currentTemplate.templateType,
3631
- parameterName: currentTemplate.resultingParameterName,
3632
- parameterValue: resultString,
3633
- // <- [3]
3634
- };
3635
- if (isReturned) {
3636
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3637
- .split('\n')
3638
- .map(function (line) { return "> ".concat(line); })
3639
- .join('\n')), "\n\n "); }));
3640
- }
3641
- return [4 /*yield*/, onProgress(progress_2)];
3642
- case 8:
3643
- _h.sent();
3644
- _h.label = 9;
3645
- case 9:
3646
- 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)));
3647
- return [2 /*return*/];
3648
- }
3649
- });
3650
- });
3651
- }
3652
- function filterJustOutputParameters() {
3653
- var e_8, _a;
3654
- var outputParameters = {};
3655
- var _loop_6 = function (parameter) {
3656
- if (parametersToPass[parameter.name] === undefined) {
3657
- // [4]
3658
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3659
- return "continue";
3660
- }
3661
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3662
- };
3663
- try {
3664
- // Note: Filter ONLY output parameters
3665
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3666
- var isOutput = _a.isOutput;
3667
- return isOutput;
3668
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3669
- var parameter = _c.value;
3670
- _loop_6(parameter);
3671
- }
3672
- }
3673
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3674
- finally {
3675
- try {
3676
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3677
- }
3678
- finally { if (e_8) throw e_8.error; }
3679
- }
3680
- return outputParameters;
3681
- }
3682
- 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;
4234
+ function executePipeline(options) {
4235
+ return __awaiter(this, void 0, void 0, function () {
4236
+ 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;
3683
4237
  var e_1, _e, e_2, _f;
3684
4238
  return __generator(this, function (_g) {
3685
4239
  switch (_g.label) {
3686
4240
  case 0:
4241
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4242
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4243
+ preparedPipeline = options.preparedPipeline;
4244
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3687
4245
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3688
4246
  return [4 /*yield*/, preparePipeline(pipeline, {
3689
4247
  llmTools: llmTools,
@@ -3692,6 +4250,7 @@ function createPipelineExecutor(options) {
3692
4250
  })];
3693
4251
  case 1:
3694
4252
  preparedPipeline = _g.sent();
4253
+ setPreparedPipeline(preparedPipeline);
3695
4254
  _g.label = 2;
3696
4255
  case 2:
3697
4256
  errors = [];
@@ -3761,7 +4320,7 @@ function createPipelineExecutor(options) {
3761
4320
  return name === parameterName;
3762
4321
  });
3763
4322
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3764
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4323
+ warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3765
4324
  return [3 /*break*/, 4];
3766
4325
  case 1:
3767
4326
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3773,10 +4332,10 @@ function createPipelineExecutor(options) {
3773
4332
  // Note: Wait a short time to prevent race conditions
3774
4333
  _h.sent();
3775
4334
  _h.label = 3;
3776
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4335
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3777
4336
  isSuccessful: false,
3778
4337
  errors: __spreadArray([
3779
- new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4338
+ new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3780
4339
  ], __read(errors), false).map(serializeError),
3781
4340
  warnings: warnings.map(serializeError),
3782
4341
  executionReport: executionReport,
@@ -3840,7 +4399,7 @@ function createPipelineExecutor(options) {
3840
4399
  case 0:
3841
4400
  if (loopLimit-- < 0) {
3842
4401
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3843
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4402
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3844
4403
  }
3845
4404
  currentTemplate = unresovedTemplates_1.find(function (template) {
3846
4405
  return template.dependentParameterNames.every(function (name) {
@@ -3850,29 +4409,52 @@ function createPipelineExecutor(options) {
3850
4409
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3851
4410
  throw new UnexpectedError(
3852
4411
  // TODO: [🐎] DRY
3853
- 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
4412
+ 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
3854
4413
  .map(function (_a) {
3855
4414
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3856
4415
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3857
4416
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3858
4417
  .join(' and '));
3859
4418
  })
3860
- .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 "); }));
4419
+ .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 "); }));
3861
4420
  case 1:
3862
4421
  if (!!currentTemplate) return [3 /*break*/, 3];
3863
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4422
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3864
4423
  case 2:
3865
- /* [5] */ _j.sent();
4424
+ /* [🤹‍♂️] */ _j.sent();
3866
4425
  return [3 /*break*/, 4];
3867
4426
  case 3:
3868
4427
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3869
- work_1 = executeSingleTemplate(currentTemplate)
3870
- .then(function () {
4428
+ work_1 = executeTemplate({
4429
+ currentTemplate: currentTemplate,
4430
+ preparedPipeline: preparedPipeline,
4431
+ parametersToPass: parametersToPass,
4432
+ tools: tools,
4433
+ llmTools: llmTools,
4434
+ onProgress: function (progress) {
4435
+ if (isReturned) {
4436
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4437
+ .split('\n')
4438
+ .map(function (line) { return "> ".concat(line); })
4439
+ .join('\n')), "\n "); }));
4440
+ }
4441
+ if (onProgress) {
4442
+ onProgress(progress);
4443
+ }
4444
+ },
4445
+ settings: settings,
4446
+ $executionReport: executionReport,
4447
+ pipelineIdentification: pipelineIdentification,
4448
+ })
4449
+ .then(function (newParametersToPass) {
4450
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3871
4451
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3872
4452
  })
3873
4453
  .then(function () {
3874
4454
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3875
4455
  });
4456
+ // <- Note: Errors are catched here [3]
4457
+ // 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
3876
4458
  resolving_1.push(work_1);
3877
4459
  _j.label = 4;
3878
4460
  case 4: return [2 /*return*/];
@@ -3899,7 +4481,12 @@ function createPipelineExecutor(options) {
3899
4481
  var result = _a.result;
3900
4482
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3901
4483
  })), false));
3902
- outputParameters_1 = filterJustOutputParameters();
4484
+ outputParameters_1 = filterJustOutputParameters({
4485
+ preparedPipeline: preparedPipeline,
4486
+ parametersToPass: parametersToPass,
4487
+ $warnings: warnings,
4488
+ pipelineIdentification: pipelineIdentification,
4489
+ });
3903
4490
  isReturned = true;
3904
4491
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3905
4492
  // Note: Wait a short time to prevent race conditions
@@ -3922,7 +4509,12 @@ function createPipelineExecutor(options) {
3922
4509
  var result = _a.result;
3923
4510
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3924
4511
  })), false));
3925
- outputParameters = filterJustOutputParameters();
4512
+ outputParameters = filterJustOutputParameters({
4513
+ preparedPipeline: preparedPipeline,
4514
+ parametersToPass: parametersToPass,
4515
+ $warnings: warnings,
4516
+ pipelineIdentification: pipelineIdentification,
4517
+ });
3926
4518
  isReturned = true;
3927
4519
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3928
4520
  // Note: Wait a short time to prevent race conditions
@@ -3942,22 +4534,63 @@ function createPipelineExecutor(options) {
3942
4534
  })];
3943
4535
  }
3944
4536
  });
4537
+ });
4538
+ }
4539
+
4540
+ /**
4541
+ * Creates executor function from pipeline and execution tools.
4542
+ *
4543
+ * @returns The executor function
4544
+ * @throws {PipelineLogicError} on logical error in the pipeline
4545
+ * @public exported from `@promptbook/core`
4546
+ */
4547
+ function createPipelineExecutor(options) {
4548
+ var _this = this;
4549
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4550
+ 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;
4551
+ validatePipeline(pipeline);
4552
+ var pipelineIdentification = (function () {
4553
+ // Note: This is a 😐 implementation of [🚞]
4554
+ var _ = [];
4555
+ if (pipeline.sourceFile !== undefined) {
4556
+ _.push("File: ".concat(pipeline.sourceFile));
4557
+ }
4558
+ if (pipeline.pipelineUrl !== undefined) {
4559
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4560
+ }
4561
+ return _.join('\n');
4562
+ })();
4563
+ var preparedPipeline;
4564
+ if (isPipelinePrepared(pipeline)) {
4565
+ preparedPipeline = pipeline;
4566
+ }
4567
+ else if (isNotPreparedWarningSupressed !== true) {
4568
+ console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4569
+ }
4570
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4571
+ return __generator(this, function (_a) {
4572
+ return [2 /*return*/, executePipeline({
4573
+ pipeline: pipeline,
4574
+ preparedPipeline: preparedPipeline,
4575
+ setPreparedPipeline: function (newPreparedPipeline) {
4576
+ preparedPipeline = newPreparedPipeline;
4577
+ },
4578
+ inputParameters: inputParameters,
4579
+ tools: tools,
4580
+ onProgress: onProgress,
4581
+ pipelineIdentification: pipelineIdentification,
4582
+ settings: {
4583
+ maxExecutionAttempts: maxExecutionAttempts,
4584
+ maxParallelCount: maxParallelCount,
4585
+ csvSettings: csvSettings,
4586
+ isVerbose: isVerbose,
4587
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4588
+ },
4589
+ })];
4590
+ });
3945
4591
  }); };
3946
4592
  return pipelineExecutor;
3947
4593
  }
3948
- /**
3949
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3950
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3951
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3952
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3953
- * TODO: [♈] Probbably move expectations from templates to parameters
3954
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3955
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3956
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3957
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3958
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3959
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
3960
- */
3961
4594
 
3962
4595
  /**
3963
4596
  * @@@
@@ -4009,7 +4642,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4009
4642
  outputParameters = result.outputParameters;
4010
4643
  knowledgePiecesRaw = outputParameters.knowledgePieces;
4011
4644
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4012
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4645
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4013
4646
  if (isVerbose) {
4014
4647
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
4015
4648
  }
@@ -4067,8 +4700,13 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4067
4700
  case 6: return [3 /*break*/, 8];
4068
4701
  case 7:
4069
4702
  error_1 = _c.sent();
4703
+ // Note: Here is expected error:
4704
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4705
+ if (!(error_1 instanceof PipelineExecutionError)) {
4706
+ throw error_1;
4707
+ }
4070
4708
  // TODO: [🟥] Detect browser / node and make it colorfull
4071
- console.error(error_1);
4709
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4072
4710
  return [3 /*break*/, 8];
4073
4711
  case 8: return [2 /*return*/, {
4074
4712
  name: name,
@@ -4089,7 +4727,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4089
4727
  });
4090
4728
  }
4091
4729
  /**
4092
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4730
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4093
4731
  * TODO: [🪂] Do it in parallel 11:11
4094
4732
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4095
4733
  */
@@ -4113,7 +4751,7 @@ function prepareKnowledgePieces(knowledgeSources, options) {
4113
4751
  var partialPieces, pieces;
4114
4752
  return __generator(this, function (_a) {
4115
4753
  switch (_a.label) {
4116
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4754
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4117
4755
  options)];
4118
4756
  case 1:
4119
4757
  partialPieces = _a.sent();
@@ -4305,7 +4943,7 @@ function preparePersona(personaDescription, options) {
4305
4943
  });
4306
4944
  }
4307
4945
  /**
4308
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4946
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4309
4947
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4310
4948
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4311
4949
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4354,7 +4992,7 @@ function prepareTemplates(pipeline, options) {
4354
4992
  case 0:
4355
4993
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4356
4994
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4357
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
4995
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4358
4996
  TODO_USE(parameters);
4359
4997
  templatesPrepared = new Array(
4360
4998
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4386,7 +5024,7 @@ function prepareTemplates(pipeline, options) {
4386
5024
  /**
4387
5025
  * TODO: [🧠] Add context to each template (if missing)
4388
5026
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4389
- * TODO: [♨] !!! Prepare index the samples and maybe templates
5027
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4390
5028
  * TODO: Write tests for `preparePipeline`
4391
5029
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4392
5030
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4558,7 +5196,7 @@ var knowledgeCommandParser = {
4558
5196
  if (sourceContent === '') {
4559
5197
  throw new ParseError("Source is not defined");
4560
5198
  }
4561
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5199
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4562
5200
  if (sourceContent.startsWith('http://')) {
4563
5201
  throw new ParseError("Source is not secure");
4564
5202
  }
@@ -4761,7 +5399,7 @@ var templateCommandParser = {
4761
5399
  if (command.templateType === 'KNOWLEDGE') {
4762
5400
  knowledgeCommandParser.$applyToPipelineJson({
4763
5401
  type: 'KNOWLEDGE',
4764
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5402
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4765
5403
  }, $pipelineJson);
4766
5404
  $templateJson.isTemplate = false;
4767
5405
  return;
@@ -5111,6 +5749,171 @@ function normalizeTo_SCREAMING_CASE(text) {
5111
5749
  * TODO: [🌺] Use some intermediate util splitWords
5112
5750
  */
5113
5751
 
5752
+ /**
5753
+ * @@@
5754
+ *
5755
+ * @param text @@@
5756
+ * @param _isFirstLetterCapital @@@
5757
+ * @returns @@@
5758
+ * @example 'helloWorld'
5759
+ * @example 'iLovePromptbook'
5760
+ * @public exported from `@promptbook/utils`
5761
+ */
5762
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5763
+ var e_1, _a;
5764
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5765
+ var charType;
5766
+ var lastCharType = null;
5767
+ var normalizedName = '';
5768
+ try {
5769
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5770
+ var char = text_1_1.value;
5771
+ var normalizedChar = void 0;
5772
+ if (/^[a-z]$/.test(char)) {
5773
+ charType = 'LOWERCASE';
5774
+ normalizedChar = char;
5775
+ }
5776
+ else if (/^[A-Z]$/.test(char)) {
5777
+ charType = 'UPPERCASE';
5778
+ normalizedChar = char.toLowerCase();
5779
+ }
5780
+ else if (/^[0-9]$/.test(char)) {
5781
+ charType = 'NUMBER';
5782
+ normalizedChar = char;
5783
+ }
5784
+ else {
5785
+ charType = 'OTHER';
5786
+ normalizedChar = '';
5787
+ }
5788
+ if (!lastCharType) {
5789
+ if (_isFirstLetterCapital) {
5790
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5791
+ }
5792
+ }
5793
+ else if (charType !== lastCharType &&
5794
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5795
+ !(lastCharType === 'NUMBER') &&
5796
+ !(charType === 'NUMBER')) {
5797
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5798
+ }
5799
+ normalizedName += normalizedChar;
5800
+ lastCharType = charType;
5801
+ }
5802
+ }
5803
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5804
+ finally {
5805
+ try {
5806
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5807
+ }
5808
+ finally { if (e_1) throw e_1.error; }
5809
+ }
5810
+ return normalizedName;
5811
+ }
5812
+ /**
5813
+ * TODO: [🌺] Use some intermediate util splitWords
5814
+ */
5815
+
5816
+ /**
5817
+ * Removes quotes from a string
5818
+ *
5819
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5820
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5821
+ * Note: There are two simmilar functions:
5822
+ * - `removeQuotes` which removes only bounding quotes
5823
+ * - `unwrapResult` which removes whole introduce sentence
5824
+ *
5825
+ * @param text optionally quoted text
5826
+ * @returns text without quotes
5827
+ * @public exported from `@promptbook/utils`
5828
+ */
5829
+ function removeQuotes(text) {
5830
+ if (text.startsWith('"') && text.endsWith('"')) {
5831
+ return text.slice(1, -1);
5832
+ }
5833
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5834
+ return text.slice(1, -1);
5835
+ }
5836
+ return text;
5837
+ }
5838
+
5839
+ /**
5840
+ * Function `validateParameterName` will @@@
5841
+ *
5842
+ * @param parameterName @@@
5843
+ * @returns @@@
5844
+ * @throws {ParseError} @@@
5845
+ * @private within the repository
5846
+ */
5847
+ function validateParameterName(parameterName) {
5848
+ var e_1, _a;
5849
+ var rawParameterName = parameterName;
5850
+ try {
5851
+ for (var _b = __values([
5852
+ ['`', '`'],
5853
+ ['{', '}'],
5854
+ ['[', ']'],
5855
+ ['(', ')'],
5856
+ ['<', '>'],
5857
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5858
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5859
+ if (parameterName.substring(0, 1) === start &&
5860
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5861
+ // <- TODO: More universal that 1 character
5862
+ ) {
5863
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5864
+ // <- TODO: More universal that 1 character
5865
+ }
5866
+ }
5867
+ }
5868
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5869
+ finally {
5870
+ try {
5871
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5872
+ }
5873
+ finally { if (e_1) throw e_1.error; }
5874
+ }
5875
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5876
+ try {
5877
+ /*
5878
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5879
+ if (parameterName.includes(' ')) {
5880
+ throw new ParseError(`Parameter name cannot contain spaces`);
5881
+ }
5882
+ */
5883
+ if (parameterName.includes('.')) {
5884
+ throw new ParseError("Parameter name cannot contain dots");
5885
+ }
5886
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5887
+ throw new ParseError("Parameter name cannot contain slashes");
5888
+ }
5889
+ if (parameterName.includes('(') ||
5890
+ parameterName.includes(')') ||
5891
+ parameterName.includes('{') ||
5892
+ parameterName.includes('}') ||
5893
+ parameterName.includes('[') ||
5894
+ parameterName.includes(']')) {
5895
+ throw new ParseError("Parameter name cannot contain braces");
5896
+ }
5897
+ parameterName = removeDiacritics(parameterName);
5898
+ parameterName = removeEmojis(parameterName);
5899
+ parameterName = removeQuotes(parameterName);
5900
+ parameterName = normalizeTo_camelCase(parameterName);
5901
+ if (parameterName === '') {
5902
+ throw new ParseError("Parameter name cannot be empty");
5903
+ }
5904
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5905
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5906
+ }
5907
+ }
5908
+ catch (error) {
5909
+ if (!(error instanceof ParseError)) {
5910
+ throw error;
5911
+ }
5912
+ throw new ParseError(spaceTrim$1(function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
5913
+ }
5914
+ return parameterName;
5915
+ }
5916
+
5114
5917
  /**
5115
5918
  * Parses the foreach command
5116
5919
  *
@@ -5140,67 +5943,61 @@ var foreachCommandParser = {
5140
5943
  /**
5141
5944
  * Link to discussion
5142
5945
  */
5143
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5946
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5144
5947
  /**
5145
5948
  * Example usages of the FOREACH command
5146
5949
  */
5147
5950
  examples: [
5148
- 'FOREACH List Line -> `{customer}`',
5149
- 'FOR List Line -> `{customer}`',
5150
- 'EACH List Line -> `{customer}`',
5151
- // <- TODO: [🍭] !!!!!! More
5951
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5952
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5953
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
5152
5954
  ],
5153
5955
  /**
5154
5956
  * Parses the FOREACH command
5155
5957
  */
5156
5958
  parse: function (input) {
5157
- var args = input.args, rawArgs = input.rawArgs;
5959
+ var args = input.args;
5158
5960
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5159
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5160
- var assignSign = args[2];
5161
- var parameter = args[3];
5162
- if (![
5163
- 'LIST',
5164
- 'CSV',
5165
- // <- TODO: [🏢] Unhardcode formats
5166
- ].includes(formatName)) {
5167
- console.info({ args: args, formatName: formatName });
5168
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5961
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5962
+ var parameterNameArg = args[2] || '';
5963
+ var assignSign = args[3];
5964
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5965
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5966
+ });
5967
+ if (formatDefinition === undefined) {
5968
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
5969
+ .map(function (formatName) { return "- ".concat(formatName); })
5970
+ .join('\n')), "\n "); }));
5169
5971
  // <- TODO: [🏢] List all supported format names
5170
5972
  }
5171
- if (![
5172
- 'LINE',
5173
- 'ROW',
5174
- 'COLUMN',
5175
- 'CELL',
5176
- // <- TODO: [🏢] Unhardcode format cekks
5177
- ].includes(cellName)) {
5178
- console.info({ args: args, cellName: cellName });
5179
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5180
- // <- TODO: [🏢] List all supported cell names for the format
5973
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5974
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5975
+ });
5976
+ if (subvalueDefinition === undefined) {
5977
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unsupported subformat name \"".concat(subformatName, "\" for format \"").concat(formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
5978
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5979
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5980
+ .join('\n')), "\n "); }));
5981
+ // <- TODO: [🏢] List all supported subformat names for the format
5181
5982
  }
5182
5983
  if (assignSign !== '->') {
5183
- console.info({ args: args, assignSign: assignSign });
5184
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5185
- }
5186
- var parameterNames = extractParameterNames(parameter || rawArgs);
5187
- if (parameterNames.size !== 1) {
5188
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5189
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5190
- }
5191
- var parameterName = parameterNames.values().next().value;
5192
- if (typeof parameterName !== 'string'
5193
- // <- TODO: !!!!!! Replace with propper parameter name validation
5194
- ) {
5195
- console.info({ args: args, parameterName: parameterName });
5196
- throw new Error("Invalid parameter name");
5197
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
5984
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5985
+ }
5986
+ var parameterName = validateParameterName(parameterNameArg);
5987
+ var subparameterNames = args
5988
+ .slice(4)
5989
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5990
+ .filter(function (parameterName) { return parameterName !== ''; })
5991
+ .map(validateParameterName);
5992
+ if (subparameterNames.length === 0) {
5993
+ throw new ParseError("FOREACH command must have at least one subparameter");
5198
5994
  }
5199
5995
  return {
5200
5996
  type: 'FOREACH',
5201
5997
  formatName: formatName,
5202
- cellName: cellName,
5998
+ subformatName: subformatName,
5203
5999
  parameterName: parameterName,
6000
+ subparameterNames: subparameterNames,
5204
6001
  };
5205
6002
  },
5206
6003
  /**
@@ -5209,8 +6006,12 @@ var foreachCommandParser = {
5209
6006
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5210
6007
  */
5211
6008
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5212
- keepUnused(command, $templateJson, $pipelineJson);
5213
- // <- TODO: [🍭] !!!!!! Implement
6009
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6010
+ // TODO: [🍭] Detect double use
6011
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6012
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
6013
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
6014
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5214
6015
  },
5215
6016
  /**
5216
6017
  * Converts the FOREACH command back to string
@@ -5219,8 +6020,7 @@ var foreachCommandParser = {
5219
6020
  */
5220
6021
  stringify: function (command) {
5221
6022
  keepUnused(command);
5222
- return "";
5223
- // <- TODO: [🍭] !!!!!! Implement
6023
+ return "---"; // <- TODO: [🛋] Implement
5224
6024
  },
5225
6025
  /**
5226
6026
  * Reads the FOREACH command from the `TemplateJson`
@@ -5229,13 +6029,11 @@ var foreachCommandParser = {
5229
6029
  */
5230
6030
  takeFromTemplateJson: function ($templateJson) {
5231
6031
  keepUnused($templateJson);
5232
- return [];
5233
- // <- TODO: [🍭] !!!!!! Implement
6032
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5234
6033
  },
5235
6034
  };
5236
6035
  /**
5237
- * TODO: !!!!!! Comment console logs
5238
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6036
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5239
6037
  */
5240
6038
 
5241
6039
  /**
@@ -5345,11 +6143,11 @@ var jokerCommandParser = {
5345
6143
  */
5346
6144
  parse: function (input) {
5347
6145
  var args = input.args;
5348
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5349
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5350
- throw new ParseError("Invalid joker");
6146
+ if (args.length !== 1) {
6147
+ throw new ParseError("JOKE command expects exactly one parameter name");
5351
6148
  }
5352
- var parameterName = parametersMatch.groups.parameterName;
6149
+ var parameterNameArg = args[0] || '';
6150
+ var parameterName = validateParameterName(parameterNameArg);
5353
6151
  return {
5354
6152
  type: 'JOKER',
5355
6153
  parameterName: parameterName,
@@ -5424,6 +6222,9 @@ var modelCommandParser = {
5424
6222
  */
5425
6223
  parse: function (input) {
5426
6224
  var args = input.args, normalized = input.normalized;
6225
+ var availableVariantsMessage = spaceTrim$1(function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6226
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6227
+ }).join('\n')), "\n "); });
5427
6228
  // TODO: Make this more elegant and dynamically
5428
6229
  if (normalized.startsWith('MODEL_VARIANT')) {
5429
6230
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5439,17 +6240,13 @@ var modelCommandParser = {
5439
6240
  key: 'modelVariant',
5440
6241
  value: 'COMPLETION',
5441
6242
  };
6243
+ // <- Note: [🤖]
5442
6244
  }
5443
6245
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5444
- return {
5445
- type: 'MODEL',
5446
- key: 'modelVariant',
5447
- value: 'EMBEDDING',
5448
- };
5449
- // <- Note: [🤖]
6246
+ spaceTrim$1(function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5450
6247
  }
5451
6248
  else {
5452
- throw new ParseError(spaceTrim$1(function (block) { return "\n Unknown model variant in command:\n\n Supported variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) { return "- ".concat(variantName); }).join('\n')), "\n "); }));
6249
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5453
6250
  }
5454
6251
  }
5455
6252
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5474,6 +6271,7 @@ var modelCommandParser = {
5474
6271
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5475
6272
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5476
6273
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6274
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5477
6275
  }
5478
6276
  else {
5479
6277
  throw new ParseError(spaceTrim$1("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -5573,14 +6371,13 @@ var parameterCommandParser = {
5573
6371
  * Parses the PARAMETER command
5574
6372
  */
5575
6373
  parse: function (input) {
5576
- var normalized = input.normalized, raw = input.raw;
5577
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5578
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5579
- throw new ParseError("Invalid parameter");
5580
- }
5581
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5582
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5583
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6374
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6375
+ var parameterNameRaw = args.shift() || '';
6376
+ var parameterDescriptionRaw = args.join(' ');
6377
+ // <- TODO: When [🥶] fixed, change to:
6378
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6379
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6380
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameterNameRaw, "} can not contain another parameter in description\n\n The description:\n ").concat(block(parameterDescriptionRaw), "\n "); }));
5584
6381
  }
5585
6382
  var isInput = normalized.startsWith('INPUT');
5586
6383
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5588,11 +6385,12 @@ var parameterCommandParser = {
5588
6385
  isInput = false;
5589
6386
  isOutput = false;
5590
6387
  }
5591
- // TODO: !!!!!! Add parameter name validation
6388
+ var parameterName = validateParameterName(parameterNameRaw);
6389
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5592
6390
  return {
5593
6391
  type: 'PARAMETER',
5594
6392
  parameterName: parameterName,
5595
- parameterDescription: parameterDescription.trim() || null,
6393
+ parameterDescription: parameterDescription,
5596
6394
  isInput: isInput,
5597
6395
  isOutput: isOutput,
5598
6396
  };
@@ -5917,6 +6715,7 @@ var promptbookVersionCommandParser = {
5917
6715
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
5918
6716
  */
5919
6717
  $applyToPipelineJson: function (command, $pipelineJson) {
6718
+ // TODO: Warn if the version is overridden
5920
6719
  $pipelineJson.promptbookVersion = command.promptbookVersion;
5921
6720
  },
5922
6721
  /**
@@ -6399,7 +7198,9 @@ function parseCommand(raw, usagePlace) {
6399
7198
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6400
7199
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6401
7200
  var args = items.slice(commandNameSegmentsCount + 1);
6402
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7201
+ var rawArgs = raw
7202
+ .substring(commandNameRaw.length)
7203
+ .trim();
6403
7204
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6404
7205
  if (command !== null) {
6405
7206
  return command;
@@ -6410,7 +7211,9 @@ function parseCommand(raw, usagePlace) {
6410
7211
  {
6411
7212
  var commandNameRaw = items.slice(-1).join('_');
6412
7213
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6413
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7214
+ var rawArgs = raw
7215
+ .substring(0, raw.length - commandNameRaw.length)
7216
+ .trim();
6414
7217
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6415
7218
  if (command !== null) {
6416
7219
  return command;
@@ -6550,7 +7353,7 @@ function extractAllListItemsFromMarkdown(markdown) {
6550
7353
  function extractOneBlockFromMarkdown(markdown) {
6551
7354
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6552
7355
  if (codeBlocks.length !== 1) {
6553
- throw new ParseError(spaceTrim$1(function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7356
+ throw new ParseError(spaceTrim$1(function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6554
7357
  }
6555
7358
  return codeBlocks[0];
6556
7359
  }
@@ -6737,7 +7540,7 @@ function pipelineStringToJsonSync(pipelineString) {
6737
7540
  var $pipelineJson = {
6738
7541
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6739
7542
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6740
- promptbookVersion: PROMPTBOOK_VERSION,
7543
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6741
7544
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6742
7545
  parameters: [],
6743
7546
  templates: [],
@@ -7028,7 +7831,7 @@ function pipelineStringToJsonSync(pipelineString) {
7028
7831
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7029
7832
  }
7030
7833
  /**
7031
- * TODO: !!!! Warn if used only sync version
7834
+ * TODO:[main] !!!! Warn if used only sync version
7032
7835
  * TODO: [🚞] Report here line/column of error
7033
7836
  * TODO: Use spaceTrim more effectively
7034
7837
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7533,7 +8336,7 @@ function isSerializableAsJson(value) {
7533
8336
  }
7534
8337
  }
7535
8338
  /**
7536
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8339
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7537
8340
  * TODO: [🧠][💺] Can be done this on type-level?
7538
8341
  */
7539
8342
 
@@ -7590,21 +8393,41 @@ function usageToWorktime(usage) {
7590
8393
  * @public exported from `@promptbook/core`
7591
8394
  */
7592
8395
  function usageToHuman(usage) {
7593
- var report = 'Usage:';
8396
+ var reportItems = [];
7594
8397
  var uncertainNumberToHuman = function (_a) {
7595
8398
  var value = _a.value, isUncertain = _a.isUncertain;
7596
8399
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7597
8400
  };
7598
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7599
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7600
- return spaceTrim$1(report);
8401
+ if (usage.price.value > 0.01
8402
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8403
+ ) {
8404
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8405
+ }
8406
+ else {
8407
+ reportItems.push("Negligible cost");
8408
+ }
8409
+ var worktime = usageToWorktime(usage);
8410
+ if (worktime.value >
8411
+ 1 / 60
8412
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8413
+ ) {
8414
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8415
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8416
+ }
8417
+ if (usage.output.charactersCount.value > 0) {
8418
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8419
+ }
8420
+ if (reportItems.length === 0) {
8421
+ // Note: For negligible usage, we report at least something
8422
+ reportItems.push('Negligible');
8423
+ }
8424
+ return spaceTrim$1(function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7601
8425
  }
7602
8426
  /**
7603
- * TODO: Use "$1" not "1 USD"
7604
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7605
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8427
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8428
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8429
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7606
8430
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7607
- * TODO: When negligible usage, report "Negligible" or just don't report it
7608
8431
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7609
8432
  * TODO: [🏛] Maybe make some markdown builder
7610
8433
  */
@@ -8374,7 +9197,7 @@ function initializeMakeCommand(program) {
8374
9197
  });
8375
9198
  }
8376
9199
  /**
8377
- * TODO: [🥃] !!! Allow `ptbk make` without configuring any llm tools
9200
+ * TODO: [🥃][main] !!! Allow `ptbk make` without configuring any llm tools
8378
9201
  * TODO: Maybe remove this command - "about" command should be enough?
8379
9202
  * TODO: [0] DRY Javascript and typescript - Maybe make ONLY typescript and for javascript just remove types
8380
9203
  * Note: [🟡] This code should never be published outside of `@promptbook/cli`
@@ -8408,70 +9231,6 @@ function addAutoGeneratedSection(content, options) {
8408
9231
  * TODO: [🏛] This can be part of markdown builder
8409
9232
  */
8410
9233
 
8411
- /**
8412
- * @@@
8413
- *
8414
- * @param text @@@
8415
- * @param _isFirstLetterCapital @@@
8416
- * @returns @@@
8417
- * @example 'helloWorld'
8418
- * @example 'iLovePromptbook'
8419
- * @public exported from `@promptbook/utils`
8420
- */
8421
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
8422
- var e_1, _a;
8423
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
8424
- var charType;
8425
- var lastCharType = null;
8426
- var normalizedName = '';
8427
- try {
8428
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
8429
- var char = text_1_1.value;
8430
- var normalizedChar = void 0;
8431
- if (/^[a-z]$/.test(char)) {
8432
- charType = 'LOWERCASE';
8433
- normalizedChar = char;
8434
- }
8435
- else if (/^[A-Z]$/.test(char)) {
8436
- charType = 'UPPERCASE';
8437
- normalizedChar = char.toLowerCase();
8438
- }
8439
- else if (/^[0-9]$/.test(char)) {
8440
- charType = 'NUMBER';
8441
- normalizedChar = char;
8442
- }
8443
- else {
8444
- charType = 'OTHER';
8445
- normalizedChar = '';
8446
- }
8447
- if (!lastCharType) {
8448
- if (_isFirstLetterCapital) {
8449
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
8450
- }
8451
- }
8452
- else if (charType !== lastCharType &&
8453
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
8454
- !(lastCharType === 'NUMBER') &&
8455
- !(charType === 'NUMBER')) {
8456
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
8457
- }
8458
- normalizedName += normalizedChar;
8459
- lastCharType = charType;
8460
- }
8461
- }
8462
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
8463
- finally {
8464
- try {
8465
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
8466
- }
8467
- finally { if (e_1) throw e_1.error; }
8468
- }
8469
- return normalizedName;
8470
- }
8471
- /**
8472
- * TODO: [🌺] Use some intermediate util splitWords
8473
- */
8474
-
8475
9234
  /**
8476
9235
  * Creates a Mermaid graph based on the promptbook
8477
9236
  *
@@ -8528,6 +9287,9 @@ function renderPromptbookMermaid(pipelineJson, options) {
8528
9287
  return promptbookMermaid;
8529
9288
  }
8530
9289
  /**
9290
+ * TODO: !!!!! FOREACH in mermaid graph
9291
+ * TODO: !!!!! Knowledge in mermaid graph
9292
+ * TODO: !!!!! Personas in mermaid graph
8531
9293
  * TODO: Maybe use some Mermaid package instead of string templating
8532
9294
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8533
9295
  */
@@ -8853,7 +9615,7 @@ var RemoteLlmExecutionTools = /** @class */ (function () {
8853
9615
  socket.on('connect', function () {
8854
9616
  resolve(socket);
8855
9617
  });
8856
- // TODO: !!!! Better timeout handling
9618
+ // TODO:[main] !!!! Better timeout handling
8857
9619
  setTimeout(function () {
8858
9620
  reject(new Error("Timeout while connecting to ".concat(_this.options.remoteUrl)));
8859
9621
  }, CONNECTION_TIMEOUT_MS);
@@ -9033,11 +9795,11 @@ var ANTHROPIC_CLAUDE_MODELS = $asDeeplyFrozenSerializableJson('ANTHROPIC_CLAUDE_
9033
9795
  output: computeUsage("$2.40 / 1M tokens"),
9034
9796
  },
9035
9797
  },
9036
- // TODO: !!! Claude 1 and 2 has also completion versions - ask Hoagy
9798
+ // TODO:[main] !!! Claude 1 and 2 has also completion versions - ask Hoagy
9037
9799
  ]);
9038
9800
  /**
9039
9801
  * Note: [🤖] Add models of new variant
9040
- * TODO: [🧠] !!! Add embedding models OR Anthropic has only chat+completion models?
9802
+ * TODO: [🧠][main] !!! Add embedding models OR Anthropic has only chat+completion models?
9041
9803
  * TODO: [🧠] Some mechanism to propagate unsureness
9042
9804
  * TODO: [🧠][👮‍♀️] Put here more info like description, isVision, trainingDateCutoff, languages, strengths ( Top-level performance, intelligence, fluency, and understanding), contextWindow,...
9043
9805
  * TODO: [🎰] Some mechanism to auto-update available models
@@ -9246,7 +10008,7 @@ var AnthropicClaudeExecutionTools = /** @class */ (function () {
9246
10008
  resultContent = contentBlock.text;
9247
10009
  // eslint-disable-next-line prefer-const
9248
10010
  complete = getCurrentIsoDate();
9249
- usage = computeAnthropicClaudeUsage(content, '', rawResponse);
10011
+ usage = computeAnthropicClaudeUsage(rawPromptContent || '', resultContent || '', rawResponse);
9250
10012
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('AnthropicClaudeExecutionTools ChatPromptResult', {
9251
10013
  content: resultContent,
9252
10014
  modelName: rawResponse.model,
@@ -9393,8 +10155,8 @@ var createAnthropicClaudeExecutionTools = Object.assign(function (options) {
9393
10155
  className: 'AnthropicClaudeExecutionTools',
9394
10156
  });
9395
10157
  /**
9396
- * TODO: [🧠] !!!! Make anonymous this with all LLM providers
9397
- * TODO: [🧠][🧱] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
10158
+ * TODO: [🧠][main] !!!! Make anonymous this with all LLM providers
10159
+ * TODO: [🧠][🧱][main] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
9398
10160
  * TODO: [🧠] Maybe auto-detect usage in browser and determine default value of `isProxied`
9399
10161
  * TODO: [🦺] Is there some way how to put `packageName` and `className` on top and function definition on bottom?
9400
10162
  * TODO: [🎶] Naming "constructor" vs "creator" vs "factory"
@@ -9772,6 +10534,7 @@ var OPENAI_MODELS = $asDeeplyFrozenSerializableJson('OPENAI_MODELS', [
9772
10534
  prompt: computeUsage("$5.00 / 1M tokens"),
9773
10535
  output: computeUsage("$15.00 / 1M tokens"),
9774
10536
  },
10537
+ //TODO:[main] !!!!!! Add gpt-4o-mini-2024-07-18 and all others to be up to date
9775
10538
  },
9776
10539
  /**/
9777
10540
  /**/
@@ -9786,6 +10549,51 @@ var OPENAI_MODELS = $asDeeplyFrozenSerializableJson('OPENAI_MODELS', [
9786
10549
  },
9787
10550
  /**/
9788
10551
  /**/
10552
+ {
10553
+ modelVariant: 'CHAT',
10554
+ modelTitle: 'o1-preview',
10555
+ modelName: 'o1-preview',
10556
+ pricing: {
10557
+ prompt: computeUsage("$15.00 / 1M tokens"),
10558
+ output: computeUsage("$60.00 / 1M tokens"),
10559
+ },
10560
+ },
10561
+ /**/
10562
+ /**/
10563
+ {
10564
+ modelVariant: 'CHAT',
10565
+ modelTitle: 'o1-preview-2024-09-12',
10566
+ modelName: 'o1-preview-2024-09-12',
10567
+ // <- TODO:[main] !!!!!! Some better system to organize theese date suffixes and versions
10568
+ pricing: {
10569
+ prompt: computeUsage("$15.00 / 1M tokens"),
10570
+ output: computeUsage("$60.00 / 1M tokens"),
10571
+ },
10572
+ },
10573
+ /**/
10574
+ /**/
10575
+ {
10576
+ modelVariant: 'CHAT',
10577
+ modelTitle: 'o1-mini',
10578
+ modelName: 'o1-mini',
10579
+ pricing: {
10580
+ prompt: computeUsage("$3.00 / 1M tokens"),
10581
+ output: computeUsage("$12.00 / 1M tokens"),
10582
+ },
10583
+ },
10584
+ /**/
10585
+ /**/
10586
+ {
10587
+ modelVariant: 'CHAT',
10588
+ modelTitle: 'o1-mini-2024-09-12',
10589
+ modelName: 'o1-mini-2024-09-12',
10590
+ pricing: {
10591
+ prompt: computeUsage("$3.00 / 1M tokens"),
10592
+ output: computeUsage("$12.00 / 1M tokens"),
10593
+ },
10594
+ },
10595
+ /**/
10596
+ /**/
9789
10597
  {
9790
10598
  modelVariant: 'CHAT',
9791
10599
  modelTitle: 'gpt-3.5-turbo-16k-0613',
@@ -9874,7 +10682,7 @@ var AzureOpenAiExecutionTools = /** @class */ (function () {
9874
10682
  AzureOpenAiExecutionTools.prototype.listModels = function () {
9875
10683
  return __awaiter(this, void 0, void 0, function () {
9876
10684
  return __generator(this, function (_a) {
9877
- // TODO: !!! Do here some filtering which models are really available as deployment
10685
+ // TODO:[main] !!! Do here some filtering which models are really available as deployment
9878
10686
  // @see https://management.azure.com/subscriptions/subscriptionId/resourceGroups/resourceGroupName/providers/Microsoft.CognitiveServices/accounts/accountName/deployments?api-version=2023-05-01
9879
10687
  return [2 /*return*/, OPENAI_MODELS.map(function (_a) {
9880
10688
  var modelTitle = _a.modelTitle, modelName = _a.modelName, modelVariant = _a.modelVariant;
@@ -10360,7 +11168,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10360
11168
  resultContent = rawResponse.choices[0].message.content;
10361
11169
  // eslint-disable-next-line prefer-const
10362
11170
  complete = getCurrentIsoDate();
10363
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11171
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10364
11172
  if (resultContent === null) {
10365
11173
  throw new PipelineExecutionError('No response message from OpenAI');
10366
11174
  }
@@ -10432,7 +11240,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10432
11240
  resultContent = rawResponse.choices[0].text;
10433
11241
  // eslint-disable-next-line prefer-const
10434
11242
  complete = getCurrentIsoDate();
10435
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11243
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10436
11244
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools CompletionPromptResult', {
10437
11245
  content: resultContent,
10438
11246
  modelName: rawResponse.model || modelName,
@@ -10492,7 +11300,9 @@ var OpenAiExecutionTools = /** @class */ (function () {
10492
11300
  resultContent = rawResponse.data[0].embedding;
10493
11301
  // eslint-disable-next-line prefer-const
10494
11302
  complete = getCurrentIsoDate();
10495
- usage = computeOpenAiUsage(content, '', rawResponse);
11303
+ usage = computeOpenAiUsage(content || '', '',
11304
+ // <- Note: Embedding does not have result content
11305
+ rawResponse);
10496
11306
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools EmbeddingPromptResult', {
10497
11307
  content: resultContent,
10498
11308
  modelName: rawResponse.model || modelName,
@@ -10563,7 +11373,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10563
11373
  * @public exported from `@promptbook/openai`
10564
11374
  */
10565
11375
  var createOpenAiExecutionTools = Object.assign(function (options) {
10566
- // TODO: [🧠] !!!! If browser, auto add `dangerouslyAllowBrowser`
11376
+ // TODO: [🧠][main] !!!! If browser, auto add `dangerouslyAllowBrowser`
10567
11377
  if (($isRunningInBrowser() || $isRunningInWebWorker()) && !options.dangerouslyAllowBrowser) {
10568
11378
  options = __assign(__assign({}, options), { dangerouslyAllowBrowser: true });
10569
11379
  }