@promptbook/cli 0.69.0-2 → 0.69.0-21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +21 -58
  2. package/esm/index.es.js +2039 -1249
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/promptbook-collection/index.d.ts +0 -3
  5. package/esm/typings/src/_packages/core.index.d.ts +9 -1
  6. package/esm/typings/src/_packages/types.index.d.ts +10 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  8. package/esm/typings/src/cli/cli-commands/make.d.ts +1 -1
  9. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +1 -1
  10. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +1 -1
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +6 -5
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +1 -1
  14. package/esm/typings/src/config.d.ts +11 -4
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -3
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +6 -5
  19. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +9 -8
  20. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +45 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +40 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +19 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  31. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  32. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  33. package/esm/typings/src/execution/embeddingVectorToString.d.ts +1 -1
  34. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  35. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  36. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  37. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +31 -0
  38. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  39. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  40. package/esm/typings/src/formats/index.d.ts +1 -1
  41. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  42. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  43. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  44. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  45. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  48. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  50. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  51. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  52. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  53. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -1
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/execution-report/executionReportJsonToString.d.ts +2 -1
  57. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  58. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  59. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  60. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  61. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  62. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  63. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  64. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  65. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  67. package/package.json +17 -12
  68. package/umd/index.umd.js +2042 -1253
  69. package/umd/index.umd.js.map +1 -1
  70. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  71. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  72. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  73. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  74. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  75. /package/esm/typings/src/{personas/preparePersona.test.d.ts → utils/validators/parameterName/validateParameterName.test.d.ts} +0 -0
package/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-1';
24
- // TODO: !!!! List here all the versions and annotate + put into script
24
+ var PROMPTBOOK_VERSION = '0.69.0-20';
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,6 +503,17 @@ 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
  *
@@ -669,7 +682,7 @@ function pipelineJsonToString(pipelineJson) {
669
682
  commands.push("PIPELINE URL ".concat(pipelineUrl));
670
683
  }
671
684
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
672
- // 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
673
686
  pipelineString = prettifyMarkdown(pipelineString);
674
687
  try {
675
688
  for (var _g = __values(parameters.filter(function (_a) {
@@ -817,12 +830,12 @@ function pipelineJsonToString(pipelineJson) {
817
830
  pipelineString += '```' + contentLanguage;
818
831
  pipelineString += '\n';
819
832
  pipelineString += spaceTrim$1(content);
820
- // <- TODO: !!! Escape
833
+ // <- TODO:[main] !!! Escape
821
834
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
822
835
  pipelineString += '\n';
823
836
  pipelineString += '```';
824
837
  pipelineString += '\n\n';
825
- 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
826
839
  }
827
840
  }
828
841
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -1049,7 +1062,7 @@ function forEachAsync(array, options, callbackfunction) {
1049
1062
  });
1050
1063
  }
1051
1064
 
1052
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
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"}];
1053
1066
 
1054
1067
  /**
1055
1068
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1124,7 +1137,7 @@ function isValidPromptbookVersion(version) {
1124
1137
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
1125
1138
  return false;
1126
1139
  }
1127
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1140
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1128
1141
  return true;
1129
1142
  }
1130
1143
 
@@ -1293,19 +1306,19 @@ function validatePipelineCore(pipeline) {
1293
1306
  // <- Note: [🚲]
1294
1307
  throw new PipelineLogicError(spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1295
1308
  }
1296
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1309
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1297
1310
  // <- Note: [🚲]
1298
1311
  throw new PipelineLogicError(spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1299
1312
  }
1300
1313
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1301
1314
  if (!Array.isArray(pipeline.parameters)) {
1302
1315
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1303
- 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 "); }));
1304
1317
  }
1305
1318
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1306
1319
  if (!Array.isArray(pipeline.templates)) {
1307
1320
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1308
- 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 "); }));
1309
1322
  }
1310
1323
  var _loop_1 = function (parameter) {
1311
1324
  if (parameter.isInput && parameter.isOutput) {
@@ -1476,6 +1489,7 @@ function validatePipelineCore(pipeline) {
1476
1489
  }
1477
1490
  }
1478
1491
  /**
1492
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1479
1493
  * TODO: [🧠] Work with promptbookVersion
1480
1494
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1481
1495
  * > /**
@@ -1487,11 +1501,11 @@ function validatePipelineCore(pipeline) {
1487
1501
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1488
1502
  */
1489
1503
  /**
1490
- * TODO: [🐣] !!!! Validate that all samples match expectations
1491
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1492
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1493
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1494
- * 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
1495
1509
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1496
1510
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1497
1511
  */
@@ -2197,121 +2211,35 @@ function assertsExecutionSuccessful(executionResult) {
2197
2211
  */
2198
2212
 
2199
2213
  /**
2200
- * Parses the given script and returns the list of all used variables that are not defined in the script
2201
- *
2202
- * @param script from which to extract the variables
2203
- * @returns the list of variable names
2204
- * @throws {ParseError} if the script is invalid
2205
- * @public exported from `@promptbook/utils`
2206
- */
2207
- function extractVariables(script) {
2208
- var variables = new Set();
2209
- script = "(()=>{".concat(script, "})()");
2210
- try {
2211
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2212
- try {
2213
- eval(script);
2214
- }
2215
- catch (error) {
2216
- if (!(error instanceof ReferenceError)) {
2217
- throw error;
2218
- }
2219
- var undefinedName = error.message.split(' ')[0];
2220
- /*
2221
- Note: Parsing the error
2222
- [PipelineUrlError: thing is not defined]
2223
- */
2224
- if (!undefinedName) {
2225
- throw error;
2226
- }
2227
- if (script.includes(undefinedName + '(')) {
2228
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2229
- }
2230
- else {
2231
- variables.add(undefinedName);
2232
- script = "const ".concat(undefinedName, " = '';") + script;
2233
- }
2234
- }
2235
- }
2236
- catch (error) {
2237
- if (!(error instanceof Error)) {
2238
- throw error;
2239
- }
2240
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2241
- }
2242
- return variables;
2243
- }
2244
- /**
2245
- * TODO: [🔣] Support for multiple languages - python, java,...
2246
- */
2247
-
2248
- /**
2249
- * Parses the template and returns the set of all used parameters
2214
+ * Determine if the pipeline is fully prepared
2250
2215
  *
2251
- * @param template the template with used parameters
2252
- * @returns the set of parameter names
2253
- * @throws {ParseError} if the script is invalid
2254
- * @public exported from `@promptbook/utils`
2216
+ * @public exported from `@promptbook/core`
2255
2217
  */
2256
- function extractParameterNamesFromTemplate(template) {
2257
- var e_1, _a, e_2, _b, e_3, _c;
2258
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2259
- var parameterNames = new Set();
2260
- try {
2261
- 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()) {
2262
- var parameterName = _e.value;
2263
- parameterNames.add(parameterName);
2264
- }
2265
- }
2266
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2267
- finally {
2268
- try {
2269
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2270
- }
2271
- finally { if (e_1) throw e_1.error; }
2272
- }
2273
- if (templateType === 'SCRIPT_TEMPLATE') {
2274
- try {
2275
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2276
- var parameterName = _g.value;
2277
- parameterNames.add(parameterName);
2278
- }
2279
- }
2280
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2281
- finally {
2282
- try {
2283
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2284
- }
2285
- finally { if (e_2) throw e_2.error; }
2286
- }
2287
- }
2288
- try {
2289
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2290
- var jokerName = _j.value;
2291
- parameterNames.add(jokerName);
2292
- }
2293
- }
2294
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2295
- finally {
2296
- try {
2297
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2298
- }
2299
- finally { if (e_3) throw e_3.error; }
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;
2300
2223
  }
2301
- parameterNames.delete('content');
2302
- // <- Note {websiteContent} is used in `preparedContent`
2303
- // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2304
- if (foreach !== undefined) {
2305
- if (parameterNames.has(foreach.subparameterName)) {
2306
- parameterNames.delete(foreach.subparameterName);
2307
- parameterNames.add(foreach.parameterName);
2308
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2309
- }
2224
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2225
+ return false;
2310
2226
  }
2311
- 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;
2312
2234
  }
2313
2235
  /**
2314
- * 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
2315
2243
  */
2316
2244
 
2317
2245
  /**
@@ -2331,27 +2259,6 @@ function serializeError(error) {
2331
2259
  };
2332
2260
  }
2333
2261
 
2334
- /**
2335
- * Function isValidJsonString will tell you if the string is valid JSON or not
2336
- *
2337
- * @public exported from `@promptbook/utils`
2338
- */
2339
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2340
- try {
2341
- JSON.parse(value);
2342
- return true;
2343
- }
2344
- catch (error) {
2345
- if (!(error instanceof Error)) {
2346
- throw error;
2347
- }
2348
- if (error.message.includes('Unexpected token')) {
2349
- return false;
2350
- }
2351
- return false;
2352
- }
2353
- }
2354
-
2355
2262
  /**
2356
2263
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2357
2264
  *
@@ -2378,9 +2285,10 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2378
2285
  });
2379
2286
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2380
2287
  get: function () {
2381
- return this.llmExecutionTools
2382
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2383
- .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');
2384
2292
  },
2385
2293
  enumerable: false,
2386
2294
  configurable: true
@@ -2578,9 +2486,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2578
2486
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2579
2487
  }
2580
2488
  else {
2581
- 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
2582
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2583
- .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 "); }));
2584
2490
  }
2585
2491
  }
2586
2492
  });
@@ -2646,288 +2552,153 @@ function joinLlmExecutionTools() {
2646
2552
  */
2647
2553
 
2648
2554
  /**
2649
- * Extracts all code blocks from markdown.
2555
+ * Takes an item or an array of items and returns an array of items
2650
2556
  *
2651
- * Note: There are multiple simmilar function:
2652
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2653
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2654
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2655
- * - `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
2656
2560
  *
2657
- * @param markdown any valid markdown
2658
- * @returns code blocks with language and content
2659
- * @throws {ParseError} if block is not closed properly
2660
- * @public exported from `@promptbook/markdown-utils`
2561
+ * @private internal utility
2661
2562
  */
