@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/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('path'), require('prettier'), require('prettier/parser-html'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv'), require('glob-promise'), require('socket.io-client'), require('@anthropic-ai/sdk'), require('@azure/openai'), require('openai')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'path', 'prettier', 'prettier/parser-html', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv', 'glob-promise', 'socket.io-client', '@anthropic-ai/sdk', '@azure/openai', 'openai'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.path, global.prettier, global.parserHtml, global.hexEncoder, global.sha256, global.posix, global.dotenv, global.glob, global.socket_ioClient, global.Anthropic, global.openai, global.OpenAI));
5
- })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, path, prettier, parserHtml, hexEncoder, sha256, posix, dotenv, glob, socket_ioClient, Anthropic, openai, OpenAI) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('path'), require('prettier'), require('prettier/parser-html'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv'), require('glob-promise'), require('socket.io-client'), require('@anthropic-ai/sdk'), require('@azure/openai'), require('openai')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'path', 'prettier', 'prettier/parser-html', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv', 'glob-promise', 'socket.io-client', '@anthropic-ai/sdk', '@azure/openai', 'openai'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.path, global.prettier, global.parserHtml, global.papaparse, global.hexEncoder, global.sha256, global.posix, global.dotenv, global.glob, global.socket_ioClient, global.Anthropic, global.openai, global.OpenAI));
5
+ })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, path, prettier, parserHtml, papaparse, hexEncoder, sha256, posix, dotenv, glob, socket_ioClient, Anthropic, openai, OpenAI) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -39,7 +39,7 @@
39
39
  /**
40
40
  * The version of the Promptbook library
41
41
  */
42
- var PROMPTBOOK_VERSION = '0.69.0-0';
42
+ var PROMPTBOOK_VERSION = '0.69.0-10';
43
43
  // TODO: !!!! List here all the versions and annotate + put into script
44
44
 
45
45
  /*! *****************************************************************************
@@ -449,13 +449,13 @@
449
449
  *
450
450
  * @public exported from `@promptbook/core`
451
451
  */
452
- var MAX_PARALLEL_COUNT = 5;
452
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
453
453
  /**
454
454
  * The maximum number of attempts to execute LLM task before giving up
455
455
  *
456
456
  * @public exported from `@promptbook/core`
457
457
  */
458
- var MAX_EXECUTION_ATTEMPTS = 3;
458
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
459
459
  /**
460
460
  * The maximum length of the (generated) filename
461
461
  *
@@ -492,6 +492,7 @@
492
492
  'samples',
493
493
  'modelName',
494
494
  'currentDate',
495
+ // <- TODO: !!!!! list here all command names
495
496
  // <- TODO: Add more like 'date', 'modelName',...
496
497
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
497
498
  ]);
@@ -526,6 +527,15 @@
526
527
  * @public exported from `@promptbook/core`
527
528
  */
528
529
  var IS_VERBOSE = false;
530
+ /**
531
+ * @@@
532
+ *
533
+ * @private within the repository
534
+ */
535
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
536
+ /**/
537
+ // Note: In normal situations, we check the pipeline logic:
538
+ true);
529
539
  /**
530
540
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
531
541
  */
@@ -1059,7 +1069,7 @@
1059
1069
  });
1060
1070
  }
1061
1071
 
1062
- 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"}];
1072
+ 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"}];
1063
1073
 
1064
1074
  /**
1065
1075
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1266,6 +1276,26 @@
1266
1276
  * @public exported from `@promptbook/core`
1267
1277
  */
