@promptbook/cli 0.69.0-1 → 0.69.0-11

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 (55) hide show
  1. package/README.md +17 -58
  2. package/esm/index.es.js +1913 -1163
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/core.index.d.ts +5 -1
  5. package/esm/typings/src/_packages/types.index.d.ts +8 -0
  6. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  7. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +2 -6
  8. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +26 -0
  9. package/esm/typings/src/commands/FOREACH/foreachCommand.test.d.ts +3 -0
  10. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +2 -1
  11. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  12. package/esm/typings/src/config.d.ts +7 -1
  13. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  14. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  15. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +5 -0
  16. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +5 -3
  17. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +21 -0
  18. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  19. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +33 -0
  20. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +21 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  31. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  32. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +9 -12
  33. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  34. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +3 -2
  35. package/esm/typings/src/formats/index.d.ts +1 -1
  36. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +1 -1
  37. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +17 -0
  38. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +1 -1
  39. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  40. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  41. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  42. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  43. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  44. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  45. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  46. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  47. package/package.json +2 -1
  48. package/umd/index.umd.js +1916 -1167
  49. package/umd/index.umd.js.map +1 -1
  50. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  51. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  52. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  53. /package/esm/typings/src/{collection/constructors/createCollectionFromDirectory.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  54. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  55. /package/esm/typings/src/{execution/utils/usageToHuman.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,7 +21,7 @@ import OpenAI from 'openai';
20
21
  /**
21
22
  * The version of the Promptbook library
22
23
  */
23
- var PROMPTBOOK_VERSION = '0.69.0-0';
24
+ var PROMPTBOOK_VERSION = '0.69.0-10';
24
25
  // TODO: !!!! List here all the versions and annotate + put into script
25
26
 
26
27
  /*! *****************************************************************************
@@ -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
  ]);
@@ -507,6 +509,15 @@ var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
507
509
  * @public exported from `@promptbook/core`
508
510
  */
509
511
  var IS_VERBOSE = false;
512
+ /**
513
+ * @@@
514
+ *
515
+ * @private within the repository
516
+ */
517
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
518
+ /**/
519
+ // Note: In normal situations, we check the pipeline logic:
520
+ true);
510
521
  /**
511
522
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
512
523
  */
@@ -1040,7 +1051,7 @@ function forEachAsync(array, options, callbackfunction) {
1040
1051
  });
1041
1052
  }
1042
1053
 
1043
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1054
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-10",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-10",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-10",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-10",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1044
1055
 
1045
1056
  /**
1046
1057
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1247,6 +1258,26 @@ function isValidPipelineUrl(url) {
1247
1258
  * @public exported from `@promptbook/core`
1248
1259
  */