2662
- function extractAllBlocksFromMarkdown(markdown) {
2663
- var e_1, _a;
2664
- var codeBlocks = [];
2665
- var lines = markdown.split('\n');
2666
- // Note: [0] Ensure that the last block notated by gt > will be closed
2667
- lines.push('');
2668
- var currentCodeBlock = null;
2563
+ function arrayableToArray(input) {
2564
+ if (input === undefined) {
2565
+ return [];
2566
+ }
2567
+ if (input instanceof Array) {
2568
+ return input;
2569
+ }
2570
+ return [input];
2571
+ }
2572
+
2573
+ /**
2574
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2575
+ *
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`
2580
+ */
2581
+ function extractVariables(script) {
2582
+ var variables = new Set();
2583
+ script = "(()=>{".concat(script, "})()");
2669
2584
  try {
2670
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2671
- var line = lines_1_1.value;
2672
- if (line.startsWith('> ') || line === '>') {
2673
- if (currentCodeBlock === null) {
2674
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2675
- } /* not else */
2676
- if (currentCodeBlock.blockNotation === '>') {
2677
- if (currentCodeBlock.content !== '') {
2678
- currentCodeBlock.content += '\n';
2679
- }
2680
- currentCodeBlock.content += line.slice(2);
2681
- }
2682
- }
2683
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2684
- codeBlocks.push(currentCodeBlock);
2685
- currentCodeBlock = null;
2585
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2586
+ try {
2587
+ eval(script);
2686
2588
  }
2687
- /* not else */
2688
- if (line.startsWith('```')) {
2689
- var language = line.slice(3).trim() || null;
2690
- if (currentCodeBlock === null) {
2691
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2589
+ catch (error) {
2590
+ if (!(error instanceof ReferenceError)) {
2591
+ throw error;
2692
2592
  }
2693
- else {
2694
- if (language !== null) {
2695
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2696
- }
2697
- codeBlocks.push(currentCodeBlock);
2698
- currentCodeBlock = null;
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;
2699
2600
  }
2700
- }
2701
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2702
- if (currentCodeBlock.content !== '') {
2703
- currentCodeBlock.content += '\n';
2601
+ if (script.includes(undefinedName + '(')) {
2602
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2603
+ }
2604
+ else {
2605
+ variables.add(undefinedName);
2606
+ script = "const ".concat(undefinedName, " = '';") + script;
2704
2607
  }
2705
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2706
2608
  }
2707
- }
2708
2609
  }
2709
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2710
- finally {
2711
- try {
2712
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2610
+ catch (error) {
2611
+ if (!(error instanceof Error)) {
2612
+ throw error;
2713
2613
  }
2714
- finally { if (e_1) throw e_1.error; }
2715
- }
2716
- if (currentCodeBlock !== null) {
2717
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2718
- }
2719
- return codeBlocks;
2720
- }
2721
- /**
2722
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2723
- */
2724
-
2725
- /**
2726
- * Extracts extracts exactly one valid JSON code block
2727
- *
2728
- * - When given string is a valid JSON as it is, it just returns it
2729
- * - When there is no JSON code block the function throws a `ParseError`
2730
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2731
- *
2732
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2733
- * Note: There are multiple simmilar function:
2734
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2735
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2736
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2737
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2738
- *
2739
- * @public exported from `@promptbook/markdown-utils`
2740
- * @throws {ParseError} if there is no valid JSON block in the markdown
2741
- */
2742
- function extractJsonBlock(markdown) {
2743
- if (isValidJsonString(markdown)) {
2744
- return markdown;
2745
- }
2746
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2747
- var jsonBlocks = codeBlocks.filter(function (_a) {
2748
- var content = _a.content;
2749
- return isValidJsonString(content);
2750
- });
2751
- if (jsonBlocks.length === 0) {
2752
- throw new Error('There is no valid JSON block in the markdown');
2753
- }
2754
- if (jsonBlocks.length > 1) {
2755
- throw new Error('There are multiple JSON code blocks in the markdown');
2756
- }
2757
- return jsonBlocks[0].content;
2758
- }
2759
- /**
2760
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2761
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2762
- */
2763
-
2764
- /**
2765
- * Determine if the pipeline is fully prepared
2766
- *
2767
- * @public exported from `@promptbook/core`
2768
- */
2769
- function isPipelinePrepared(pipeline) {
2770
- // Note: Ignoring `pipeline.preparations` @@@
2771
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2772
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2773
- return false;
2774
- }
2775
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2776
- return false;
2777
- }
2778
- /*
2779
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2780
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2781
- > return false;
2782
- > }
2783
- */
2784
- return true;
2785
- }
2786
- /**
2787
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2788
- * TODO: [🐠] Maybe base this on `makeValidator`
2789
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2790
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2791
- * - [🏍] ? Is context in each template
2792
- * - [♨] Are samples prepared
2793
- * - [♨] Are templates prepared
2794
- */
2795
-
2796
- /**
2797
- * Takes an item or an array of items and returns an array of items
2798
- *
2799
- * 1) Any item except array and undefined returns array with that one item (also null)
2800
- * 2) Undefined returns empty array
2801
- * 3) Array returns itself
2802
- *
2803
- * @private internal utility
2804
- */
2805
- function arrayableToArray(input) {
2806
- if (input === undefined) {
2807
- return [];
2808
- }
2809
- if (input instanceof Array) {
2810
- return input;
2811
- }
2812
- return [input];
2813
- }
2814
-
2815
- /**
2816
- * Just says that the variable is not used but should be kept
2817
- * No side effects.
2818
- *
2819
- * Note: It can be usefull for:
2820
- *
2821
- * 1) Suppressing eager optimization of unused imports
2822
- * 2) Suppressing eslint errors of unused variables in the tests
2823
- * 3) Keeping the type of the variable for type testing
2824
- *
2825
- * @param value any values
2826
- * @returns void
2827
- * @private within the repository
2828
- */
2829
- function keepUnused() {
2830
- var valuesToKeep = [];
2831
- for (var _i = 0; _i < arguments.length; _i++) {
2832
- valuesToKeep[_i] = arguments[_i];
2614
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2833
2615
  }
2616
+ return variables;
2834
2617
  }
2835
-
2836
2618
  /**
2837
- * Just marks a place of place where should be something implemented
2838
- * No side effects.
2839
- *
2840
- * Note: It can be usefull suppressing eslint errors of unused variables
2841
- *
2842
- * @param value any values
2843
- * @returns void
2844
- * @private within the repository
2619
+ * TODO: [🔣] Support for multiple languages - python, java,...
2845
2620
  */
2846
- function TODO_USE() {
2847
- var value = [];
2848
- for (var _i = 0; _i < arguments.length; _i++) {
2849
- value[_i] = arguments[_i];
2850
- }
2851
- }
2852
2621
 
2853
2622
  /**
2854
- * Replaces parameters in template with values from parameters object
2623
+ * Parses the template and returns the set of all used parameters
2855
2624
  *
2856
- * @param template the template with parameters in {curly} braces
2857
- * @param parameters the object with parameters
2858
- * @returns the template with replaced parameters
2859
- * @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
2860
2628
  * @public exported from `@promptbook/utils`
2861
2629
  */
2862
- function replaceParameters(template, parameters) {
2863
- 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();
2864
2634
  try {
2865
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2866
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2867
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2868
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2869
- }
2870
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2871
- // TODO: [🍵]
2872
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2873
- }
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);
2874
2638
  }
2875
2639
  }
2876
2640
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2877
2641
  finally {
2878
2642
  try {
2879
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2643
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2880
2644
  }
2881
2645
  finally { if (e_1) throw e_1.error; }
2882
2646
  }
2883
- var replacedTemplate = template;
2884
- var match;
2885
- var loopLimit = LOOP_LIMIT;
2886
- var _loop_1 = function () {
2887
- if (loopLimit-- < 0) {
2888
- 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
+ }
2889
2653
  }
2890
- var precol = match.groups.precol;
2891
- var parameterName = match.groups.parameterName;
2892
- if (parameterName === '') {
2893
- 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; }
2894
2660
  }
2895
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2896
- 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);
2897
2666
  }
2898
- if (parameters[parameterName] === undefined) {
2899
- 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);
2900
2672
  }
2901
- var parameterValue = parameters[parameterName];
2902
- if (parameterValue === undefined) {
2903
- 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.inputSubparameterNames), _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
+ }
2904
2688
  }
2905
- parameterValue = parameterValue.toString();
2906
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2907
- parameterValue = parameterValue
2908
- .split('\n')
2909
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2910
- .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; }
2911
2695
  }
2912
- replacedTemplate =
2913
- replacedTemplate.substring(0, match.index + precol.length) +
2914
- parameterValue +
2915
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2916
- };
2917
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2918
- .exec(replacedTemplate))) {
2919
- _loop_1();
2920
- }
2921
- // [💫] Check if there are parameters that are not closed properly
2922
- if (/{\w+$/.test(replacedTemplate)) {
2923
- throw new PipelineExecutionError('Parameter is not closed');
2924
- }
2925
- // [💫] Check if there are parameters that are not opened properly
2926
- if (/^\w+}/.test(replacedTemplate)) {
2927
- throw new PipelineExecutionError('Parameter is not opened');
2928
2696
  }
2929
- return replacedTemplate;
2697
+ return parameterNames;
2930
2698
  }
2699
+ /**
2700
+ * TODO: [🔣] If script require contentLanguage
2701
+ */
2931
2702
 
2932
2703
  /**
2933
2704
  * Create difference set of two sets.
@@ -3005,24 +2776,621 @@ function union() {
3005
2776
  }
3006
2777
 
3007
2778
  /**
3008
- * Counts number of characters in the text
2779
+ * Just marks a place of place where should be something implemented
2780
+ * No side effects.
3009
2781
  *
3010
- * @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
3011
2787
  */
3012
- function countCharacters(text) {
3013
- // Remove null characters
3014
- text = text.replace(/\0/g, '');
3015
- // Replace emojis (and also ZWJ sequence) with hyphens
3016
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3017
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3018
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3019
- return text.length;
2788
+ function TODO_USE() {
2789
+ var value = [];
2790
+ for (var _i = 0; _i < arguments.length; _i++) {
2791
+ value[_i] = arguments[_i];
2792
+ }
3020
2793
  }
3021
2794
 
3022
2795
  /**
3023
- * Counts number of lines in the text
2796
+ * @@@
3024
2797
  *
3025
- * @public exported from `@promptbook/utils`
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, outputParameterName, 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, _b;
2850
+ var _c;
2851
+ return __generator(this, function (_d) {
2852
+ switch (_d.label) {
2853
+ case 0:
2854
+ if (row[outputParameterName]) {
2855
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2856
+ "Can not overwrite existing column \"".concat(outputParameterName, "\" in CSV row"));
2857
+ }
2858
+ _a = [__assign({}, row)];
2859
+ _c = {};
2860
+ _b = outputParameterName;
2861
+ return [4 /*yield*/, mapCallback(row, index)];
2862
+ case 1: return [2 /*return*/, __assign.apply(void 0, _a.concat([(_c[_b] = _d.sent(), _c)]))];
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, outputParameterName, 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, outputParameterName, 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');
3386
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3387
+ return text.length;
3388
+ }
3389
+
3390
+ /**
3391
+ * Counts number of lines in the text
3392
+ *
3393
+ * @public exported from `@promptbook/utils`
3026
3394
  */