1268
1278
  function validatePipeline(pipeline) {
1279
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1280
+ validatePipelineCore(pipeline);
1281
+ }
1282
+ else {
1283
+ try {
1284
+ validatePipelineCore(pipeline);
1285
+ }
1286
+ catch (error) {
1287
+ if (!(error instanceof PipelineLogicError)) {
1288
+ throw error;
1289
+ }
1290
+ console.error(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1291
+ }
1292
+ }
1293
+ return pipeline;
1294
+ }
1295
+ /**
1296
+ * @private internal function for `validatePipeline`
1297
+ */
1298
+ function validatePipelineCore(pipeline) {
1269
1299
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1270
1300
  var e_1, _a, e_2, _b, e_3, _c;
1271
1301
  var pipelineIdentification = (function () {
@@ -1290,12 +1320,12 @@
1290
1320
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1291
1321
  if (!Array.isArray(pipeline.parameters)) {
1292
1322
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1293
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1323
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1294
1324
  }
1295
1325
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1296
1326
  if (!Array.isArray(pipeline.templates)) {
1297
1327
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1298
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1328
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1299
1329
  }
1300
1330
  var _loop_1 = function (parameter) {
1301
1331
  if (parameter.isInput && parameter.isOutput) {
@@ -1464,9 +1494,9 @@
1464
1494
  while (unresovedTemplates.length > 0) {
1465
1495
  _loop_3();
1466
1496
  }
1467
- return pipeline;
1468
1497
  }
1469
1498
  /**
1499
+ * TODO: !!!!!! [🧞‍♀️] Do not allow joker + foreach
1470
1500
  * TODO: [🧠] Work with promptbookVersion
1471
1501
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1472
1502
  * > /**
@@ -2188,113 +2218,35 @@
2188
2218
  */
2189
2219
 
2190
2220
  /**
2191
- * Parses the given script and returns the list of all used variables that are not defined in the script
2192
- *
2193
- * @param script from which to extract the variables
2194
- * @returns the list of variable names
2195
- * @throws {ParseError} if the script is invalid
2196
- * @public exported from `@promptbook/utils`
2197
- */
2198
- function extractVariables(script) {
2199
- var variables = new Set();
2200
- script = "(()=>{".concat(script, "})()");
2201
- try {
2202
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2203
- try {
2204
- eval(script);
2205
- }
2206
- catch (error) {
2207
- if (!(error instanceof ReferenceError)) {
2208
- throw error;
2209
- }
2210
- var undefinedName = error.message.split(' ')[0];
2211
- /*
2212
- Note: Parsing the error
2213
- [PipelineUrlError: thing is not defined]
2214
- */
2215
- if (!undefinedName) {
2216
- throw error;
2217
- }
2218
- if (script.includes(undefinedName + '(')) {
2219
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2220
- }
2221
- else {
2222
- variables.add(undefinedName);
2223
- script = "const ".concat(undefinedName, " = '';") + script;
2224
- }
2225
- }
2226
- }
2227
- catch (error) {
2228
- if (!(error instanceof Error)) {
2229
- throw error;
2230
- }
2231
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2232
- }
2233
- return variables;
2234
- }
2235
- /**
2236
- * TODO: [🔣] Support for multiple languages - python, java,...
2237
- */
2238
-
2239
- /**
2240
- * Parses the template and returns the set of all used parameters
2221
+ * Determine if the pipeline is fully prepared
2241
2222
  *
2242
- * @param template the template with used parameters
2243
- * @returns the set of parameter names
2244
- * @throws {ParseError} if the script is invalid
2245
- * @public exported from `@promptbook/utils`
2223
+ * @public exported from `@promptbook/core`
2246
2224
  */
2247
- function extractParameterNamesFromTemplate(template) {
2248
- var e_1, _a, e_2, _b, e_3, _c;
2249
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2250
- var parameterNames = new Set();
2251
- try {
2252
- 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()) {
2253
- var parameterName = _e.value;
2254
- parameterNames.add(parameterName);
2255
- }
2256
- }
2257
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2258
- finally {
2259
- try {
2260
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2261
- }
2262
- finally { if (e_1) throw e_1.error; }
2263
- }
2264
- if (templateType === 'SCRIPT_TEMPLATE') {
2265
- try {
2266
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2267
- var parameterName = _g.value;
2268
- parameterNames.add(parameterName);
2269
- }
2270
- }
2271
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2272
- finally {
2273
- try {
2274
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2275
- }
2276
- finally { if (e_2) throw e_2.error; }
2277
- }
2278
- }
2279
- try {
2280
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2281
- var jokerName = _j.value;
2282
- parameterNames.add(jokerName);
2283
- }
2225
+ function isPipelinePrepared(pipeline) {
2226
+ // Note: Ignoring `pipeline.preparations` @@@
2227
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2228
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2229
+ return false;
2284
2230
  }
2285
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2286
- finally {
2287
- try {
2288
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2289
- }
2290
- finally { if (e_3) throw e_3.error; }
2231
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2232
+ return false;
2291
2233
  }
2292
- parameterNames.delete('content');
2293
- // <- Note {websiteContent} is used in `preparedContent`
2294
- return parameterNames;
2234
+ /*
2235
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2236
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2237
+ > return false;
2238
+ > }
2239
+ */
2240
+ return true;
2295
2241
  }
2296
2242
  /**
2297
- * TODO: [🔣] If script require contentLanguage
2243
+ * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2244
+ * TODO: [🐠] Maybe base this on `makeValidator`
2245
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2246
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2247
+ * - [🏍] ? Is context in each template
2248
+ * - [♨] Are samples prepared
2249
+ * - [♨] Are templates prepared
2298
2250
  */
2299
2251
 
2300
2252
  /**
@@ -2314,27 +2266,6 @@
2314
2266
  };
2315
2267
  }
2316
2268
 
2317
- /**
2318
- * Function isValidJsonString will tell you if the string is valid JSON or not
2319
- *
2320
- * @public exported from `@promptbook/utils`
2321
- */
2322
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2323
- try {
2324
- JSON.parse(value);
2325
- return true;
2326
- }
2327
- catch (error) {
2328
- if (!(error instanceof Error)) {
2329
- throw error;
2330
- }
2331
- if (error.message.includes('Unexpected token')) {
2332
- return false;
2333
- }
2334
- return false;
2335
- }
2336
- }
2337
-
2338
2269
  /**
2339
2270
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2340
2271
  *
@@ -2629,288 +2560,153 @@
2629
2560
  */
2630
2561
 
2631
2562
  /**
2632
- * Extracts all code blocks from markdown.
2563
+ * Takes an item or an array of items and returns an array of items
2633
2564
  *
2634
- * Note: There are multiple simmilar function:
2635
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2636
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2637
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2638
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2565
+ * 1) Any item except array and undefined returns array with that one item (also null)
2566
+ * 2) Undefined returns empty array
2567
+ * 3) Array returns itself
2639
2568
  *
2640
- * @param markdown any valid markdown
2641
- * @returns code blocks with language and content
2642
- * @throws {ParseError} if block is not closed properly
2643
- * @public exported from `@promptbook/markdown-utils`
2569
+ * @private internal utility
2644
2570
  */
2645
- function extractAllBlocksFromMarkdown(markdown) {
2646
- var e_1, _a;
2647
- var codeBlocks = [];
2648
- var lines = markdown.split('\n');
2649
- // Note: [0] Ensure that the last block notated by gt > will be closed
2650
- lines.push('');
2651
- var currentCodeBlock = null;
2571
+ function arrayableToArray(input) {
2572
+ if (input === undefined) {
2573
+ return [];
2574
+ }
2575
+ if (input instanceof Array) {
2576
+ return input;
2577
+ }
2578
+ return [input];
2579
+ }
2580
+
2581
+ /**
2582
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2583
+ *
2584
+ * @param script from which to extract the variables
2585
+ * @returns the list of variable names
2586
+ * @throws {ParseError} if the script is invalid
2587
+ * @public exported from `@promptbook/utils`
2588
+ */
2589
+ function extractVariables(script) {
2590
+ var variables = new Set();
2591
+ script = "(()=>{".concat(script, "})()");
2652
2592
  try {
2653
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2654
- var line = lines_1_1.value;
2655
- if (line.startsWith('> ') || line === '>') {
2656
- if (currentCodeBlock === null) {
2657
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2658
- } /* not else */
2659
- if (currentCodeBlock.blockNotation === '>') {
2660
- if (currentCodeBlock.content !== '') {
2661
- currentCodeBlock.content += '\n';
2662
- }
2663
- currentCodeBlock.content += line.slice(2);
2664
- }
2665
- }
2666
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2667
- codeBlocks.push(currentCodeBlock);
2668
- currentCodeBlock = null;
2593
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2594
+ try {
2595
+ eval(script);
2669
2596
  }
2670
- /* not else */
2671
- if (line.startsWith('```')) {
2672
- var language = line.slice(3).trim() || null;
2673
- if (currentCodeBlock === null) {
2674
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2597
+ catch (error) {
2598
+ if (!(error instanceof ReferenceError)) {
2599
+ throw error;
2675
2600
  }
2676
- else {
2677
- if (language !== null) {
2678
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2679
- }
2680
- codeBlocks.push(currentCodeBlock);
2681
- currentCodeBlock = null;
2601
+ var undefinedName = error.message.split(' ')[0];
2602
+ /*
2603
+ Note: Parsing the error
2604
+ [PipelineUrlError: thing is not defined]
2605
+ */
2606
+ if (!undefinedName) {
2607
+ throw error;
2682
2608
  }
2683
- }
2684
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2685
- if (currentCodeBlock.content !== '') {
2686
- currentCodeBlock.content += '\n';
2609
+ if (script.includes(undefinedName + '(')) {
2610
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2611
+ }
2612
+ else {
2613
+ variables.add(undefinedName);
2614
+ script = "const ".concat(undefinedName, " = '';") + script;
2687
2615
  }
2688
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2689
2616
  }
2617
+ }
2618
+ catch (error) {
2619
+ if (!(error instanceof Error)) {
2620
+ throw error;
2690
2621
  }
2622
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2691
2623
  }
2692
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2693
- finally {
2694
- try {
2695
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2696
- }
2697
- finally { if (e_1) throw e_1.error; }
2698
- }
2699
- if (currentCodeBlock !== null) {
2700
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2701
- }
2702
- return codeBlocks;
2703
- }
2704
- /**
2705
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2706
- */
2707
-
2708
- /**
2709
- * Extracts extracts exactly one valid JSON code block
2710
- *
2711
- * - When given string is a valid JSON as it is, it just returns it
2712
- * - When there is no JSON code block the function throws a `ParseError`
2713
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2714
- *
2715
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2716
- * Note: There are multiple simmilar function:
2717
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2718
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2719
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2720
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2721
- *
2722
- * @public exported from `@promptbook/markdown-utils`
2723
- * @throws {ParseError} if there is no valid JSON block in the markdown
2724
- */
2725
- function extractJsonBlock(markdown) {
2726
- if (isValidJsonString(markdown)) {
2727
- return markdown;
2728
- }
2729
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2730
- var jsonBlocks = codeBlocks.filter(function (_a) {
2731
- var content = _a.content;
2732
- return isValidJsonString(content);
2733
- });
2734
- if (jsonBlocks.length === 0) {
2735
- throw new Error('There is no valid JSON block in the markdown');
2736
- }
2737
- if (jsonBlocks.length > 1) {
2738
- throw new Error('There are multiple JSON code blocks in the markdown');
2739
- }
2740
- return jsonBlocks[0].content;
2741
- }
2742
- /**
2743
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2744
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2745
- */
2746
-
2747
- /**
2748
- * Determine if the pipeline is fully prepared
2749
- *
2750
- * @public exported from `@promptbook/core`
2751
- */
2752
- function isPipelinePrepared(pipeline) {
2753
- // Note: Ignoring `pipeline.preparations` @@@
2754
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2755
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2756
- return false;
2757
- }
2758
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2759
- return false;
2760
- }
2761
- /*
2762
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2763
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2764
- > return false;
2765
- > }
2766
- */
2767
- return true;
2768
- }
2769
- /**
2770
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2771
- * TODO: [🐠] Maybe base this on `makeValidator`
2772
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2773
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2774
- * - [🏍] ? Is context in each template
2775
- * - [♨] Are samples prepared
2776
- * - [♨] Are templates prepared
2777
- */
2778
-
2779
- /**
2780
- * Takes an item or an array of items and returns an array of items
2781
- *
2782
- * 1) Any item except array and undefined returns array with that one item (also null)
2783
- * 2) Undefined returns empty array
2784
- * 3) Array returns itself
2785
- *
2786
- * @private internal utility
2787
- */
2788
- function arrayableToArray(input) {
2789
- if (input === undefined) {
2790
- return [];
2791
- }
2792
- if (input instanceof Array) {
2793
- return input;
2794
- }
2795
- return [input];
2796
- }
2797
-
2798
- /**
2799
- * Just says that the variable is not used but should be kept
2800
- * No side effects.
2801
- *
2802
- * Note: It can be usefull for:
2803
- *
2804
- * 1) Suppressing eager optimization of unused imports
2805
- * 2) Suppressing eslint errors of unused variables in the tests
2806
- * 3) Keeping the type of the variable for type testing
2807
- *
2808
- * @param value any values
2809
- * @returns void
2810
- * @private within the repository
2811
- */
2812
- function keepUnused() {
2813
- var valuesToKeep = [];
2814
- for (var _i = 0; _i < arguments.length; _i++) {
2815
- valuesToKeep[_i] = arguments[_i];
2816
- }
2624
+ return variables;
2817
2625
  }
2818
-
2819
2626
  /**
2820
- * Just marks a place of place where should be something implemented
2821
- * No side effects.
2822
- *
2823
- * Note: It can be usefull suppressing eslint errors of unused variables
2824
- *
2825
- * @param value any values
2826
- * @returns void
2827
- * @private within the repository
2627
+ * TODO: [🔣] Support for multiple languages - python, java,...
2828
2628
  */
2829
- function TODO_USE() {
2830
- var value = [];
2831
- for (var _i = 0; _i < arguments.length; _i++) {
2832
- value[_i] = arguments[_i];
2833
- }
2834
- }
2835
2629
 
2836
2630
  /**
2837
- * Replaces parameters in template with values from parameters object
2631
+ * Parses the template and returns the set of all used parameters
2838
2632
  *
2839
- * @param template the template with parameters in {curly} braces
2840
- * @param parameters the object with parameters
2841
- * @returns the template with replaced parameters
2842
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2633
+ * @param template the template with used parameters
2634
+ * @returns the set of parameter names
2635
+ * @throws {ParseError} if the script is invalid
2843
2636
  * @public exported from `@promptbook/utils`
2844
2637
  */
2845
- function replaceParameters(template, parameters) {
2846
- var e_1, _a;
2638
+ function extractParameterNamesFromTemplate(template) {
2639
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2640
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2641
+ var parameterNames = new Set();
2847
2642
  try {
2848
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2849
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2850
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2851
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2852
- }
2853
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2854
- // TODO: [🍵]
2855
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2856
- }
2643
+ 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()) {
2644
+ var parameterName = _f.value;
2645
+ parameterNames.add(parameterName);
2857
2646
  }
2858
2647
  }
2859
2648
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2860
2649
  finally {
2861
2650
  try {
2862
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2651
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2863
2652
  }
2864
2653
  finally { if (e_1) throw e_1.error; }
2865
2654
  }
2866
- var replacedTemplate = template;
2867
- var match;
2868
- var loopLimit = LOOP_LIMIT;
2869
- var _loop_1 = function () {
2870
- if (loopLimit-- < 0) {
2871
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2655
+ if (templateType === 'SCRIPT_TEMPLATE') {
2656
+ try {
2657
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2658
+ var parameterName = _h.value;
2659
+ parameterNames.add(parameterName);
2660
+ }
2872
2661
  }
2873
- var precol = match.groups.precol;
2874
- var parameterName = match.groups.parameterName;
2875
- if (parameterName === '') {
2876
- return "continue";
2662
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2663
+ finally {
2664
+ try {
2665
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2666
+ }
2667
+ finally { if (e_2) throw e_2.error; }
2877
2668
  }
2878
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2879
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2669
+ }
2670
+ try {
2671
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2672
+ var jokerName = _k.value;
2673
+ parameterNames.add(jokerName);
2880
2674
  }
2881
- if (parameters[parameterName] === undefined) {
2882
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2675
+ }
2676
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2677
+ finally {
2678
+ try {
2679
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2883
2680
  }
2884
- var parameterValue = parameters[parameterName];
2885
- if (parameterValue === undefined) {
2886
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2681
+ finally { if (e_3) throw e_3.error; }
2682
+ }
2683
+ parameterNames.delete('content');
2684
+ // <- Note {websiteContent} is used in `preparedContent`
2685
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2686
+ if (foreach !== undefined) {
2687
+ try {
2688
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2689
+ var subparameterName = _m.value;
2690
+ if (parameterNames.has(subparameterName)) {
2691
+ parameterNames.delete(subparameterName);
2692
+ parameterNames.add(foreach.parameterName);
2693
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2694
+ }
2695
+ }
2887
2696
  }
2888
- parameterValue = parameterValue.toString();
2889
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2890
- parameterValue = parameterValue
2891
- .split('\n')
2892
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2893
- .join('\n');
2697
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2698
+ finally {
2699
+ try {
2700
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2701
+ }
2702
+ finally { if (e_4) throw e_4.error; }
2894
2703
  }
2895
- replacedTemplate =
2896
- replacedTemplate.substring(0, match.index + precol.length) +
2897
- parameterValue +
2898
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2899
- };
2900
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2901
- .exec(replacedTemplate))) {
2902
- _loop_1();
2903
2704
  }
2904
- // [💫] Check if there are parameters that are not closed properly
2905
- if (/{\w+$/.test(replacedTemplate)) {
2906
- throw new PipelineExecutionError('Parameter is not closed');
2907
- }
2908
- // [💫] Check if there are parameters that are not opened properly
2909
- if (/^\w+}/.test(replacedTemplate)) {
2910
- throw new PipelineExecutionError('Parameter is not opened');
2911
- }
2912
- return replacedTemplate;
2705
+ return parameterNames;
2913
2706
  }
2707
+ /**
2708
+ * TODO: [🔣] If script require contentLanguage
2709
+ */
2914
2710
 
2915
2711
  /**
2916
2712
  * Create difference set of two sets.
@@ -2988,117 +2784,364 @@
2988
2784
  }
2989
2785
 
2990
2786
  /**
2991
- * Counts number of characters in the text
2787
+ * Just marks a place of place where should be something implemented
2788
+ * No side effects.
2992
2789
  *
2993
- * @public exported from `@promptbook/utils`
2994
- */
2995
- function countCharacters(text) {
2996
- // Remove null characters
2997
- text = text.replace(/\0/g, '');
2998
- // Replace emojis (and also ZWJ sequence) with hyphens
2999
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3000
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3001
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3002
- return text.length;
3003
- }
3004
-
3005
- /**
3006
- * Counts number of lines in the text
2790
+ * Note: It can be usefull suppressing eslint errors of unused variables
3007
2791
  *
3008
- * @public exported from `@promptbook/utils`
2792
+ * @param value any values
2793
+ * @returns void
2794
+ * @private within the repository
3009
2795
  */
3010
- function countLines(text) {
3011
- if (text === '') {
3012
- return 0;
2796
+ function TODO_USE() {
2797
+ var value = [];
2798
+ for (var _i = 0; _i < arguments.length; _i++) {
2799
+ value[_i] = arguments[_i];
3013
2800
  }
3014
- return text.split('\n').length;
3015
2801
  }
3016
2802
 
3017
2803
  /**
3018
- * Counts number of pages in the text
2804
+ * Definition for CSV spreadsheet
3019
2805
  *
3020
- * @public exported from `@promptbook/utils`
2806
+ * @public exported from `@promptbook/core`
2807
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2808
+ */
2809
+ var CsvFormatDefinition = {
2810
+ formatName: 'CSV',
2811
+ aliases: ['SPREADSHEET', 'TABLE'],
2812
+ isValid: function (value, schema) {
2813
+ TODO_USE(value /* <- TODO: Use value here */);
2814
+ TODO_USE(schema /* <- TODO: Use schema here */);
2815
+ return true;
2816
+ },
2817
+ canBeValid: function (partialValue, schema) {
2818
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2819
+ TODO_USE(schema /* <- TODO: Use schema here */);
2820
+ return true;
2821
+ },
2822
+ heal: function (value, schema) {
2823
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2824
+ TODO_USE(schema /* <- TODO: Use schema here */);
2825
+ throw new Error('Not implemented');
2826
+ },
2827
+ subvalueDefinitions: [
2828
+ {
2829
+ subvalueName: 'ROW',
2830
+ mapValues: function (value, mapCallback) {
2831
+ return __awaiter(this, void 0, void 0, function () {
2832
+ var csv, mappedData;
2833
+ var _this = this;
2834
+ return __generator(this, function (_a) {
2835
+ switch (_a.label) {
2836
+ case 0:
2837
+ csv = papaparse.parse(value, {
2838
+ header: true,
2839
+ delimiter: ',',
2840
+ quoteChar: '"',
2841
+ newline: '\r\n',
2842
+ skipEmptyLines: true,
2843
+ // encoding: 'utf8',
2844
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2845
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2846
+ });
2847
+ if (csv.errors.length !== 0) {
2848
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2849
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2850
+ }
2851
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2852
+ var _a;
2853
+ var _b;
2854
+ return __generator(this, function (_c) {
2855
+ switch (_c.label) {
2856
+ case 0:
2857
+ _a = [__assign({}, row)];
2858
+ _b = {};
2859
+ // <- TODO: !!!!!! Dynamic new column name and position
2860
+ return [4 /*yield*/, mapCallback(row, index)];
2861
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2862
+ // <- TODO: !!!!!! Dynamic new column name and position
2863
+ _c.sent(), _b)])))];
2864
+ }
2865
+ });
2866
+ }); }))];
2867
+ case 1:
2868
+ mappedData = _a.sent();
2869
+ return [2 /*return*/, papaparse.unparse(mappedData, {
2870
+ header: true,
2871
+ delimiter: ',',
2872
+ quoteChar: '"',
2873
+ newline: '\r\n',
2874
+ skipEmptyLines: true,
2875
+ // encoding: 'utf8',
2876
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2877
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2878
+ })];
2879
+ }
2880
+ });
2881
+ });
2882
+ },
2883
+ },
2884
+ {
2885
+ subvalueName: 'CELL',
2886
+ mapValues: function (value, mapCallback) {
2887
+ return __awaiter(this, void 0, void 0, function () {
2888
+ var csv, mappedData;
2889
+ var _this = this;
2890
+ return __generator(this, function (_a) {
2891
+ switch (_a.label) {
2892
+ case 0:
2893
+ csv = papaparse.parse(value, {
2894
+ header: true,
2895
+ delimiter: ',',
2896
+ quoteChar: '"',
2897
+ newline: '\r\n',
2898
+ skipEmptyLines: true,
2899
+ // encoding: 'utf8',
2900
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2901
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2902
+ });
2903
+ if (csv.errors.length !== 0) {
2904
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2905
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2906
+ }
2907
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2908
+ var _this = this;
2909
+ return __generator(this, function (_a) {
2910
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2911
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2912
+ return __awaiter(_this, void 0, void 0, function () {
2913
+ var index;
2914
+ var _c;
2915
+ return __generator(this, function (_d) {
2916
+ index = rowIndex * Object.keys(row).length + columnIndex;
2917
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2918
+ });
2919
+ });
2920
+ }))];
2921
+ });
2922
+ }); }))];
2923
+ case 1:
2924
+ mappedData = _a.sent();
2925
+ return [2 /*return*/, papaparse.unparse(mappedData, {
2926
+ header: true,
2927
+ delimiter: ',',
2928
+ quoteChar: '"',
2929
+ newline: '\r\n',
2930
+ skipEmptyLines: true,
2931
+ // encoding: 'utf8',
2932
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2933
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2934
+ })];
2935
+ }
2936
+ });
2937
+ });
2938
+ },
2939
+ },
2940
+ ],
2941
+ };
2942
+ /**
2943
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2944
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2945
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2946
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2947
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3021
2948
  */
3022
- function countPages(text) {
3023
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
3024
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3025
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3026
- return pageCount;
3027
- }
3028
2949
 
3029
2950
  /**
3030
- * Counts number of paragraphs in the text
2951
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3031
2952
  *
3032
2953
  * @public exported from `@promptbook/utils`
3033
2954
  */