1249
1260
  function validatePipeline(pipeline) {
1261
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1262
+ validatePipelineCore(pipeline);
1263
+ }
1264
+ else {
1265
+ try {
1266
+ validatePipelineCore(pipeline);
1267
+ }
1268
+ catch (error) {
1269
+ if (!(error instanceof PipelineLogicError)) {
1270
+ throw error;
1271
+ }
1272
+ console.error(spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1273
+ }
1274
+ }
1275
+ return pipeline;
1276
+ }
1277
+ /**
1278
+ * @private internal function for `validatePipeline`
1279
+ */
1280
+ function validatePipelineCore(pipeline) {
1250
1281
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1251
1282
  var e_1, _a, e_2, _b, e_3, _c;
1252
1283
  var pipelineIdentification = (function () {
@@ -1271,12 +1302,12 @@ function validatePipeline(pipeline) {
1271
1302
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1272
1303
  if (!Array.isArray(pipeline.parameters)) {
1273
1304
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1274
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1305
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1275
1306
  }
1276
1307
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1277
1308
  if (!Array.isArray(pipeline.templates)) {
1278
1309
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1279
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1310
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1280
1311
  }
1281
1312
  var _loop_1 = function (parameter) {
1282
1313
  if (parameter.isInput && parameter.isOutput) {
@@ -1445,9 +1476,9 @@ function validatePipeline(pipeline) {
1445
1476
  while (unresovedTemplates.length > 0) {
1446
1477
  _loop_3();
1447
1478
  }
1448
- return pipeline;
1449
1479
  }
1450
1480
  /**
1481
+ * TODO: !!!!!! [🧞‍♀️] Do not allow joker + foreach
1451
1482
  * TODO: [🧠] Work with promptbookVersion
1452
1483
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1453
1484
  * > /**
@@ -2169,113 +2200,35 @@ function assertsExecutionSuccessful(executionResult) {
2169
2200
  */
2170
2201
 
2171
2202
  /**
2172
- * Parses the given script and returns the list of all used variables that are not defined in the script
2173
- *
2174
- * @param script from which to extract the variables
2175
- * @returns the list of variable names
2176
- * @throws {ParseError} if the script is invalid
2177
- * @public exported from `@promptbook/utils`
2178
- */
2179
- function extractVariables(script) {
2180
- var variables = new Set();
2181
- script = "(()=>{".concat(script, "})()");
2182
- try {
2183
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2184
- try {
2185
- eval(script);
2186
- }
2187
- catch (error) {
2188
- if (!(error instanceof ReferenceError)) {
2189
- throw error;
2190
- }
2191
- var undefinedName = error.message.split(' ')[0];
2192
- /*
2193
- Note: Parsing the error
2194
- [PipelineUrlError: thing is not defined]
2195
- */
2196
- if (!undefinedName) {
2197
- throw error;
2198
- }
2199
- if (script.includes(undefinedName + '(')) {
2200
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2201
- }
2202
- else {
2203
- variables.add(undefinedName);
2204
- script = "const ".concat(undefinedName, " = '';") + script;
2205
- }
2206
- }
2207
- }
2208
- catch (error) {
2209
- if (!(error instanceof Error)) {
2210
- throw error;
2211
- }
2212
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2213
- }
2214
- return variables;
2215
- }
2216
- /**
2217
- * TODO: [🔣] Support for multiple languages - python, java,...
2218
- */
2219
-
2220
- /**
2221
- * Parses the template and returns the set of all used parameters
2203
+ * Determine if the pipeline is fully prepared
2222
2204
  *
2223
- * @param template the template with used parameters
2224
- * @returns the set of parameter names
2225
- * @throws {ParseError} if the script is invalid
2226
- * @public exported from `@promptbook/utils`
2205
+ * @public exported from `@promptbook/core`
2227
2206
  */
2228
- function extractParameterNamesFromTemplate(template) {
2229
- var e_1, _a, e_2, _b, e_3, _c;
2230
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2231
- var parameterNames = new Set();
2232
- try {
2233
- for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2234
- var parameterName = _e.value;
2235
- parameterNames.add(parameterName);
2236
- }
2237
- }
2238
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2239
- finally {
2240
- try {
2241
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2242
- }
2243
- finally { if (e_1) throw e_1.error; }
2244
- }
2245
- if (templateType === 'SCRIPT_TEMPLATE') {
2246
- try {
2247
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2248
- var parameterName = _g.value;
2249
- parameterNames.add(parameterName);
2250
- }
2251
- }
2252
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2253
- finally {
2254
- try {
2255
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2256
- }
2257
- finally { if (e_2) throw e_2.error; }
2258
- }
2259
- }
2260
- try {
2261
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2262
- var jokerName = _j.value;
2263
- parameterNames.add(jokerName);
2264
- }
2207
+ function isPipelinePrepared(pipeline) {
2208
+ // Note: Ignoring `pipeline.preparations` @@@
2209
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2210
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2211
+ return false;
2265
2212
  }
2266
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2267
- finally {
2268
- try {
2269
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2270
- }
2271
- finally { if (e_3) throw e_3.error; }
2213
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2214
+ return false;
2272
2215
  }
2273
- parameterNames.delete('content');
2274
- // <- Note {websiteContent} is used in `preparedContent`
2275
- return parameterNames;
2216
+ /*
2217
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2218
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2219
+ > return false;
2220
+ > }
2221
+ */
2222
+ return true;
2276
2223
  }
2277
2224
  /**
2278
- * TODO: [🔣] If script require contentLanguage
2225
+ * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2226
+ * TODO: [🐠] Maybe base this on `makeValidator`
2227
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2228
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2229
+ * - [🏍] ? Is context in each template
2230
+ * - [♨] Are samples prepared
2231
+ * - [♨] Are templates prepared
2279
2232
  */
2280
2233
 
2281
2234
  /**
@@ -2295,27 +2248,6 @@ function serializeError(error) {
2295
2248
  };
2296
2249
  }
2297
2250
 
2298
- /**
2299
- * Function isValidJsonString will tell you if the string is valid JSON or not
2300
- *
2301
- * @public exported from `@promptbook/utils`
2302
- */
2303
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2304
- try {
2305
- JSON.parse(value);
2306
- return true;
2307
- }
2308
- catch (error) {
2309
- if (!(error instanceof Error)) {
2310
- throw error;
2311
- }
2312
- if (error.message.includes('Unexpected token')) {
2313
- return false;
2314
- }
2315
- return false;
2316
- }
2317
- }
2318
-
2319
2251
  /**
2320
2252
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2321
2253
  *
@@ -2610,288 +2542,153 @@ function joinLlmExecutionTools() {
2610
2542
  */
2611
2543
 
2612
2544
  /**
2613
- * Extracts all code blocks from markdown.
2545
+ * Takes an item or an array of items and returns an array of items
2614
2546
  *
2615
- * Note: There are multiple simmilar function:
2616
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2617
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2618
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2619
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2547
+ * 1) Any item except array and undefined returns array with that one item (also null)
2548
+ * 2) Undefined returns empty array
2549
+ * 3) Array returns itself
2620
2550
  *
2621
- * @param markdown any valid markdown
2622
- * @returns code blocks with language and content
2623
- * @throws {ParseError} if block is not closed properly
2624
- * @public exported from `@promptbook/markdown-utils`
2551
+ * @private internal utility
2625
2552
  */
2626
- function extractAllBlocksFromMarkdown(markdown) {
2627
- var e_1, _a;
2628
- var codeBlocks = [];
2629
- var lines = markdown.split('\n');
2630
- // Note: [0] Ensure that the last block notated by gt > will be closed
2631
- lines.push('');
2632
- var currentCodeBlock = null;
2553
+ function arrayableToArray(input) {
2554
+ if (input === undefined) {
2555
+ return [];
2556
+ }
2557
+ if (input instanceof Array) {
2558
+ return input;
2559
+ }
2560
+ return [input];
2561
+ }
2562
+
2563
+ /**
2564
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2565
+ *
2566
+ * @param script from which to extract the variables
2567
+ * @returns the list of variable names
2568
+ * @throws {ParseError} if the script is invalid
2569
+ * @public exported from `@promptbook/utils`
2570
+ */
2571
+ function extractVariables(script) {
2572
+ var variables = new Set();
2573
+ script = "(()=>{".concat(script, "})()");
2633
2574
  try {
2634
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2635
- var line = lines_1_1.value;
2636
- if (line.startsWith('> ') || line === '>') {
2637
- if (currentCodeBlock === null) {
2638
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2639
- } /* not else */
2640
- if (currentCodeBlock.blockNotation === '>') {
2641
- if (currentCodeBlock.content !== '') {
2642
- currentCodeBlock.content += '\n';
2643
- }
2644
- currentCodeBlock.content += line.slice(2);
2645
- }
2646
- }
2647
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2648
- codeBlocks.push(currentCodeBlock);
2649
- currentCodeBlock = null;
2575
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2576
+ try {
2577
+ eval(script);
2650
2578
  }
2651
- /* not else */
2652
- if (line.startsWith('```')) {
2653
- var language = line.slice(3).trim() || null;
2654
- if (currentCodeBlock === null) {
2655
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2579
+ catch (error) {
2580
+ if (!(error instanceof ReferenceError)) {
2581
+ throw error;
2656
2582
  }
2657
- else {
2658
- if (language !== null) {
2659
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2660
- }
2661
- codeBlocks.push(currentCodeBlock);
2662
- currentCodeBlock = null;
2583
+ var undefinedName = error.message.split(' ')[0];
2584
+ /*
2585
+ Note: Parsing the error
2586
+ [PipelineUrlError: thing is not defined]
2587
+ */
2588
+ if (!undefinedName) {
2589
+ throw error;
2663
2590
  }
2664
- }
2665
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2666
- if (currentCodeBlock.content !== '') {
2667
- currentCodeBlock.content += '\n';
2591
+ if (script.includes(undefinedName + '(')) {
2592
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2593
+ }
2594
+ else {
2595
+ variables.add(undefinedName);
2596
+ script = "const ".concat(undefinedName, " = '';") + script;
2668
2597
  }
2669
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2670
2598
  }
2599
+ }
2600
+ catch (error) {
2601
+ if (!(error instanceof Error)) {
2602
+ throw error;
2671
2603
  }
2604
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2672
2605
  }
2673
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2674
- finally {
2675
- try {
2676
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2677
- }
2678
- finally { if (e_1) throw e_1.error; }
2679
- }
2680
- if (currentCodeBlock !== null) {
2681
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2682
- }
2683
- return codeBlocks;
2684
- }
2685
- /**
2686
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2687
- */
2688
-
2689
- /**
2690
- * Extracts extracts exactly one valid JSON code block
2691
- *
2692
- * - When given string is a valid JSON as it is, it just returns it
2693
- * - When there is no JSON code block the function throws a `ParseError`
2694
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2695
- *
2696
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2697
- * Note: There are multiple simmilar function:
2698
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2699
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2700
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2701
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2702
- *
2703
- * @public exported from `@promptbook/markdown-utils`
2704
- * @throws {ParseError} if there is no valid JSON block in the markdown
2705
- */
2706
- function extractJsonBlock(markdown) {
2707
- if (isValidJsonString(markdown)) {
2708
- return markdown;
2709
- }
2710
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2711
- var jsonBlocks = codeBlocks.filter(function (_a) {
2712
- var content = _a.content;
2713
- return isValidJsonString(content);
2714
- });
2715
- if (jsonBlocks.length === 0) {
2716
- throw new Error('There is no valid JSON block in the markdown');
2717
- }
2718
- if (jsonBlocks.length > 1) {
2719
- throw new Error('There are multiple JSON code blocks in the markdown');
2720
- }
2721
- return jsonBlocks[0].content;
2722
- }
2723
- /**
2724
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2725
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2726
- */
2727
-
2728
- /**
2729
- * Determine if the pipeline is fully prepared
2730
- *
2731
- * @public exported from `@promptbook/core`
2732
- */
2733
- function isPipelinePrepared(pipeline) {
2734
- // Note: Ignoring `pipeline.preparations` @@@
2735
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2736
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2737
- return false;
2738
- }
2739
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2740
- return false;
2741
- }
2742
- /*
2743
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2744
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2745
- > return false;
2746
- > }
2747
- */
2748
- return true;
2749
- }
2750
- /**
2751
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2752
- * TODO: [🐠] Maybe base this on `makeValidator`
2753
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2754
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2755
- * - [🏍] ? Is context in each template
2756
- * - [♨] Are samples prepared
2757
- * - [♨] Are templates prepared
2758
- */
2759
-
2760
- /**
2761
- * Takes an item or an array of items and returns an array of items
2762
- *
2763
- * 1) Any item except array and undefined returns array with that one item (also null)
2764
- * 2) Undefined returns empty array
2765
- * 3) Array returns itself
2766
- *
2767
- * @private internal utility
2768
- */
2769
- function arrayableToArray(input) {
2770
- if (input === undefined) {
2771
- return [];
2772
- }
2773
- if (input instanceof Array) {
2774
- return input;
2775
- }
2776
- return [input];
2777
- }
2778
-
2779
- /**
2780
- * Just says that the variable is not used but should be kept
2781
- * No side effects.
2782
- *
2783
- * Note: It can be usefull for:
2784
- *
2785
- * 1) Suppressing eager optimization of unused imports
2786
- * 2) Suppressing eslint errors of unused variables in the tests
2787
- * 3) Keeping the type of the variable for type testing
2788
- *
2789
- * @param value any values
2790
- * @returns void
2791
- * @private within the repository
2792
- */
2793
- function keepUnused() {
2794
- var valuesToKeep = [];
2795
- for (var _i = 0; _i < arguments.length; _i++) {
2796
- valuesToKeep[_i] = arguments[_i];
2797
- }
2606
+ return variables;
2798
2607
  }
2799
-
2800
2608
  /**
2801
- * Just marks a place of place where should be something implemented
2802
- * No side effects.
2803
- *
2804
- * Note: It can be usefull suppressing eslint errors of unused variables
2805
- *
2806
- * @param value any values
2807
- * @returns void
2808
- * @private within the repository
2609
+ * TODO: [🔣] Support for multiple languages - python, java,...
2809
2610
  */
2810
- function TODO_USE() {
2811
- var value = [];
2812
- for (var _i = 0; _i < arguments.length; _i++) {
2813
- value[_i] = arguments[_i];
2814
- }
2815
- }
2816
2611
 
2817
2612
  /**
2818
- * Replaces parameters in template with values from parameters object
2613
+ * Parses the template and returns the set of all used parameters
2819
2614
  *
2820
- * @param template the template with parameters in {curly} braces
2821
- * @param parameters the object with parameters
2822
- * @returns the template with replaced parameters
2823
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2615
+ * @param template the template with used parameters
2616
+ * @returns the set of parameter names
2617
+ * @throws {ParseError} if the script is invalid
2824
2618
  * @public exported from `@promptbook/utils`
2825
2619
  */
2826
- function replaceParameters(template, parameters) {
2827
- var e_1, _a;
2620
+ function extractParameterNamesFromTemplate(template) {
2621
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2622
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2623
+ var parameterNames = new Set();
2828
2624
  try {
2829
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2830
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2831
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2832
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2833
- }
2834
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2835
- // TODO: [🍵]
2836
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2837
- }
2625
+ 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()) {
2626
+ var parameterName = _f.value;
2627
+ parameterNames.add(parameterName);
2838
2628
  }
2839
2629
  }
2840
2630
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2841
2631
  finally {
2842
2632
  try {
2843
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2633
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2844
2634
  }
2845
2635
  finally { if (e_1) throw e_1.error; }
2846
2636
  }
2847
- var replacedTemplate = template;
2848
- var match;
2849
- var loopLimit = LOOP_LIMIT;
2850
- var _loop_1 = function () {
2851
- if (loopLimit-- < 0) {
2852
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2637
+ if (templateType === 'SCRIPT_TEMPLATE') {
2638
+ try {
2639
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2640
+ var parameterName = _h.value;
2641
+ parameterNames.add(parameterName);
2642
+ }
2853
2643
  }
2854
- var precol = match.groups.precol;
2855
- var parameterName = match.groups.parameterName;
2856
- if (parameterName === '') {
2857
- return "continue";
2644
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2645
+ finally {
2646
+ try {
2647
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2648
+ }
2649
+ finally { if (e_2) throw e_2.error; }
2858
2650
  }
2859
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2860
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2651
+ }
2652
+ try {
2653
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2654
+ var jokerName = _k.value;
2655
+ parameterNames.add(jokerName);
2861
2656
  }
2862
- if (parameters[parameterName] === undefined) {
2863
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2657
+ }
2658
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2659
+ finally {
2660
+ try {
2661
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2864
2662
  }
2865
- var parameterValue = parameters[parameterName];
2866
- if (parameterValue === undefined) {
2867
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2663
+ finally { if (e_3) throw e_3.error; }
2664
+ }
2665
+ parameterNames.delete('content');
2666
+ // <- Note {websiteContent} is used in `preparedContent`
2667
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2668
+ if (foreach !== undefined) {
2669
+ try {
2670
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2671
+ var subparameterName = _m.value;
2672
+ if (parameterNames.has(subparameterName)) {
2673
+ parameterNames.delete(subparameterName);
2674
+ parameterNames.add(foreach.parameterName);
2675
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2676
+ }
2677
+ }
2868
2678
  }
2869
- parameterValue = parameterValue.toString();
2870
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2871
- parameterValue = parameterValue
2872
- .split('\n')
2873
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2874
- .join('\n');
2679
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2680
+ finally {
2681
+ try {
2682
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2683
+ }
2684
+ finally { if (e_4) throw e_4.error; }
2875
2685
  }
2876
- replacedTemplate =
2877
- replacedTemplate.substring(0, match.index + precol.length) +
2878
- parameterValue +
2879
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2880
- };
2881
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2882
- .exec(replacedTemplate))) {
2883
- _loop_1();
2884
2686
  }
2885
- // [💫] Check if there are parameters that are not closed properly
2886
- if (/{\w+$/.test(replacedTemplate)) {
2887
- throw new PipelineExecutionError('Parameter is not closed');
2888
- }
2889
- // [💫] Check if there are parameters that are not opened properly
2890
- if (/^\w+}/.test(replacedTemplate)) {
2891
- throw new PipelineExecutionError('Parameter is not opened');
2892
- }
2893
- return replacedTemplate;
2687
+ return parameterNames;
2894
2688
  }
2689
+ /**
2690
+ * TODO: [🔣] If script require contentLanguage
2691
+ */
2895
2692
 
2896
2693
  /**
2897
2694
  * Create difference set of two sets.
@@ -2969,117 +2766,364 @@ function union() {
2969
2766
  }
2970
2767
 
2971
2768
  /**
2972
- * Counts number of characters in the text
2769
+ * Just marks a place of place where should be something implemented
2770
+ * No side effects.
2973
2771
  *
2974
- * @public exported from `@promptbook/utils`
2975
- */
2976
- function countCharacters(text) {
2977
- // Remove null characters
2978
- text = text.replace(/\0/g, '');
2979
- // Replace emojis (and also ZWJ sequence) with hyphens
2980
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2981
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2982
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
2983
- return text.length;
2984
- }
2985
-
2986
- /**
2987
- * Counts number of lines in the text
2772
+ * Note: It can be usefull suppressing eslint errors of unused variables
2988
2773
  *
2989
- * @public exported from `@promptbook/utils`
2774
+ * @param value any values
2775
+ * @returns void
2776
+ * @private within the repository
2990
2777
  */
2991
- function countLines(text) {
2992
- if (text === '') {
2993
- return 0;
2778
+ function TODO_USE() {
2779
+ var value = [];
2780
+ for (var _i = 0; _i < arguments.length; _i++) {
2781
+ value[_i] = arguments[_i];
2994
2782
  }
2995
- return text.split('\n').length;
2996
2783
  }
2997
2784
 
2998
2785
  /**
2999
- * Counts number of pages in the text
2786
+ * Definition for CSV spreadsheet
3000
2787
  *
3001
- * @public exported from `@promptbook/utils`
2788
+ * @public exported from `@promptbook/core`
2789
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2790
+ */
2791
+ var CsvFormatDefinition = {
2792
+ formatName: 'CSV',
2793
+ aliases: ['SPREADSHEET', 'TABLE'],
2794
+ isValid: function (value, schema) {
2795
+ TODO_USE(value /* <- TODO: Use value here */);
2796
+ TODO_USE(schema /* <- TODO: Use schema here */);
2797
+ return true;
2798
+ },
2799
+ canBeValid: function (partialValue, schema) {
2800
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2801
+ TODO_USE(schema /* <- TODO: Use schema here */);
2802
+ return true;
2803
+ },
2804
+ heal: function (value, schema) {
2805
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2806
+ TODO_USE(schema /* <- TODO: Use schema here */);
2807
+ throw new Error('Not implemented');
2808
+ },
2809
+ subvalueDefinitions: [
2810
+ {
2811
+ subvalueName: 'ROW',
2812
+ mapValues: function (value, mapCallback) {
2813
+ return __awaiter(this, void 0, void 0, function () {
2814
+ var csv, mappedData;
2815
+ var _this = this;
2816
+ return __generator(this, function (_a) {
2817
+ switch (_a.label) {
2818
+ case 0:
2819
+ csv = parse(value, {
2820
+ header: true,
2821
+ delimiter: ',',
2822
+ quoteChar: '"',
2823
+ newline: '\r\n',
2824
+ skipEmptyLines: true,
2825
+ // encoding: 'utf8',
2826
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2827
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2828
+ });
2829
+ if (csv.errors.length !== 0) {
2830
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2831
+ 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 "); }));
2832
+ }
2833
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2834
+ var _a;
2835
+ var _b;
2836
+ return __generator(this, function (_c) {
2837
+ switch (_c.label) {
2838
+ case 0:
2839
+ _a = [__assign({}, row)];
2840
+ _b = {};
2841
+ // <- TODO: !!!!!! Dynamic new column name and position
2842
+ return [4 /*yield*/, mapCallback(row, index)];
2843
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2844
+ // <- TODO: !!!!!! Dynamic new column name and position
2845
+ _c.sent(), _b)])))];
2846
+ }
2847
+ });
2848
+ }); }))];
2849
+ case 1:
2850
+ mappedData = _a.sent();
2851
+ return [2 /*return*/, unparse(mappedData, {
2852
+ header: true,
2853
+ delimiter: ',',
2854
+ quoteChar: '"',
2855
+ newline: '\r\n',
2856
+ skipEmptyLines: true,
2857
+ // encoding: 'utf8',
2858
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2859
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2860
+ })];
2861
+ }
2862
+ });
2863
+ });
2864
+ },
2865
+ },
2866
+ {
2867
+ subvalueName: 'CELL',
2868
+ mapValues: function (value, mapCallback) {
2869
+ return __awaiter(this, void 0, void 0, function () {
2870
+ var csv, mappedData;
2871
+ var _this = this;
2872
+ return __generator(this, function (_a) {
2873
+ switch (_a.label) {
2874
+ case 0:
2875
+ csv = parse(value, {
2876
+ header: true,
2877
+ delimiter: ',',
2878
+ quoteChar: '"',
2879
+ newline: '\r\n',
2880
+ skipEmptyLines: true,
2881
+ // encoding: 'utf8',
2882
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2883
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2884
+ });
2885
+ if (csv.errors.length !== 0) {
2886
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2887
+ 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 "); }));
2888
+ }
2889
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2890
+ var _this = this;
2891
+ return __generator(this, function (_a) {
2892
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2893
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2894
+ return __awaiter(_this, void 0, void 0, function () {
2895
+ var index;
2896
+ var _c;
2897
+ return __generator(this, function (_d) {
2898
+ index = rowIndex * Object.keys(row).length + columnIndex;
2899
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2900
+ });
2901
+ });
2902
+ }))];
2903
+ });
2904
+ }); }))];
2905
+ case 1:
2906
+ mappedData = _a.sent();
2907
+ return [2 /*return*/, unparse(mappedData, {
2908
+ header: true,
2909
+ delimiter: ',',
2910
+ quoteChar: '"',
2911
+ newline: '\r\n',
2912
+ skipEmptyLines: true,
2913
+ // encoding: 'utf8',
2914
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2915
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2916
+ })];
2917
+ }
2918
+ });
2919
+ });
2920
+ },
2921
+ },
2922
+ ],
2923
+ };
2924
+ /**
2925
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2926
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2927
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2928
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2929
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3002
2930
  */
3003
- function countPages(text) {
3004
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
3005
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3006
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3007
- return pageCount;
3008
- }
3009
2931
 
3010
2932
  /**
3011
- * Counts number of paragraphs in the text
2933
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3012
2934
  *
3013
2935
  * @public exported from `@promptbook/utils`
3014
2936
  */
3015
- function countParagraphs(text) {
3016
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
2937
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2938
+ try {
2939
+ JSON.parse(value);
2940
+ return true;
2941
+ }
2942
+ catch (error) {
2943
+ if (!(error instanceof Error)) {
2944
+ throw error;
2945
+ }
2946
+ if (error.message.includes('Unexpected token')) {
2947
+ return false;
2948
+ }
2949
+ return false;
2950
+ }
3017
2951
  }
3018
2952
 
3019
2953
  /**
3020
- * Split text into sentences
2954
+ * Definition for JSON format
3021
2955
  *
3022
- * @public exported from `@promptbook/utils`
2956
+ * @private still in development [🏢]
3023
2957
  */