3027
3395
  function countLines(text) {
3028
3396
  if (text === '') {
@@ -3061,62 +3429,789 @@ function splitIntoSentences(text) {
3061
3429
  return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3062
3430
  }
3063
3431
  /**
3064
- * 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, template.foreach.outputSubparameterName, 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.inputSubparameterNames.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 Subparameter index: ").concat(index, "\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: spaceTrim$1(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Subparameter index: ").concat(index, "\n "); }) }))];
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
+ * @@@
3065
4007
  *
3066
- * @public exported from `@promptbook/utils`
4008
+ * @private internal utility of `createPipelineExecutor`
3067
4009
  */
3068
- function countSentences(text) {
3069
- 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
+ });
3070
4060
  }
3071
4061
 
3072
4062
  /**
3073
- * Counts number of words in the text
4063
+ * @@@
3074
4064
  *
3075
- * @public exported from `@promptbook/utils`
4065
+ * @private internal utility of `createPipelineExecutor`
3076
4066
  */
3077
- function countWords(text) {
3078
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3079
- text = removeDiacritics(text);
3080
- 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
+ });
3081
4184
  }
3082
-
3083
4185
  /**
3084
- * Index of all counter functions
3085
- *
3086
- * @public exported from `@promptbook/utils`
4186
+ * TODO: [🤹‍♂️]
3087
4187
  */
3088
- var CountUtils = {
3089
- CHARACTERS: countCharacters,
3090
- WORDS: countWords,
3091
- SENTENCES: countSentences,
3092
- PARAGRAPHS: countParagraphs,
3093
- LINES: countLines,
3094
- PAGES: countPages,
3095
- };
3096
4188
 
3097
4189
  /**
3098
- * Function checkExpectations will check if the expectations on given value are met
3099
- *
3100
- * Note: There are two simmilar functions:
3101
- * - `checkExpectations` which throws an error if the expectations are not met
3102
- * - `isPassingExpectations` which returns a boolean
4190
+ * @@@
3103
4191
  *
3104
- * @throws {ExpectError} if the expectations are not met
3105
- * @returns {void} Nothing
3106
- * @private internal function of `createPipelineExecutor`
4192
+ * @private internal utility of `createPipelineExecutor`
3107
4193
  */
3108
- function checkExpectations(expectations, value) {
4194
+ function filterJustOutputParameters(options) {
3109
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
+ };
3110
4206
  try {
3111
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3112
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3113
- var amount = CountUtils[unit.toUpperCase()](value);
3114
- if (min && amount < min) {
3115
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3116
- } /* not else */
3117
- if (max && amount > max) {
3118
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3119
- }
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);
3120
4215
  }
3121
4216
  }
3122
4217
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3126,614 +4221,27 @@ function checkExpectations(expectations, value) {
3126
4221
  }
3127
4222
  finally { if (e_1) throw e_1.error; }
3128
4223
  }
4224
+ return outputParameters;
3129
4225
  }
3130
- /**
3131
- * TODO: [💝] Unite object for expecting amount and format
3132
- */
3133
4226
 
3134
4227
  /**
3135
- * Creates executor function from pipeline and execution tools.
4228
+ * @@@
3136
4229
  *
3137
- * @returns The executor function
3138
- * @throws {PipelineLogicError} on logical error in the pipeline
3139
- * @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`
3140
4233
  */