3034
- function countParagraphs(text) {
3035
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
2955
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2956
+ try {
2957
+ JSON.parse(value);
2958
+ return true;
2959
+ }
2960
+ catch (error) {
2961
+ if (!(error instanceof Error)) {
2962
+ throw error;
2963
+ }
2964
+ if (error.message.includes('Unexpected token')) {
2965
+ return false;
2966
+ }
2967
+ return false;
2968
+ }
3036
2969
  }
3037
2970
 
3038
2971
  /**
3039
- * Split text into sentences
2972
+ * Definition for JSON format
3040
2973
  *
3041
- * @public exported from `@promptbook/utils`
2974
+ * @private still in development [🏢]
3042
2975
  */
3043
- function splitIntoSentences(text) {
3044
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3045
- }
2976
+ var JsonFormatDefinition = {
2977
+ formatName: 'JSON',
2978
+ mimeType: 'application/json',
2979
+ isValid: function (value, schema) {
2980
+ TODO_USE(schema /* <- TODO: Use schema here */);
2981
+ return isValidJsonString(value);
2982
+ },
2983
+ canBeValid: function (partialValue, schema) {
2984
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2985
+ TODO_USE(schema /* <- TODO: Use schema here */);
2986
+ return true;
2987
+ },
2988
+ heal: function (value, schema) {
2989
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2990
+ TODO_USE(schema /* <- TODO: Use schema here */);
2991
+ throw new Error('Not implemented');
2992
+ },
2993
+ subvalueDefinitions: [],
2994
+ };
3046
2995
  /**
3047
- * Counts number of sentences in the text
3048
- *
3049
- * @public exported from `@promptbook/utils`
2996
+ * TODO: [🧠] Maybe propper instance of object
2997
+ * TODO: [0] Make string_serialized_json
2998
+ * TODO: [1] Make type for JSON Schema
2999
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3000
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3001
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3002
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3003
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3004
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3050
3005
  */
3051
- function countSentences(text) {
3052
- return splitIntoSentences(text).length;
3053
- }
3054
3006
 
3055
3007
  /**
3056
- * Counts number of words in the text
3008
+ * Definition for any text - this will be always valid
3057
3009
  *
3058
- * @public exported from `@promptbook/utils`
3010
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3011
+ *
3012
+ * @public exported from `@promptbook/core`
3013
+ */
3014
+ var TextFormatDefinition = {
3015
+ formatName: 'TEXT',
3016
+ isValid: function (value) {
3017
+ return typeof value === 'string';
3018
+ },
3019
+ canBeValid: function (partialValue) {
3020
+ return typeof partialValue === 'string';
3021
+ },
3022
+ heal: function () {
3023
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3024
+ },
3025
+ subvalueDefinitions: [
3026
+ {
3027
+ subvalueName: 'LINE',
3028
+ mapValues: function (value, mapCallback) {
3029
+ return __awaiter(this, void 0, void 0, function () {
3030
+ var lines, mappedLines;
3031
+ return __generator(this, function (_a) {
3032
+ switch (_a.label) {
3033
+ case 0:
3034
+ lines = value.split('\n');
3035
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3036
+ // TODO: [🧠] Maybe option to skip empty line
3037
+ /* not await */ return mapCallback({
3038
+ lineContent: lineContent,
3039
+ // TODO: [🧠] Maybe also put here `lineNumber`
3040
+ }, lineNumber);
3041
+ }))];
3042
+ case 1:
3043
+ mappedLines = _a.sent();
3044
+ return [2 /*return*/, mappedLines.join('\n')];
3045
+ }
3046
+ });
3047
+ });
3048
+ },
3049
+ },
3050
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3051
+ ],
3052
+ };
3053
+ /**
3054
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3055
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3056
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3057
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3058
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3059
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3059
3060
  */
3060
- function countWords(text) {
3061
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3062
- text = removeDiacritics(text);
3063
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3064
- }
3065
3061
 
3066
3062
  /**
3067
- * Index of all counter functions
3063
+ * Definition for XML format
3068
3064
  *
3069
- * @public exported from `@promptbook/utils`
3065
+ * @private still in development [🏢]
3070
3066
  */
3071
- var CountUtils = {
3072
- CHARACTERS: countCharacters,
3073
- WORDS: countWords,
3074
- SENTENCES: countSentences,
3075
- PARAGRAPHS: countParagraphs,
3076
- LINES: countLines,
3077
- PAGES: countPages,
3067
+ var XmlFormatDefinition = {
3068
+ formatName: 'XML',
3069
+ mimeType: 'application/xml',
3070
+ isValid: function (value, schema) {
3071
+ TODO_USE(value /* <- TODO: Use value here */);
3072
+ TODO_USE(schema /* <- TODO: Use schema here */);
3073
+ return true;
3074
+ },
3075
+ canBeValid: function (partialValue, schema) {
3076
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3077
+ TODO_USE(schema /* <- TODO: Use schema here */);
3078
+ return true;
3079
+ },
3080
+ heal: function (value, schema) {
3081
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3082
+ TODO_USE(schema /* <- TODO: Use schema here */);
3083
+ throw new Error('Not implemented');
3084
+ },
3085
+ subvalueDefinitions: [],
3078
3086
  };
3087
+ /**
3088
+ * TODO: [🧠] Maybe propper instance of object
3089
+ * TODO: [0] Make string_serialized_xml
3090
+ * TODO: [1] Make type for XML Schema
3091
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3092
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3093
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3094
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3095
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3096
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3097
+ */
3079
3098
 
3080
3099
  /**
3081
- * Function checkExpectations will check if the expectations on given value are met
3100
+ * Definitions for all formats supported by Promptbook
3082
3101
  *
3083
- * Note: There are two simmilar functions:
3084
- * - `checkExpectations` which throws an error if the expectations are not met
3085
- * - `isPassingExpectations` which returns a boolean
3102
+ * @private internal index of `...` <- TODO [🏢]
3103
+ */
3104
+ var FORMAT_DEFINITIONS = [
3105
+ JsonFormatDefinition,
3106
+ XmlFormatDefinition,
3107
+ TextFormatDefinition,
3108
+ CsvFormatDefinition,
3109
+ ];
3110
+
3111
+ /**
3112
+ * Maps available parameters to expected parameters
3086
3113
  *
3087
- * @throws {ExpectError} if the expectations are not met
3088
- * @returns {void} Nothing
3089
- * @private internal function of `createPipelineExecutor`
3114
+ * The strategy is:
3115
+ * 1) @@@
3116
+ * 2) @@@
3117
+ *
3118
+ * @throws {PipelineExecutionError} @@@
3119
+ * @private within the repository used in `createPipelineExecutor`
3090
3120
  */
3091
- function checkExpectations(expectations, value) {
3121
+ function mapAvailableToExpectedParameters(options) {
3092
3122
  var e_1, _a;
3123
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3124
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3125
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3126
+ var mappedParameters = {};
3093
3127
  try {
3094
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3095
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3096
- var amount = CountUtils[unit.toUpperCase()](value);
3097
- if (min && amount < min) {
3098
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3099
- } /* not else */
3100
- if (max && amount > max) {
3101
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3128
+ // Phase 1️⃣: Matching mapping
3129
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3130
+ var parameterName = _c.value;
3131
+ // Situation: Parameter is available and expected
3132
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3133
+ mappedParameters[parameterName] = availableParameters[parameterName];
3134
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3135
+ availableParametersNames.delete(parameterName);
3136
+ expectedParameterNames.delete(parameterName);
3137
+ }
3138
+ // Situation: Parameter is available but NOT expected
3139
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3140
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3141
+ }
3142
+ // Situation: Parameter is NOT available BUT expected
3143
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3144
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3102
3145
  }
3103
3146
  }
3104
3147
  }
@@ -3109,600 +3152,1123 @@
3109
3152
  }
3110
3153
  finally { if (e_1) throw e_1.error; }
3111
3154
  }
3155
+ if (expectedParameterNames.size === 0) {
3156
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3157
+ Object.freeze(mappedParameters);
3158
+ return mappedParameters;
3159
+ }
3160
+ // Phase 2️⃣: Non-matching mapping
3161
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3162
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3163
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3164
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3165
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3166
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3167
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3168
+ .join('\n')), "\n\n "); }));
3169
+ }
3170
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3171
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3172
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3173
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3174
+ }
3175
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3176
+ Object.freeze(mappedParameters);
3177
+ return mappedParameters;
3112
3178
  }
3113
- /**
3114
- * TODO: [💝] Unite object for expecting amount and format
3115
- */
3116
3179
 
3117
3180
  /**
3118
- * Creates executor function from pipeline and execution tools.
3181
+ * Extracts all code blocks from markdown.
3119
3182
  *
3120
- * @returns The executor function
3121
- * @throws {PipelineLogicError} on logical error in the pipeline
3122
- * @public exported from `@promptbook/core`
3183
+ * Note: There are multiple simmilar function:
3184
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3185
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3186
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3187
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3188
+ *
3189
+ * @param markdown any valid markdown
3190
+ * @returns code blocks with language and content
3191
+ * @throws {ParseError} if block is not closed properly
3192
+ * @public exported from `@promptbook/markdown-utils`
3123
3193
  */