3024
- function splitIntoSentences(text) {
3025
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3026
- }
2958
+ var JsonFormatDefinition = {
2959
+ formatName: 'JSON',
2960
+ mimeType: 'application/json',
2961
+ isValid: function (value, schema) {
2962
+ TODO_USE(schema /* <- TODO: Use schema here */);
2963
+ return isValidJsonString(value);
2964
+ },
2965
+ canBeValid: function (partialValue, schema) {
2966
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2967
+ TODO_USE(schema /* <- TODO: Use schema here */);
2968
+ return true;
2969
+ },
2970
+ heal: function (value, schema) {
2971
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2972
+ TODO_USE(schema /* <- TODO: Use schema here */);
2973
+ throw new Error('Not implemented');
2974
+ },
2975
+ subvalueDefinitions: [],
2976
+ };
3027
2977
  /**
3028
- * Counts number of sentences in the text
3029
- *
3030
- * @public exported from `@promptbook/utils`
2978
+ * TODO: [🧠] Maybe propper instance of object
2979
+ * TODO: [0] Make string_serialized_json
2980
+ * TODO: [1] Make type for JSON Schema
2981
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2982
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2983
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2984
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2985
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2986
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3031
2987
  */
3032
- function countSentences(text) {
3033
- return splitIntoSentences(text).length;
3034
- }
3035
2988
 
3036
2989
  /**
3037
- * Counts number of words in the text
2990
+ * Definition for any text - this will be always valid
3038
2991
  *
3039
- * @public exported from `@promptbook/utils`
2992
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
2993
+ *
2994
+ * @public exported from `@promptbook/core`
2995
+ */
2996
+ var TextFormatDefinition = {
2997
+ formatName: 'TEXT',
2998
+ isValid: function (value) {
2999
+ return typeof value === 'string';
3000
+ },
3001
+ canBeValid: function (partialValue) {
3002
+ return typeof partialValue === 'string';
3003
+ },
3004
+ heal: function () {
3005
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3006
+ },
3007
+ subvalueDefinitions: [
3008
+ {
3009
+ subvalueName: 'LINE',
3010
+ mapValues: function (value, mapCallback) {
3011
+ return __awaiter(this, void 0, void 0, function () {
3012
+ var lines, mappedLines;
3013
+ return __generator(this, function (_a) {
3014
+ switch (_a.label) {
3015
+ case 0:
3016
+ lines = value.split('\n');
3017
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3018
+ // TODO: [🧠] Maybe option to skip empty line
3019
+ /* not await */ return mapCallback({
3020
+ lineContent: lineContent,
3021
+ // TODO: [🧠] Maybe also put here `lineNumber`
3022
+ }, lineNumber);
3023
+ }))];
3024
+ case 1:
3025
+ mappedLines = _a.sent();
3026
+ return [2 /*return*/, mappedLines.join('\n')];
3027
+ }
3028
+ });
3029
+ });
3030
+ },
3031
+ },
3032
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3033
+ ],
3034
+ };
3035
+ /**
3036
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3037
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3038
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3039
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3040
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3041
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3040
3042
  */
3041
- function countWords(text) {
3042
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3043
- text = removeDiacritics(text);
3044
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3045
- }
3046
3043
 
3047
3044
  /**
3048
- * Index of all counter functions
3045
+ * Definition for XML format
3049
3046
  *
3050
- * @public exported from `@promptbook/utils`
3047
+ * @private still in development [🏢]
3051
3048
  */
3052
- var CountUtils = {
3053
- CHARACTERS: countCharacters,
3054
- WORDS: countWords,
3055
- SENTENCES: countSentences,
3056
- PARAGRAPHS: countParagraphs,
3057
- LINES: countLines,
3058
- PAGES: countPages,
3049
+ var XmlFormatDefinition = {
3050
+ formatName: 'XML',
3051
+ mimeType: 'application/xml',
3052
+ isValid: function (value, schema) {
3053
+ TODO_USE(value /* <- TODO: Use value here */);
3054
+ TODO_USE(schema /* <- TODO: Use schema here */);
3055
+ return true;
3056
+ },
3057
+ canBeValid: function (partialValue, schema) {
3058
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3059
+ TODO_USE(schema /* <- TODO: Use schema here */);
3060
+ return true;
3061
+ },
3062
+ heal: function (value, schema) {
3063
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3064
+ TODO_USE(schema /* <- TODO: Use schema here */);
3065
+ throw new Error('Not implemented');
3066
+ },
3067
+ subvalueDefinitions: [],
3059
3068
  };
3069
+ /**
3070
+ * TODO: [🧠] Maybe propper instance of object
3071
+ * TODO: [0] Make string_serialized_xml
3072
+ * TODO: [1] Make type for XML Schema
3073
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3074
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3075
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3076
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3077
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3078
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3079
+ */
3060
3080
 
3061
3081
  /**
3062
- * Function checkExpectations will check if the expectations on given value are met
3082
+ * Definitions for all formats supported by Promptbook
3063
3083
  *
3064
- * Note: There are two simmilar functions:
3065
- * - `checkExpectations` which throws an error if the expectations are not met
3066
- * - `isPassingExpectations` which returns a boolean
3084
+ * @private internal index of `...` <- TODO [🏢]
3085
+ */
3086
+ var FORMAT_DEFINITIONS = [
3087
+ JsonFormatDefinition,
3088
+ XmlFormatDefinition,
3089
+ TextFormatDefinition,
3090
+ CsvFormatDefinition,
3091
+ ];
3092
+
3093
+ /**
3094
+ * Maps available parameters to expected parameters
3067
3095
  *
3068
- * @throws {ExpectError} if the expectations are not met
3069
- * @returns {void} Nothing
3070
- * @private internal function of `createPipelineExecutor`
3096
+ * The strategy is:
3097
+ * 1) @@@
3098
+ * 2) @@@
3099
+ *
3100
+ * @throws {PipelineExecutionError} @@@
3101
+ * @private within the repository used in `createPipelineExecutor`
3071
3102
  */
3072
- function checkExpectations(expectations, value) {
3103
+ function mapAvailableToExpectedParameters(options) {
3073
3104
  var e_1, _a;
3105
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3106
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3107
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3108
+ var mappedParameters = {};
3074
3109
  try {
3075
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3076
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3077
- var amount = CountUtils[unit.toUpperCase()](value);
3078
- if (min && amount < min) {
3079
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3080
- } /* not else */
3081
- if (max && amount > max) {
3082
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3110
+ // Phase 1️⃣: Matching mapping
3111
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3112
+ var parameterName = _c.value;
3113
+ // Situation: Parameter is available and expected
3114
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3115
+ mappedParameters[parameterName] = availableParameters[parameterName];
3116
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3117
+ availableParametersNames.delete(parameterName);
3118
+ expectedParameterNames.delete(parameterName);
3119
+ }
3120
+ // Situation: Parameter is available but NOT expected
3121
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3122
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3123
+ }
3124
+ // Situation: Parameter is NOT available BUT expected
3125
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3126
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3083
3127
  }
3084
3128
  }
3085
3129
  }
@@ -3090,600 +3134,1123 @@ function checkExpectations(expectations, value) {
3090
3134
  }
3091
3135
  finally { if (e_1) throw e_1.error; }
3092
3136
  }
3137
+ if (expectedParameterNames.size === 0) {
3138
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3139
+ Object.freeze(mappedParameters);
3140
+ return mappedParameters;
3141
+ }
3142
+ // Phase 2️⃣: Non-matching mapping
3143
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3144
+ 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)
3145
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3146
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3147
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3148
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3149
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3150
+ .join('\n')), "\n\n "); }));
3151
+ }
3152
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3153
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3154
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3155
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3156
+ }
3157
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3158
+ Object.freeze(mappedParameters);
3159
+ return mappedParameters;
3093
3160
  }
3094
- /**
3095
- * TODO: [💝] Unite object for expecting amount and format
3096
- */
3097
3161
 
3098
3162
  /**
3099
- * Creates executor function from pipeline and execution tools.
3163
+ * Extracts all code blocks from markdown.
3100
3164
  *
3101
- * @returns The executor function
3102
- * @throws {PipelineLogicError} on logical error in the pipeline
3103
- * @public exported from `@promptbook/core`
3165
+ * Note: There are multiple simmilar function:
3166
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3167
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3168
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3169
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3170
+ *
3171
+ * @param markdown any valid markdown
3172
+ * @returns code blocks with language and content
3173
+ * @throws {ParseError} if block is not closed properly
3174
+ * @public exported from `@promptbook/markdown-utils`
3104
3175
  */