3141
- function createPipelineExecutor(options) {
3142
- var _this = this;
3143
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3144
- 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;
3145
- validatePipeline(pipeline);
3146
- var pipelineIdentification = (function () {
3147
- // Note: This is a 😐 implementation of [🚞]
3148
- var _ = [];
3149
- if (pipeline.sourceFile !== undefined) {
3150
- _.push("File: ".concat(pipeline.sourceFile));
3151
- }
3152
- if (pipeline.pipelineUrl !== undefined) {
3153
- _.push("Url: ".concat(pipeline.pipelineUrl));
3154
- }
3155
- return _.join('\n');
3156
- })();
3157
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3158
- var preparedPipeline;
3159
- if (isPipelinePrepared(pipeline)) {
3160
- preparedPipeline = pipeline;
3161
- }
3162
- else if (isNotPreparedWarningSupressed !== true) {
3163
- 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 "); }));
3164
- }
3165
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3166
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3167
- function getContextForTemplate(template) {
3168
- return __awaiter(this, void 0, void 0, function () {
3169
- return __generator(this, function (_a) {
3170
- TODO_USE(template);
3171
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3172
- });
3173
- });
3174
- }
3175
- function getKnowledgeForTemplate(template) {
3176
- return __awaiter(this, void 0, void 0, function () {
3177
- return __generator(this, function (_a) {
3178
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3179
- TODO_USE(template);
3180
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3181
- var content = _a.content;
3182
- return "- ".concat(content);
3183
- }).join('\n')];
3184
- });
3185
- });
3186
- }
3187
- function getSamplesForTemplate(template) {
3188
- return __awaiter(this, void 0, void 0, function () {
3189
- return __generator(this, function (_a) {
3190
- // TODO: [♨] Implement Better - use real index and keyword search
3191
- TODO_USE(template);
3192
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3193
- });
3194
- });
3195
- }
3196
- function getReservedParametersForTemplate(template) {
3197
- return __awaiter(this, void 0, void 0, function () {
3198
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3199
- var e_3, _a;
3200
- return __generator(this, function (_b) {
3201
- switch (_b.label) {
3202
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3203
- case 1:
3204
- context = _b.sent();
3205
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3206
- case 2:
3207
- knowledge = _b.sent();
3208
- return [4 /*yield*/, getSamplesForTemplate(template)];
3209
- case 3:
3210
- samples = _b.sent();
3211
- currentDate = new Date().toISOString();
3212
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3213
- reservedParameters = {
3214
- content: RESERVED_PARAMETER_RESTRICTED,
3215
- context: context,
3216
- knowledge: knowledge,
3217
- samples: samples,
3218
- currentDate: currentDate,
3219
- modelName: modelName,
3220
- };
3221
- _loop_3 = function (parameterName) {
3222
- if (reservedParameters[parameterName] === undefined) {
3223
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3224
- }
3225
- };
3226
- try {
3227
- // Note: Doublecheck that ALL reserved parameters are defined:
3228
- 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()) {
3229
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3230
- _loop_3(parameterName);
3231
- }
3232
- }
3233
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3234
- finally {
3235
- try {
3236
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3237
- }
3238
- finally { if (e_3) throw e_3.error; }
3239
- }
3240
- return [2 /*return*/, reservedParameters];
3241
- }
3242
- });
3243
- });
3244
- }
3245
- function executeSingleTemplate(currentTemplate) {
3246
- return __awaiter(this, void 0, void 0, function () {
3247
- 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;
3248
- var e_4, _f, _g;
3249
- return __generator(this, function (_h) {
3250
- switch (_h.label) {
3251
- case 0:
3252
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3253
- title = currentTemplate.title;
3254
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3255
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3256
- progress_1 = {
3257
- name: name,
3258
- title: title,
3259
- isStarted: false,
3260
- isDone: false,
3261
- templateType: currentTemplate.templateType,
3262
- parameterName: currentTemplate.resultingParameterName,
3263
- parameterValue: null,
3264
- // <- [3]
3265
- };
3266
- if (isReturned) {
3267
- 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)
3268
- .split('\n')
3269
- .map(function (line) { return "> ".concat(line); })
3270
- .join('\n')), "\n "); }));
3271
- }
3272
- return [4 /*yield*/, onProgress(progress_1)];
3273
- case 1:
3274
- _h.sent();
3275
- _h.label = 2;
3276
- case 2:
3277
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3278
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3279
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3280
- 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)
3281
- .map(function (name) { return "{".concat(name, "}"); })
3282
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3283
- .map(function (name) { return "{".concat(name, "}"); })
3284
- .join(', '), "\n\n "); }));
3285
- }
3286
- _b = (_a = Object).freeze;
3287
- _c = [{}];
3288
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3289
- case 3:
3290
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3291
- definedParameterNames = new Set(Object.keys(definedParameters));
3292
- parameters = {};
3293
- _loop_4 = function (parameterName) {
3294
- // Situation: Parameter is defined and used
3295
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3296
- parameters[parameterName] = definedParameters[parameterName];
3297
- }
3298
- // Situation: Parameter is defined but NOT used
3299
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3300
- // Situation: Parameter is NOT defined BUT used
3301
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3302
- // Houston, we have a problem
3303
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3304
- 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 "); }));
3305
- }
3306
- };
3307
- try {
3308
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3309
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3310
- parameterName = _e.value;
3311
- _loop_4(parameterName);
3312
- }
3313
- }
3314
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3315
- finally {
3316
- try {
3317
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3318
- }
3319
- finally { if (e_4) throw e_4.error; }
3320
- }
3321
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3322
- Object.freeze(parameters);
3323
- result = null;
3324
- resultString = null;
3325
- expectError = null;
3326
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3327
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3328
- preparedContent = (currentTemplate.preparedContent || '{content}')
3329
- .split('{content}')
3330
- .join(currentTemplate.content);
3331
- _loop_5 = function (attempt) {
3332
- 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;
3333
- var e_5, _s, e_7, _t, e_6, _u;
3334
- return __generator(this, function (_v) {
3335
- switch (_v.label) {
3336
- case 0:
3337
- isJokerAttempt = attempt < 0;
3338
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3339
- // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3340
- if (isJokerAttempt && !jokerParameterName) {
3341
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3342
- }
3343
- result = null;
3344
- resultString = null;
3345
- expectError = null;
3346
- if (isJokerAttempt) {
3347
- if (parameters[jokerParameterName] === undefined) {
3348
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3349
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3350
- }
3351
- else {
3352
- resultString = parameters[jokerParameterName];
3353
- }
3354
- }
3355
- _v.label = 1;
3356
- case 1:
3357
- _v.trys.push([1, 44, 45, 46]);
3358
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3359
- _j = currentTemplate.templateType;
3360
- switch (_j) {
3361
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3362
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3363
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3364
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3365
- }
3366
- return [3 /*break*/, 25];
3367
- case 2:
3368
- resultString = replaceParameters(preparedContent, parameters);
3369
- return [3 /*break*/, 26];
3370
- case 3:
3371
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3372
- prompt = {
3373
- title: currentTemplate.title,
3374
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3375
- ? preparedPipeline.pipelineUrl
3376
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3377
- parameters: parameters,
3378
- content: preparedContent,
3379
- modelRequirements: modelRequirements,
3380
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3381
- var name = _a.name;
3382
- return name === currentTemplate.personaName;
3383
- }) || {})), currentTemplate.expectations),
3384
- format: currentTemplate.format,
3385
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3386
- }; // <- TODO: Not very good type guard
3387
- _k = modelRequirements.modelVariant;
3388
- switch (_k) {
3389
- case 'CHAT': return [3 /*break*/, 4];
3390
- case 'COMPLETION': return [3 /*break*/, 6];
3391
- case 'EMBEDDING': return [3 /*break*/, 8];
3392
- }
3393
- return [3 /*break*/, 10];
3394
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3395
- case 5:
3396
- chatResult = _v.sent();
3397
- // TODO: [🍬] Destroy chatThread
3398
- result = chatResult;
3399
- resultString = chatResult.content;
3400
- return [3 /*break*/, 11];
3401
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3402
- case 7:
3403
- completionResult = _v.sent();
3404
- result = completionResult;
3405
- resultString = completionResult.content;
3406
- return [3 /*break*/, 11];
3407
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3408
- case 9:
3409
- embeddingResult = _v.sent();
3410
- result = embeddingResult;
3411
- resultString = embeddingResult.content.join(',');
3412
- return [3 /*break*/, 11];
3413
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3414
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3415
- case 11: return [3 /*break*/, 26];
3416
- case 12:
3417
- if (arrayableToArray(tools.script).length === 0) {
3418
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3419
- }
3420
- if (!currentTemplate.contentLanguage) {
3421
- 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 "); }));
3422
- }
3423
- // TODO: DRY [1]
3424
- scriptPipelineExecutionErrors = [];
3425
- _v.label = 13;
3426
- case 13:
3427
- _v.trys.push([13, 20, 21, 22]);
3428
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3429
- _v.label = 14;
3430
- case 14:
3431
- if (!!_m.done) return [3 /*break*/, 19];
3432
- scriptTools = _m.value;
3433
- _v.label = 15;
3434
- case 15:
3435
- _v.trys.push([15, 17, , 18]);
3436
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3437
- scriptLanguage: currentTemplate.contentLanguage,
3438
- script: preparedContent,
3439
- parameters: parameters,
3440
- }))];
3441
- case 16:
3442
- resultString = _v.sent();
3443
- return [3 /*break*/, 19];
3444
- case 17:
3445
- error_2 = _v.sent();
3446
- if (!(error_2 instanceof Error)) {
3447
- throw error_2;
3448
- }
3449
- if (error_2 instanceof UnexpectedError) {
3450
- throw error_2;
3451
- }
3452
- scriptPipelineExecutionErrors.push(error_2);
3453
- return [3 /*break*/, 18];
3454
- case 18:
3455
- _m = _l.next();
3456
- return [3 /*break*/, 14];
3457
- case 19: return [3 /*break*/, 22];
3458
- case 20:
3459
- e_5_1 = _v.sent();
3460
- e_5 = { error: e_5_1 };
3461
- return [3 /*break*/, 22];
3462
- case 21:
3463
- try {
3464
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3465
- }
3466
- finally { if (e_5) throw e_5.error; }
3467
- return [7 /*endfinally*/];
3468
- case 22:
3469
- if (resultString !== null) {
3470
- return [3 /*break*/, 26];
3471
- }
3472
- if (scriptPipelineExecutionErrors.length === 1) {
3473
- throw scriptPipelineExecutionErrors[0];
3474
- }
3475
- else {
3476
- 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
3477
- .map(function (error) { return '- ' + error.message; })
3478
- .join('\n\n')), "\n "); }));
3479
- }
3480
- case 23:
3481
- if (tools.userInterface === undefined) {
3482
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3483
- }
3484
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3485
- promptTitle: currentTemplate.title,
3486
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3487
- defaultValue: replaceParameters(preparedContent, parameters),
3488
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3489
- placeholder: undefined,
3490
- priority: priority,
3491
- }))];
3492
- case 24:
3493
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3494
- resultString = _v.sent();
3495
- return [3 /*break*/, 26];
3496
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3497
- case 26:
3498
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3499
- _v.label = 27;
3500
- case 27:
3501
- _v.trys.push([27, 41, 42, 43]);
3502
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3503
- _v.label = 28;
3504
- case 28:
3505
- if (!!_p.done) return [3 /*break*/, 40];
3506
- functionName = _p.value;
3507
- // TODO: DRY [1]
3508
- scriptPipelineExecutionErrors = [];
3509
- postprocessingError = null;
3510
- _v.label = 29;
3511
- case 29:
3512
- _v.trys.push([29, 36, 37, 38]);
3513
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3514
- _v.label = 30;
3515
- case 30:
3516
- if (!!_r.done) return [3 /*break*/, 35];
3517
- scriptTools = _r.value;
3518
- _v.label = 31;
3519
- case 31:
3520
- _v.trys.push([31, 33, , 34]);
3521
- return [4 /*yield*/, scriptTools.execute({
3522
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3523
- script: "".concat(functionName, "(resultString)"),
3524
- parameters: {
3525
- resultString: resultString || '',
3526
- // Note: No ...parametersForTemplate, because working with result only
3527
- },
3528
- })];
3529
- case 32:
3530
- resultString = _v.sent();
3531
- postprocessingError = null;
3532
- return [3 /*break*/, 35];
3533
- case 33:
3534
- error_3 = _v.sent();
3535
- if (!(error_3 instanceof Error)) {
3536
- throw error_3;
3537
- }
3538
- if (error_3 instanceof UnexpectedError) {
3539
- throw error_3;
3540
- }
3541
- postprocessingError = error_3;
3542
- scriptPipelineExecutionErrors.push(error_3);
3543
- return [3 /*break*/, 34];
3544
- case 34:
3545
- _r = _q.next();
3546
- return [3 /*break*/, 30];
3547
- case 35: return [3 /*break*/, 38];
3548
- case 36:
3549
- e_6_1 = _v.sent();
3550
- e_6 = { error: e_6_1 };
3551
- return [3 /*break*/, 38];
3552
- case 37:
3553
- try {
3554
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3555
- }
3556
- finally { if (e_6) throw e_6.error; }
3557
- return [7 /*endfinally*/];
3558
- case 38:
3559
- if (postprocessingError) {
3560
- throw postprocessingError;
3561
- }
3562
- _v.label = 39;
3563
- case 39:
3564
- _p = _o.next();
3565
- return [3 /*break*/, 28];
3566
- case 40: return [3 /*break*/, 43];
3567
- case 41:
3568
- e_7_1 = _v.sent();
3569
- e_7 = { error: e_7_1 };
3570
- return [3 /*break*/, 43];
3571
- case 42:
3572
- try {
3573
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3574
- }
3575
- finally { if (e_7) throw e_7.error; }
3576
- return [7 /*endfinally*/];
3577
- case 43:
3578
- // TODO: [💝] Unite object for expecting amount and format
3579
- if (currentTemplate.format) {
3580
- if (currentTemplate.format === 'JSON') {
3581
- if (!isValidJsonString(resultString || '')) {
3582
- // TODO: [🏢] Do more universally via `FormatDefinition`
3583
- try {
3584
- resultString = extractJsonBlock(resultString || '');
3585
- }
3586
- catch (error) {
3587
- keepUnused(error);
3588
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3589
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3590
- }
3591
- }
3592
- }
3593
- else {
3594
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3595
- }
3596
- }
3597
- // TODO: [💝] Unite object for expecting amount and format
3598
- if (currentTemplate.expectations) {
3599
- checkExpectations(currentTemplate.expectations, resultString || '');
3600
- }
3601
- return [2 /*return*/, "break-attempts"];
3602
- case 44:
3603
- error_4 = _v.sent();
3604
- if (!(error_4 instanceof ExpectError)) {
3605
- throw error_4;
3606
- }
3607
- expectError = error_4;
3608
- return [3 /*break*/, 46];
3609
- case 45:
3610
- if (!isJokerAttempt &&
3611
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3612
- prompt
3613
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3614
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3615
- ) {
3616
- // TODO: [🧠] Maybe put other templateTypes into report
3617
- executionReport.promptExecutions.push({
3618
- prompt: __assign({}, prompt),
3619
- result: result || undefined,
3620
- error: expectError === null ? undefined : serializeError(expectError),
3621
- });
3622
- }
3623
- return [7 /*endfinally*/];
3624
- case 46:
3625
- if (expectError !== null && attempt === maxAttempts - 1) {
3626
- 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
3627
- .split('\n')
3628
- .map(function (line) { return "> ".concat(line); })
3629
- .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) || '')
3630
- .split('\n')
3631
- .map(function (line) { return "> ".concat(line); })
3632
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3633
- ? 'null'
3634
- : resultString
3635
- .split('\n')
3636
- .map(function (line) { return "> ".concat(line); })
3637
- .join('\n')), "\n ---\n "); }));
3638
- }
3639
- return [2 /*return*/];
3640
- }
3641
- });
3642
- };
3643
- attempt = -jokerParameterNames.length;
3644
- _h.label = 4;
3645
- case 4:
3646
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3647
- return [5 /*yield**/, _loop_5(attempt)];
3648
- case 5:
3649
- state_2 = _h.sent();
3650
- switch (state_2) {
3651
- case "break-attempts": return [3 /*break*/, 7];
3652
- }
3653
- _h.label = 6;
3654
- case 6:
3655
- attempt++;
3656
- return [3 /*break*/, 4];
3657
- case 7:
3658
- //------------------------------------
3659
- /*
3660
-
3661
-
3662
-
3663
-
3664
-
3665
-
3666
-
3667
-
3668
-
3669
- */
3670
- //------------------------------------
3671
- if (resultString === null) {
3672
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3673
- }
3674
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3675
- progress_2 = {
3676
- name: name,
3677
- title: title,
3678
- isStarted: true,
3679
- isDone: true,
3680
- templateType: currentTemplate.templateType,
3681
- parameterName: currentTemplate.resultingParameterName,
3682
- parameterValue: resultString,
3683
- // <- [3]
3684
- };
3685
- if (isReturned) {
3686
- 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)
3687
- .split('\n')
3688
- .map(function (line) { return "> ".concat(line); })
3689
- .join('\n')), "\n\n "); }));
3690
- }
3691
- return [4 /*yield*/, onProgress(progress_2)];
3692
- case 8:
3693
- _h.sent();
3694
- _h.label = 9;
3695
- case 9:
3696
- 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)));
3697
- return [2 /*return*/];
3698
- }
3699
- });
3700
- });
3701
- }
3702
- function filterJustOutputParameters() {
3703
- var e_8, _a;
3704
- var outputParameters = {};
3705
- var _loop_6 = function (parameter) {
3706
- if (parametersToPass[parameter.name] === undefined) {
3707
- // [4]
3708
- 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 "); })));
3709
- return "continue";
3710
- }
3711
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3712
- };
3713
- try {
3714
- // Note: Filter ONLY output parameters
3715
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3716
- var isOutput = _a.isOutput;
3717
- return isOutput;
3718
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3719
- var parameter = _c.value;
3720
- _loop_6(parameter);
3721
- }
3722
- }
3723
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3724
- finally {
3725
- try {
3726
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3727
- }
3728
- finally { if (e_8) throw e_8.error; }
3729
- }
3730
- return outputParameters;
3731
- }
3732
- 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;
3733
4237
  var e_1, _e, e_2, _f;