3124
- function createPipelineExecutor(options) {
3125
- var _this = this;
3126
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3127
- 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;
3128
- validatePipeline(pipeline);
3129
- var pipelineIdentification = (function () {
3130
- // Note: This is a 😐 implementation of [🚞]
3131
- var _ = [];
3132
- if (pipeline.sourceFile !== undefined) {
3133
- _.push("File: ".concat(pipeline.sourceFile));
3194
+ function extractAllBlocksFromMarkdown(markdown) {
3195
+ var e_1, _a;
3196
+ var codeBlocks = [];
3197
+ var lines = markdown.split('\n');
3198
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3199
+ lines.push('');
3200
+ var currentCodeBlock = null;
3201
+ try {
3202
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3203
+ var line = lines_1_1.value;
3204
+ if (line.startsWith('> ') || line === '>') {
3205
+ if (currentCodeBlock === null) {
3206
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3207
+ } /* not else */
3208
+ if (currentCodeBlock.blockNotation === '>') {
3209
+ if (currentCodeBlock.content !== '') {
3210
+ currentCodeBlock.content += '\n';
3211
+ }
3212
+ currentCodeBlock.content += line.slice(2);
3213
+ }
3214
+ }
3215
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3216
+ codeBlocks.push(currentCodeBlock);
3217
+ currentCodeBlock = null;
3218
+ }
3219
+ /* not else */
3220
+ if (line.startsWith('```')) {
3221
+ var language = line.slice(3).trim() || null;
3222
+ if (currentCodeBlock === null) {
3223
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3224
+ }
3225
+ else {
3226
+ if (language !== null) {
3227
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3228
+ }
3229
+ codeBlocks.push(currentCodeBlock);
3230
+ currentCodeBlock = null;
3231
+ }
3232
+ }
3233
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3234
+ if (currentCodeBlock.content !== '') {
3235
+ currentCodeBlock.content += '\n';
3236
+ }
3237
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3238
+ }
3134
3239
  }
3135
- if (pipeline.pipelineUrl !== undefined) {
3136
- _.push("Url: ".concat(pipeline.pipelineUrl));
3240
+ }
3241
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3242
+ finally {
3243
+ try {
3244
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3137
3245
  }
3138
- return _.join('\n');
3139
- })();
3140
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3141
- var preparedPipeline;
3142
- if (isPipelinePrepared(pipeline)) {
3143
- preparedPipeline = pipeline;
3246
+ finally { if (e_1) throw e_1.error; }
3144
3247
  }
3145
- else if (isNotPreparedWarningSupressed !== true) {
3146
- console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3248
+ if (currentCodeBlock !== null) {
3249
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3147
3250
  }
3148
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3149
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3150
- function getContextForTemplate(template) {
3151
- return __awaiter(this, void 0, void 0, function () {
3152
- return __generator(this, function (_a) {
3153
- TODO_USE(template);
3154
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3155
- });
3156
- });
3157
- }
3158
- function getKnowledgeForTemplate(template) {
3159
- return __awaiter(this, void 0, void 0, function () {
3160
- return __generator(this, function (_a) {
3161
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3162
- TODO_USE(template);
3163
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3164
- var content = _a.content;
3165
- return "- ".concat(content);
3166
- }).join('\n')];
3167
- });
3168
- });
3169
- }
3170
- function getSamplesForTemplate(template) {
3171
- return __awaiter(this, void 0, void 0, function () {
3172
- return __generator(this, function (_a) {
3173
- // TODO: [♨] Implement Better - use real index and keyword search
3174
- TODO_USE(template);
3175
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3176
- });
3177
- });
3178
- }
3179
- function getReservedParametersForTemplate(template) {
3180
- return __awaiter(this, void 0, void 0, function () {
3181
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3182
- var e_3, _a;
3183
- return __generator(this, function (_b) {
3184
- switch (_b.label) {
3185
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3186
- case 1:
3187
- context = _b.sent();
3188
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3189
- case 2:
3190
- knowledge = _b.sent();
3191
- return [4 /*yield*/, getSamplesForTemplate(template)];
3192
- case 3:
3193
- samples = _b.sent();
3194
- currentDate = new Date().toISOString();
3195
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3196
- reservedParameters = {
3197
- content: RESERVED_PARAMETER_RESTRICTED,
3198
- context: context,
3199
- knowledge: knowledge,
3200
- samples: samples,
3201
- currentDate: currentDate,
3202
- modelName: modelName,
3203
- };
3204
- _loop_3 = function (parameterName) {
3205
- if (reservedParameters[parameterName] === undefined) {
3206
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3207
- }
3208
- };
3209
- try {
3210
- // Note: Doublecheck that ALL reserved parameters are defined:
3211
- 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()) {
3212
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3213
- _loop_3(parameterName);
3214
- }
3215
- }
3216
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3217
- finally {
3218
- try {
3219
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3220
- }
3221
- finally { if (e_3) throw e_3.error; }
3222
- }
3223
- return [2 /*return*/, reservedParameters];
3224
- }
3225
- });
3226
- });
3227
- }
3228
- function executeSingleTemplate(currentTemplate) {
3229
- return __awaiter(this, void 0, void 0, function () {
3230
- 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;
3231
- var e_4, _f, _g;
3232
- return __generator(this, function (_h) {
3233
- switch (_h.label) {
3234
- case 0:
3235
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3236
- title = currentTemplate.title;
3237
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3238
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3239
- progress_1 = {
3240
- name: name,
3241
- title: title,
3242
- isStarted: false,
3243
- isDone: false,
3244
- templateType: currentTemplate.templateType,
3245
- parameterName: currentTemplate.resultingParameterName,
3246
- parameterValue: null,
3247
- // <- [3]
3248
- };
3249
- if (isReturned) {
3250
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3251
- .split('\n')
3252
- .map(function (line) { return "> ".concat(line); })
3253
- .join('\n')), "\n "); }));
3254
- }
3255
- return [4 /*yield*/, onProgress(progress_1)];
3256
- case 1:
3257
- _h.sent();
3258
- _h.label = 2;
3259
- case 2:
3260
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3261
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3262
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3263
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3264
- .map(function (name) { return "{".concat(name, "}"); })
3265
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3266
- .map(function (name) { return "{".concat(name, "}"); })
3267
- .join(', '), "\n\n "); }));
3268
- }
3269
- _b = (_a = Object).freeze;
3270
- _c = [{}];
3271
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3272
- case 3:
3273
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3274
- definedParameterNames = new Set(Object.keys(definedParameters));
3275
- parameters = {};
3276
- _loop_4 = function (parameterName) {
3277
- // Situation: Parameter is defined and used
3278
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3279
- parameters[parameterName] = definedParameters[parameterName];
3280
- }
3281
- // Situation: Parameter is defined but NOT used
3282
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3283
- // Situation: Parameter is NOT defined BUT used
3284
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3285
- // Houston, we have a problem
3286
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3287
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3288
- }
3289
- };
3290
- try {
3291
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3292
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3293
- parameterName = _e.value;
3294
- _loop_4(parameterName);
3295
- }
3296
- }
3297
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3298
- finally {
3299
- try {
3300
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3301
- }
3302
- finally { if (e_4) throw e_4.error; }
3303
- }
3304
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3305
- Object.freeze(parameters);
3306
- result = null;
3307
- resultString = null;
3308
- expectError = null;
3309
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3310
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3311
- preparedContent = (currentTemplate.preparedContent || '{content}')
3312
- .split('{content}')
3313
- .join(currentTemplate.content);
3314
- _loop_5 = function (attempt) {
3315
- 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;
3316
- var e_5, _s, e_7, _t, e_6, _u;
3317
- return __generator(this, function (_v) {
3318
- switch (_v.label) {
3319
- case 0:
3320
- isJokerAttempt = attempt < 0;
3321
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3322
- if (isJokerAttempt && !jokerParameterName) {
3323
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3324
- }
3325
- result = null;
3326
- resultString = null;
3327
- expectError = null;
3328
- if (isJokerAttempt) {
3329
- if (parameters[jokerParameterName] === undefined) {
3330
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3331
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3332
- }
3333
- else {
3334
- resultString = parameters[jokerParameterName];
3335
- }
3336
- }
3337
- _v.label = 1;
3338
- case 1:
3339
- _v.trys.push([1, 44, 45, 46]);
3340
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3341
- _j = currentTemplate.templateType;
3342
- switch (_j) {
3343
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3344
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3345
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3346
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3347
- }
3348
- return [3 /*break*/, 25];
3349
- case 2:
3350
- resultString = replaceParameters(preparedContent, parameters);
3351
- return [3 /*break*/, 26];
3352
- case 3:
3353
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3354
- prompt = {
3355
- title: currentTemplate.title,
3356
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3357
- ? preparedPipeline.pipelineUrl
3358
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3359
- parameters: parameters,
3360
- content: preparedContent,
3361
- modelRequirements: modelRequirements,
3362
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3363
- var name = _a.name;
3364
- return name === currentTemplate.personaName;
3365
- }) || {})), currentTemplate.expectations),
3366
- format: currentTemplate.format,
3367
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3368
- }; // <- TODO: Not very good type guard
3369
- _k = modelRequirements.modelVariant;
3370
- switch (_k) {
3371
- case 'CHAT': return [3 /*break*/, 4];
3372
- case 'COMPLETION': return [3 /*break*/, 6];
3373
- case 'EMBEDDING': return [3 /*break*/, 8];
3374
- }
3375
- return [3 /*break*/, 10];
3376
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3377
- case 5:
3378
- chatResult = _v.sent();
3379
- // TODO: [🍬] Destroy chatThread
3380
- result = chatResult;
3381
- resultString = chatResult.content;
3382
- return [3 /*break*/, 11];
3383
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3384
- case 7:
3385
- completionResult = _v.sent();
3386
- result = completionResult;
3387
- resultString = completionResult.content;
3388
- return [3 /*break*/, 11];
3389
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3390
- case 9:
3391
- embeddingResult = _v.sent();
3392
- result = embeddingResult;
3393
- resultString = embeddingResult.content.join(',');
3394
- return [3 /*break*/, 11];
3395
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3396
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3397
- case 11: return [3 /*break*/, 26];
3398
- case 12:
3399
- if (arrayableToArray(tools.script).length === 0) {
3400
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3401
- }
3402
- if (!currentTemplate.contentLanguage) {
3403
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3404
- }
3405
- // TODO: DRY [1]
3406
- scriptPipelineExecutionErrors = [];
3407
- _v.label = 13;
3408
- case 13:
3409
- _v.trys.push([13, 20, 21, 22]);
3410
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3411
- _v.label = 14;
3412
- case 14:
3413
- if (!!_m.done) return [3 /*break*/, 19];
3414
- scriptTools = _m.value;
3415
- _v.label = 15;
3416
- case 15:
3417
- _v.trys.push([15, 17, , 18]);
3418
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3419
- scriptLanguage: currentTemplate.contentLanguage,
3420
- script: preparedContent,
3421
- parameters: parameters,
3422
- }))];
3423
- case 16:
3424
- resultString = _v.sent();
3425
- return [3 /*break*/, 19];
3426
- case 17:
3427
- error_2 = _v.sent();
3428
- if (!(error_2 instanceof Error)) {
3429
- throw error_2;
3430
- }
3431
- if (error_2 instanceof UnexpectedError) {
3432
- throw error_2;
3433
- }
3434
- scriptPipelineExecutionErrors.push(error_2);
3435
- return [3 /*break*/, 18];
3436
- case 18:
3437
- _m = _l.next();
3438
- return [3 /*break*/, 14];
3439
- case 19: return [3 /*break*/, 22];
3440
- case 20:
3441
- e_5_1 = _v.sent();
3442
- e_5 = { error: e_5_1 };
3443
- return [3 /*break*/, 22];
3444
- case 21:
3445
- try {
3446
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3447
- }
3448
- finally { if (e_5) throw e_5.error; }
3449
- return [7 /*endfinally*/];
3450
- case 22:
3451
- if (resultString !== null) {
3452
- return [3 /*break*/, 26];
3453
- }
3454
- if (scriptPipelineExecutionErrors.length === 1) {
3455
- throw scriptPipelineExecutionErrors[0];
3456
- }
3457
- else {
3458
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3459
- .map(function (error) { return '- ' + error.message; })
3460
- .join('\n\n')), "\n "); }));
3461
- }
3462
- case 23:
3463
- if (tools.userInterface === undefined) {
3464
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3465
- }
3466
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3467
- promptTitle: currentTemplate.title,
3468
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3469
- defaultValue: replaceParameters(preparedContent, parameters),
3470
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3471
- placeholder: undefined,
3472
- priority: priority,
3473
- }))];
3474
- case 24:
3475
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3476
- resultString = _v.sent();
3477
- return [3 /*break*/, 26];
3478
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3479
- case 26:
3480
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3481
- _v.label = 27;
3482
- case 27:
3483
- _v.trys.push([27, 41, 42, 43]);
3484
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3485
- _v.label = 28;
3486
- case 28:
3487
- if (!!_p.done) return [3 /*break*/, 40];
3488
- functionName = _p.value;
3489
- // TODO: DRY [1]
3490
- scriptPipelineExecutionErrors = [];
3491
- postprocessingError = null;
3492
- _v.label = 29;
3493
- case 29:
3494
- _v.trys.push([29, 36, 37, 38]);
3495
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3496
- _v.label = 30;
3497
- case 30:
3498
- if (!!_r.done) return [3 /*break*/, 35];
3499
- scriptTools = _r.value;
3500
- _v.label = 31;
3501
- case 31:
3502
- _v.trys.push([31, 33, , 34]);
3503
- return [4 /*yield*/, scriptTools.execute({
3504
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3505
- script: "".concat(functionName, "(resultString)"),
3506
- parameters: {
3507
- resultString: resultString || '',
3508
- // Note: No ...parametersForTemplate, because working with result only
3509
- },
3510
- })];
3511
- case 32:
3512
- resultString = _v.sent();
3513
- postprocessingError = null;
3514
- return [3 /*break*/, 35];
3515
- case 33:
3516
- error_3 = _v.sent();
3517
- if (!(error_3 instanceof Error)) {
3518
- throw error_3;
3519
- }
3520
- if (error_3 instanceof UnexpectedError) {
3521
- throw error_3;
3522
- }
3523
- postprocessingError = error_3;
3524
- scriptPipelineExecutionErrors.push(error_3);
3525
- return [3 /*break*/, 34];
3526
- case 34:
3527
- _r = _q.next();
3528
- return [3 /*break*/, 30];
3529
- case 35: return [3 /*break*/, 38];
3530
- case 36:
3531
- e_6_1 = _v.sent();
3532
- e_6 = { error: e_6_1 };
3533
- return [3 /*break*/, 38];
3534
- case 37:
3535
- try {
3536
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3537
- }
3538
- finally { if (e_6) throw e_6.error; }
3539
- return [7 /*endfinally*/];
3540
- case 38:
3541
- if (postprocessingError) {
3542
- throw postprocessingError;
3543
- }
3544
- _v.label = 39;
3545
- case 39:
3546
- _p = _o.next();
3547
- return [3 /*break*/, 28];
3548
- case 40: return [3 /*break*/, 43];
3549
- case 41:
3550
- e_7_1 = _v.sent();
3551
- e_7 = { error: e_7_1 };
3552
- return [3 /*break*/, 43];
3553
- case 42:
3554
- try {
3555
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3556
- }
3557
- finally { if (e_7) throw e_7.error; }
3558
- return [7 /*endfinally*/];
3559
- case 43:
3560
- // TODO: [💝] Unite object for expecting amount and format
3561
- if (currentTemplate.format) {
3562
- if (currentTemplate.format === 'JSON') {
3563
- if (!isValidJsonString(resultString || '')) {
3564
- // TODO: [🏢] Do more universally via `FormatDefinition`
3565
- try {
3566
- resultString = extractJsonBlock(resultString || '');
3567
- }
3568
- catch (error) {
3569
- keepUnused(error);
3570
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3571
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3572
- }
3573
- }
3251
+ return codeBlocks;
3252
+ }
3253
+ /**
3254
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3255
+ */
3256
+
3257
+ /**
3258
+ * Extracts extracts exactly one valid JSON code block
3259
+ *
3260
+ * - When given string is a valid JSON as it is, it just returns it
3261
+ * - When there is no JSON code block the function throws a `ParseError`
3262
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3263
+ *
3264
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3265
+ * Note: There are multiple simmilar function:
3266
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3267
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3268
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3269
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3270
+ *
3271
+ * @public exported from `@promptbook/markdown-utils`
3272
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3273
+ */
3274
+ function extractJsonBlock(markdown) {
3275
+ if (isValidJsonString(markdown)) {
3276
+ return markdown;
3277
+ }
3278
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3279
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3280
+ var content = _a.content;
3281
+ return isValidJsonString(content);
3282
+ });
3283
+ if (jsonBlocks.length === 0) {
3284
+ throw new Error('There is no valid JSON block in the markdown');
3285
+ }
3286
+ if (jsonBlocks.length > 1) {
3287
+ throw new Error('There are multiple JSON code blocks in the markdown');
3288
+ }
3289
+ return jsonBlocks[0].content;
3290
+ }
3291
+ /**
3292
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3293
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3294
+ */
3295
+
3296
+ /**
3297
+ * Just says that the variable is not used but should be kept
3298
+ * No side effects.
3299
+ *
3300
+ * Note: It can be usefull for:
3301
+ *
3302
+ * 1) Suppressing eager optimization of unused imports
3303
+ * 2) Suppressing eslint errors of unused variables in the tests
3304
+ * 3) Keeping the type of the variable for type testing
3305
+ *
3306
+ * @param value any values
3307
+ * @returns void
3308
+ * @private within the repository
3309
+ */
3310
+ function keepUnused() {
3311
+ var valuesToKeep = [];
3312
+ for (var _i = 0; _i < arguments.length; _i++) {
3313
+ valuesToKeep[_i] = arguments[_i];
3314
+ }
3315
+ }
3316
+
3317
+ /**
3318
+ * Replaces parameters in template with values from parameters object
3319
+ *
3320
+ * @param template the template with parameters in {curly} braces
3321
+ * @param parameters the object with parameters
3322
+ * @returns the template with replaced parameters
3323
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3324
+ * @public exported from `@promptbook/utils`
3325
+ */
3326
+ function replaceParameters(template, parameters) {
3327
+ var e_1, _a;
3328
+ try {
3329
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3330
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3331
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3332
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3333
+ }
3334
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3335
+ // TODO: [🍵]
3336
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3337
+ }
3338
+ }
3339
+ }
3340
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3341
+ finally {
3342
+ try {
3343
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3344
+ }
3345
+ finally { if (e_1) throw e_1.error; }
3346
+ }
3347
+ var replacedTemplate = template;
3348
+ var match;
3349
+ var loopLimit = LOOP_LIMIT;
3350
+ var _loop_1 = function () {
3351
+ if (loopLimit-- < 0) {
3352
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3353
+ }
3354
+ var precol = match.groups.precol;
3355
+ var parameterName = match.groups.parameterName;
3356
+ if (parameterName === '') {
3357
+ return "continue";
3358
+ }
3359
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3360
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3361
+ }
3362
+ if (parameters[parameterName] === undefined) {
3363
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3364
+ }
3365
+ var parameterValue = parameters[parameterName];
3366
+ if (parameterValue === undefined) {
3367
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3368
+ }
3369
+ parameterValue = parameterValue.toString();
3370
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3371
+ parameterValue = parameterValue
3372
+ .split('\n')
3373
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3374
+ .join('\n');
3375
+ }
3376
+ replacedTemplate =
3377
+ replacedTemplate.substring(0, match.index + precol.length) +
3378
+ parameterValue +
3379
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3380
+ };
3381
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3382
+ .exec(replacedTemplate))) {
3383
+ _loop_1();
3384
+ }
3385
+ // [💫] Check if there are parameters that are not closed properly
3386
+ if (/{\w+$/.test(replacedTemplate)) {
3387
+ throw new PipelineExecutionError('Parameter is not closed');
3388
+ }
3389
+ // [💫] Check if there are parameters that are not opened properly
3390
+ if (/^\w+}/.test(replacedTemplate)) {
3391
+ throw new PipelineExecutionError('Parameter is not opened');
3392
+ }
3393
+ return replacedTemplate;
3394
+ }
3395
+
3396
+ /**
3397
+ * Counts number of characters in the text
3398
+ *
3399
+ * @public exported from `@promptbook/utils`
3400
+ */
3401
+ function countCharacters(text) {
3402
+ // Remove null characters
3403
+ text = text.replace(/\0/g, '');
3404
+ // Replace emojis (and also ZWJ sequence) with hyphens
3405
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3406
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3407
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3408
+ return text.length;
3409
+ }
3410
+
3411
+ /**
3412
+ * Counts number of lines in the text
3413
+ *
3414
+ * @public exported from `@promptbook/utils`
3415
+ */
3416
+ function countLines(text) {
3417
+ if (text === '') {
3418
+ return 0;
3419
+ }
3420
+ return text.split('\n').length;
3421
+ }
3422
+
3423
+ /**
3424
+ * Counts number of pages in the text
3425
+ *
3426
+ * @public exported from `@promptbook/utils`
3427
+ */
3428
+ function countPages(text) {
3429
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3430
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3431
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3432
+ return pageCount;
3433
+ }
3434
+
3435
+ /**
3436
+ * Counts number of paragraphs in the text
3437
+ *
3438
+ * @public exported from `@promptbook/utils`
3439
+ */
3440
+ function countParagraphs(text) {
3441
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3442
+ }
3443
+
3444
+ /**
3445
+ * Split text into sentences
3446
+ *
3447
+ * @public exported from `@promptbook/utils`
3448
+ */
3449
+ function splitIntoSentences(text) {
3450
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3451
+ }
3452
+ /**
3453
+ * Counts number of sentences in the text
3454
+ *
3455
+ * @public exported from `@promptbook/utils`
3456
+ */
3457
+ function countSentences(text) {
3458
+ return splitIntoSentences(text).length;
3459
+ }
3460
+
3461
+ /**
3462
+ * Counts number of words in the text
3463
+ *
3464
+ * @public exported from `@promptbook/utils`
3465
+ */
3466
+ function countWords(text) {
3467
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3468
+ text = removeDiacritics(text);
3469
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3470
+ }
3471
+
3472
+ /**
3473
+ * Index of all counter functions
3474
+ *
3475
+ * @public exported from `@promptbook/utils`
3476
+ */
3477
+ var CountUtils = {
3478
+ CHARACTERS: countCharacters,
3479
+ WORDS: countWords,
3480
+ SENTENCES: countSentences,
3481
+ PARAGRAPHS: countParagraphs,
3482
+ LINES: countLines,
3483
+ PAGES: countPages,
3484
+ };
3485
+ /**
3486
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3487
+ */
3488
+
3489
+ /**
3490
+ * Function checkExpectations will check if the expectations on given value are met
3491
+ *
3492
+ * Note: There are two simmilar functions:
3493
+ * - `checkExpectations` which throws an error if the expectations are not met
3494
+ * - `isPassingExpectations` which returns a boolean
3495
+ *
3496
+ * @throws {ExpectError} if the expectations are not met
3497
+ * @returns {void} Nothing
3498
+ * @private internal function of `createPipelineExecutor`
3499
+ */
3500
+ function checkExpectations(expectations, value) {
3501
+ var e_1, _a;
3502
+ try {
3503
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3504
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3505
+ var amount = CountUtils[unit.toUpperCase()](value);
3506
+ if (min && amount < min) {
3507
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3508
+ } /* not else */
3509
+ if (max && amount > max) {
3510
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3511
+ }
3512
+ }
3513
+ }
3514
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3515
+ finally {
3516
+ try {
3517
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3518
+ }
3519
+ finally { if (e_1) throw e_1.error; }
3520
+ }
3521
+ }
3522
+ /**
3523
+ * TODO: [💝] Unite object for expecting amount and format
3524
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3525
+ * Note: [💝] and [🤠] are interconnected together
3526
+ */
3527
+
3528
+ /**
3529
+ * @@@
3530
+ *
3531
+ * @private internal utility of `createPipelineExecutor`
3532
+ */
3533
+ function executeAttempts(options) {
3534
+ return __awaiter(this, void 0, void 0, function () {
3535
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3536
+ return __generator(this, function (_a) {
3537
+ switch (_a.label) {
3538
+ case 0:
3539
+ 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;
3540
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3541
+ $ongoingTemplateResult = {
3542
+ $result: null,
3543
+ $resultString: null,
3544
+ $expectError: null,
3545
+ $scriptPipelineExecutionErrors: [],
3546
+ };
3547
+ _loop_1 = function (attempt) {
3548
+ 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;
3549
+ var e_1, _r, e_3, _s, e_2, _t;
3550
+ return __generator(this, function (_u) {
3551
+ switch (_u.label) {
3552
+ case 0:
3553
+ isJokerAttempt = attempt < 0;
3554
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3555
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3556
+ if (isJokerAttempt && !jokerParameterName) {
3557
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3558
+ }
3559
+ $ongoingTemplateResult.$result = null;
3560
+ $ongoingTemplateResult.$resultString = null;
3561
+ $ongoingTemplateResult.$expectError = null;
3562
+ if (isJokerAttempt) {
3563
+ if (parameters[jokerParameterName] === undefined) {
3564
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3565
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3566
+ }
3567
+ else {
3568
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3569
+ }
3570
+ }
3571
+ _u.label = 1;
3572
+ case 1:
3573
+ _u.trys.push([1, 44, 45, 46]);
3574
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3575
+ _b = template.templateType;
3576
+ switch (_b) {
3577
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3578
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3579
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3580
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3581
+ }
3582
+ return [3 /*break*/, 25];
3583
+ case 2:
3584
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3585
+ return [3 /*break*/, 26];
3586
+ case 3:
3587
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3588
+ $ongoingTemplateResult.$prompt = {
3589
+ title: template.title,
3590
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3591
+ ? preparedPipeline.pipelineUrl
3592
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3593
+ parameters: parameters,
3594
+ content: preparedContent,
3595
+ modelRequirements: modelRequirements,
3596
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3597
+ var name = _a.name;
3598
+ return name === template.personaName;
3599
+ }) ||
3600
+ {})), template.expectations),
3601
+ format: template.format,
3602
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3603
+ }; // <- TODO: Not very good type guard
3604
+ _c = modelRequirements.modelVariant;
3605
+ switch (_c) {
3606
+ case 'CHAT': return [3 /*break*/, 4];
3607
+ case 'COMPLETION': return [3 /*break*/, 6];
3608
+ case 'EMBEDDING': return [3 /*break*/, 8];
3609
+ }
3610
+ return [3 /*break*/, 10];
3611
+ case 4:
3612
+ _d = $ongoingTemplateResult;
3613
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3614
+ case 5:
3615
+ _d.$chatResult = _u.sent();
3616
+ // TODO: [🍬] Destroy chatThread
3617
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3618
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3619
+ return [3 /*break*/, 11];
3620
+ case 6:
3621
+ _e = $ongoingTemplateResult;
3622
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3623
+ case 7:
3624
+ _e.$completionResult = _u.sent();
3625
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3626
+ $ongoingTemplateResult.$resultString =
3627
+ $ongoingTemplateResult.$completionResult.content;
3628
+ return [3 /*break*/, 11];
3629
+ case 8:
3630
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3631
+ _f = $ongoingTemplateResult;
3632
+ return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze($ongoingTemplateResult.$prompt))];
3633
+ case 9:
3634
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3635
+ _f.$embeddingResult = _u.sent();
3636
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$embeddingResult;
3637
+ $ongoingTemplateResult.$resultString =
3638
+ $ongoingTemplateResult.$embeddingResult.content.join(',');
3639
+ return [3 /*break*/, 11];
3640
+ case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3641
+ case 11: return [3 /*break*/, 26];
3642
+ case 12:
3643
+ if (arrayableToArray(tools.script).length === 0) {
3644
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3645
+ }
3646
+ if (!template.contentLanguage) {
3647
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3648
+ }
3649
+ _u.label = 13;
3650
+ case 13:
3651
+ _u.trys.push([13, 20, 21, 22]);
3652
+ _g = (e_1 = void 0, __values(arrayableToArray(tools.script))), _h = _g.next();
3653
+ _u.label = 14;
3654
+ case 14:
3655
+ if (!!_h.done) return [3 /*break*/, 19];
3656
+ scriptTools = _h.value;
3657
+ _u.label = 15;
3658
+ case 15:
3659
+ _u.trys.push([15, 17, , 18]);
3660
+ _j = $ongoingTemplateResult;
3661
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3662
+ scriptLanguage: template.contentLanguage,
3663
+ script: preparedContent,
3664
+ parameters: parameters,
3665
+ }))];
3666
+ case 16:
3667
+ _j.$resultString = _u.sent();
3668
+ return [3 /*break*/, 19];
3669
+ case 17:
3670
+ error_1 = _u.sent();
3671
+ if (!(error_1 instanceof Error)) {
3672
+ throw error_1;
3673
+ }
3674
+ if (error_1 instanceof UnexpectedError) {
3675
+ throw error_1;
3676
+ }
3677
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3678
+ return [3 /*break*/, 18];
3679
+ case 18:
3680
+ _h = _g.next();
3681
+ return [3 /*break*/, 14];
3682
+ case 19: return [3 /*break*/, 22];
3683
+ case 20:
3684
+ e_1_1 = _u.sent();
3685
+ e_1 = { error: e_1_1 };
3686
+ return [3 /*break*/, 22];
3687
+ case 21:
3688
+ try {
3689
+ if (_h && !_h.done && (_r = _g.return)) _r.call(_g);
3690
+ }
3691
+ finally { if (e_1) throw e_1.error; }
3692
+ return [7 /*endfinally*/];
3693
+ case 22:
3694
+ if ($ongoingTemplateResult.$resultString !== null) {
3695
+ return [3 /*break*/, 26];
3696
+ }
3697
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3698
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3699
+ }
3700
+ else {
3701
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3702
+ .map(function (error) { return '- ' + error.message; })
3703
+ .join('\n\n')), "\n "); }));
3704
+ }
3705
+ case 23:
3706
+ if (tools.userInterface === undefined) {
3707
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3708
+ }
3709
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3710
+ _k = $ongoingTemplateResult;
3711
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3712
+ promptTitle: template.title,
3713
+ promptMessage: replaceParameters(template.description || '', parameters),
3714
+ defaultValue: replaceParameters(preparedContent, parameters),
3715
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3716
+ placeholder: undefined,
3717
+ priority: priority,
3718
+ }))];
3719
+ case 24:
3720
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3721
+ _k.$resultString = _u.sent();
3722
+ return [3 /*break*/, 26];
3723
+ case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3724
+ case 26:
3725
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 43];
3726
+ _u.label = 27;
3727
+ case 27:
3728
+ _u.trys.push([27, 41, 42, 43]);
3729
+ _l = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _m = _l.next();
3730
+ _u.label = 28;
3731
+ case 28:
3732
+ if (!!_m.done) return [3 /*break*/, 40];
3733
+ functionName = _m.value;
3734
+ postprocessingError = null;
3735
+ _u.label = 29;
3736
+ case 29:
3737
+ _u.trys.push([29, 36, 37, 38]);
3738
+ _o = (e_2 = void 0, __values(arrayableToArray(tools.script))), _p = _o.next();
3739
+ _u.label = 30;
3740
+ case 30:
3741
+ if (!!_p.done) return [3 /*break*/, 35];
3742
+ scriptTools = _p.value;
3743
+ _u.label = 31;
3744
+ case 31:
3745
+ _u.trys.push([31, 33, , 34]);
3746
+ _q = $ongoingTemplateResult;
3747
+ return [4 /*yield*/, scriptTools.execute({
3748
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3749
+ script: "".concat(functionName, "(resultString)"),
3750
+ parameters: {
3751
+ resultString: $ongoingTemplateResult.$resultString || '',
3752
+ // Note: No ...parametersForTemplate, because working with result only
3753
+ },
3754
+ })];
3755
+ case 32:
3756
+ _q.$resultString = _u.sent();
3757
+ postprocessingError = null;
3758
+ return [3 /*break*/, 35];
3759
+ case 33:
3760
+ error_2 = _u.sent();
3761
+ if (!(error_2 instanceof Error)) {
3762
+ throw error_2;
3763
+ }
3764
+ if (error_2 instanceof UnexpectedError) {
3765
+ throw error_2;
3766
+ }
3767
+ postprocessingError = error_2;
3768
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3769
+ return [3 /*break*/, 34];
3770
+ case 34:
3771
+ _p = _o.next();
3772
+ return [3 /*break*/, 30];
3773
+ case 35: return [3 /*break*/, 38];
3774
+ case 36:
3775
+ e_2_1 = _u.sent();
3776
+ e_2 = { error: e_2_1 };
3777
+ return [3 /*break*/, 38];
3778
+ case 37:
3779
+ try {
3780
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3781
+ }
3782
+ finally { if (e_2) throw e_2.error; }
3783
+ return [7 /*endfinally*/];
3784
+ case 38:
3785
+ if (postprocessingError) {
3786
+ throw postprocessingError;
3787
+ }
3788
+ _u.label = 39;
3789
+ case 39:
3790
+ _m = _l.next();
3791
+ return [3 /*break*/, 28];
3792
+ case 40: return [3 /*break*/, 43];
3793
+ case 41:
3794
+ e_3_1 = _u.sent();
3795
+ e_3 = { error: e_3_1 };
3796
+ return [3 /*break*/, 43];
3797
+ case 42:
3798
+ try {
3799
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3800
+ }
3801
+ finally { if (e_3) throw e_3.error; }
3802
+ return [7 /*endfinally*/];
3803
+ case 43:
3804
+ // TODO: [💝] Unite object for expecting amount and format
3805
+ if (template.format) {
3806
+ if (template.format === 'JSON') {
3807
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3808
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3809
+ try {
3810
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3574
3811
  }
3575
- else {
3576
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3812
+ catch (error) {
3813
+ keepUnused(error);
3814
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3815
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3577
3816
  }
3578
3817
  }
3579
- // TODO: [💝] Unite object for expecting amount and format
3580
- if (currentTemplate.expectations) {
3581
- checkExpectations(currentTemplate.expectations, resultString || '');
3582
- }
3583
- return [2 /*return*/, "break-attempts"];
3584
- case 44:
3585
- error_4 = _v.sent();
3586
- if (!(error_4 instanceof ExpectError)) {
3587
- throw error_4;
3588
- }
3589
- expectError = error_4;
3590
- return [3 /*break*/, 46];
3591
- case 45:
3592
- if (!isJokerAttempt &&
3593
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3594
- prompt
3595
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3596
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3597
- ) {
3598
- // TODO: [🧠] Maybe put other templateTypes into report
3599
- executionReport.promptExecutions.push({
3600
- prompt: __assign({}, prompt),
3601
- result: result || undefined,
3602
- error: expectError === null ? undefined : serializeError(expectError),
3603
- });
3604
- }
3605
- return [7 /*endfinally*/];
3606
- case 46:
3607
- if (expectError !== null && attempt === maxAttempts - 1) {
3608
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3609
- .split('\n')
3610
- .map(function (line) { return "> ".concat(line); })
3611
- .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) || '')
3818
+ }
3819
+ else {
3820
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3821
+ }
3822
+ }
3823
+ // TODO: [💝] Unite object for expecting amount and format
3824
+ if (template.expectations) {
3825
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3826
+ }
3827
+ return [2 /*return*/, "break-attempts"];
3828
+ case 44:
3829
+ error_3 = _u.sent();
3830
+ if (!(error_3 instanceof ExpectError)) {
3831
+ throw error_3;
3832
+ }
3833
+ $ongoingTemplateResult.$expectError = error_3;
3834
+ return [3 /*break*/, 46];
3835
+ case 45:
3836
+ if (!isJokerAttempt &&
3837
+ template.templateType === 'PROMPT_TEMPLATE' &&
3838
+ $ongoingTemplateResult.$prompt
3839
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3840
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3841
+ ) {
3842
+ // TODO: [🧠] Maybe put other templateTypes into report
3843
+ $executionReport.promptExecutions.push({
3844
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3845
+ result: $ongoingTemplateResult.$result || undefined,
3846
+ error: $ongoingTemplateResult.$expectError === null
3847
+ ? undefined
3848
+ : serializeError($ongoingTemplateResult.$expectError),
3849
+ });
3850
+ }
3851
+ return [7 /*endfinally*/];
3852
+ case 46:
3853
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3854
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3855
+ var _a, _b, _c;
3856
+ 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) || '')
3857
+ .split('\n')
3858
+ .map(function (line) { return "> ".concat(line); })
3859
+ .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) || '')
3860
+ .split('\n')
3861
+ .map(function (line) { return "> ".concat(line); })
3862
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3863
+ ? 'null'
3864
+ : $ongoingTemplateResult.$resultString
3612
3865
  .split('\n')