3105
- function createPipelineExecutor(options) {
3106
- var _this = this;
3107
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3108
- var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
3109
- validatePipeline(pipeline);
3110
- var pipelineIdentification = (function () {
3111
- // Note: This is a 😐 implementation of [🚞]
3112
- var _ = [];
3113
- if (pipeline.sourceFile !== undefined) {
3114
- _.push("File: ".concat(pipeline.sourceFile));
3176
+ function extractAllBlocksFromMarkdown(markdown) {
3177
+ var e_1, _a;
3178
+ var codeBlocks = [];
3179
+ var lines = markdown.split('\n');
3180
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3181
+ lines.push('');
3182
+ var currentCodeBlock = null;
3183
+ try {
3184
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3185
+ var line = lines_1_1.value;
3186
+ if (line.startsWith('> ') || line === '>') {
3187
+ if (currentCodeBlock === null) {
3188
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3189
+ } /* not else */
3190
+ if (currentCodeBlock.blockNotation === '>') {
3191
+ if (currentCodeBlock.content !== '') {
3192
+ currentCodeBlock.content += '\n';
3193
+ }
3194
+ currentCodeBlock.content += line.slice(2);
3195
+ }
3196
+ }
3197
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3198
+ codeBlocks.push(currentCodeBlock);
3199
+ currentCodeBlock = null;
3200
+ }
3201
+ /* not else */
3202
+ if (line.startsWith('```')) {
3203
+ var language = line.slice(3).trim() || null;
3204
+ if (currentCodeBlock === null) {
3205
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3206
+ }
3207
+ else {
3208
+ if (language !== null) {
3209
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3210
+ }
3211
+ codeBlocks.push(currentCodeBlock);
3212
+ currentCodeBlock = null;
3213
+ }
3214
+ }
3215
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3216
+ if (currentCodeBlock.content !== '') {
3217
+ currentCodeBlock.content += '\n';
3218
+ }
3219
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3220
+ }
3115
3221
  }
3116
- if (pipeline.pipelineUrl !== undefined) {
3117
- _.push("Url: ".concat(pipeline.pipelineUrl));
3222
+ }
3223
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3224
+ finally {
3225
+ try {
3226
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3118
3227
  }
3119
- return _.join('\n');
3120
- })();
3121
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3122
- var preparedPipeline;
3123
- if (isPipelinePrepared(pipeline)) {
3124
- preparedPipeline = pipeline;
3228
+ finally { if (e_1) throw e_1.error; }
3125
3229
  }
3126
- else if (isNotPreparedWarningSupressed !== true) {
3127
- console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3230
+ if (currentCodeBlock !== null) {
3231
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3128
3232
  }
3129
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3130
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3131
- function getContextForTemplate(template) {
3132
- return __awaiter(this, void 0, void 0, function () {
3133
- return __generator(this, function (_a) {
3134
- TODO_USE(template);
3135
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3136
- });
3137
- });
3138
- }
3139
- function getKnowledgeForTemplate(template) {
3140
- return __awaiter(this, void 0, void 0, function () {
3141
- return __generator(this, function (_a) {
3142
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3143
- TODO_USE(template);
3144
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3145
- var content = _a.content;
3146
- return "- ".concat(content);
3147
- }).join('\n')];
3148
- });
3149
- });
3150
- }
3151
- function getSamplesForTemplate(template) {
3152
- return __awaiter(this, void 0, void 0, function () {
3153
- return __generator(this, function (_a) {
3154
- // TODO: [♨] Implement Better - use real index and keyword search
3155
- TODO_USE(template);
3156
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3157
- });
3158
- });
3159
- }
3160
- function getReservedParametersForTemplate(template) {
3161
- return __awaiter(this, void 0, void 0, function () {
3162
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3163
- var e_3, _a;
3164
- return __generator(this, function (_b) {
3165
- switch (_b.label) {
3166
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3167
- case 1:
3168
- context = _b.sent();
3169
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3170
- case 2:
3171
- knowledge = _b.sent();
3172
- return [4 /*yield*/, getSamplesForTemplate(template)];
3173
- case 3:
3174
- samples = _b.sent();
3175
- currentDate = new Date().toISOString();
3176
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3177
- reservedParameters = {
3178
- content: RESERVED_PARAMETER_RESTRICTED,
3179
- context: context,
3180
- knowledge: knowledge,
3181
- samples: samples,
3182
- currentDate: currentDate,
3183
- modelName: modelName,
3184
- };
3185
- _loop_3 = function (parameterName) {
3186
- if (reservedParameters[parameterName] === undefined) {
3187
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3188
- }
3189
- };
3190
- try {
3191
- // Note: Doublecheck that ALL reserved parameters are defined:
3192
- for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3193
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3194
- _loop_3(parameterName);
3195
- }
3196
- }
3197
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3198
- finally {
3199
- try {
3200
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3201
- }
3202
- finally { if (e_3) throw e_3.error; }
3203
- }
3204
- return [2 /*return*/, reservedParameters];
3205
- }
3206
- });
3207
- });
3208
- }
3209
- function executeSingleTemplate(currentTemplate) {
3210
- return __awaiter(this, void 0, void 0, function () {
3211
- var name, title, priority, progress_1, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_4, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_5, attempt, state_2, progress_2;
3212
- var e_4, _f, _g;
3213
- return __generator(this, function (_h) {
3214
- switch (_h.label) {
3215
- case 0:
3216
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3217
- title = currentTemplate.title;
3218
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3219
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3220
- progress_1 = {
3221
- name: name,
3222
- title: title,
3223
- isStarted: false,
3224
- isDone: false,
3225
- templateType: currentTemplate.templateType,
3226
- parameterName: currentTemplate.resultingParameterName,
3227
- parameterValue: null,
3228
- // <- [3]
3229
- };
3230
- if (isReturned) {
3231
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3232
- .split('\n')
3233
- .map(function (line) { return "> ".concat(line); })
3234
- .join('\n')), "\n "); }));
3235
- }
3236
- return [4 /*yield*/, onProgress(progress_1)];
3237
- case 1:
3238
- _h.sent();
3239
- _h.label = 2;
3240
- case 2:
3241
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3242
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3243
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3244
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3245
- .map(function (name) { return "{".concat(name, "}"); })
3246
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3247
- .map(function (name) { return "{".concat(name, "}"); })
3248
- .join(', '), "\n\n "); }));
3249
- }
3250
- _b = (_a = Object).freeze;
3251
- _c = [{}];
3252
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3253
- case 3:
3254
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3255
- definedParameterNames = new Set(Object.keys(definedParameters));
3256
- parameters = {};
3257
- _loop_4 = function (parameterName) {
3258
- // Situation: Parameter is defined and used
3259
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3260
- parameters[parameterName] = definedParameters[parameterName];
3261
- }
3262
- // Situation: Parameter is defined but NOT used
3263
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3264
- // Situation: Parameter is NOT defined BUT used
3265
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3266
- // Houston, we have a problem
3267
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3268
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3269
- }
3270
- };
3271
- try {
3272
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3273
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3274
- parameterName = _e.value;
3275
- _loop_4(parameterName);
3276
- }
3277
- }
3278
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3279
- finally {
3280
- try {
3281
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3282
- }
3283
- finally { if (e_4) throw e_4.error; }
3284
- }
3285
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3286
- Object.freeze(parameters);
3287
- result = null;
3288
- resultString = null;
3289
- expectError = null;
3290
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3291
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3292
- preparedContent = (currentTemplate.preparedContent || '{content}')
3293
- .split('{content}')
3294
- .join(currentTemplate.content);
3295
- _loop_5 = function (attempt) {
3296
- var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_2, e_5_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_3, e_6_1, e_7_1, error_4;
3297
- var e_5, _s, e_7, _t, e_6, _u;
3298
- return __generator(this, function (_v) {
3299
- switch (_v.label) {
3300
- case 0:
3301
- isJokerAttempt = attempt < 0;
3302
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3303
- if (isJokerAttempt && !jokerParameterName) {
3304
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3305
- }
3306
- result = null;
3307
- resultString = null;
3308
- expectError = null;
3309
- if (isJokerAttempt) {
3310
- if (parameters[jokerParameterName] === undefined) {
3311
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3312
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3313
- }
3314
- else {
3315
- resultString = parameters[jokerParameterName];
3316
- }
3317
- }
3318
- _v.label = 1;
3319
- case 1:
3320
- _v.trys.push([1, 44, 45, 46]);
3321
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3322
- _j = currentTemplate.templateType;
3323
- switch (_j) {
3324
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3325
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3326
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3327
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3328
- }
3329
- return [3 /*break*/, 25];
3330
- case 2:
3331
- resultString = replaceParameters(preparedContent, parameters);
3332
- return [3 /*break*/, 26];
3333
- case 3:
3334
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3335
- prompt = {
3336
- title: currentTemplate.title,
3337
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3338
- ? preparedPipeline.pipelineUrl
3339
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3340
- parameters: parameters,
3341
- content: preparedContent,
3342
- modelRequirements: modelRequirements,
3343
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3344
- var name = _a.name;
3345
- return name === currentTemplate.personaName;
3346
- }) || {})), currentTemplate.expectations),
3347
- format: currentTemplate.format,
3348
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3349
- }; // <- TODO: Not very good type guard
3350
- _k = modelRequirements.modelVariant;
3351
- switch (_k) {
3352
- case 'CHAT': return [3 /*break*/, 4];
3353
- case 'COMPLETION': return [3 /*break*/, 6];
3354
- case 'EMBEDDING': return [3 /*break*/, 8];
3355
- }
3356
- return [3 /*break*/, 10];
3357
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3358
- case 5:
3359
- chatResult = _v.sent();
3360
- // TODO: [🍬] Destroy chatThread
3361
- result = chatResult;
3362
- resultString = chatResult.content;
3363
- return [3 /*break*/, 11];
3364
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3365
- case 7:
3366
- completionResult = _v.sent();
3367
- result = completionResult;
3368
- resultString = completionResult.content;
3369
- return [3 /*break*/, 11];
3370
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3371
- case 9:
3372
- embeddingResult = _v.sent();
3373
- result = embeddingResult;
3374
- resultString = embeddingResult.content.join(',');
3375
- return [3 /*break*/, 11];
3376
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3377
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3378
- case 11: return [3 /*break*/, 26];
3379
- case 12:
3380
- if (arrayableToArray(tools.script).length === 0) {
3381
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3382
- }
3383
- if (!currentTemplate.contentLanguage) {
3384
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3385
- }
3386
- // TODO: DRY [1]
3387
- scriptPipelineExecutionErrors = [];
3388
- _v.label = 13;
3389
- case 13:
3390
- _v.trys.push([13, 20, 21, 22]);
3391
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3392
- _v.label = 14;
3393
- case 14:
3394
- if (!!_m.done) return [3 /*break*/, 19];
3395
- scriptTools = _m.value;
3396
- _v.label = 15;
3397
- case 15:
3398
- _v.trys.push([15, 17, , 18]);
3399
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3400
- scriptLanguage: currentTemplate.contentLanguage,
3401
- script: preparedContent,
3402
- parameters: parameters,
3403
- }))];
3404
- case 16:
3405
- resultString = _v.sent();
3406
- return [3 /*break*/, 19];
3407
- case 17:
3408
- error_2 = _v.sent();
3409
- if (!(error_2 instanceof Error)) {
3410
- throw error_2;
3411
- }
3412
- if (error_2 instanceof UnexpectedError) {
3413
- throw error_2;
3414
- }
3415
- scriptPipelineExecutionErrors.push(error_2);
3416
- return [3 /*break*/, 18];
3417
- case 18:
3418
- _m = _l.next();
3419
- return [3 /*break*/, 14];
3420
- case 19: return [3 /*break*/, 22];
3421
- case 20:
3422
- e_5_1 = _v.sent();
3423
- e_5 = { error: e_5_1 };
3424
- return [3 /*break*/, 22];
3425
- case 21:
3426
- try {
3427
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3428
- }
3429
- finally { if (e_5) throw e_5.error; }
3430
- return [7 /*endfinally*/];
3431
- case 22:
3432
- if (resultString !== null) {
3433
- return [3 /*break*/, 26];
3434
- }
3435
- if (scriptPipelineExecutionErrors.length === 1) {
3436
- throw scriptPipelineExecutionErrors[0];
3437
- }
3438
- else {
3439
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3440
- .map(function (error) { return '- ' + error.message; })
3441
- .join('\n\n')), "\n "); }));
3442
- }
3443
- case 23:
3444
- if (tools.userInterface === undefined) {
3445
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3446
- }
3447
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3448
- promptTitle: currentTemplate.title,
3449
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3450
- defaultValue: replaceParameters(preparedContent, parameters),
3451
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3452
- placeholder: undefined,
3453
- priority: priority,
3454
- }))];
3455
- case 24:
3456
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3457
- resultString = _v.sent();
3458
- return [3 /*break*/, 26];
3459
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3460
- case 26:
3461
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3462
- _v.label = 27;
3463
- case 27:
3464
- _v.trys.push([27, 41, 42, 43]);
3465
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3466
- _v.label = 28;
3467
- case 28:
3468
- if (!!_p.done) return [3 /*break*/, 40];
3469
- functionName = _p.value;
3470
- // TODO: DRY [1]
3471
- scriptPipelineExecutionErrors = [];
3472
- postprocessingError = null;
3473
- _v.label = 29;
3474
- case 29:
3475
- _v.trys.push([29, 36, 37, 38]);
3476
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3477
- _v.label = 30;
3478
- case 30:
3479
- if (!!_r.done) return [3 /*break*/, 35];
3480
- scriptTools = _r.value;
3481
- _v.label = 31;
3482
- case 31:
3483
- _v.trys.push([31, 33, , 34]);
3484
- return [4 /*yield*/, scriptTools.execute({
3485
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3486
- script: "".concat(functionName, "(resultString)"),
3487
- parameters: {
3488
- resultString: resultString || '',
3489
- // Note: No ...parametersForTemplate, because working with result only
3490
- },
3491
- })];
3492
- case 32:
3493
- resultString = _v.sent();
3494
- postprocessingError = null;
3495
- return [3 /*break*/, 35];
3496
- case 33:
3497
- error_3 = _v.sent();
3498
- if (!(error_3 instanceof Error)) {
3499
- throw error_3;
3500
- }
3501
- if (error_3 instanceof UnexpectedError) {
3502
- throw error_3;
3503
- }
3504
- postprocessingError = error_3;
3505
- scriptPipelineExecutionErrors.push(error_3);
3506
- return [3 /*break*/, 34];
3507
- case 34:
3508
- _r = _q.next();
3509
- return [3 /*break*/, 30];
3510
- case 35: return [3 /*break*/, 38];
3511
- case 36:
3512
- e_6_1 = _v.sent();
3513
- e_6 = { error: e_6_1 };
3514
- return [3 /*break*/, 38];
3515
- case 37:
3516
- try {
3517
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3518
- }
3519
- finally { if (e_6) throw e_6.error; }
3520
- return [7 /*endfinally*/];
3521
- case 38:
3522
- if (postprocessingError) {
3523
- throw postprocessingError;
3524
- }
3525
- _v.label = 39;
3526
- case 39:
3527
- _p = _o.next();
3528
- return [3 /*break*/, 28];
3529
- case 40: return [3 /*break*/, 43];
3530
- case 41:
3531
- e_7_1 = _v.sent();
3532
- e_7 = { error: e_7_1 };
3533
- return [3 /*break*/, 43];
3534
- case 42:
3535
- try {
3536
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3537
- }
3538
- finally { if (e_7) throw e_7.error; }
3539
- return [7 /*endfinally*/];
3540
- case 43:
3541
- // TODO: [💝] Unite object for expecting amount and format
3542
- if (currentTemplate.format) {
3543
- if (currentTemplate.format === 'JSON') {
3544
- if (!isValidJsonString(resultString || '')) {
3545
- // TODO: [🏢] Do more universally via `FormatDefinition`
3546
- try {
3547
- resultString = extractJsonBlock(resultString || '');
3548
- }
3549
- catch (error) {
3550
- keepUnused(error);
3551
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3552
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3553
- }
3554
- }
3233
+ return codeBlocks;
3234
+ }
3235
+ /**
3236
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3237
+ */
3238
+
3239
+ /**
3240
+ * Extracts extracts exactly one valid JSON code block
3241
+ *
3242
+ * - When given string is a valid JSON as it is, it just returns it
3243
+ * - When there is no JSON code block the function throws a `ParseError`
3244
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3245
+ *
3246
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3247
+ * Note: There are multiple simmilar function:
3248
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3249
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3250
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3251
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3252
+ *
3253
+ * @public exported from `@promptbook/markdown-utils`
3254
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3255
+ */
3256
+ function extractJsonBlock(markdown) {
3257
+ if (isValidJsonString(markdown)) {
3258
+ return markdown;
3259
+ }
3260
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3261
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3262
+ var content = _a.content;
3263
+ return isValidJsonString(content);
3264
+ });
3265
+ if (jsonBlocks.length === 0) {
3266
+ throw new Error('There is no valid JSON block in the markdown');
3267
+ }
3268
+ if (jsonBlocks.length > 1) {
3269
+ throw new Error('There are multiple JSON code blocks in the markdown');
3270
+ }
3271
+ return jsonBlocks[0].content;
3272
+ }
3273
+ /**
3274
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3275
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3276
+ */
3277
+
3278
+ /**
3279
+ * Just says that the variable is not used but should be kept
3280
+ * No side effects.
3281
+ *
3282
+ * Note: It can be usefull for:
3283
+ *
3284
+ * 1) Suppressing eager optimization of unused imports
3285
+ * 2) Suppressing eslint errors of unused variables in the tests
3286
+ * 3) Keeping the type of the variable for type testing
3287
+ *
3288
+ * @param value any values
3289
+ * @returns void
3290
+ * @private within the repository
3291
+ */
3292
+ function keepUnused() {
3293
+ var valuesToKeep = [];
3294
+ for (var _i = 0; _i < arguments.length; _i++) {
3295
+ valuesToKeep[_i] = arguments[_i];
3296
+ }
3297
+ }
3298
+
3299
+ /**
3300
+ * Replaces parameters in template with values from parameters object
3301
+ *
3302
+ * @param template the template with parameters in {curly} braces
3303
+ * @param parameters the object with parameters
3304
+ * @returns the template with replaced parameters
3305
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3306
+ * @public exported from `@promptbook/utils`
3307
+ */
3308
+ function replaceParameters(template, parameters) {
3309
+ var e_1, _a;
3310
+ try {
3311
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3312
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3313
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3314
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3315
+ }
3316
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3317
+ // TODO: [🍵]
3318
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3319
+ }
3320
+ }
3321
+ }
3322
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3323
+ finally {
3324
+ try {
3325
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3326
+ }
3327
+ finally { if (e_1) throw e_1.error; }
3328
+ }
3329
+ var replacedTemplate = template;
3330
+ var match;
3331
+ var loopLimit = LOOP_LIMIT;
3332
+ var _loop_1 = function () {
3333
+ if (loopLimit-- < 0) {
3334
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3335
+ }
3336
+ var precol = match.groups.precol;
3337
+ var parameterName = match.groups.parameterName;
3338
+ if (parameterName === '') {
3339
+ return "continue";
3340
+ }
3341
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3342
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3343
+ }
3344
+ if (parameters[parameterName] === undefined) {
3345
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3346
+ }
3347
+ var parameterValue = parameters[parameterName];
3348
+ if (parameterValue === undefined) {
3349
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3350
+ }
3351
+ parameterValue = parameterValue.toString();
3352
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3353
+ parameterValue = parameterValue
3354
+ .split('\n')
3355
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3356
+ .join('\n');
3357
+ }
3358
+ replacedTemplate =
3359
+ replacedTemplate.substring(0, match.index + precol.length) +
3360
+ parameterValue +
3361
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3362
+ };
3363
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3364
+ .exec(replacedTemplate))) {
3365
+ _loop_1();
3366
+ }
3367
+ // [💫] Check if there are parameters that are not closed properly
3368
+ if (/{\w+$/.test(replacedTemplate)) {
3369
+ throw new PipelineExecutionError('Parameter is not closed');
3370
+ }
3371
+ // [💫] Check if there are parameters that are not opened properly
3372
+ if (/^\w+}/.test(replacedTemplate)) {
3373
+ throw new PipelineExecutionError('Parameter is not opened');
3374
+ }
3375
+ return replacedTemplate;
3376
+ }
3377
+
3378
+ /**
3379
+ * Counts number of characters in the text
3380
+ *
3381
+ * @public exported from `@promptbook/utils`
3382
+ */
3383
+ function countCharacters(text) {
3384
+ // Remove null characters
3385
+ text = text.replace(/\0/g, '');
3386
+ // Replace emojis (and also ZWJ sequence) with hyphens
3387
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3388
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3389
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3390
+ return text.length;
3391
+ }
3392
+
3393
+ /**
3394
+ * Counts number of lines in the text
3395
+ *
3396
+ * @public exported from `@promptbook/utils`
3397
+ */
3398
+ function countLines(text) {
3399
+ if (text === '') {
3400
+ return 0;
3401
+ }
3402
+ return text.split('\n').length;
3403
+ }
3404
+
3405
+ /**
3406
+ * Counts number of pages in the text
3407
+ *
3408
+ * @public exported from `@promptbook/utils`
3409
+ */
3410
+ function countPages(text) {
3411
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3412
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3413
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3414
+ return pageCount;
3415
+ }
3416
+
3417
+ /**
3418
+ * Counts number of paragraphs in the text
3419
+ *
3420
+ * @public exported from `@promptbook/utils`
3421
+ */
3422
+ function countParagraphs(text) {
3423
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3424
+ }
3425
+
3426
+ /**
3427
+ * Split text into sentences
3428
+ *
3429
+ * @public exported from `@promptbook/utils`
3430
+ */
3431
+ function splitIntoSentences(text) {
3432
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3433
+ }
3434
+ /**
3435
+ * Counts number of sentences in the text
3436
+ *
3437
+ * @public exported from `@promptbook/utils`
3438
+ */
3439
+ function countSentences(text) {
3440
+ return splitIntoSentences(text).length;
3441
+ }
3442
+
3443
+ /**
3444
+ * Counts number of words in the text
3445
+ *
3446
+ * @public exported from `@promptbook/utils`
3447
+ */
3448
+ function countWords(text) {
3449
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3450
+ text = removeDiacritics(text);
3451
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3452
+ }
3453
+
3454
+ /**
3455
+ * Index of all counter functions
3456
+ *
3457
+ * @public exported from `@promptbook/utils`
3458
+ */
3459
+ var CountUtils = {
3460
+ CHARACTERS: countCharacters,
3461
+ WORDS: countWords,
3462
+ SENTENCES: countSentences,
3463
+ PARAGRAPHS: countParagraphs,
3464
+ LINES: countLines,
3465
+ PAGES: countPages,
3466
+ };
3467
+ /**
3468
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3469
+ */
3470
+
3471
+ /**
3472
+ * Function checkExpectations will check if the expectations on given value are met
3473
+ *
3474
+ * Note: There are two simmilar functions:
3475
+ * - `checkExpectations` which throws an error if the expectations are not met
3476
+ * - `isPassingExpectations` which returns a boolean
3477
+ *
3478
+ * @throws {ExpectError} if the expectations are not met
3479
+ * @returns {void} Nothing
3480
+ * @private internal function of `createPipelineExecutor`
3481
+ */
3482
+ function checkExpectations(expectations, value) {
3483
+ var e_1, _a;
3484
+ try {
3485
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3486
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3487
+ var amount = CountUtils[unit.toUpperCase()](value);
3488
+ if (min && amount < min) {
3489
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3490
+ } /* not else */
3491
+ if (max && amount > max) {
3492
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3493
+ }
3494
+ }
3495
+ }
3496
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3497
+ finally {
3498
+ try {
3499
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3500
+ }
3501
+ finally { if (e_1) throw e_1.error; }
3502
+ }
3503
+ }
3504
+ /**
3505
+ * TODO: [💝] Unite object for expecting amount and format
3506
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3507
+ * Note: [💝] and [🤠] are interconnected together
3508
+ */
3509
+
3510
+ /**
3511
+ * @@@
3512
+ *
3513
+ * @private internal utility of `createPipelineExecutor`
3514
+ */
3515
+ function executeAttempts(options) {
3516
+ return __awaiter(this, void 0, void 0, function () {
3517
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3518
+ return __generator(this, function (_a) {
3519
+ switch (_a.label) {
3520
+ case 0:
3521
+ 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;
3522
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3523
+ $ongoingTemplateResult = {
3524
+ $result: null,
3525
+ $resultString: null,
3526
+ $expectError: null,
3527
+ $scriptPipelineExecutionErrors: [],
3528
+ };
3529
+ _loop_1 = function (attempt) {
3530
+ var isJokerAttempt, jokerParameterName, _b, modelRequirements, _c, _d, _e, _f, _g, _h, scriptTools, _j, error_1, e_1_1, _k, _l, _m, functionName, postprocessingError, _o, _p, scriptTools, _q, error_2, e_2_1, e_3_1, error_3;
3531
+ var e_1, _r, e_3, _s, e_2, _t;
3532
+ return __generator(this, function (_u) {
3533
+ switch (_u.label) {
3534
+ case 0:
3535
+ isJokerAttempt = attempt < 0;
3536
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3537
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3538
+ if (isJokerAttempt && !jokerParameterName) {
3539
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3540
+ }
3541
+ $ongoingTemplateResult.$result = null;
3542
+ $ongoingTemplateResult.$resultString = null;
3543
+ $ongoingTemplateResult.$expectError = null;
3544
+ if (isJokerAttempt) {
3545
+ if (parameters[jokerParameterName] === undefined) {
3546
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3547
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3548
+ }
3549
+ else {
3550
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3551
+ }
3552
+ }
3553
+ _u.label = 1;
3554
+ case 1:
3555
+ _u.trys.push([1, 44, 45, 46]);
3556
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3557
+ _b = template.templateType;
3558
+ switch (_b) {
3559
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3560
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3561
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3562
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3563
+ }
3564
+ return [3 /*break*/, 25];
3565
+ case 2:
3566
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3567
+ return [3 /*break*/, 26];
3568
+ case 3:
3569
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3570
+ $ongoingTemplateResult.$prompt = {
3571
+ title: template.title,
3572
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3573
+ ? preparedPipeline.pipelineUrl
3574
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3575
+ parameters: parameters,
3576
+ content: preparedContent,
3577
+ modelRequirements: modelRequirements,
3578
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3579
+ var name = _a.name;
3580
+ return name === template.personaName;
3581
+ }) ||
3582
+ {})), template.expectations),
3583
+ format: template.format,
3584
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3585
+ }; // <- TODO: Not very good type guard
3586
+ _c = modelRequirements.modelVariant;
3587
+ switch (_c) {
3588
+ case 'CHAT': return [3 /*break*/, 4];
3589
+ case 'COMPLETION': return [3 /*break*/, 6];
3590
+ case 'EMBEDDING': return [3 /*break*/, 8];
3591
+ }
3592
+ return [3 /*break*/, 10];
3593
+ case 4:
3594
+ _d = $ongoingTemplateResult;
3595
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3596
+ case 5:
3597
+ _d.$chatResult = _u.sent();
3598
+ // TODO: [🍬] Destroy chatThread
3599
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3600
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3601
+ return [3 /*break*/, 11];
3602
+ case 6:
3603
+ _e = $ongoingTemplateResult;
3604
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3605
+ case 7:
3606
+ _e.$completionResult = _u.sent();
3607
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3608
+ $ongoingTemplateResult.$resultString =
3609
+ $ongoingTemplateResult.$completionResult.content;
3610
+ return [3 /*break*/, 11];
3611
+ case 8:
3612
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3613
+ _f = $ongoingTemplateResult;
3614
+ return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze($ongoingTemplateResult.$prompt))];
3615
+ case 9:
3616
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3617
+ _f.$embeddingResult = _u.sent();
3618
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$embeddingResult;
3619
+ $ongoingTemplateResult.$resultString =
3620
+ $ongoingTemplateResult.$embeddingResult.content.join(',');
3621
+ return [3 /*break*/, 11];
3622
+ case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3623
+ case 11: return [3 /*break*/, 26];
3624
+ case 12:
3625
+ if (arrayableToArray(tools.script).length === 0) {
3626
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3627
+ }
3628
+ if (!template.contentLanguage) {
3629
+ 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 "); }));
3630
+ }
3631
+ _u.label = 13;
3632
+ case 13:
3633
+ _u.trys.push([13, 20, 21, 22]);
3634
+ _g = (e_1 = void 0, __values(arrayableToArray(tools.script))), _h = _g.next();
3635
+ _u.label = 14;
3636
+ case 14:
3637
+ if (!!_h.done) return [3 /*break*/, 19];
3638
+ scriptTools = _h.value;
3639
+ _u.label = 15;
3640
+ case 15:
3641
+ _u.trys.push([15, 17, , 18]);
3642
+ _j = $ongoingTemplateResult;
3643
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3644
+ scriptLanguage: template.contentLanguage,
3645
+ script: preparedContent,
3646
+ parameters: parameters,
3647
+ }))];
3648
+ case 16:
3649
+ _j.$resultString = _u.sent();
3650
+ return [3 /*break*/, 19];
3651
+ case 17:
3652
+ error_1 = _u.sent();
3653
+ if (!(error_1 instanceof Error)) {
3654
+ throw error_1;
3655
+ }
3656
+ if (error_1 instanceof UnexpectedError) {
3657
+ throw error_1;
3658
+ }
3659
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3660
+ return [3 /*break*/, 18];
3661
+ case 18:
3662
+ _h = _g.next();
3663
+ return [3 /*break*/, 14];
3664
+ case 19: return [3 /*break*/, 22];
3665
+ case 20:
3666
+ e_1_1 = _u.sent();
3667
+ e_1 = { error: e_1_1 };
3668
+ return [3 /*break*/, 22];
3669
+ case 21:
3670
+ try {
3671
+ if (_h && !_h.done && (_r = _g.return)) _r.call(_g);
3672
+ }
3673
+ finally { if (e_1) throw e_1.error; }
3674
+ return [7 /*endfinally*/];
3675
+ case 22:
3676
+ if ($ongoingTemplateResult.$resultString !== null) {
3677
+ return [3 /*break*/, 26];
3678
+ }
3679
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3680
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3681
+ }
3682
+ else {
3683
+ 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
3684
+ .map(function (error) { return '- ' + error.message; })
3685
+ .join('\n\n')), "\n "); }));
3686
+ }
3687
+ case 23:
3688
+ if (tools.userInterface === undefined) {
3689
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3690
+ }
3691
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3692
+ _k = $ongoingTemplateResult;
3693
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3694
+ promptTitle: template.title,
3695
+ promptMessage: replaceParameters(template.description || '', parameters),
3696
+ defaultValue: replaceParameters(preparedContent, parameters),
3697
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3698
+ placeholder: undefined,
3699
+ priority: priority,
3700
+ }))];
3701
+ case 24:
3702
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3703
+ _k.$resultString = _u.sent();
3704
+ return [3 /*break*/, 26];
3705
+ case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3706
+ case 26:
3707
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 43];
3708
+ _u.label = 27;
3709
+ case 27:
3710
+ _u.trys.push([27, 41, 42, 43]);
3711
+ _l = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _m = _l.next();
3712
+ _u.label = 28;
3713
+ case 28:
3714
+ if (!!_m.done) return [3 /*break*/, 40];
3715
+ functionName = _m.value;
3716
+ postprocessingError = null;
3717
+ _u.label = 29;
3718
+ case 29:
3719
+ _u.trys.push([29, 36, 37, 38]);
3720
+ _o = (e_2 = void 0, __values(arrayableToArray(tools.script))), _p = _o.next();
3721
+ _u.label = 30;
3722
+ case 30:
3723
+ if (!!_p.done) return [3 /*break*/, 35];
3724
+ scriptTools = _p.value;
3725
+ _u.label = 31;
3726
+ case 31:
3727
+ _u.trys.push([31, 33, , 34]);
3728
+ _q = $ongoingTemplateResult;
3729
+ return [4 /*yield*/, scriptTools.execute({
3730
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3731
+ script: "".concat(functionName, "(resultString)"),
3732
+ parameters: {
3733
+ resultString: $ongoingTemplateResult.$resultString || '',
3734
+ // Note: No ...parametersForTemplate, because working with result only
3735
+ },
3736
+ })];
3737
+ case 32:
3738
+ _q.$resultString = _u.sent();
3739
+ postprocessingError = null;
3740
+ return [3 /*break*/, 35];
3741
+ case 33:
3742
+ error_2 = _u.sent();
3743
+ if (!(error_2 instanceof Error)) {
3744
+ throw error_2;
3745
+ }
3746
+ if (error_2 instanceof UnexpectedError) {
3747
+ throw error_2;
3748
+ }
3749
+ postprocessingError = error_2;
3750
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3751
+ return [3 /*break*/, 34];
3752
+ case 34:
3753
+ _p = _o.next();
3754
+ return [3 /*break*/, 30];
3755
+ case 35: return [3 /*break*/, 38];
3756
+ case 36:
3757
+ e_2_1 = _u.sent();
3758
+ e_2 = { error: e_2_1 };
3759
+ return [3 /*break*/, 38];
3760
+ case 37:
3761
+ try {
3762
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3763
+ }
3764
+ finally { if (e_2) throw e_2.error; }
3765
+ return [7 /*endfinally*/];
3766
+ case 38:
3767
+ if (postprocessingError) {
3768
+ throw postprocessingError;
3769
+ }
3770
+ _u.label = 39;
3771
+ case 39:
3772
+ _m = _l.next();
3773
+ return [3 /*break*/, 28];
3774
+ case 40: return [3 /*break*/, 43];
3775
+ case 41:
3776
+ e_3_1 = _u.sent();
3777
+ e_3 = { error: e_3_1 };
3778
+ return [3 /*break*/, 43];
3779
+ case 42:
3780
+ try {
3781
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3782
+ }
3783
+ finally { if (e_3) throw e_3.error; }
3784
+ return [7 /*endfinally*/];
3785
+ case 43:
3786
+ // TODO: [💝] Unite object for expecting amount and format
3787
+ if (template.format) {
3788
+ if (template.format === 'JSON') {
3789
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3790
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3791
+ try {
3792
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3555
3793
  }
3556
- else {
3557
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3794
+ catch (error) {
3795
+ keepUnused(error);
3796
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3797
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3558
3798
  }
3559
3799
  }
3560
- // TODO: [💝] Unite object for expecting amount and format
3561
- if (currentTemplate.expectations) {
3562
- checkExpectations(currentTemplate.expectations, resultString || '');
3563
- }
3564
- return [2 /*return*/, "break-attempts"];
3565
- case 44:
3566
- error_4 = _v.sent();
3567
- if (!(error_4 instanceof ExpectError)) {
3568
- throw error_4;
3569
- }
3570
- expectError = error_4;
3571
- return [3 /*break*/, 46];
3572
- case 45:
3573
- if (!isJokerAttempt &&
3574
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3575
- prompt
3576
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3577
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3578
- ) {
3579
- // TODO: [🧠] Maybe put other templateTypes into report
3580
- executionReport.promptExecutions.push({
3581
- prompt: __assign({}, prompt),
3582
- result: result || undefined,
3583
- error: expectError === null ? undefined : serializeError(expectError),
3584
- });
3585
- }
3586
- return [7 /*endfinally*/];
3587
- case 46:
3588
- if (expectError !== null && attempt === maxAttempts - 1) {
3589
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3590
- .split('\n')
3591
- .map(function (line) { return "> ".concat(line); })
3592
- .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3800
+ }
3801
+ else {
3802
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3803
+ }
3804
+ }
3805
+ // TODO: [💝] Unite object for expecting amount and format
3806
+ if (template.expectations) {
3807
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3808
+ }
3809
+ return [2 /*return*/, "break-attempts"];
3810
+ case 44:
3811
+ error_3 = _u.sent();
3812
+ if (!(error_3 instanceof ExpectError)) {
3813
+ throw error_3;
3814
+ }
3815
+ $ongoingTemplateResult.$expectError = error_3;
3816
+ return [3 /*break*/, 46];
3817
+ case 45:
3818
+ if (!isJokerAttempt &&
3819
+ template.templateType === 'PROMPT_TEMPLATE' &&
3820
+ $ongoingTemplateResult.$prompt
3821
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3822
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3823
+ ) {
3824
+ // TODO: [🧠] Maybe put other templateTypes into report
3825
+ $executionReport.promptExecutions.push({
3826
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3827
+ result: $ongoingTemplateResult.$result || undefined,
3828
+ error: $ongoingTemplateResult.$expectError === null
3829
+ ? undefined
3830
+ : serializeError($ongoingTemplateResult.$expectError),
3831
+ });
3832
+ }
3833
+ return [7 /*endfinally*/];
3834
+ case 46:
3835
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3836
+ throw new PipelineExecutionError(spaceTrim(function (block) {
3837
+ var _a, _b, _c;
3838
+ 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) || '')
3839
+ .split('\n')
3840
+ .map(function (line) { return "> ".concat(line); })
3841
+ .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) || '')
3842
+ .split('\n')
3843
+ .map(function (line) { return "> ".concat(line); })
3844
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3845
+ ? 'null'
3846
+ : $ongoingTemplateResult.$resultString
3593
3847
  .split('\n')