3734
4238
  return __generator(this, function (_g) {
3735
4239
  switch (_g.label) {
3736
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));
3737
4245
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3738
4246
  return [4 /*yield*/, preparePipeline(pipeline, {
3739
4247
  llmTools: llmTools,
@@ -3742,6 +4250,7 @@ function createPipelineExecutor(options) {
3742
4250
  })];
3743
4251
  case 1:
3744
4252
  preparedPipeline = _g.sent();
4253
+ setPreparedPipeline(preparedPipeline);
3745
4254
  _g.label = 2;
3746
4255
  case 2:
3747
4256
  errors = [];
@@ -3811,7 +4320,7 @@ function createPipelineExecutor(options) {
3811
4320
  return name === parameterName;
3812
4321
  });
3813
4322
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3814
- 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 "); })));
3815
4324
  return [3 /*break*/, 4];
3816
4325
  case 1:
3817
4326
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3823,10 +4332,10 @@ function createPipelineExecutor(options) {
3823
4332
  // Note: Wait a short time to prevent race conditions
3824
4333
  _h.sent();
3825
4334
  _h.label = 3;
3826
- 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 "); }), {
3827
4336
  isSuccessful: false,
3828
4337
  errors: __spreadArray([
3829
- 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 "); }))
3830
4339
  ], __read(errors), false).map(serializeError),
3831
4340
  warnings: warnings.map(serializeError),
3832
4341
  executionReport: executionReport,
@@ -3890,7 +4399,7 @@ function createPipelineExecutor(options) {
3890
4399
  case 0:
3891
4400
  if (loopLimit-- < 0) {
3892
4401
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3893
- 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 "); }));
3894
4403
  }
3895
4404
  currentTemplate = unresovedTemplates_1.find(function (template) {
3896
4405
  return template.dependentParameterNames.every(function (name) {
@@ -3900,29 +4409,52 @@ function createPipelineExecutor(options) {
3900
4409
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3901
4410
  throw new UnexpectedError(
3902
4411
  // TODO: [🐎] DRY
3903
- 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
3904
4413
  .map(function (_a) {
3905
4414
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3906
4415
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3907
4416
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3908
4417
  .join(' and '));
3909
4418
  })
3910
- .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 "); }));
3911
4420
  case 1:
3912
4421
  if (!!currentTemplate) return [3 /*break*/, 3];
3913
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4422
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3914
4423
  case 2:
3915
- /* [5] */ _j.sent();
4424
+ /* [🤹‍♂️] */ _j.sent();
3916
4425
  return [3 /*break*/, 4];
3917
4426
  case 3:
3918
4427
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3919
- work_1 = executeSingleTemplate(currentTemplate)
3920
- .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: spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Template name: ").concat(currentTemplate.name, "\n Template title: ").concat(currentTemplate.title, "\n "); }),
4448
+ })
4449
+ .then(function (newParametersToPass) {
4450
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3921
4451
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3922
4452
  })
3923
4453
  .then(function () {
3924
4454
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3925
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
3926
4458
  resolving_1.push(work_1);
3927
4459
  _j.label = 4;
3928
4460
  case 4: return [2 /*return*/];
@@ -3949,7 +4481,12 @@ function createPipelineExecutor(options) {
3949
4481
  var result = _a.result;
3950
4482
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3951
4483
  })), false));
3952
- outputParameters_1 = filterJustOutputParameters();
4484
+ outputParameters_1 = filterJustOutputParameters({
4485
+ preparedPipeline: preparedPipeline,
4486
+ parametersToPass: parametersToPass,
4487
+ $warnings: warnings,
4488
+ pipelineIdentification: pipelineIdentification,
4489
+ });
3953
4490
  isReturned = true;
3954
4491
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3955
4492
  // Note: Wait a short time to prevent race conditions
@@ -3972,7 +4509,12 @@ function createPipelineExecutor(options) {
3972
4509
  var result = _a.result;
3973
4510
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3974
4511
  })), false));
3975
- outputParameters = filterJustOutputParameters();
4512
+ outputParameters = filterJustOutputParameters({
4513
+ preparedPipeline: preparedPipeline,
4514
+ parametersToPass: parametersToPass,
4515
+ $warnings: warnings,
4516
+ pipelineIdentification: pipelineIdentification,
4517
+ });
3976
4518
  isReturned = true;
3977
4519
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3978
4520
  // Note: Wait a short time to prevent race conditions
@@ -3992,22 +4534,65 @@ function createPipelineExecutor(options) {
3992
4534
  })];
3993
4535
  }
3994
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 runCount = 0;
4571
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4572
+ return __generator(this, function (_a) {
4573
+ runCount++;
4574
+ return [2 /*return*/, /* not await */ executePipeline({
4575
+ pipeline: pipeline,
4576
+ preparedPipeline: preparedPipeline,
4577
+ setPreparedPipeline: function (newPreparedPipeline) {
4578
+ preparedPipeline = newPreparedPipeline;
4579
+ },
4580
+ inputParameters: inputParameters,
4581
+ tools: tools,
4582
+ onProgress: onProgress,
4583
+ pipelineIdentification: spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n ").concat(runCount === 1 ? '' : "Run #".concat(runCount), "\n "); }),
4584
+ settings: {
4585
+ maxExecutionAttempts: maxExecutionAttempts,
4586
+ maxParallelCount: maxParallelCount,
4587
+ csvSettings: csvSettings,
4588
+ isVerbose: isVerbose,
4589
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4590
+ },
4591
+ })];
4592
+ });
3995
4593
  }); };
3996
4594
  return pipelineExecutor;
3997
4595
  }
3998
- /**
3999
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4000
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4001
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4002
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4003
- * TODO: [♈] Probbably move expectations from templates to parameters
4004
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4005
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4006
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4007
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4008
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4009
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4010
- */
4011
4596
 
4012
4597
  /**
4013
4598
  * @@@
@@ -4059,7 +4644,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4059
4644
  outputParameters = result.outputParameters;
4060
4645
  knowledgePiecesRaw = outputParameters.knowledgePieces;
4061
4646
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4062
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4647
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4063
4648
  if (isVerbose) {
4064
4649
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
4065
4650
  }
@@ -4117,8 +4702,13 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4117
4702
  case 6: return [3 /*break*/, 8];
4118
4703
  case 7:
4119
4704
  error_1 = _c.sent();
4705
+ // Note: Here is expected error:
4706
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4707
+ if (!(error_1 instanceof PipelineExecutionError)) {
4708
+ throw error_1;
4709
+ }
4120
4710
  // TODO: [🟥] Detect browser / node and make it colorfull
4121
- console.error(error_1);
4711
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4122
4712
  return [3 /*break*/, 8];
4123
4713
  case 8: return [2 /*return*/, {
4124
4714
  name: name,
@@ -4139,7 +4729,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4139
4729
  });
4140
4730
  }
4141
4731
  /**
4142
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4732
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4143
4733
  * TODO: [🪂] Do it in parallel 11:11
4144
4734
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4145
4735
  */
@@ -4163,7 +4753,7 @@ function prepareKnowledgePieces(knowledgeSources, options) {
4163
4753
  var partialPieces, pieces;
4164
4754
  return __generator(this, function (_a) {
4165
4755
  switch (_a.label) {
4166
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4756
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝][main] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4167
4757
  options)];
4168
4758
  case 1:
4169
4759
  partialPieces = _a.sent();
@@ -4355,7 +4945,7 @@ function preparePersona(personaDescription, options) {
4355
4945
  });
4356
4946
  }
4357
4947
  /**
4358
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4948
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4359
4949
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4360
4950
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4361
4951
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4404,7 +4994,7 @@ function prepareTemplates(pipeline, options) {
4404
4994
  case 0:
4405
4995
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4406
4996
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4407
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
4997
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4408
4998
  TODO_USE(parameters);
4409
4999
  templatesPrepared = new Array(
4410
5000
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4436,7 +5026,7 @@ function prepareTemplates(pipeline, options) {
4436
5026
  /**
4437
5027
  * TODO: [🧠] Add context to each template (if missing)
4438
5028
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4439
- * TODO: [♨] !!! Prepare index the samples and maybe templates
5029
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4440
5030
  * TODO: Write tests for `preparePipeline`
4441
5031
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4442
5032
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4608,7 +5198,7 @@ var knowledgeCommandParser = {
4608
5198
  if (sourceContent === '') {
4609
5199
  throw new ParseError("Source is not defined");
4610
5200
  }
4611
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5201
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4612
5202
  if (sourceContent.startsWith('http://')) {
4613
5203
  throw new ParseError("Source is not secure");
4614
5204
  }
@@ -4811,7 +5401,7 @@ var templateCommandParser = {
4811
5401
  if (command.templateType === 'KNOWLEDGE') {
4812
5402
  knowledgeCommandParser.$applyToPipelineJson({
4813
5403
  type: 'KNOWLEDGE',
4814
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5404
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4815
5405
  }, $pipelineJson);
4816
5406
  $templateJson.isTemplate = false;
4817
5407
  return;
@@ -5161,6 +5751,171 @@ function normalizeTo_SCREAMING_CASE(text) {
5161
5751
  * TODO: [🌺] Use some intermediate util splitWords
5162
5752
  */
5163
5753
 