3613
3866
  .map(function (line) { return "> ".concat(line); })
3614
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3615
- ? 'null'
3616
- : resultString
3617
- .split('\n')
3618
- .map(function (line) { return "> ".concat(line); })
3619
- .join('\n')), "\n ---\n "); }));
3620
- }
3621
- return [2 /*return*/];
3867
+ .join('\n')), "\n ---\n ");
3868
+ }));
3622
3869
  }
3623
- });
3624
- };
3625
- attempt = -jokerParameterNames.length;
3626
- _h.label = 4;
3627
- case 4:
3628
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3629
- return [5 /*yield**/, _loop_5(attempt)];
3630
- case 5:
3631
- state_2 = _h.sent();
3632
- switch (state_2) {
3633
- case "break-attempts": return [3 /*break*/, 7];
3634
- }
3635
- _h.label = 6;
3636
- case 6:
3637
- attempt++;
3638
- return [3 /*break*/, 4];
3639
- case 7:
3640
- if (resultString === null) {
3641
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3642
- }
3643
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3644
- progress_2 = {
3645
- name: name,
3646
- title: title,
3647
- isStarted: true,
3648
- isDone: true,
3649
- templateType: currentTemplate.templateType,
3650
- parameterName: currentTemplate.resultingParameterName,
3651
- parameterValue: resultString,
3652
- // <- [3]
3653
- };
3654
- if (isReturned) {
3655
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3656
- .split('\n')
3657
- .map(function (line) { return "> ".concat(line); })
3658
- .join('\n')), "\n\n "); }));
3870
+ return [2 /*return*/];
3659
3871
  }