3594
3848
  .map(function (line) { return "> ".concat(line); })
3595
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3596
- ? 'null'
3597
- : resultString
3598
- .split('\n')
3599
- .map(function (line) { return "> ".concat(line); })
3600
- .join('\n')), "\n ---\n "); }));
3601
- }
3602
- return [2 /*return*/];
3849
+ .join('\n')), "\n ---\n ");
3850
+ }));
3603
3851
  }
3604
- });
3605
- };
3606
- attempt = -jokerParameterNames.length;
3607
- _h.label = 4;
3608
- case 4:
3609
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3610
- return [5 /*yield**/, _loop_5(attempt)];
3611
- case 5:
3612
- state_2 = _h.sent();
3613
- switch (state_2) {
3614
- case "break-attempts": return [3 /*break*/, 7];
3615
- }
3616
- _h.label = 6;
3617
- case 6:
3618
- attempt++;
3619
- return [3 /*break*/, 4];
3620
- case 7:
3621
- if (resultString === null) {
3622
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3623
- }
3624
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3625
- progress_2 = {
3626
- name: name,
3627
- title: title,
3628
- isStarted: true,
3629
- isDone: true,
3630
- templateType: currentTemplate.templateType,
3631
- parameterName: currentTemplate.resultingParameterName,
3632
- parameterValue: resultString,
3633
- // <- [3]
3634
- };
3635
- if (isReturned) {
3636
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3637
- .split('\n')
3638
- .map(function (line) { return "> ".concat(line); })
3639
- .join('\n')), "\n\n "); }));
3852
+ return [2 /*return*/];
3640
3853
  }