5754
+ /**
5755
+ * @@@
5756
+ *
5757
+ * @param text @@@
5758
+ * @param _isFirstLetterCapital @@@
5759
+ * @returns @@@
5760
+ * @example 'helloWorld'
5761
+ * @example 'iLovePromptbook'
5762
+ * @public exported from `@promptbook/utils`
5763
+ */
5764
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5765
+ var e_1, _a;
5766
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5767
+ var charType;
5768
+ var lastCharType = null;
5769
+ var normalizedName = '';
5770
+ try {
5771
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5772
+ var char = text_1_1.value;
5773
+ var normalizedChar = void 0;
5774
+ if (/^[a-z]$/.test(char)) {
5775
+ charType = 'LOWERCASE';
5776
+ normalizedChar = char;
5777
+ }
5778
+ else if (/^[A-Z]$/.test(char)) {
5779
+ charType = 'UPPERCASE';
5780
+ normalizedChar = char.toLowerCase();
5781
+ }
5782
+ else if (/^[0-9]$/.test(char)) {
5783
+ charType = 'NUMBER';
5784
+ normalizedChar = char;
5785
+ }
5786
+ else {
5787
+ charType = 'OTHER';
5788
+ normalizedChar = '';
5789
+ }
5790
+ if (!lastCharType) {
5791
+ if (_isFirstLetterCapital) {
5792
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5793
+ }
5794
+ }
5795
+ else if (charType !== lastCharType &&
5796
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5797
+ !(lastCharType === 'NUMBER') &&
5798
+ !(charType === 'NUMBER')) {
5799
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5800
+ }
5801
+ normalizedName += normalizedChar;
5802
+ lastCharType = charType;
5803
+ }
5804
+ }
5805
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5806
+ finally {
5807
+ try {
5808
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5809
+ }
5810
+ finally { if (e_1) throw e_1.error; }
5811
+ }
5812
+ return normalizedName;
5813
+ }
5814
+ /**
5815
+ * TODO: [🌺] Use some intermediate util splitWords
5816
+ */
5817
+
5818
+ /**
5819
+ * Removes quotes from a string
5820
+ *
5821
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5822
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5823
+ * Note: There are two simmilar functions:
5824
+ * - `removeQuotes` which removes only bounding quotes
5825
+ * - `unwrapResult` which removes whole introduce sentence
5826
+ *
5827
+ * @param text optionally quoted text
5828
+ * @returns text without quotes
5829
+ * @public exported from `@promptbook/utils`
5830
+ */
5831
+ function removeQuotes(text) {
5832
+ if (text.startsWith('"') && text.endsWith('"')) {
5833
+ return text.slice(1, -1);
5834
+ }
5835
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5836
+ return text.slice(1, -1);
5837
+ }
5838
+ return text;
5839
+ }
5840
+
5841
+ /**
5842
+ * Function `validateParameterName` will @@@
5843
+ *
5844
+ * @param parameterName @@@
5845
+ * @returns @@@
5846
+ * @throws {ParseError} @@@
5847
+ * @private within the repository
5848
+ */
5849
+ function validateParameterName(parameterName) {
5850
+ var e_1, _a;
5851
+ var rawParameterName = parameterName;
5852
+ try {
5853
+ for (var _b = __values([
5854
+ ['`', '`'],
5855
+ ['{', '}'],
5856
+ ['[', ']'],
5857
+ ['(', ')'],
5858
+ ['<', '>'],
5859
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5860
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5861
+ if (parameterName.substring(0, 1) === start &&
5862
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5863
+ // <- TODO: More universal that 1 character
5864
+ ) {
5865
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5866
+ // <- TODO: More universal that 1 character
5867
+ }
5868
+ }
5869
+ }
5870
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5871
+ finally {
5872
+ try {
5873
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5874
+ }
5875
+ finally { if (e_1) throw e_1.error; }
5876
+ }
5877
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5878
+ try {
5879
+ /*
5880
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5881
+ if (parameterName.includes(' ')) {
5882
+ throw new ParseError(`Parameter name cannot contain spaces`);
5883
+ }
5884
+ */
5885
+ if (parameterName.includes('.')) {
5886
+ throw new ParseError("Parameter name cannot contain dots");
5887
+ }
5888
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5889
+ throw new ParseError("Parameter name cannot contain slashes");
5890
+ }
5891
+ if (parameterName.includes('(') ||
5892
+ parameterName.includes(')') ||
5893
+ parameterName.includes('{') ||
5894
+ parameterName.includes('}') ||
5895
+ parameterName.includes('[') ||
5896
+ parameterName.includes(']')) {
5897
+ throw new ParseError("Parameter name cannot contain braces");
5898
+ }
5899
+ parameterName = removeDiacritics(parameterName);
5900
+ parameterName = removeEmojis(parameterName);
5901
+ parameterName = removeQuotes(parameterName);
5902
+ parameterName = normalizeTo_camelCase(parameterName);
5903
+ if (parameterName === '') {
5904
+ throw new ParseError("Parameter name cannot be empty");
5905
+ }
5906
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5907
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5908
+ }
5909
+ }
5910
+ catch (error) {
5911
+ if (!(error instanceof ParseError)) {
5912
+ throw error;
5913
+ }
5914
+ 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 "); }));
5915
+ }
5916
+ return parameterName;
5917
+ }
5918
+
5164
5919
  /**
5165
5920
  * Parses the foreach command
5166
5921
  *
@@ -5190,15 +5945,16 @@ var foreachCommandParser = {
5190
5945
  /**
5191
5946
  * Link to discussion
5192
5947
  */
5193
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5948
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5194
5949
  /**
5195
5950
  * Example usages of the FOREACH command
5196
5951
  */
5197
5952
  examples: [
5198
- 'FOREACH List Line `{customers}` -> `{customer}`',
5199
- 'FOR List Line `{customers}` -> `{customer}`',
5200
- 'EACH List Line `{customers}` -> `{customer}`',
5201
- // <- TODO: [🍭] !!!!!! More
5953
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5954
+ 'FOREACH Csv Cell `{customers}` -> `{cell}`',
5955
+ 'FOREACH Csv Row `{customers}` -> `{firstName}`, `{lastName}`, `+{email}`',
5956
+ 'FOR Text Line `{customers}` -> `{customer}`',
5957
+ 'EACH Text Line `{customers}` -> `{customer}`',
5202
5958
  ],
5203
5959
  /**
5204
5960
  * Parses the FOREACH command
@@ -5206,55 +5962,75 @@ var foreachCommandParser = {
5206
5962
  parse: function (input) {
5207
5963
  var args = input.args;
5208
5964
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5209
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5210
- var parameterNameWrapped = args[2];
5965
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5966
+ var parameterNameArg = args[2] || '';
5211
5967
  var assignSign = args[3];
5212
- var subparameterNameWrapped = args[4];
5213
- if (![
5214
- 'LIST',
5215
- 'CSV',
5216
- // <- TODO: [🏢] Unhardcode formats
5217
- ].includes(formatName)) {
5218
- console.info({ args: args, formatName: formatName });
5219
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5968
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5969
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5970
+ });
5971
+ if (formatDefinition === undefined) {
5972
+ 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; })
5973
+ .map(function (formatName) { return "- ".concat(formatName); })
5974
+ .join('\n')), "\n "); }));
5220
5975
  // <- TODO: [🏢] List all supported format names
5221
5976
  }
5222
- if (![
5223
- 'LINE',
5224
- 'ROW',
5225
- 'COLUMN',
5226
- 'CELL',
5227
- // <- TODO: [🏢] Unhardcode format cells
5228
- ].includes(cellName)) {
5229
- console.info({ args: args, cellName: cellName });
5230
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5231
- // <- TODO: [🏢] List all supported cell names for the format
5977
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5978
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5979
+ });
5980
+ if (subvalueDefinition === undefined) {
5981
+ 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
5982
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5983
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5984
+ .join('\n')), "\n "); }));
5985
+ // <- TODO: [🏢] List all supported subformat names for the format
5232
5986
  }
5233
5987
  if (assignSign !== '->') {
5234
- console.info({ args: args, assignSign: assignSign });
5235
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5236
- }
5237
- // TODO: !!!!!! Replace with propper parameter name validation
5238
- if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5239
- (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5240
- console.info({ args: args, parameterNameWrapped: parameterNameWrapped }, parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1), parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length));
5241
- throw new Error("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5242
- }
5243
- var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5244
- // TODO: !!!!!! Replace with propper parameter name validation
5245
- if ((subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(0, 1)) !== '{' ||
5246
- (subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(subparameterNameWrapped.length - 1, subparameterNameWrapped.length)) !==
5247
- '}') {
5248
- console.info({ args: args, subparameterNameWrapped: subparameterNameWrapped });
5249
- throw new Error("!!!!!! 2 Here will be error (with rules and precise error) from validateParameterName");
5250
- }
5251
- var subparameterName = subparameterNameWrapped.substring(1, subparameterNameWrapped.length - 1);
5988
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5989
+ }
5990
+ var parameterName = validateParameterName(parameterNameArg);
5991
+ var outputSubparameterName = null;
5992
+ // TODO: [4] DRY
5993
+ var inputSubparameterNames = args
5994
+ .slice(4)
5995
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5996
+ .filter(function (parameterName) { return !parameterName.includes('+'); })
5997
+ .filter(function (parameterName) { return parameterName !== ''; })
5998
+ .map(validateParameterName);
5999
+ // TODO: [4] DRY
6000
+ var outputSubparameterNames = args
6001
+ .slice(4)
6002
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6003
+ .filter(function (parameterName) { return parameterName.includes('+'); })
6004
+ .map(function (parameterName) { return parameterName.split('+').join(''); })
6005
+ .map(validateParameterName);
6006
+ if (outputSubparameterNames.length === 1) {
6007
+ outputSubparameterName = outputSubparameterNames[0];
6008
+ }
6009
+ else if (outputSubparameterNames.length > 1) {
6010
+ throw new ParseError("FOREACH command can not have more than one output subparameter");
6011
+ }
6012
+ if (inputSubparameterNames.length === 0) {
6013
+ throw new ParseError("FOREACH command must have at least one input subparameter");
6014
+ }
6015
+ if (outputSubparameterName === null) {
6016
+ // TODO: Following code should be unhardcoded from here and moved to the format definition
6017
+ if (formatName === 'CSV' && subformatName === 'CELL') {
6018
+ outputSubparameterName = 'newCell';
6019
+ }
6020
+ else if (formatName === 'TEXT' && subformatName === 'LINE') {
6021
+ outputSubparameterName = 'newLine';
6022
+ }
6023
+ else {
6024
+ throw new ParseError(spaceTrim$1("\n FOREACH ".concat(formatName, " ").concat(subformatName, " must specify output subparameter\n\n Correct example:\n - FOREACH ").concat(formatName, " ").concat(subformatName, " {").concat(parameterName, "} -> {inputSubparameterName1}, {inputSubparameterName2}, +{outputSubparameterName}\n\n ")));
6025
+ }
6026
+ }
5252
6027
  return {
5253
6028
  type: 'FOREACH',
5254
6029
  formatName: formatName,
5255
- cellName: cellName,
6030
+ subformatName: subformatName,
5256
6031
  parameterName: parameterName,
5257
- subparameterName: subparameterName,
6032
+ inputSubparameterNames: inputSubparameterNames,
6033
+ outputSubparameterName: outputSubparameterName,
5258
6034
  };
5259
6035
  },
5260
6036
  /**
@@ -5263,9 +6039,17 @@ var foreachCommandParser = {
5263
6039
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5264
6040
  */