3660
- return [4 /*yield*/, onProgress(progress_2)];
3661
- case 8:
3662
- _h.sent();
3663
- _h.label = 9;
3664
- case 9:
3665
- 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)));
3666
- return [2 /*return*/];
3872
+ });
3873
+ };
3874
+ attempt = -jokerParameterNames.length;
3875
+ _a.label = 1;
3876
+ case 1:
3877
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3878
+ return [5 /*yield**/, _loop_1(attempt)];
3879
+ case 2:
3880
+ state_1 = _a.sent();
3881
+ switch (state_1) {
3882
+ case "break-attempts": return [3 /*break*/, 4];
3667
3883
  }
3668
- });
3669
- });
3884
+ _a.label = 3;
3885
+ case 3:
3886
+ attempt++;
3887
+ return [3 /*break*/, 1];
3888
+ case 4:
3889
+ if ($ongoingTemplateResult.$resultString === null) {
3890
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3891
+ }
3892
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3893
+ }
3894
+ });
3895
+ });
3896
+ }
3897
+ /**
3898
+ * TODO: Break into smaller functions
3899
+ */
3900
+
3901
+ /**
3902
+ * @@@
3903
+ *
3904
+ * @private internal utility of `createPipelineExecutor`
3905
+ */
3906
+ function executeFormatCells(options) {
3907
+ return __awaiter(this, void 0, void 0, function () {
3908
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, parameterValue, formatDefinition, subvalueDefinition, resultString;
3909
+ var _this = this;
3910
+ return __generator(this, function (_a) {
3911
+ switch (_a.label) {
3912
+ case 0:
3913
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification;
3914
+ if (template.foreach === undefined) {
3915
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3916
+ }
3917
+ if (jokerParameterNames.length !== 0) {
3918
+ throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n JOKER parameters are not supported together with FOREACH command\n\n [\uD83E\uDDDE\u200D\u2640\uFE0F] This should be prevented in `validatePipeline`\n\n ".concat(block(pipelineIdentification), "\n "); }));
3919
+ }
3920
+ parameterValue = parameters[template.foreach.parameterName] || '';
3921
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3922
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3923
+ });
3924
+ if (formatDefinition === undefined) {
3925
+ throw new UnexpectedError(
3926
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3927
+ spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(template.foreach.formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
3928
+ .map(function (formatName) { return "- ".concat(formatName); })
3929
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3930
+ }
3931
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3932
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.cellName);
3933
+ });
3934
+ if (subvalueDefinition === undefined) {
3935
+ throw new UnexpectedError(
3936
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3937
+ spaceTrim__default["default"](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
3938
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3939
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3940
+ .join('\n')), "\n\n [\u26F7] This should never happen because cell name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3941
+ }
3942
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3943
+ var mappedParameters, allSubparameters, subresultString;
3944
+ return __generator(this, function (_a) {
3945
+ switch (_a.label) {
3946
+ case 0:
3947
+ try {
3948
+ mappedParameters = mapAvailableToExpectedParameters({
3949
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3950
+ availableParameters: subparameters,
3951
+ });
3952
+ }
3953
+ catch (error) {
3954
+ if (!(error instanceof PipelineExecutionError)) {
3955
+ throw error;
3956
+ }
3957
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n ".concat(error.message, "\n\n This is error in FOREACH command\n You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command\n\n ").concat(block(pipelineIdentification), "\n "); }));
3958
+ }
3959
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3960
+ // 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
3961
+ Object.freeze(allSubparameters);
3962
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3963
+ case 1:
3964
+ subresultString = _a.sent();
3965
+ return [2 /*return*/, subresultString];
3966
+ }
3967
+ });
3968
+ }); })];
3969
+ case 1:
3970
+ resultString = _a.sent();
3971
+ return [2 /*return*/, resultString];
3972
+ }
3973
+ });
3974
+ });
3975
+ }
3976
+ /**
3977
+ * TODO: !!!!!! Make pipelineIdentification more precise
3978
+ * TODO: !!!!!! How FOREACH execution looks in the report
3979
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
3980
+ * TODO: []
3981
+ */
3982
+
3983
+ /**
3984
+ * @@@
3985
+ *
3986
+ * @private internal utility of `createPipelineExecutor`
3987
+ */
3988
+ function getContextForTemplate(template) {
3989
+ return __awaiter(this, void 0, void 0, function () {
3990
+ return __generator(this, function (_a) {
3991
+ TODO_USE(template);
3992
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3993
+ });
3994
+ });
3995
+ }
3996
+
3997
+ /**
3998
+ * @@@
3999
+ *
4000
+ * @private internal utility of `createPipelineExecutor`
4001
+ */
4002
+ function getKnowledgeForTemplate(options) {
4003
+ return __awaiter(this, void 0, void 0, function () {
4004
+ var preparedPipeline, template;
4005
+ return __generator(this, function (_a) {
4006
+ preparedPipeline = options.preparedPipeline, template = options.template;
4007
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4008
+ TODO_USE(template);
4009
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4010
+ var content = _a.content;
4011
+ return "- ".concat(content);
4012
+ }).join('\n')];
4013
+ });
4014
+ });
4015
+ }
4016
+
4017
+ /**
4018
+ * @@@
4019
+ *
4020
+ * @private internal utility of `createPipelineExecutor`
4021
+ */
4022
+ function getSamplesForTemplate(template) {
4023
+ return __awaiter(this, void 0, void 0, function () {
4024
+ return __generator(this, function (_a) {
4025
+ // TODO: [♨] Implement Better - use real index and keyword search
4026
+ TODO_USE(template);
4027
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4028
+ });
4029
+ });
4030
+ }
4031
+
4032
+ /**
4033
+ * @@@
4034
+ *
4035
+ * @private internal utility of `createPipelineExecutor`
4036
+ */
4037
+ function getReservedParametersForTemplate(options) {
4038
+ return __awaiter(this, void 0, void 0, function () {
4039
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4040
+ var e_1, _a;
4041
+ return __generator(this, function (_b) {
4042
+ switch (_b.label) {
4043
+ case 0:
4044
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4045
+ return [4 /*yield*/, getContextForTemplate(template)];
4046
+ case 1:
4047
+ context = _b.sent();
4048
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4049
+ case 2:
4050
+ knowledge = _b.sent();
4051
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4052
+ case 3:
4053
+ samples = _b.sent();
4054
+ currentDate = new Date().toISOString();
4055
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4056
+ reservedParameters = {
4057
+ content: RESERVED_PARAMETER_RESTRICTED,
4058
+ context: context,
4059
+ knowledge: knowledge,
4060
+ samples: samples,
4061
+ currentDate: currentDate,
4062
+ modelName: modelName,
4063
+ };
4064
+ _loop_1 = function (parameterName) {
4065
+ if (reservedParameters[parameterName] === undefined) {
4066
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4067
+ }
4068
+ };
4069
+ try {
4070
+ // Note: Doublecheck that ALL reserved parameters are defined:
4071
+ 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()) {
4072
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4073
+ _loop_1(parameterName);
4074
+ }
4075
+ }
4076
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4077
+ finally {
4078
+ try {
4079
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4080
+ }
4081
+ finally { if (e_1) throw e_1.error; }
4082
+ }
4083
+ return [2 /*return*/, reservedParameters];
4084
+ }
4085
+ });
4086
+ });
4087
+ }
4088
+
4089
+ /**
4090
+ * @@@
4091
+ *
4092
+ * @private internal utility of `createPipelineExecutor`
4093
+ */
4094
+ function executeTemplate(options) {
4095
+ return __awaiter(this, void 0, void 0, function () {
4096
+ 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;
4097
+ var e_1, _f, _g;
4098
+ return __generator(this, function (_h) {
4099
+ switch (_h.label) {
4100
+ case 0:
4101
+ 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;
4102
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4103
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4104
+ title = currentTemplate.title;
4105
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4106
+ return [4 /*yield*/, onProgress({
4107
+ name: name,
4108
+ title: title,
4109
+ isStarted: false,
4110
+ isDone: false,
4111
+ templateType: currentTemplate.templateType,
4112
+ parameterName: currentTemplate.resultingParameterName,
4113
+ parameterValue: null,
4114
+ // <- [🍸]
4115
+ })];
4116
+ case 1:
4117
+ _h.sent();
4118
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4119
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4120
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4121
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4122
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
4123
+ .map(function (name) { return "{".concat(name, "}"); })
4124
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4125
+ .map(function (name) { return "{".concat(name, "}"); })
4126
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4127
+ }
4128
+ _b = (_a = Object).freeze;
4129
+ _c = [{}];
4130
+ return [4 /*yield*/, getReservedParametersForTemplate({
4131
+ preparedPipeline: preparedPipeline,
4132
+ template: currentTemplate,
4133
+ pipelineIdentification: pipelineIdentification,
4134
+ })];
4135
+ case 2:
4136
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4137
+ definedParameterNames = new Set(Object.keys(definedParameters));
4138
+ parameters = {};
4139
+ _loop_1 = function (parameterName) {
4140
+ // Situation: Parameter is defined and used
4141
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4142
+ parameters[parameterName] = definedParameters[parameterName];
4143
+ }
4144
+ // Situation: Parameter is defined but NOT used
4145
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4146
+ // Situation: Parameter is NOT defined BUT used
4147
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4148
+ // Houston, we have a problem
4149
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4150
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4151
+ }
4152
+ };
4153
+ try {
4154
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4155
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4156
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4157
+ parameterName = _e.value;
4158
+ _loop_1(parameterName);
4159
+ }
4160
+ }
4161
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4162
+ finally {
4163
+ try {
4164
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4165
+ }
4166
+ finally { if (e_1) throw e_1.error; }
4167
+ }
4168
+ // 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
4169
+ Object.freeze(parameters);
4170
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4171
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4172
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4173
+ .split('{content}')
4174
+ .join(currentTemplate.content);
4175
+ return [4 /*yield*/, executeFormatCells({
4176
+ jokerParameterNames: jokerParameterNames,
4177
+ priority: priority,
4178
+ maxAttempts: maxAttempts,
4179
+ preparedContent: preparedContent,
4180
+ parameters: parameters,
4181
+ template: currentTemplate,
4182
+ preparedPipeline: preparedPipeline,
4183
+ tools: tools,
4184
+ llmTools: llmTools,
4185
+ settings: settings,
4186
+ $executionReport: $executionReport,
4187
+ pipelineIdentification: pipelineIdentification,
4188
+ })];
4189
+ case 3:
4190
+ resultString = _h.sent();
4191
+ return [4 /*yield*/, onProgress({
4192
+ name: name,
4193
+ title: title,
4194
+ isStarted: true,
4195
+ isDone: true,
4196
+ templateType: currentTemplate.templateType,
4197
+ parameterName: currentTemplate.resultingParameterName,
4198
+ parameterValue: resultString,
4199
+ // <- [🍸]
4200
+ })];
4201
+ case 4:
4202
+ _h.sent();
4203
+ return [2 /*return*/, Object.freeze((_g = {},
4204
+ _g[currentTemplate.resultingParameterName] =
4205
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4206
+ resultString,
4207
+ _g))];
4208
+ }
4209
+ });
4210
+ });
4211
+ }
4212
+ /**
4213
+ * TODO: [🤹‍♂️]
4214
+ */
4215
+
4216
+ /**
4217
+ * @@@
4218
+ *
4219
+ * @private internal utility of `createPipelineExecutor`
4220
+ */
4221
+ function filterJustOutputParameters(options) {
4222
+ var e_1, _a;
4223
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4224
+ var outputParameters = {};
4225
+ var _loop_1 = function (parameter) {
4226
+ if (parametersToPass[parameter.name] === undefined) {
4227
+ // [4]
4228
+ $warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
4229
+ return "continue";
4230
+ }
4231
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4232
+ };
4233
+ try {
4234
+ // Note: Filter ONLY output parameters
4235
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4236
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4237
+ var isOutput = _a.isOutput;
4238
+ return isOutput;
4239
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4240
+ var parameter = _c.value;
4241
+ _loop_1(parameter);
3670
4242
  }
3671
- function filterJustOutputParameters() {
3672
- var e_8, _a;
3673
- var outputParameters = {};
3674
- var _loop_6 = function (parameter) {
3675
- if (parametersToPass[parameter.name] === undefined) {
3676
- // [4]
3677
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3678
- return "continue";
3679
- }
3680
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3681
- };
3682
- try {
3683
- // Note: Filter ONLY output parameters
3684
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3685
- var isOutput = _a.isOutput;
3686
- return isOutput;
3687
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3688
- var parameter = _c.value;
3689
- _loop_6(parameter);
3690
- }
3691
- }
3692
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3693
- finally {
3694
- try {
3695
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3696
- }
3697
- finally { if (e_8) throw e_8.error; }
3698
- }
3699
- return outputParameters;
4243
+ }
4244
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4245
+ finally {
4246
+ try {
4247
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3700
4248
  }
3701
- 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;
4249
+ finally { if (e_1) throw e_1.error; }
4250
+ }
4251
+ return outputParameters;
4252
+ }
4253
+
4254
+ /**
4255
+ * @@@
4256
+ *
4257
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4258
+ *
4259
+ * @private internal utility of `createPipelineExecutor`
4260
+ */
4261
+ function executePipeline(options) {
4262
+ return __awaiter(this, void 0, void 0, function () {
4263
+ 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;
3702
4264
  var e_1, _e, e_2, _f;
3703
4265
  return __generator(this, function (_g) {
3704
4266
  switch (_g.label) {
3705
4267
  case 0:
4268
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4269
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4270
+ preparedPipeline = options.preparedPipeline;
4271
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3706
4272
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3707
4273
  return [4 /*yield*/, preparePipeline(pipeline, {
3708
4274
  llmTools: llmTools,
@@ -3711,6 +4277,7 @@
3711
4277
  })];
3712
4278
  case 1:
3713
4279
  preparedPipeline = _g.sent();
4280
+ setPreparedPipeline(preparedPipeline);
3714
4281
  _g.label = 2;
3715
4282
  case 2:
3716
4283
  errors = [];
@@ -3780,7 +4347,7 @@
3780
4347
  return name === parameterName;
3781
4348
  });
3782
4349
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3783
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4350
+ warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3784
4351
  return [3 /*break*/, 4];
3785
4352
  case 1:
3786
4353
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3792,10 +4359,10 @@
3792
4359
  // Note: Wait a short time to prevent race conditions
3793
4360
  _h.sent();
3794
4361
  _h.label = 3;
3795
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4362
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3796
4363
  isSuccessful: false,
3797
4364
  errors: __spreadArray([
3798
- new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4365
+ new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3799
4366
  ], __read(errors), false).map(serializeError),
3800
4367
  warnings: warnings.map(serializeError),
3801
4368
  executionReport: executionReport,
@@ -3859,7 +4426,7 @@
3859
4426
  case 0:
3860
4427
  if (loopLimit-- < 0) {
3861
4428
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3862
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4429
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3863
4430
  }
3864
4431
  currentTemplate = unresovedTemplates_1.find(function (template) {
3865
4432
  return template.dependentParameterNames.every(function (name) {
@@ -3869,29 +4436,52 @@
3869
4436
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3870
4437
  throw new UnexpectedError(
3871
4438
  // TODO: [🐎] DRY
3872
- spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4439
+ spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3873
4440
  .map(function (_a) {
3874
4441
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3875
4442
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3876
4443
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3877
4444
  .join(' and '));
3878
4445
  })
3879
- .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 "); }));
4446
+ .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 "); }));
3880
4447
  case 1:
3881
4448
  if (!!currentTemplate) return [3 /*break*/, 3];
3882
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4449
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3883
4450
  case 2:
3884
- /* [5] */ _j.sent();
4451
+ /* [🤹‍♂️] */ _j.sent();
3885
4452
  return [3 /*break*/, 4];
3886
4453
  case 3:
3887
4454
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3888
- work_1 = executeSingleTemplate(currentTemplate)
3889
- .then(function () {
4455
+ work_1 = executeTemplate({
4456
+ currentTemplate: currentTemplate,
4457
+ preparedPipeline: preparedPipeline,
4458
+ parametersToPass: parametersToPass,
4459
+ tools: tools,
4460
+ llmTools: llmTools,
4461
+ onProgress: function (progress) {
4462
+ if (isReturned) {
4463
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4464
+ .split('\n')
4465
+ .map(function (line) { return "> ".concat(line); })
4466
+ .join('\n')), "\n "); }));
4467
+ }
4468
+ if (onProgress) {
4469
+ onProgress(progress);
4470
+ }
4471
+ },
4472
+ settings: settings,
4473
+ $executionReport: executionReport,
4474
+ pipelineIdentification: pipelineIdentification,
4475
+ })
4476
+ .then(function (newParametersToPass) {
4477
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3890
4478
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3891
4479
  })
3892
4480
  .then(function () {
3893
4481
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3894
4482
  });
4483
+ // <- Note: Errors are catched here [3]
4484
+ // 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
3895
4485
  resolving_1.push(work_1);
3896
4486
  _j.label = 4;
3897
4487
  case 4: return [2 /*return*/];
@@ -3918,7 +4508,12 @@
3918
4508
  var result = _a.result;
3919
4509
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3920
4510
  })), false));