3641
- return [4 /*yield*/, onProgress(progress_2)];
3642
- case 8:
3643
- _h.sent();
3644
- _h.label = 9;
3645
- case 9:
3646
- parametersToPass = Object.freeze(__assign(__assign({}, parametersToPass), (_g = {}, _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _g)));
3647
- return [2 /*return*/];
3854
+ });
3855
+ };
3856
+ attempt = -jokerParameterNames.length;
3857
+ _a.label = 1;
3858
+ case 1:
3859
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3860
+ return [5 /*yield**/, _loop_1(attempt)];
3861
+ case 2:
3862
+ state_1 = _a.sent();
3863
+ switch (state_1) {
3864
+ case "break-attempts": return [3 /*break*/, 4];
3648
3865
  }
3649
- });
3650
- });
3866
+ _a.label = 3;
3867
+ case 3:
3868
+ attempt++;
3869
+ return [3 /*break*/, 1];
3870
+ case 4:
3871
+ if ($ongoingTemplateResult.$resultString === null) {
3872
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3873
+ }
3874
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3875
+ }
3876
+ });
3877
+ });
3878
+ }
3879
+ /**
3880
+ * TODO: Break into smaller functions
3881
+ */
3882
+
3883
+ /**
3884
+ * @@@
3885
+ *
3886
+ * @private internal utility of `createPipelineExecutor`
3887
+ */
3888
+ function executeFormatCells(options) {
3889
+ return __awaiter(this, void 0, void 0, function () {
3890
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, parameterValue, formatDefinition, subvalueDefinition, resultString;
3891
+ var _this = this;
3892
+ return __generator(this, function (_a) {
3893
+ switch (_a.label) {
3894
+ case 0:
3895
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification;
3896
+ if (template.foreach === undefined) {
3897
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3898
+ }
3899
+ if (jokerParameterNames.length !== 0) {
3900
+ 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 "); }));
3901
+ }
3902
+ parameterValue = parameters[template.foreach.parameterName] || '';
3903
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3904
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3905
+ });
3906
+ if (formatDefinition === undefined) {
3907
+ throw new UnexpectedError(
3908
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3909
+ 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; })
3910
+ .map(function (formatName) { return "- ".concat(formatName); })
3911
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3912
+ }
3913
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3914
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.cellName);
3915
+ });
3916
+ if (subvalueDefinition === undefined) {
3917
+ throw new UnexpectedError(
3918
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3919
+ spaceTrim$1(function (block) { return "\n Unsupported cell name \"".concat(template.foreach.cellName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available cell names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
3920
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3921
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3922
+ .join('\n')), "\n\n [\u26F7] This should never happen because cell name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3923
+ }
3924
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3925
+ var mappedParameters, allSubparameters, subresultString;
3926
+ return __generator(this, function (_a) {
3927
+ switch (_a.label) {
3928
+ case 0:
3929
+ try {
3930
+ mappedParameters = mapAvailableToExpectedParameters({
3931
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3932
+ availableParameters: subparameters,
3933
+ });
3934
+ }
3935
+ catch (error) {
3936
+ if (!(error instanceof PipelineExecutionError)) {
3937
+ throw error;
3938
+ }
3939
+ 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 "); }));
3940
+ }
3941
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3942
+ // 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
3943
+ Object.freeze(allSubparameters);
3944
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3945
+ case 1:
3946
+ subresultString = _a.sent();
3947
+ return [2 /*return*/, subresultString];
3948
+ }
3949
+ });
3950
+ }); })];
3951
+ case 1:
3952
+ resultString = _a.sent();
3953
+ return [2 /*return*/, resultString];
3954
+ }
3955
+ });
3956
+ });
3957
+ }
3958
+ /**
3959
+ * TODO: !!!!!! Make pipelineIdentification more precise
3960
+ * TODO: !!!!!! How FOREACH execution looks in the report
3961
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
3962
+ * TODO: []
3963
+ */
3964
+
3965
+ /**
3966
+ * @@@
3967
+ *
3968
+ * @private internal utility of `createPipelineExecutor`
3969
+ */
3970
+ function getContextForTemplate(template) {
3971
+ return __awaiter(this, void 0, void 0, function () {
3972
+ return __generator(this, function (_a) {
3973
+ TODO_USE(template);
3974
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3975
+ });
3976
+ });
3977
+ }
3978
+
3979
+ /**
3980
+ * @@@
3981
+ *
3982
+ * @private internal utility of `createPipelineExecutor`
3983
+ */
3984
+ function getKnowledgeForTemplate(options) {
3985
+ return __awaiter(this, void 0, void 0, function () {
3986
+ var preparedPipeline, template;
3987
+ return __generator(this, function (_a) {
3988
+ preparedPipeline = options.preparedPipeline, template = options.template;
3989
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3990
+ TODO_USE(template);
3991
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3992
+ var content = _a.content;
3993
+ return "- ".concat(content);
3994
+ }).join('\n')];
3995
+ });
3996
+ });
3997
+ }
3998
+
3999
+ /**
4000
+ * @@@
4001
+ *
4002
+ * @private internal utility of `createPipelineExecutor`
4003
+ */
4004
+ function getSamplesForTemplate(template) {
4005
+ return __awaiter(this, void 0, void 0, function () {
4006
+ return __generator(this, function (_a) {
4007
+ // TODO: [♨] Implement Better - use real index and keyword search
4008
+ TODO_USE(template);
4009
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4010
+ });
4011
+ });
4012
+ }
4013
+
4014
+ /**
4015
+ * @@@
4016
+ *
4017
+ * @private internal utility of `createPipelineExecutor`
4018
+ */
4019
+ function getReservedParametersForTemplate(options) {
4020
+ return __awaiter(this, void 0, void 0, function () {
4021
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4022
+ var e_1, _a;
4023
+ return __generator(this, function (_b) {
4024
+ switch (_b.label) {
4025
+ case 0:
4026
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4027
+ return [4 /*yield*/, getContextForTemplate(template)];
4028
+ case 1:
4029
+ context = _b.sent();
4030
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4031
+ case 2:
4032
+ knowledge = _b.sent();
4033
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4034
+ case 3:
4035
+ samples = _b.sent();
4036
+ currentDate = new Date().toISOString();
4037
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4038
+ reservedParameters = {
4039
+ content: RESERVED_PARAMETER_RESTRICTED,
4040
+ context: context,
4041
+ knowledge: knowledge,
4042
+ samples: samples,
4043
+ currentDate: currentDate,
4044
+ modelName: modelName,
4045
+ };
4046
+ _loop_1 = function (parameterName) {
4047
+ if (reservedParameters[parameterName] === undefined) {
4048
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4049
+ }
4050
+ };
4051
+ try {
4052
+ // Note: Doublecheck that ALL reserved parameters are defined:
4053
+ 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()) {
4054
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4055
+ _loop_1(parameterName);
4056
+ }
4057
+ }
4058
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4059
+ finally {
4060
+ try {
4061
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4062
+ }
4063
+ finally { if (e_1) throw e_1.error; }
4064
+ }
4065
+ return [2 /*return*/, reservedParameters];
4066
+ }
4067
+ });
4068
+ });
4069
+ }
4070
+
4071
+ /**
4072
+ * @@@
4073
+ *
4074
+ * @private internal utility of `createPipelineExecutor`
4075
+ */
4076
+ function executeTemplate(options) {
4077
+ return __awaiter(this, void 0, void 0, function () {
4078
+ 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;
4079
+ var e_1, _f, _g;
4080
+ return __generator(this, function (_h) {
4081
+ switch (_h.label) {
4082
+ case 0:
4083
+ 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;
4084
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4085
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4086
+ title = currentTemplate.title;
4087
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4088
+ return [4 /*yield*/, onProgress({
4089
+ name: name,
4090
+ title: title,
4091
+ isStarted: false,
4092
+ isDone: false,
4093
+ templateType: currentTemplate.templateType,
4094
+ parameterName: currentTemplate.resultingParameterName,
4095
+ parameterValue: null,
4096
+ // <- [🍸]
4097
+ })];
4098
+ case 1:
4099
+ _h.sent();
4100
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4101
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4102
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4103
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4104
+ 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)
4105
+ .map(function (name) { return "{".concat(name, "}"); })
4106
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4107
+ .map(function (name) { return "{".concat(name, "}"); })
4108
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4109
+ }
4110
+ _b = (_a = Object).freeze;
4111
+ _c = [{}];
4112
+ return [4 /*yield*/, getReservedParametersForTemplate({
4113
+ preparedPipeline: preparedPipeline,
4114
+ template: currentTemplate,
4115
+ pipelineIdentification: pipelineIdentification,
4116
+ })];
4117
+ case 2:
4118
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4119
+ definedParameterNames = new Set(Object.keys(definedParameters));
4120
+ parameters = {};
4121
+ _loop_1 = function (parameterName) {
4122
+ // Situation: Parameter is defined and used
4123
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4124
+ parameters[parameterName] = definedParameters[parameterName];
4125
+ }
4126
+ // Situation: Parameter is defined but NOT used
4127
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4128
+ // Situation: Parameter is NOT defined BUT used
4129
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4130
+ // Houston, we have a problem
4131
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4132
+ 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 "); }));
4133
+ }
4134
+ };
4135
+ try {
4136
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4137
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4138
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4139
+ parameterName = _e.value;
4140
+ _loop_1(parameterName);
4141
+ }
4142
+ }
4143
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4144
+ finally {
4145
+ try {
4146
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4147
+ }
4148
+ finally { if (e_1) throw e_1.error; }
4149
+ }
4150
+ // 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
4151
+ Object.freeze(parameters);
4152
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4153
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4154
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4155
+ .split('{content}')
4156
+ .join(currentTemplate.content);
4157
+ return [4 /*yield*/, executeFormatCells({
4158
+ jokerParameterNames: jokerParameterNames,
4159
+ priority: priority,
4160
+ maxAttempts: maxAttempts,
4161
+ preparedContent: preparedContent,
4162
+ parameters: parameters,
4163
+ template: currentTemplate,
4164
+ preparedPipeline: preparedPipeline,
4165
+ tools: tools,
4166
+ llmTools: llmTools,
4167
+ settings: settings,
4168
+ $executionReport: $executionReport,
4169
+ pipelineIdentification: pipelineIdentification,
4170
+ })];
4171
+ case 3:
4172
+ resultString = _h.sent();
4173
+ return [4 /*yield*/, onProgress({
4174
+ name: name,
4175
+ title: title,
4176
+ isStarted: true,
4177
+ isDone: true,
4178
+ templateType: currentTemplate.templateType,
4179
+ parameterName: currentTemplate.resultingParameterName,
4180
+ parameterValue: resultString,
4181
+ // <- [🍸]
4182
+ })];
4183
+ case 4:
4184
+ _h.sent();
4185
+ return [2 /*return*/, Object.freeze((_g = {},
4186
+ _g[currentTemplate.resultingParameterName] =
4187
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4188
+ resultString,
4189
+ _g))];
4190
+ }
4191
+ });
4192
+ });
4193
+ }
4194
+ /**
4195
+ * TODO: [🤹‍♂️]
4196
+ */
4197
+
4198
+ /**
4199
+ * @@@
4200
+ *
4201
+ * @private internal utility of `createPipelineExecutor`
4202
+ */
4203
+ function filterJustOutputParameters(options) {
4204
+ var e_1, _a;
4205
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4206
+ var outputParameters = {};
4207
+ var _loop_1 = function (parameter) {
4208
+ if (parametersToPass[parameter.name] === undefined) {
4209
+ // [4]
4210
+ $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 "); })));
4211
+ return "continue";
4212
+ }
4213
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4214
+ };
4215
+ try {
4216
+ // Note: Filter ONLY output parameters
4217
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4218
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4219
+ var isOutput = _a.isOutput;
4220
+ return isOutput;
4221
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4222
+ var parameter = _c.value;
4223
+ _loop_1(parameter);
3651
4224
  }
3652
- function filterJustOutputParameters() {
3653
- var e_8, _a;
3654
- var outputParameters = {};
3655
- var _loop_6 = function (parameter) {
3656
- if (parametersToPass[parameter.name] === undefined) {
3657
- // [4]
3658
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3659
- return "continue";
3660
- }
3661
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3662
- };
3663
- try {
3664
- // Note: Filter ONLY output parameters
3665
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3666
- var isOutput = _a.isOutput;
3667
- return isOutput;
3668
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3669
- var parameter = _c.value;
3670
- _loop_6(parameter);
3671
- }
3672
- }
3673
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3674
- finally {
3675
- try {
3676
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3677
- }
3678
- finally { if (e_8) throw e_8.error; }
3679
- }
3680
- return outputParameters;
4225
+ }
4226
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4227
+ finally {
4228
+ try {
4229
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3681
4230
  }
3682
- var errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
4231
+ finally { if (e_1) throw e_1.error; }
4232
+ }
4233
+ return outputParameters;
4234
+ }
4235
+
4236
+ /**
4237
+ * @@@
4238
+ *
4239
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4240
+ *
4241
+ * @private internal utility of `createPipelineExecutor`
4242
+ */
4243
+ function executePipeline(options) {
4244
+ return __awaiter(this, void 0, void 0, function () {
4245
+ var inputParameters, tools, onProgress, pipeline, setPreparedPipeline, pipelineIdentification, settings, maxParallelCount, isVerbose, preparedPipeline, llmTools, errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
3683
4246
  var e_1, _e, e_2, _f;
3684
4247
  return __generator(this, function (_g) {
3685
4248
  switch (_g.label) {
3686
4249
  case 0:
4250
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4251
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4252
+ preparedPipeline = options.preparedPipeline;
4253
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3687
4254
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3688
4255
  return [4 /*yield*/, preparePipeline(pipeline, {
3689
4256
  llmTools: llmTools,
@@ -3692,6 +4259,7 @@ function createPipelineExecutor(options) {
3692
4259
  })];
3693
4260
  case 1:
3694
4261
  preparedPipeline = _g.sent();
4262
+ setPreparedPipeline(preparedPipeline);
3695
4263
  _g.label = 2;
3696
4264
  case 2:
3697
4265
  errors = [];
@@ -3761,7 +4329,7 @@ function createPipelineExecutor(options) {
3761
4329
  return name === parameterName;
3762
4330
  });
3763
4331
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3764
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4332
+ warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3765
4333
  return [3 /*break*/, 4];
3766
4334
  case 1:
3767
4335
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3773,10 +4341,10 @@ function createPipelineExecutor(options) {
3773
4341
  // Note: Wait a short time to prevent race conditions
3774
4342
  _h.sent();
3775
4343
  _h.label = 3;
3776
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4344
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3777
4345
  isSuccessful: false,
3778
4346
  errors: __spreadArray([
3779
- new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4347
+ new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3780
4348
  ], __read(errors), false).map(serializeError),
3781
4349
  warnings: warnings.map(serializeError),
3782
4350
  executionReport: executionReport,
@@ -3840,7 +4408,7 @@ function createPipelineExecutor(options) {
3840
4408
  case 0:
3841
4409
  if (loopLimit-- < 0) {
3842
4410
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3843
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4411
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3844
4412
  }
3845
4413
  currentTemplate = unresovedTemplates_1.find(function (template) {
3846
4414
  return template.dependentParameterNames.every(function (name) {
@@ -3850,29 +4418,52 @@ function createPipelineExecutor(options) {
3850
4418
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3851
4419
  throw new UnexpectedError(
3852
4420
  // TODO: [🐎] DRY
3853
- spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4421
+ spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3854
4422
  .map(function (_a) {
3855
4423
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3856
4424
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3857
4425
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3858
4426
  .join(' and '));
3859
4427
  })
3860
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
4428
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
3861
4429
  case 1:
3862
4430
  if (!!currentTemplate) return [3 /*break*/, 3];
3863
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4431
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3864
4432
  case 2:
3865
- /* [5] */ _j.sent();
4433
+ /* [🤹‍♂️] */ _j.sent();
3866
4434
  return [3 /*break*/, 4];
3867
4435
  case 3:
3868
4436
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3869
- work_1 = executeSingleTemplate(currentTemplate)
3870
- .then(function () {
4437
+ work_1 = executeTemplate({
4438
+ currentTemplate: currentTemplate,
4439
+ preparedPipeline: preparedPipeline,
4440
+ parametersToPass: parametersToPass,
4441
+ tools: tools,
4442
+ llmTools: llmTools,
4443
+ onProgress: function (progress) {
4444
+ if (isReturned) {
4445
+ 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)
4446
+ .split('\n')
4447
+ .map(function (line) { return "> ".concat(line); })
4448
+ .join('\n')), "\n "); }));
4449
+ }
4450
+ if (onProgress) {
4451
+ onProgress(progress);
4452
+ }
4453
+ },
4454
+ settings: settings,
4455
+ $executionReport: executionReport,
4456
+ pipelineIdentification: pipelineIdentification,
4457
+ })
4458
+ .then(function (newParametersToPass) {
4459
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3871
4460
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3872
4461
  })
3873
4462
  .then(function () {
3874
4463
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3875
4464
  });
4465
+ // <- Note: Errors are catched here [3]
4466
+ // TODO: BUT if in multiple templates are errors, only the first one is catched so maybe we should catch errors here and save them to errors array here
3876
4467
  resolving_1.push(work_1);
3877
4468
  _j.label = 4;
3878
4469
  case 4: return [2 /*return*/];
@@ -3899,7 +4490,12 @@ function createPipelineExecutor(options) {
3899
4490
  var result = _a.result;
3900
4491
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3901
4492
  })), false));
3902
- outputParameters_1 = filterJustOutputParameters();
4493
+ outputParameters_1 = filterJustOutputParameters({
4494
+ preparedPipeline: preparedPipeline,
4495
+ parametersToPass: parametersToPass,
4496
+ $warnings: warnings,
4497
+ pipelineIdentification: pipelineIdentification,
4498
+ });
3903
4499
  isReturned = true;
3904
4500
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3905
4501
  // Note: Wait a short time to prevent race conditions
@@ -3922,7 +4518,12 @@ function createPipelineExecutor(options) {
3922
4518
  var result = _a.result;
3923
4519
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3924
4520
  })), false));
3925
- outputParameters = filterJustOutputParameters();
4521
+ outputParameters = filterJustOutputParameters({
4522
+ preparedPipeline: preparedPipeline,
4523
+ parametersToPass: parametersToPass,
4524
+ $warnings: warnings,
4525
+ pipelineIdentification: pipelineIdentification,
4526
+ });
3926
4527
  isReturned = true;
3927
4528
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3928
4529
  // Note: Wait a short time to prevent race conditions
@@ -3942,22 +4543,62 @@ function createPipelineExecutor(options) {
3942
4543
  })];