5265
6041
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5266
- var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5267
- $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5268
- keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6042
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, inputSubparameterNames = command.inputSubparameterNames, outputSubparameterName = command.outputSubparameterName;
6043
+ // TODO: [🍭] Detect double use
6044
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6045
+ $templateJson.foreach = {
6046
+ formatName: formatName,
6047
+ subformatName: subformatName,
6048
+ parameterName: parameterName,
6049
+ inputSubparameterNames: inputSubparameterNames,
6050
+ outputSubparameterName: outputSubparameterName,
6051
+ };
6052
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5269
6053
  // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5270
6054
  },
5271
6055
  /**
@@ -5288,8 +6072,7 @@ var foreachCommandParser = {
5288
6072
  },
5289
6073
  };
5290
6074
  /**
5291
- * TODO: !!!!!! Comment console logs
5292
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6075
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5293
6076
  */
5294
6077
 
5295
6078
  /**
@@ -5399,12 +6182,11 @@ var jokerCommandParser = {
5399
6182
  */
5400
6183
  parse: function (input) {
5401
6184
  var args = input.args;
5402
- // TODO: !!!!!! Replace with propper parameter name validation
5403
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5404
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5405
- throw new ParseError("Invalid joker");
6185
+ if (args.length !== 1) {
6186
+ throw new ParseError("JOKE command expects exactly one parameter name");
5406
6187
  }
5407
- var parameterName = parametersMatch.groups.parameterName;
6188
+ var parameterNameArg = args[0] || '';
6189
+ var parameterName = validateParameterName(parameterNameArg);
5408
6190
  return {
5409
6191
  type: 'JOKER',
5410
6192
  parameterName: parameterName,
@@ -5479,6 +6261,9 @@ var modelCommandParser = {
5479
6261
  */
5480
6262
  parse: function (input) {
5481
6263
  var args = input.args, normalized = input.normalized;
6264
+ var availableVariantsMessage = spaceTrim$1(function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6265
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6266
+ }).join('\n')), "\n "); });
5482
6267
  // TODO: Make this more elegant and dynamically
5483
6268
  if (normalized.startsWith('MODEL_VARIANT')) {
5484
6269
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5494,17 +6279,13 @@ var modelCommandParser = {
5494
6279
  key: 'modelVariant',
5495
6280
  value: 'COMPLETION',
5496
6281
  };
6282
+ // <- Note: [🤖]
5497
6283
  }
5498
6284
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5499
- return {
5500
- type: 'MODEL',
5501
- key: 'modelVariant',
5502
- value: 'EMBEDDING',
5503
- };
5504
- // <- Note: [🤖]
6285
+ spaceTrim$1(function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5505
6286
  }
5506
6287
  else {
5507
- 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 "); }));
6288
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5508
6289
  }
5509
6290
  }
5510
6291
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5629,14 +6410,13 @@ var parameterCommandParser = {
5629
6410
  * Parses the PARAMETER command
5630
6411
  */
5631
6412
  parse: function (input) {
5632
- var normalized = input.normalized, raw = input.raw;
5633
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5634
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5635
- throw new ParseError("Invalid parameter");
5636
- }
5637
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5638
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5639
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6413
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6414
+ var parameterNameRaw = args.shift() || '';
6415
+ var parameterDescriptionRaw = args.join(' ');
6416
+ // <- TODO: When [🥶] fixed, change to:
6417
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6418
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6419
+ 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 "); }));
5640
6420
  }
5641
6421
  var isInput = normalized.startsWith('INPUT');
5642
6422
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5644,11 +6424,12 @@ var parameterCommandParser = {
5644
6424
  isInput = false;
5645
6425
  isOutput = false;
5646
6426
  }
5647
- // TODO: !!!!!! Add parameter name validation
6427
+ var parameterName = validateParameterName(parameterNameRaw);
6428
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5648
6429
  return {
5649
6430
  type: 'PARAMETER',
5650
6431
  parameterName: parameterName,
5651
- parameterDescription: parameterDescription.trim() || null,
6432
+ parameterDescription: parameterDescription,
5652
6433
  isInput: isInput,
5653
6434
  isOutput: isOutput,
5654
6435
  };
@@ -5973,6 +6754,7 @@ var promptbookVersionCommandParser = {
5973
6754
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
5974
6755
  */
5975
6756
  $applyToPipelineJson: function (command, $pipelineJson) {
6757
+ // TODO: Warn if the version is overridden
5976
6758
  $pipelineJson.promptbookVersion = command.promptbookVersion;
5977
6759
  },
5978
6760
  /**
@@ -6455,7 +7237,9 @@ function parseCommand(raw, usagePlace) {
6455
7237
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6456
7238
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6457
7239
  var args = items.slice(commandNameSegmentsCount + 1);
6458
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7240
+ var rawArgs = raw
7241
+ .substring(commandNameRaw.length)
7242
+ .trim();
6459
7243
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6460
7244
  if (command !== null) {
6461
7245
  return command;
@@ -6466,7 +7250,9 @@ function parseCommand(raw, usagePlace) {
6466
7250
  {
6467
7251
  var commandNameRaw = items.slice(-1).join('_');
6468
7252
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6469
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7253
+ var rawArgs = raw
7254
+ .substring(0, raw.length - commandNameRaw.length)
7255
+ .trim();
6470
7256
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6471
7257
  if (command !== null) {
6472
7258
  return command;
@@ -6606,7 +7392,7 @@ function extractAllListItemsFromMarkdown(markdown) {
6606
7392
  function extractOneBlockFromMarkdown(markdown) {
6607
7393
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6608
7394
  if (codeBlocks.length !== 1) {
6609
- 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 "); }));
7395
+ 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 "); }));
6610
7396
  }
6611
7397
  return codeBlocks[0];
6612
7398
  }
@@ -6793,7 +7579,7 @@ function pipelineStringToJsonSync(pipelineString) {
6793
7579
  var $pipelineJson = {
6794
7580
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6795
7581
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6796
- promptbookVersion: PROMPTBOOK_VERSION,
7582
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6797
7583
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6798
7584
  parameters: [],
6799
7585
  templates: [],
@@ -7084,7 +7870,7 @@ function pipelineStringToJsonSync(pipelineString) {
7084
7870
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7085
7871
  }
7086
7872
  /**
7087
- * TODO: !!!! Warn if used only sync version
7873
+ * TODO:[main] !!!! Warn if used only sync version
7088
7874
  * TODO: [🚞] Report here line/column of error
7089
7875
  * TODO: Use spaceTrim more effectively
7090
7876
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7589,7 +8375,7 @@ function isSerializableAsJson(value) {
7589
8375
  }
7590
8376
  }
7591
8377
  /**
7592
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8378
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7593
8379
  * TODO: [🧠][💺] Can be done this on type-level?
7594
8380
  */
7595
8381
 
@@ -7646,21 +8432,41 @@ function usageToWorktime(usage) {
7646
8432
  * @public exported from `@promptbook/core`
7647
8433
  */
7648
8434
  function usageToHuman(usage) {
7649
- var report = 'Usage:';
8435
+ var reportItems = [];
7650
8436
  var uncertainNumberToHuman = function (_a) {
7651
8437
  var value = _a.value, isUncertain = _a.isUncertain;
7652
8438
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7653
8439
  };
7654
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7655
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7656
- return spaceTrim$1(report);
8440
+ if (usage.price.value > 0.01
8441
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8442
+ ) {
8443
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8444
+ }
8445
+ else {
8446
+ reportItems.push("Negligible cost");
8447
+ }
8448
+ var worktime = usageToWorktime(usage);
8449
+ if (worktime.value >
8450
+ 1 / 60
8451
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8452
+ ) {
8453
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8454
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8455
+ }
8456
+ if (usage.output.charactersCount.value > 0) {
8457
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8458
+ }
8459
+ if (reportItems.length === 0) {
8460
+ // Note: For negligible usage, we report at least something
8461
+ reportItems.push('Negligible');
8462
+ }
8463
+ return spaceTrim$1(function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7657
8464
  }
7658
8465
  /**
7659
- * TODO: Use "$1" not "1 USD"
7660
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7661
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8466
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8467
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8468
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7662
8469
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7663
- * TODO: When negligible usage, report "Negligible" or just don't report it
7664
8470
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7665
8471
  * TODO: [🏛] Maybe make some markdown builder
7666
8472
  */
@@ -8430,7 +9236,7 @@ function initializeMakeCommand(program) {
8430
9236
  });
8431
9237
  }
8432
9238
  /**
8433
- * TODO: [🥃] !!! Allow `ptbk make` without configuring any llm tools
9239
+ * TODO: [🥃][main] !!! Allow `ptbk make` without configuring any llm tools
8434
9240
  * TODO: Maybe remove this command - "about" command should be enough?
8435
9241
  * TODO: [0] DRY Javascript and typescript - Maybe make ONLY typescript and for javascript just remove types
8436
9242
  * Note: [🟡] This code should never be published outside of `@promptbook/cli`
@@ -8464,70 +9270,6 @@ function addAutoGeneratedSection(content, options) {
8464
9270
  * TODO: [🏛] This can be part of markdown builder
8465
9271
  */
8466
9272
 
8467
- /**
8468
- * @@@
8469
- *
8470
- * @param text @@@
8471
- * @param _isFirstLetterCapital @@@
8472
- * @returns @@@
8473
- * @example 'helloWorld'
8474
- * @example 'iLovePromptbook'
8475
- * @public exported from `@promptbook/utils`
8476
- */
8477
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
8478
- var e_1, _a;
8479
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
8480
- var charType;
8481
- var lastCharType = null;
8482
- var normalizedName = '';
8483
- try {
8484
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
8485
- var char = text_1_1.value;
8486
- var normalizedChar = void 0;
8487
- if (/^[a-z]$/.test(char)) {
8488
- charType = 'LOWERCASE';
8489
- normalizedChar = char;
8490
- }
8491
- else if (/^[A-Z]$/.test(char)) {
8492
- charType = 'UPPERCASE';
8493
- normalizedChar = char.toLowerCase();
8494
- }
8495
- else if (/^[0-9]$/.test(char)) {
8496
- charType = 'NUMBER';
8497
- normalizedChar = char;
8498
- }
8499
- else {
8500
- charType = 'OTHER';
8501
- normalizedChar = '';
8502
- }
8503
- if (!lastCharType) {
8504
- if (_isFirstLetterCapital) {
8505
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
8506
- }
8507
- }
8508
- else if (charType !== lastCharType &&
8509
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
8510
- !(lastCharType === 'NUMBER') &&
8511
- !(charType === 'NUMBER')) {
8512
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
8513
- }
8514
- normalizedName += normalizedChar;
8515
- lastCharType = charType;
8516
- }
8517
- }
8518
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
8519
- finally {
8520
- try {
8521
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
8522
- }
8523
- finally { if (e_1) throw e_1.error; }
8524
- }
8525
- return normalizedName;
8526
- }
8527
- /**
8528
- * TODO: [🌺] Use some intermediate util splitWords
8529
- */
8530
-
8531
9273
  /**
8532
9274
  * Creates a Mermaid graph based on the promptbook
8533
9275
  *
@@ -8584,9 +9326,9 @@ function renderPromptbookMermaid(pipelineJson, options) {
8584
9326
  return promptbookMermaid;
8585
9327
  }
8586
9328
  /**
8587
- * TODO: !!!!!! FOREACH in mermaid graph
8588
- * TODO: !!!!!! Knowledge in mermaid graph
8589
- * TODO: !!!!!! Personas in mermaid graph
9329
+ * TODO: !!!!! FOREACH in mermaid graph
9330
+ * TODO: !!!!! Knowledge in mermaid graph
9331
+ * TODO: !!!!! Personas in mermaid graph
8590
9332
  * TODO: Maybe use some Mermaid package instead of string templating
8591
9333
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8592
9334
  */