3921
- outputParameters_1 = filterJustOutputParameters();
4511
+ outputParameters_1 = filterJustOutputParameters({
4512
+ preparedPipeline: preparedPipeline,
4513
+ parametersToPass: parametersToPass,
4514
+ $warnings: warnings,
4515
+ pipelineIdentification: pipelineIdentification,
4516
+ });
3922
4517
  isReturned = true;
3923
4518
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3924
4519
  // Note: Wait a short time to prevent race conditions
@@ -3941,7 +4536,12 @@
3941
4536
  var result = _a.result;
3942
4537
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3943
4538
  })), false));
3944
- outputParameters = filterJustOutputParameters();
4539
+ outputParameters = filterJustOutputParameters({
4540
+ preparedPipeline: preparedPipeline,
4541
+ parametersToPass: parametersToPass,
4542
+ $warnings: warnings,
4543
+ pipelineIdentification: pipelineIdentification,
4544
+ });
3945
4545
  isReturned = true;
3946
4546
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3947
4547
  // Note: Wait a short time to prevent race conditions
@@ -3961,22 +4561,62 @@
3961
4561
  })];
3962
4562
  }
3963
4563
  });
3964
- }); };
3965
- return pipelineExecutor;
4564
+ });
3966
4565
  }
4566
+
3967
4567
  /**
3968
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3969
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3970
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3971
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3972
- * TODO: [♈] Probbably move expectations from templates to parameters
3973
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3974
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3975
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3976
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3977
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3978
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4568
+ * Creates executor function from pipeline and execution tools.
4569
+ *
4570
+ * @returns The executor function
4571
+ * @throws {PipelineLogicError} on logical error in the pipeline
4572
+ * @public exported from `@promptbook/core`
3979
4573
  */
4574
+ function createPipelineExecutor(options) {
4575
+ var _this = this;
4576
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4577
+ 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;
4578
+ validatePipeline(pipeline);
4579
+ var pipelineIdentification = (function () {
4580
+ // Note: This is a 😐 implementation of [🚞]
4581
+ var _ = [];
4582
+ if (pipeline.sourceFile !== undefined) {
4583
+ _.push("File: ".concat(pipeline.sourceFile));
4584
+ }
4585
+ if (pipeline.pipelineUrl !== undefined) {
4586
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4587
+ }
4588
+ return _.join('\n');
4589
+ })();
4590
+ var preparedPipeline;
4591
+ if (isPipelinePrepared(pipeline)) {
4592
+ preparedPipeline = pipeline;
4593
+ }
4594
+ else if (isNotPreparedWarningSupressed !== true) {
4595
+ console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4596
+ }
4597
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4598
+ return __generator(this, function (_a) {
4599
+ return [2 /*return*/, executePipeline({
4600
+ pipeline: pipeline,
4601
+ preparedPipeline: preparedPipeline,
4602
+ setPreparedPipeline: function (newPreparedPipeline) {
4603
+ preparedPipeline = newPreparedPipeline;
4604
+ },
4605
+ inputParameters: inputParameters,
4606
+ tools: tools,
4607
+ onProgress: onProgress,
4608
+ pipelineIdentification: pipelineIdentification,
4609
+ settings: {
4610
+ maxExecutionAttempts: maxExecutionAttempts,
4611
+ maxParallelCount: maxParallelCount,
4612
+ isVerbose: isVerbose,
4613
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4614
+ },
4615
+ })];
4616
+ });
4617
+ }); };
4618
+ return pipelineExecutor;
4619
+ }
3980
4620
 
3981
4621
  /**
3982
4622
  * @@@
@@ -5130,6 +5770,145 @@
5130
5770
  * TODO: [🌺] Use some intermediate util splitWords
5131
5771
  */
5132
5772
 