3943
4544
  }
3944
4545
  });
3945
- }); };
3946
- return pipelineExecutor;
4546
+ });
3947
4547
  }
4548
+
3948
4549
  /**
3949
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3950
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3951
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3952
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3953
- * TODO: [♈] Probbably move expectations from templates to parameters
3954
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3955
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3956
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3957
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3958
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3959
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4550
+ * Creates executor function from pipeline and execution tools.
4551
+ *
4552
+ * @returns The executor function
4553
+ * @throws {PipelineLogicError} on logical error in the pipeline
4554
+ * @public exported from `@promptbook/core`
3960
4555
  */
4556
+ function createPipelineExecutor(options) {
4557
+ var _this = this;
4558
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4559
+ 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;
4560
+ validatePipeline(pipeline);
4561
+ var pipelineIdentification = (function () {
4562
+ // Note: This is a 😐 implementation of [🚞]
4563
+ var _ = [];
4564
+ if (pipeline.sourceFile !== undefined) {
4565
+ _.push("File: ".concat(pipeline.sourceFile));
4566
+ }
4567
+ if (pipeline.pipelineUrl !== undefined) {
4568
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4569
+ }
4570
+ return _.join('\n');
4571
+ })();
4572
+ var preparedPipeline;
4573
+ if (isPipelinePrepared(pipeline)) {
4574
+ preparedPipeline = pipeline;
4575
+ }
4576
+ else if (isNotPreparedWarningSupressed !== true) {
4577
+ 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 "); }));
4578
+ }
4579
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4580
+ return __generator(this, function (_a) {
4581
+ return [2 /*return*/, executePipeline({
4582
+ pipeline: pipeline,
4583
+ preparedPipeline: preparedPipeline,
4584
+ setPreparedPipeline: function (newPreparedPipeline) {
4585
+ preparedPipeline = newPreparedPipeline;
4586
+ },
4587
+ inputParameters: inputParameters,
4588
+ tools: tools,
4589
+ onProgress: onProgress,
4590
+ pipelineIdentification: pipelineIdentification,
4591
+ settings: {
4592
+ maxExecutionAttempts: maxExecutionAttempts,
4593
+ maxParallelCount: maxParallelCount,
4594
+ isVerbose: isVerbose,
4595
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4596
+ },
4597
+ })];
4598
+ });
4599
+ }); };
4600
+ return pipelineExecutor;
4601
+ }
3961
4602
 
3962
4603
  /**
3963
4604
  * @@@
@@ -5111,6 +5752,145 @@ function normalizeTo_SCREAMING_CASE(text) {
5111
5752
  * TODO: [🌺] Use some intermediate util splitWords
5112
5753
  */
5113
5754
 
5755
+ /**
5756
+ * @@@
5757
+ *
5758
+ * @param text @@@
5759
+ * @param _isFirstLetterCapital @@@
5760
+ * @returns @@@
5761
+ * @example 'helloWorld'
5762
+ * @example 'iLovePromptbook'
5763
+ * @public exported from `@promptbook/utils`
5764
+ */
5765
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5766
+ var e_1, _a;
5767
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5768
+ var charType;
5769
+ var lastCharType = null;
5770
+ var normalizedName = '';
5771
+ try {
5772
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5773
+ var char = text_1_1.value;
5774
+ var normalizedChar = void 0;
5775
+ if (/^[a-z]$/.test(char)) {
5776
+ charType = 'LOWERCASE';
5777
+ normalizedChar = char;
5778
+ }
5779
+ else if (/^[A-Z]$/.test(char)) {
5780
+ charType = 'UPPERCASE';
5781
+ normalizedChar = char.toLowerCase();
5782
+ }
5783
+ else if (/^[0-9]$/.test(char)) {
5784
+ charType = 'NUMBER';
5785
+ normalizedChar = char;
5786
+ }
5787
+ else {
5788
+ charType = 'OTHER';
5789
+ normalizedChar = '';
5790
+ }
5791
+ if (!lastCharType) {
5792
+ if (_isFirstLetterCapital) {
5793
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5794
+ }
5795
+ }
5796
+ else if (charType !== lastCharType &&
5797
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5798
+ !(lastCharType === 'NUMBER') &&
5799
+ !(charType === 'NUMBER')) {
5800
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5801
+ }
5802
+ normalizedName += normalizedChar;
5803
+ lastCharType = charType;
5804
+ }
5805
+ }
5806
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5807
+ finally {
5808
+ try {
5809
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5810
+ }
5811
+ finally { if (e_1) throw e_1.error; }
5812
+ }
5813
+ return normalizedName;
5814
+ }
5815
+ /**
5816
+ * TODO: [🌺] Use some intermediate util splitWords
5817
+ */
5818
+
5819
+ /**
5820
+ * Function `validateParameterName` will @@@
5821
+ *
5822
+ * @param parameterName @@@
5823
+ * @returns @@@
5824
+ * @throws {ParseError} @@@
5825
+ * @private within the repository
5826
+ */
5827
+ function validateParameterName(parameterName) {
5828
+ var e_1, _a;
5829
+ var rawParameterName = parameterName;
5830
+ try {
5831
+ for (var _b = __values([
5832
+ ['`', '`'],
5833
+ ['{', '}'],
5834
+ ['[', ']'],
5835
+ ['(', ')'],
5836
+ ['<', '>'],
5837
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5838
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5839
+ if (parameterName.substring(0, 1) === start &&
5840
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5841
+ // <- TODO: More universal that 1 character
5842
+ ) {
5843
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5844
+ // <- TODO: More universal that 1 character
5845
+ }
5846
+ }
5847
+ }
5848
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5849
+ finally {
5850
+ try {
5851
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5852
+ }
5853
+ finally { if (e_1) throw e_1.error; }
5854
+ }
5855
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5856
+ try {
5857
+ /*
5858
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5859
+ if (parameterName.includes(' ')) {
5860
+ throw new ParseError(`Parameter name cannot contain spaces`);
5861
+ }
5862
+ */
5863
+ if (parameterName.includes('.')) {
5864
+ throw new ParseError("Parameter name cannot contain dots");
5865
+ }
5866
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5867
+ throw new ParseError("Parameter name cannot contain slashes");
5868
+ }
5869
+ if (parameterName.includes('(') ||
5870
+ parameterName.includes(')') ||
5871
+ parameterName.includes('{') ||
5872
+ parameterName.includes('}') ||
5873
+ parameterName.includes('[') ||
5874
+ parameterName.includes(']')) {
5875
+ throw new ParseError("Parameter name cannot contain braces");
5876
+ }
5877
+ parameterName = normalizeTo_camelCase(parameterName);
5878
+ if (parameterName === '') {
5879
+ throw new ParseError("Parameter name cannot be empty");
5880
+ }
5881
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5882
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5883
+ }
5884
+ }
5885
+ catch (error) {
5886
+ if (!(error instanceof ParseError)) {
5887
+ throw error;
5888
+ }
5889
+ 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 "); }));
5890
+ }
5891
+ return parameterName;
5892
+ }
5893
+
5114
5894
  /**
5115
5895
  * Parses the foreach command
5116
5896
  *
@@ -5145,62 +5925,66 @@ var foreachCommandParser = {
5145
5925
  * Example usages of the FOREACH command
5146
5926
  */