@@ -8912,7 +9654,7 @@ var RemoteLlmExecutionTools = /** @class */ (function () {
8912
9654
  socket.on('connect', function () {
8913
9655
  resolve(socket);
8914
9656
  });
8915
- // TODO: !!!! Better timeout handling
9657
+ // TODO:[main] !!!! Better timeout handling
8916
9658
  setTimeout(function () {
8917
9659
  reject(new Error("Timeout while connecting to ".concat(_this.options.remoteUrl)));
8918
9660
  }, CONNECTION_TIMEOUT_MS);
@@ -9092,11 +9834,11 @@ var ANTHROPIC_CLAUDE_MODELS = $asDeeplyFrozenSerializableJson('ANTHROPIC_CLAUDE_
9092
9834
  output: computeUsage("$2.40 / 1M tokens"),
9093
9835
  },
9094
9836
  },
9095
- // TODO: !!! Claude 1 and 2 has also completion versions - ask Hoagy
9837
+ // TODO:[main] !!! Claude 1 and 2 has also completion versions - ask Hoagy
9096
9838
  ]);
9097
9839
  /**
9098
9840
  * Note: [🤖] Add models of new variant
9099
- * TODO: [🧠] !!! Add embedding models OR Anthropic has only chat+completion models?
9841
+ * TODO: [🧠][main] !!! Add embedding models OR Anthropic has only chat+completion models?
9100
9842
  * TODO: [🧠] Some mechanism to propagate unsureness
9101
9843
  * TODO: [🧠][👮‍♀️] Put here more info like description, isVision, trainingDateCutoff, languages, strengths ( Top-level performance, intelligence, fluency, and understanding), contextWindow,...
9102
9844
  * TODO: [🎰] Some mechanism to auto-update available models
@@ -9305,7 +10047,7 @@ var AnthropicClaudeExecutionTools = /** @class */ (function () {
9305
10047
  resultContent = contentBlock.text;
9306
10048
  // eslint-disable-next-line prefer-const
9307
10049
  complete = getCurrentIsoDate();
9308
- usage = computeAnthropicClaudeUsage(content, '', rawResponse);
10050
+ usage = computeAnthropicClaudeUsage(rawPromptContent || '', resultContent || '', rawResponse);
9309
10051
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('AnthropicClaudeExecutionTools ChatPromptResult', {
9310
10052
  content: resultContent,
9311
10053
  modelName: rawResponse.model,
@@ -9452,8 +10194,8 @@ var createAnthropicClaudeExecutionTools = Object.assign(function (options) {
9452
10194
  className: 'AnthropicClaudeExecutionTools',
9453
10195
  });
9454
10196
  /**
9455
- * TODO: [🧠] !!!! Make anonymous this with all LLM providers
9456
- * TODO: [🧠][🧱] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
10197
+ * TODO: [🧠][main] !!!! Make anonymous this with all LLM providers
10198
+ * TODO: [🧠][🧱][main] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
9457
10199
  * TODO: [🧠] Maybe auto-detect usage in browser and determine default value of `isProxied`
9458
10200
  * TODO: [🦺] Is there some way how to put `packageName` and `className` on top and function definition on bottom?
9459
10201
  * TODO: [🎶] Naming "constructor" vs "creator" vs "factory"
@@ -9831,6 +10573,7 @@ var OPENAI_MODELS = $asDeeplyFrozenSerializableJson('OPENAI_MODELS', [
9831
10573
  prompt: computeUsage("$5.00 / 1M tokens"),
9832
10574
  output: computeUsage("$15.00 / 1M tokens"),
9833
10575
  },
10576
+ //TODO:[main] !!!!!! Add gpt-4o-mini-2024-07-18 and all others to be up to date
9834
10577
  },
9835
10578
  /**/
9836
10579
  /**/
@@ -9845,6 +10588,51 @@ var OPENAI_MODELS = $asDeeplyFrozenSerializableJson('OPENAI_MODELS', [
9845
10588
  },
9846
10589
  /**/
9847
10590
  /**/
10591
+ {
10592
+ modelVariant: 'CHAT',
10593
+ modelTitle: 'o1-preview',
10594
+ modelName: 'o1-preview',
10595
+ pricing: {
10596
+ prompt: computeUsage("$15.00 / 1M tokens"),
10597
+ output: computeUsage("$60.00 / 1M tokens"),
10598
+ },
10599
+ },
10600
+ /**/
10601
+ /**/
10602
+ {
10603
+ modelVariant: 'CHAT',
10604
+ modelTitle: 'o1-preview-2024-09-12',
10605
+ modelName: 'o1-preview-2024-09-12',
10606
+ // <- TODO:[main] !!!!!! Some better system to organize theese date suffixes and versions
10607
+ pricing: {
10608
+ prompt: computeUsage("$15.00 / 1M tokens"),
10609
+ output: computeUsage("$60.00 / 1M tokens"),
10610
+ },
10611
+ },
10612
+ /**/
10613
+ /**/
10614
+ {
10615
+ modelVariant: 'CHAT',
10616
+ modelTitle: 'o1-mini',
10617
+ modelName: 'o1-mini',
10618
+ pricing: {
10619
+ prompt: computeUsage("$3.00 / 1M tokens"),
10620
+ output: computeUsage("$12.00 / 1M tokens"),
10621
+ },
10622
+ },
10623
+ /**/
10624
+ /**/
10625
+ {
10626
+ modelVariant: 'CHAT',
10627
+ modelTitle: 'o1-mini-2024-09-12',
10628
+ modelName: 'o1-mini-2024-09-12',
10629
+ pricing: {
10630
+ prompt: computeUsage("$3.00 / 1M tokens"),
10631
+ output: computeUsage("$12.00 / 1M tokens"),
10632
+ },
10633
+ },
10634
+ /**/
10635
+ /**/
9848
10636
  {
9849
10637
  modelVariant: 'CHAT',
9850
10638
  modelTitle: 'gpt-3.5-turbo-16k-0613',
@@ -9933,7 +10721,7 @@ var AzureOpenAiExecutionTools = /** @class */ (function () {
9933
10721
  AzureOpenAiExecutionTools.prototype.listModels = function () {
9934
10722
  return __awaiter(this, void 0, void 0, function () {
9935
10723
  return __generator(this, function (_a) {
9936
- // TODO: !!! Do here some filtering which models are really available as deployment
10724
+ // TODO:[main] !!! Do here some filtering which models are really available as deployment
9937
10725
  // @see https://management.azure.com/subscriptions/subscriptionId/resourceGroups/resourceGroupName/providers/Microsoft.CognitiveServices/accounts/accountName/deployments?api-version=2023-05-01
9938
10726
  return [2 /*return*/, OPENAI_MODELS.map(function (_a) {
9939
10727
  var modelTitle = _a.modelTitle, modelName = _a.modelName, modelVariant = _a.modelVariant;
@@ -10419,7 +11207,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10419
11207
  resultContent = rawResponse.choices[0].message.content;
10420
11208
  // eslint-disable-next-line prefer-const
10421
11209
  complete = getCurrentIsoDate();
10422
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11210
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10423
11211
  if (resultContent === null) {
10424
11212
  throw new PipelineExecutionError('No response message from OpenAI');
10425
11213
  }
@@ -10491,7 +11279,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10491
11279
  resultContent = rawResponse.choices[0].text;
10492
11280
  // eslint-disable-next-line prefer-const
10493
11281
  complete = getCurrentIsoDate();
10494
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11282
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10495
11283
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools CompletionPromptResult', {
10496
11284
  content: resultContent,
10497
11285
  modelName: rawResponse.model || modelName,
@@ -10551,7 +11339,9 @@ var OpenAiExecutionTools = /** @class */ (function () {
10551
11339
  resultContent = rawResponse.data[0].embedding;
10552
11340
  // eslint-disable-next-line prefer-const
10553
11341
  complete = getCurrentIsoDate();
10554
- usage = computeOpenAiUsage(content, '', rawResponse);
11342
+ usage = computeOpenAiUsage(content || '', '',
11343
+ // <- Note: Embedding does not have result content
11344
+ rawResponse);
10555
11345
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools EmbeddingPromptResult', {
10556
11346
  content: resultContent,
10557
11347
  modelName: rawResponse.model || modelName,
@@ -10622,7 +11412,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10622
11412
  * @public exported from `@promptbook/openai`
10623
11413
  */
10624
11414
  var createOpenAiExecutionTools = Object.assign(function (options) {
10625
- // TODO: [🧠] !!!! If browser, auto add `dangerouslyAllowBrowser`
11415
+ // TODO: [🧠][main] !!!! If browser, auto add `dangerouslyAllowBrowser`
10626
11416
  if (($isRunningInBrowser() || $isRunningInWebWorker()) && !options.dangerouslyAllowBrowser) {
10627
11417
  options = __assign(__assign({}, options), { dangerouslyAllowBrowser: true });
10628
11418
  }