5773
+ /**
5774
+ * @@@
5775
+ *
5776
+ * @param text @@@
5777
+ * @param _isFirstLetterCapital @@@
5778
+ * @returns @@@
5779
+ * @example 'helloWorld'
5780
+ * @example 'iLovePromptbook'
5781
+ * @public exported from `@promptbook/utils`
5782
+ */
5783
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5784
+ var e_1, _a;
5785
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5786
+ var charType;
5787
+ var lastCharType = null;
5788
+ var normalizedName = '';
5789
+ try {
5790
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5791
+ var char = text_1_1.value;
5792
+ var normalizedChar = void 0;
5793
+ if (/^[a-z]$/.test(char)) {
5794
+ charType = 'LOWERCASE';
5795
+ normalizedChar = char;
5796
+ }
5797
+ else if (/^[A-Z]$/.test(char)) {
5798
+ charType = 'UPPERCASE';
5799
+ normalizedChar = char.toLowerCase();
5800
+ }
5801
+ else if (/^[0-9]$/.test(char)) {
5802
+ charType = 'NUMBER';
5803
+ normalizedChar = char;
5804
+ }
5805
+ else {
5806
+ charType = 'OTHER';
5807
+ normalizedChar = '';
5808
+ }
5809
+ if (!lastCharType) {
5810
+ if (_isFirstLetterCapital) {
5811
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5812
+ }
5813
+ }
5814
+ else if (charType !== lastCharType &&
5815
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5816
+ !(lastCharType === 'NUMBER') &&
5817
+ !(charType === 'NUMBER')) {
5818
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5819
+ }
5820
+ normalizedName += normalizedChar;
5821
+ lastCharType = charType;
5822
+ }
5823
+ }
5824
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5825
+ finally {
5826
+ try {
5827
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5828
+ }
5829
+ finally { if (e_1) throw e_1.error; }
5830
+ }
5831
+ return normalizedName;
5832
+ }
5833
+ /**
5834
+ * TODO: [🌺] Use some intermediate util splitWords
5835
+ */
5836
+
5837
+ /**
5838
+ * Function `validateParameterName` will @@@
5839
+ *
5840
+ * @param parameterName @@@
5841
+ * @returns @@@
5842
+ * @throws {ParseError} @@@
5843
+ * @private within the repository
5844
+ */
5845
+ function validateParameterName(parameterName) {
5846
+ var e_1, _a;
5847
+ var rawParameterName = parameterName;
5848
+ try {
5849
+ for (var _b = __values([
5850
+ ['`', '`'],
5851
+ ['{', '}'],
5852
+ ['[', ']'],
5853
+ ['(', ')'],
5854
+ ['<', '>'],
5855
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5856
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5857
+ if (parameterName.substring(0, 1) === start &&
5858
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5859
+ // <- TODO: More universal that 1 character
5860
+ ) {
5861
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5862
+ // <- TODO: More universal that 1 character
5863
+ }
5864
+ }
5865
+ }
5866
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5867
+ finally {
5868
+ try {
5869
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5870
+ }
5871
+ finally { if (e_1) throw e_1.error; }
5872
+ }
5873
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5874
+ try {
5875
+ /*
5876
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5877
+ if (parameterName.includes(' ')) {
5878
+ throw new ParseError(`Parameter name cannot contain spaces`);
5879
+ }
5880
+ */
5881
+ if (parameterName.includes('.')) {
5882
+ throw new ParseError("Parameter name cannot contain dots");
5883
+ }
5884
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5885
+ throw new ParseError("Parameter name cannot contain slashes");
5886
+ }
5887
+ if (parameterName.includes('(') ||
5888
+ parameterName.includes(')') ||
5889
+ parameterName.includes('{') ||
5890
+ parameterName.includes('}') ||
5891
+ parameterName.includes('[') ||
5892
+ parameterName.includes(']')) {
5893
+ throw new ParseError("Parameter name cannot contain braces");
5894
+ }
5895
+ parameterName = normalizeTo_camelCase(parameterName);
5896
+ if (parameterName === '') {
5897
+ throw new ParseError("Parameter name cannot be empty");
5898
+ }
5899
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5900
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5901
+ }
5902
+ }
5903
+ catch (error) {
5904
+ if (!(error instanceof ParseError)) {
5905
+ throw error;
5906
+ }
5907
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
5908
+ }
5909
+ return parameterName;
5910
+ }
5911
+
5133
5912
  /**
5134
5913
  * Parses the foreach command
5135
5914
  *
@@ -5164,62 +5943,66 @@
5164
5943
  * Example usages of the FOREACH command
5165
5944
  */
5166
5945
  examples: [
5167
- 'FOREACH List Line -> `{customer}`',
5168
- 'FOR List Line -> `{customer}`',
5169
- 'EACH List Line -> `{customer}`',
5946
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5947
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5948
+ 'EACH Csv Cell `{customers}` -> `{cell}`',
5170
5949
  // <- TODO: [🍭] !!!!!! More
5171
5950
  ],
5172
5951
  /**
5173
5952
  * Parses the FOREACH command
5174
5953
  */
5175
5954
  parse: function (input) {
5176
- var args = input.args, rawArgs = input.rawArgs;
5955
+ var args = input.args;
5177
5956
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5178
5957
  var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5179
- var assignSign = args[2];
5180
- var parameter = args[3];
5181
- if (![
5182
- 'LIST',
5183
- 'CSV',
5184
- // <- TODO: [🏢] Unhardcode formats
5185
- ].includes(formatName)) {
5958
+ var parameterNameWrapped = args[2];
5959
+ var assignSign = args[3];
5960
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5961
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5962
+ });
5963
+ if (formatDefinition === undefined) {
5186
5964
  console.info({ args: args, formatName: formatName });
5187
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5965
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
5966
+ .map(function (formatName) { return "- ".concat(formatName); })
5967
+ .join('\n')), "\n "); }));
5188
5968
  // <- TODO: [🏢] List all supported format names
5189
5969
  }
5190
- if (![
5191
- 'LINE',
5192
- 'ROW',
5193
- 'COLUMN',
5194
- 'CELL',
5195
- // <- TODO: [🏢] Unhardcode format cekks
5196
- ].includes(cellName)) {
5970
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5971
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(cellName);
5972
+ });
5973
+ if (subvalueDefinition === undefined) {
5197
5974
  console.info({ args: args, cellName: cellName });
5198
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5975
+ throw new ParseError(spaceTrim__default["default"](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
5976
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5977
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5978
+ .join('\n')), "\n "); }));
5199
5979
  // <- TODO: [🏢] List all supported cell names for the format
5200
5980
  }
5201
5981
  if (assignSign !== '->') {
5202
5982
  console.info({ args: args, assignSign: assignSign });
5203
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5204
- }
5205
- var parameterNames = extractParameterNames(parameter || rawArgs);
5206
- if (parameterNames.size !== 1) {
5207
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5208
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5209
- }
5210
- var parameterName = parameterNames.values().next().value;
5211
- if (typeof parameterName !== 'string'
5212
- // <- TODO: !!!!!! Replace with propper parameter name validation
5213
- ) {
5214
- console.info({ args: args, parameterName: parameterName });
5215
- throw new Error("Invalid parameter name");
5216
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
5983
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5984
+ }
5985
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5986
+ if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5987
+ (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5988
+ 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));
5989
+ throw new ParseError("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5990
+ }
5991
+ var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5992
+ var subparameterNames = args
5993
+ .slice(4)
5994
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5995
+ .filter(function (parameterName) { return parameterName !== ''; })
5996
+ .map(validateParameterName);
5997
+ if (subparameterNames.length === 0) {
5998
+ throw new ParseError("FOREACH command must have at least one subparameter");
5217
5999
  }
5218
6000
  return {
5219
6001
  type: 'FOREACH',
5220
6002
  formatName: formatName,
5221
6003
  cellName: cellName,
5222
6004
  parameterName: parameterName,
6005
+ subparameterNames: subparameterNames,
5223
6006
  };
5224
6007
  },
5225
6008
  /**
@@ -5228,8 +6011,12 @@
5228
6011
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5229
6012
  */
5230
6013
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5231
- keepUnused(command, $templateJson, $pipelineJson);
5232
- // <- TODO: [🍭] !!!!!! Implement
6014
+ var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6015
+ // TODO: !!!!!! Detect double use
6016
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
6017
+ $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterNames: subparameterNames };
6018
+ keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6019
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5233
6020
  },
5234
6021
  /**
5235
6022
  * Converts the FOREACH command back to string
@@ -5238,8 +6025,7 @@
5238
6025
  */
5239
6026
  stringify: function (command) {
5240
6027
  keepUnused(command);
5241
- return "";
5242
- // <- TODO: [🍭] !!!!!! Implement
6028
+ return "---"; // <- TODO: [🛋] Implement
5243
6029
  },
5244
6030
  /**
5245
6031
  * Reads the FOREACH command from the `TemplateJson`
@@ -5248,12 +6034,12 @@
5248
6034
  */
5249
6035
  takeFromTemplateJson: function ($templateJson) {
5250
6036
  keepUnused($templateJson);
5251
- return [];
5252
- // <- TODO: [🍭] !!!!!! Implement
6037
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5253
6038
  },
5254
6039
  };
5255
6040
  /**
5256
- * TODO: !!!!!! Comment console logs
6041
+ * TODO: !!!!!! Remove console logs
6042
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
5257
6043
  * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5258
6044
  */
5259
6045
 
@@ -5364,6 +6150,7 @@
5364
6150
  */
5365
6151
  parse: function (input) {
5366
6152
  var args = input.args;
6153
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5367
6154
  var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5368
6155
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5369
6156
  throw new ParseError("Invalid joker");
@@ -5493,6 +6280,7 @@
5493
6280
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5494
6281
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5495
6282
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6283
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5496
6284
  }
5497
6285
  else {
5498
6286
  throw new ParseError(spaceTrim__default["default"]("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -6569,7 +7357,7 @@
6569
7357
  function extractOneBlockFromMarkdown(markdown) {
6570
7358
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6571
7359
  if (codeBlocks.length !== 1) {
6572
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7360
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6573
7361
  }
6574
7362
  return codeBlocks[0];
6575
7363
  }
@@ -7609,21 +8397,41 @@
7609
8397
  * @public exported from `@promptbook/core`
7610
8398
  */
7611
8399
  function usageToHuman(usage) {
7612
- var report = 'Usage:';
8400
+ var reportItems = [];
7613
8401
  var uncertainNumberToHuman = function (_a) {
7614
8402
  var value = _a.value, isUncertain = _a.isUncertain;
7615
8403
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7616
8404
  };
7617
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7618
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7619
- return spaceTrim__default["default"](report);
8405
+ if (usage.price.value > 0.01
8406
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8407
+ ) {
8408
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8409
+ }
8410
+ else {
8411
+ reportItems.push("Negligible cost");
8412
+ }
8413
+ var worktime = usageToWorktime(usage);
8414
+ if (worktime.value >
8415
+ 1 / 60
8416
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8417
+ ) {
8418
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8419
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8420
+ }
8421
+ if (usage.output.charactersCount.value > 0) {
8422
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8423
+ }
8424
+ if (reportItems.length === 0) {
8425
+ // Note: For negligible usage, we report at least something
8426
+ reportItems.push('Negligible');
8427
+ }
8428
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7620
8429
  }
7621
8430
  /**
7622
- * TODO: Use "$1" not "1 USD"
7623
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7624
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8431
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8432
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8433
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7625
8434
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7626
- * TODO: When negligible usage, report "Negligible" or just don't report it
7627
8435
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7628
8436
  * TODO: [🏛] Maybe make some markdown builder
7629
8437
  */
@@ -8427,70 +9235,6 @@
8427
9235
  * TODO: [🏛] This can be part of markdown builder
8428
9236
  */
8429
9237
 
8430
- /**
8431
- * @@@
8432
- *
8433
- * @param text @@@
8434
- * @param _isFirstLetterCapital @@@
8435
- * @returns @@@
8436
- * @example 'helloWorld'
8437
- * @example 'iLovePromptbook'
8438
- * @public exported from `@promptbook/utils`
8439
- */
8440
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
8441
- var e_1, _a;
8442
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
8443
- var charType;
8444
- var lastCharType = null;
8445
- var normalizedName = '';
8446
- try {
8447
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
8448
- var char = text_1_1.value;
8449
- var normalizedChar = void 0;
8450
- if (/^[a-z]$/.test(char)) {
8451
- charType = 'LOWERCASE';
8452
- normalizedChar = char;
8453
- }
8454
- else if (/^[A-Z]$/.test(char)) {
8455
- charType = 'UPPERCASE';
8456
- normalizedChar = char.toLowerCase();
8457
- }
8458
- else if (/^[0-9]$/.test(char)) {
8459
- charType = 'NUMBER';
8460
- normalizedChar = char;
8461
- }
8462
- else {
8463
- charType = 'OTHER';
8464
- normalizedChar = '';
8465
- }
8466
- if (!lastCharType) {
8467
- if (_isFirstLetterCapital) {
8468
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
8469
- }
8470
- }
8471
- else if (charType !== lastCharType &&
8472
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
8473
- !(lastCharType === 'NUMBER') &&
8474
- !(charType === 'NUMBER')) {
8475
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
8476
- }
8477
- normalizedName += normalizedChar;
8478
- lastCharType = charType;
8479
- }
8480
- }
8481
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
8482
- finally {
8483
- try {
8484
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
8485
- }
8486
- finally { if (e_1) throw e_1.error; }
8487
- }
8488
- return normalizedName;
8489
- }
8490
- /**
8491
- * TODO: [🌺] Use some intermediate util splitWords
8492
- */
8493
-
8494
9238
  /**
8495
9239
  * Creates a Mermaid graph based on the promptbook
8496
9240
  *
@@ -8547,6 +9291,9 @@
8547
9291
  return promptbookMermaid;
8548
9292
  }
8549
9293
  /**
9294
+ * TODO: !!!!!! FOREACH in mermaid graph
9295
+ * TODO: !!!!!! Knowledge in mermaid graph
9296
+ * TODO: !!!!!! Personas in mermaid graph
8550
9297
  * TODO: Maybe use some Mermaid package instead of string templating
8551
9298
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8552
9299
  */
@@ -9265,7 +10012,7 @@
9265
10012
  resultContent = contentBlock.text;
9266
10013
  // eslint-disable-next-line prefer-const
9267
10014
  complete = getCurrentIsoDate();
9268
- usage = computeAnthropicClaudeUsage(content, '', rawResponse);
10015
+ usage = computeAnthropicClaudeUsage(rawPromptContent || '', resultContent || '', rawResponse);
9269
10016
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('AnthropicClaudeExecutionTools ChatPromptResult', {
9270
10017
  content: resultContent,
9271
10018
  modelName: rawResponse.model,
@@ -10379,7 +11126,7 @@
10379
11126
  resultContent = rawResponse.choices[0].message.content;
10380
11127
  // eslint-disable-next-line prefer-const
10381
11128
  complete = getCurrentIsoDate();
10382
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11129
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10383
11130
  if (resultContent === null) {
10384
11131
  throw new PipelineExecutionError('No response message from OpenAI');
10385
11132
  }
@@ -10451,7 +11198,7 @@
10451
11198
  resultContent = rawResponse.choices[0].text;
10452
11199
  // eslint-disable-next-line prefer-const
10453
11200
  complete = getCurrentIsoDate();
10454
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11201
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10455
11202
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools CompletionPromptResult', {
10456
11203
  content: resultContent,
10457
11204
  modelName: rawResponse.model || modelName,
@@ -10511,7 +11258,9 @@
10511
11258
  resultContent = rawResponse.data[0].embedding;
10512
11259
  // eslint-disable-next-line prefer-const
10513
11260
  complete = getCurrentIsoDate();
10514
- usage = computeOpenAiUsage(content, '', rawResponse);
11261
+ usage = computeOpenAiUsage(content || '', '',
11262
+ // <- Note: Embedding does not have result content
11263
+ rawResponse);
10515
11264
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools EmbeddingPromptResult', {
10516
11265
  content: resultContent,
10517
11266
  modelName: rawResponse.model || modelName,