5147
5927
  examples: [
5148
- 'FOREACH List Line -> `{customer}`',
5149
- 'FOR List Line -> `{customer}`',
5150
- 'EACH List Line -> `{customer}`',
5928
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5929
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5930
+ 'EACH Csv Cell `{customers}` -> `{cell}`',
5151
5931
  // <- TODO: [🍭] !!!!!! More
5152
5932
  ],
5153
5933
  /**
5154
5934
  * Parses the FOREACH command
5155
5935
  */
5156
5936
  parse: function (input) {
5157
- var args = input.args, rawArgs = input.rawArgs;
5937
+ var args = input.args;
5158
5938
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5159
5939
  var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5160
- var assignSign = args[2];
5161
- var parameter = args[3];
5162
- if (![
5163
- 'LIST',
5164
- 'CSV',
5165
- // <- TODO: [🏢] Unhardcode formats
5166
- ].includes(formatName)) {
5940
+ var parameterNameWrapped = args[2];
5941
+ var assignSign = args[3];
5942
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5943
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5944
+ });
5945
+ if (formatDefinition === undefined) {
5167
5946
  console.info({ args: args, formatName: formatName });
5168
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5947
+ 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; })
5948
+ .map(function (formatName) { return "- ".concat(formatName); })
5949
+ .join('\n')), "\n "); }));
5169
5950
  // <- TODO: [🏢] List all supported format names
5170
5951
  }
5171
- if (![
5172
- 'LINE',
5173
- 'ROW',
5174
- 'COLUMN',
5175
- 'CELL',
5176
- // <- TODO: [🏢] Unhardcode format cekks
5177
- ].includes(cellName)) {
5952
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5953
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(cellName);
5954
+ });
5955
+ if (subvalueDefinition === undefined) {
5178
5956
  console.info({ args: args, cellName: cellName });
5179
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5957
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Unsupported cell name \"".concat(cellName, "\" for format \"").concat(formatName, "\"\n\n Available cell names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
5958
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5959
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5960
+ .join('\n')), "\n "); }));
5180
5961
  // <- TODO: [🏢] List all supported cell names for the format
5181
5962
  }
5182
5963
  if (assignSign !== '->') {
5183
5964
  console.info({ args: args, assignSign: assignSign });
5184
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5185
- }
5186
- var parameterNames = extractParameterNames(parameter || rawArgs);
5187
- if (parameterNames.size !== 1) {
5188
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5189
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5190
- }
5191
- var parameterName = parameterNames.values().next().value;
5192
- if (typeof parameterName !== 'string'
5193
- // <- TODO: !!!!!! Replace with propper parameter name validation
5194
- ) {
5195
- console.info({ args: args, parameterName: parameterName });
5196
- throw new Error("Invalid parameter name");
5197
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
5965
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5966
+ }
5967
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5968
+ if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5969
+ (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5970
+ 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));
5971
+ throw new ParseError("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5972
+ }
5973
+ var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5974
+ var subparameterNames = args
5975
+ .slice(4)
5976
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5977
+ .filter(function (parameterName) { return parameterName !== ''; })
5978
+ .map(validateParameterName);
5979
+ if (subparameterNames.length === 0) {
5980
+ throw new ParseError("FOREACH command must have at least one subparameter");
5198
5981
  }
5199
5982
  return {
5200
5983
  type: 'FOREACH',
5201
5984
  formatName: formatName,
5202
5985
  cellName: cellName,
5203
5986
  parameterName: parameterName,
5987
+ subparameterNames: subparameterNames,
5204
5988
  };
5205
5989
  },
5206
5990
  /**
@@ -5209,8 +5993,12 @@ var foreachCommandParser = {
5209
5993
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5210
5994
  */
5211
5995
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5212
- keepUnused(command, $templateJson, $pipelineJson);
5213
- // <- TODO: [🍭] !!!!!! Implement
5996
+ var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
5997
+ // TODO: !!!!!! Detect double use
5998
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
5999
+ $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterNames: subparameterNames };
6000
+ keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6001
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5214
6002
  },
5215
6003
  /**
5216
6004
  * Converts the FOREACH command back to string
@@ -5219,8 +6007,7 @@ var foreachCommandParser = {
5219
6007
  */
5220
6008
  stringify: function (command) {
5221
6009
  keepUnused(command);
5222
- return "";
5223
- // <- TODO: [🍭] !!!!!! Implement
6010
+ return "---"; // <- TODO: [🛋] Implement
5224
6011
  },
5225
6012
  /**
5226
6013
  * Reads the FOREACH command from the `TemplateJson`
@@ -5229,12 +6016,12 @@ var foreachCommandParser = {
5229
6016
  */
5230
6017
  takeFromTemplateJson: function ($templateJson) {
5231
6018
  keepUnused($templateJson);
5232
- return [];
5233
- // <- TODO: [🍭] !!!!!! Implement
6019
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5234
6020
  },
5235
6021
  };
5236
6022
  /**
5237
- * TODO: !!!!!! Comment console logs
6023
+ * TODO: !!!!!! Remove console logs
6024
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
5238
6025
  * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5239
6026
  */
5240
6027
 
@@ -5345,6 +6132,7 @@ var jokerCommandParser = {
5345
6132
  */
5346
6133
  parse: function (input) {
5347
6134
  var args = input.args;
6135
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5348
6136
  var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5349
6137
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5350
6138
  throw new ParseError("Invalid joker");
@@ -5474,6 +6262,7 @@ var modelCommandParser = {
5474
6262
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5475
6263
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5476
6264
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6265
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5477
6266
  }
5478
6267
  else {
5479
6268
  throw new ParseError(spaceTrim$1("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -6550,7 +7339,7 @@ function extractAllListItemsFromMarkdown(markdown) {
6550
7339
  function extractOneBlockFromMarkdown(markdown) {
6551
7340
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6552
7341
  if (codeBlocks.length !== 1) {
6553
- throw new ParseError(spaceTrim$1(function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7342
+ throw new ParseError(spaceTrim$1(function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6554
7343
  }
6555
7344
  return codeBlocks[0];
6556
7345
  }
@@ -7590,21 +8379,41 @@ function usageToWorktime(usage) {
7590
8379
  * @public exported from `@promptbook/core`
7591
8380
  */
7592
8381
  function usageToHuman(usage) {
7593
- var report = 'Usage:';
8382
+ var reportItems = [];
7594
8383
  var uncertainNumberToHuman = function (_a) {
7595
8384
  var value = _a.value, isUncertain = _a.isUncertain;
7596
8385
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7597
8386
  };
7598
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7599
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7600
- return spaceTrim$1(report);
8387
+ if (usage.price.value > 0.01
8388
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8389
+ ) {
8390
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8391
+ }
8392
+ else {
8393
+ reportItems.push("Negligible cost");
8394
+ }
8395
+ var worktime = usageToWorktime(usage);
8396
+ if (worktime.value >
8397
+ 1 / 60
8398
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8399
+ ) {
8400
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8401
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8402
+ }
8403
+ if (usage.output.charactersCount.value > 0) {
8404
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8405
+ }
8406
+ if (reportItems.length === 0) {
8407
+ // Note: For negligible usage, we report at least something
8408
+ reportItems.push('Negligible');
8409
+ }
8410
+ return spaceTrim$1(function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7601
8411
  }
7602
8412
  /**
7603
- * TODO: Use "$1" not "1 USD"
7604
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7605
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8413
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8414
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8415
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7606
8416
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7607
- * TODO: When negligible usage, report "Negligible" or just don't report it
7608
8417
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7609
8418
  * TODO: [🏛] Maybe make some markdown builder
7610
8419
  */
@@ -8408,70 +9217,6 @@ function addAutoGeneratedSection(content, options) {
8408
9217
  * TODO: [🏛] This can be part of markdown builder
8409
9218
  */
8410
9219
 
8411
- /**
8412
- * @@@
8413
- *
8414
- * @param text @@@
8415
- * @param _isFirstLetterCapital @@@
8416
- * @returns @@@
8417
- * @example 'helloWorld'
8418
- * @example 'iLovePromptbook'
8419
- * @public exported from `@promptbook/utils`
8420
- */
8421
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
8422
- var e_1, _a;
8423
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
8424
- var charType;
8425
- var lastCharType = null;
8426
- var normalizedName = '';
8427
- try {
8428
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
8429
- var char = text_1_1.value;
8430
- var normalizedChar = void 0;
8431
- if (/^[a-z]$/.test(char)) {
8432
- charType = 'LOWERCASE';
8433
- normalizedChar = char;
8434
- }
8435
- else if (/^[A-Z]$/.test(char)) {
8436
- charType = 'UPPERCASE';
8437
- normalizedChar = char.toLowerCase();
8438
- }
8439
- else if (/^[0-9]$/.test(char)) {
8440
- charType = 'NUMBER';
8441
- normalizedChar = char;
8442
- }
8443
- else {
8444
- charType = 'OTHER';
8445
- normalizedChar = '';
8446
- }
8447
- if (!lastCharType) {
8448
- if (_isFirstLetterCapital) {
8449
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
8450
- }
8451
- }
8452
- else if (charType !== lastCharType &&
8453
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
8454
- !(lastCharType === 'NUMBER') &&
8455
- !(charType === 'NUMBER')) {
8456
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
8457
- }
8458
- normalizedName += normalizedChar;
8459
- lastCharType = charType;
8460
- }
8461
- }
8462
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
8463
- finally {
8464
- try {
8465
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
8466
- }
8467
- finally { if (e_1) throw e_1.error; }
8468
- }
8469
- return normalizedName;
8470
- }
8471
- /**
8472
- * TODO: [🌺] Use some intermediate util splitWords
8473
- */
8474
-
8475
9220
  /**
8476
9221
  * Creates a Mermaid graph based on the promptbook
8477
9222
  *
@@ -8528,6 +9273,9 @@ function renderPromptbookMermaid(pipelineJson, options) {
8528
9273
  return promptbookMermaid;
8529
9274
  }
8530
9275
  /**
9276
+ * TODO: !!!!!! FOREACH in mermaid graph
9277
+ * TODO: !!!!!! Knowledge in mermaid graph
9278
+ * TODO: !!!!!! Personas in mermaid graph
8531
9279
  * TODO: Maybe use some Mermaid package instead of string templating
8532
9280
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8533
9281
  */
@@ -9246,7 +9994,7 @@ var AnthropicClaudeExecutionTools = /** @class */ (function () {
9246
9994
  resultContent = contentBlock.text;
9247
9995
  // eslint-disable-next-line prefer-const
9248
9996
  complete = getCurrentIsoDate();
9249
- usage = computeAnthropicClaudeUsage(content, '', rawResponse);
9997
+ usage = computeAnthropicClaudeUsage(rawPromptContent || '', resultContent || '', rawResponse);
9250
9998
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('AnthropicClaudeExecutionTools ChatPromptResult', {
9251
9999
  content: resultContent,
9252
10000
  modelName: rawResponse.model,
@@ -10360,7 +11108,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10360
11108
  resultContent = rawResponse.choices[0].message.content;
10361
11109
  // eslint-disable-next-line prefer-const
10362
11110
  complete = getCurrentIsoDate();
10363
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11111
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10364
11112
  if (resultContent === null) {
10365
11113
  throw new PipelineExecutionError('No response message from OpenAI');
10366
11114
  }
@@ -10432,7 +11180,7 @@ var OpenAiExecutionTools = /** @class */ (function () {
10432
11180
  resultContent = rawResponse.choices[0].text;
10433
11181
  // eslint-disable-next-line prefer-const
10434
11182
  complete = getCurrentIsoDate();
10435
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11183
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10436
11184
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools CompletionPromptResult', {
10437
11185
  content: resultContent,
10438
11186
  modelName: rawResponse.model || modelName,
@@ -10492,7 +11240,9 @@ var OpenAiExecutionTools = /** @class */ (function () {
10492
11240
  resultContent = rawResponse.data[0].embedding;
10493
11241
  // eslint-disable-next-line prefer-const
10494
11242
  complete = getCurrentIsoDate();
10495
- usage = computeOpenAiUsage(content, '', rawResponse);
11243
+ usage = computeOpenAiUsage(content || '', '',
11244
+ // <- Note: Embedding does not have result content
11245
+ rawResponse);
10496
11246
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools EmbeddingPromptResult', {
10497
11247
  content: resultContent,
10498
11248
  modelName: rawResponse.model || modelName,