@promptbook/cli 0.69.0-1 → 0.69.0-10

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 -57
  2. package/esm/index.es.js +1895 -1162
  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/esm/typings/src/utils/validators/parameterName/validateParameterName.test.d.ts +1 -0
  48. package/package.json +2 -1
  49. package/umd/index.umd.js +1898 -1166
  50. package/umd/index.umd.js.map +1 -1
  51. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  52. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  53. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  54. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  55. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.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-9';
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-9",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-9",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-9",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-9",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,348 @@
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
+ return __generator(this, function (_a) {
2834
+ switch (_a.label) {
2835
+ case 0:
2836
+ csv = papaparse.parse(value, {
2837
+ header: true,
2838
+ delimiter: ',',
2839
+ quoteChar: '"',
2840
+ newline: '\r\n',
2841
+ skipEmptyLines: true,
2842
+ // encoding: 'utf8',
2843
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2844
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2845
+ });
2846
+ if (csv.errors.length !== 0) {
2847
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2848
+ 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 "); }));
2849
+ }
2850
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { /*not await */ return mapCallback(row, index); }))];
2851
+ case 1:
2852
+ mappedData = _a.sent();
2853
+ return [2 /*return*/, papaparse.unparse(mappedData, {
2854
+ header: true,
2855
+ delimiter: ',',
2856
+ quoteChar: '"',
2857
+ newline: '\r\n',
2858
+ skipEmptyLines: true,
2859
+ // encoding: 'utf8',
2860
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2861
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2862
+ })];
2863
+ }
2864
+ });
2865
+ });
2866
+ },
2867
+ },
2868
+ {
2869
+ subvalueName: 'CELL',
2870
+ mapValues: function (value, mapCallback) {
2871
+ return __awaiter(this, void 0, void 0, function () {
2872
+ var csv, mappedData;
2873
+ var _this = this;
2874
+ return __generator(this, function (_a) {
2875
+ switch (_a.label) {
2876
+ case 0:
2877
+ csv = papaparse.parse(value, {
2878
+ header: true,
2879
+ delimiter: ',',
2880
+ quoteChar: '"',
2881
+ newline: '\r\n',
2882
+ skipEmptyLines: true,
2883
+ // encoding: 'utf8',
2884
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2885
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2886
+ });
2887
+ if (csv.errors.length !== 0) {
2888
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2889
+ 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 "); }));
2890
+ }
2891
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2892
+ var _this = this;
2893
+ return __generator(this, function (_a) {
2894
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2895
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2896
+ return __awaiter(_this, void 0, void 0, function () {
2897
+ var index;
2898
+ var _c;
2899
+ return __generator(this, function (_d) {
2900
+ index = rowIndex * Object.keys(row).length + columnIndex;
2901
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2902
+ });
2903
+ });
2904
+ }))];
2905
+ });
2906
+ }); }))];
2907
+ case 1:
2908
+ mappedData = _a.sent();
2909
+ return [2 /*return*/, papaparse.unparse(mappedData, {
2910
+ header: true,
2911
+ delimiter: ',',
2912
+ quoteChar: '"',
2913
+ newline: '\r\n',
2914
+ skipEmptyLines: true,
2915
+ // encoding: 'utf8',
2916
+ // <- TODO: !!!!!! DEFAULT_CSV_OPTIONS
2917
+ // <- TODO: [🧠] How to define parsing options for formats, its different concept than schema
2918
+ })];
2919
+ }
2920
+ });
2921
+ });
2922
+ },
2923
+ },
2924
+ ],
2925
+ };
2926
+ /**
2927
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2928
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2929
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2930
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2931
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3021
2932
  */
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
2933
 
3029
2934
  /**
3030
- * Counts number of paragraphs in the text
2935
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3031
2936
  *
3032
2937
  * @public exported from `@promptbook/utils`
3033
2938
  */
3034
- function countParagraphs(text) {
3035
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
2939
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2940
+ try {
2941
+ JSON.parse(value);
2942
+ return true;
2943
+ }
2944
+ catch (error) {
2945
+ if (!(error instanceof Error)) {
2946
+ throw error;
2947
+ }
2948
+ if (error.message.includes('Unexpected token')) {
2949
+ return false;
2950
+ }
2951
+ return false;
2952
+ }
3036
2953
  }
3037
2954
 
3038
2955
  /**
3039
- * Split text into sentences
2956
+ * Definition for JSON format
3040
2957
  *
3041
- * @public exported from `@promptbook/utils`
2958
+ * @private still in development [🏢]
3042
2959
  */
3043
- function splitIntoSentences(text) {
3044
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3045
- }
2960
+ var JsonFormatDefinition = {
2961
+ formatName: 'JSON',
2962
+ mimeType: 'application/json',
2963
+ isValid: function (value, schema) {
2964
+ TODO_USE(schema /* <- TODO: Use schema here */);
2965
+ return isValidJsonString(value);
2966
+ },
2967
+ canBeValid: function (partialValue, schema) {
2968
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2969
+ TODO_USE(schema /* <- TODO: Use schema here */);
2970
+ return true;
2971
+ },
2972
+ heal: function (value, schema) {
2973
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2974
+ TODO_USE(schema /* <- TODO: Use schema here */);
2975
+ throw new Error('Not implemented');
2976
+ },
2977
+ subvalueDefinitions: [],
2978
+ };
3046
2979
  /**
3047
- * Counts number of sentences in the text
3048
- *
3049
- * @public exported from `@promptbook/utils`
2980
+ * TODO: [🧠] Maybe propper instance of object
2981
+ * TODO: [0] Make string_serialized_json
2982
+ * TODO: [1] Make type for JSON Schema
2983
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2984
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2985
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2986
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2987
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2988
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3050
2989
  */
3051
- function countSentences(text) {
3052
- return splitIntoSentences(text).length;
3053
- }
3054
2990
 
3055
2991
  /**
3056
- * Counts number of words in the text
2992
+ * Definition for any text - this will be always valid
3057
2993
  *
3058
- * @public exported from `@promptbook/utils`
2994
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
2995
+ *
2996
+ * @public exported from `@promptbook/core`
2997
+ */
2998
+ var TextFormatDefinition = {
2999
+ formatName: 'TEXT',
3000
+ isValid: function (value) {
3001
+ return typeof value === 'string';
3002
+ },
3003
+ canBeValid: function (partialValue) {
3004
+ return typeof partialValue === 'string';
3005
+ },
3006
+ heal: function () {
3007
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3008
+ },
3009
+ subvalueDefinitions: [
3010
+ {
3011
+ subvalueName: 'LINE',
3012
+ mapValues: function (value, mapCallback) {
3013
+ return __awaiter(this, void 0, void 0, function () {
3014
+ var lines, mappedLines;
3015
+ return __generator(this, function (_a) {
3016
+ switch (_a.label) {
3017
+ case 0:
3018
+ lines = value.split('\n');
3019
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3020
+ // TODO: [🧠] Maybe option to skip empty line
3021
+ /* not await */ return mapCallback({
3022
+ lineContent: lineContent,
3023
+ // TODO: [🧠] Maybe also put here `lineNumber`
3024
+ }, lineNumber);
3025
+ }))];
3026
+ case 1:
3027
+ mappedLines = _a.sent();
3028
+ return [2 /*return*/, mappedLines.join('\n')];
3029
+ }
3030
+ });
3031
+ });
3032
+ },
3033
+ },
3034
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3035
+ ],
3036
+ };
3037
+ /**
3038
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3039
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3040
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3041
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3042
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3043
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3059
3044
  */
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
3045
 
3066
3046
  /**
3067
- * Index of all counter functions
3047
+ * Definition for XML format
3068
3048
  *
3069
- * @public exported from `@promptbook/utils`
3049
+ * @private still in development [🏢]
3070
3050
  */
3071
- var CountUtils = {
3072
- CHARACTERS: countCharacters,
3073
- WORDS: countWords,
3074
- SENTENCES: countSentences,
3075
- PARAGRAPHS: countParagraphs,
3076
- LINES: countLines,
3077
- PAGES: countPages,
3051
+ var XmlFormatDefinition = {
3052
+ formatName: 'XML',
3053
+ mimeType: 'application/xml',
3054
+ isValid: function (value, schema) {
3055
+ TODO_USE(value /* <- TODO: Use value here */);
3056
+ TODO_USE(schema /* <- TODO: Use schema here */);
3057
+ return true;
3058
+ },
3059
+ canBeValid: function (partialValue, schema) {
3060
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3061
+ TODO_USE(schema /* <- TODO: Use schema here */);
3062
+ return true;
3063
+ },
3064
+ heal: function (value, schema) {
3065
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3066
+ TODO_USE(schema /* <- TODO: Use schema here */);
3067
+ throw new Error('Not implemented');
3068
+ },
3069
+ subvalueDefinitions: [],
3078
3070
  };
3071
+ /**
3072
+ * TODO: [🧠] Maybe propper instance of object
3073
+ * TODO: [0] Make string_serialized_xml
3074
+ * TODO: [1] Make type for XML Schema
3075
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3076
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3077
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3078
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3079
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3080
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3081
+ */
3079
3082
 
3080
3083
  /**
3081
- * Function checkExpectations will check if the expectations on given value are met
3084
+ * Definitions for all formats supported by Promptbook
3082
3085
  *
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
3086
+ * @private internal index of `...` <- TODO [🏢]
3087
+ */
3088
+ var FORMAT_DEFINITIONS = [
3089
+ JsonFormatDefinition,
3090
+ XmlFormatDefinition,
3091
+ TextFormatDefinition,
3092
+ CsvFormatDefinition,
3093
+ ];
3094
+
3095
+ /**
3096
+ * Maps available parameters to expected parameters
3086
3097
  *
3087
- * @throws {ExpectError} if the expectations are not met
3088
- * @returns {void} Nothing
3089
- * @private internal function of `createPipelineExecutor`
3098
+ * The strategy is:
3099
+ * 1) @@@
3100
+ * 2) @@@
3101
+ *
3102
+ * @throws {PipelineExecutionError} @@@
3103
+ * @private within the repository used in `createPipelineExecutor`
3090
3104
  */
3091
- function checkExpectations(expectations, value) {
3105
+ function mapAvailableToExpectedParameters(options) {
3092
3106
  var e_1, _a;
3107
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3108
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3109
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3110
+ var mappedParameters = {};
3093
3111
  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));
3112
+ // Phase 1️⃣: Matching mapping
3113
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3114
+ var parameterName = _c.value;
3115
+ // Situation: Parameter is available and expected
3116
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3117
+ mappedParameters[parameterName] = availableParameters[parameterName];
3118
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3119
+ availableParametersNames.delete(parameterName);
3120
+ expectedParameterNames.delete(parameterName);
3121
+ }
3122
+ // Situation: Parameter is available but NOT expected
3123
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3124
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3125
+ }
3126
+ // Situation: Parameter is NOT available BUT expected
3127
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3128
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3102
3129
  }
3103
3130
  }
3104
3131
  }
@@ -3109,600 +3136,1123 @@
3109
3136
  }
3110
3137
  finally { if (e_1) throw e_1.error; }
3111
3138
  }
3139
+ if (expectedParameterNames.size === 0) {
3140
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3141
+ Object.freeze(mappedParameters);
3142
+ return mappedParameters;
3143
+ }
3144
+ // Phase 2️⃣: Non-matching mapping
3145
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3146
+ 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)
3147
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3148
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3149
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3150
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3151
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3152
+ .join('\n')), "\n\n "); }));
3153
+ }
3154
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3155
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3156
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3157
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3158
+ }
3159
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3160
+ Object.freeze(mappedParameters);
3161
+ return mappedParameters;
3112
3162
  }
3113
- /**
3114
- * TODO: [💝] Unite object for expecting amount and format
3115
- */
3116
3163
 
3117
3164
  /**
3118
- * Creates executor function from pipeline and execution tools.
3165
+ * Extracts all code blocks from markdown.
3119
3166
  *
3120
- * @returns The executor function
3121
- * @throws {PipelineLogicError} on logical error in the pipeline
3122
- * @public exported from `@promptbook/core`
3167
+ * Note: There are multiple simmilar function:
3168
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3169
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3170
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3171
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3172
+ *
3173
+ * @param markdown any valid markdown
3174
+ * @returns code blocks with language and content
3175
+ * @throws {ParseError} if block is not closed properly
3176
+ * @public exported from `@promptbook/markdown-utils`
3123
3177
  */
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));
3178
+ function extractAllBlocksFromMarkdown(markdown) {
3179
+ var e_1, _a;
3180
+ var codeBlocks = [];
3181
+ var lines = markdown.split('\n');
3182
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3183
+ lines.push('');
3184
+ var currentCodeBlock = null;
3185
+ try {
3186
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3187
+ var line = lines_1_1.value;
3188
+ if (line.startsWith('> ') || line === '>') {
3189
+ if (currentCodeBlock === null) {
3190
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3191
+ } /* not else */
3192
+ if (currentCodeBlock.blockNotation === '>') {
3193
+ if (currentCodeBlock.content !== '') {
3194
+ currentCodeBlock.content += '\n';
3195
+ }
3196
+ currentCodeBlock.content += line.slice(2);
3197
+ }
3198
+ }
3199
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3200
+ codeBlocks.push(currentCodeBlock);
3201
+ currentCodeBlock = null;
3202
+ }
3203
+ /* not else */
3204
+ if (line.startsWith('```')) {
3205
+ var language = line.slice(3).trim() || null;
3206
+ if (currentCodeBlock === null) {
3207
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3208
+ }
3209
+ else {
3210
+ if (language !== null) {
3211
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3212
+ }
3213
+ codeBlocks.push(currentCodeBlock);
3214
+ currentCodeBlock = null;
3215
+ }
3216
+ }
3217
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3218
+ if (currentCodeBlock.content !== '') {
3219
+ currentCodeBlock.content += '\n';
3220
+ }
3221
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3222
+ }
3134
3223
  }
3135
- if (pipeline.pipelineUrl !== undefined) {
3136
- _.push("Url: ".concat(pipeline.pipelineUrl));
3224
+ }
3225
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3226
+ finally {
3227
+ try {
3228
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3137
3229
  }
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;
3230
+ finally { if (e_1) throw e_1.error; }
3144
3231
  }
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 "); }));
3232
+ if (currentCodeBlock !== null) {
3233
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3147
3234
  }
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
- }
3235
+ return codeBlocks;
3236
+ }
3237
+ /**
3238
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3239
+ */
3240
+
3241
+ /**
3242
+ * Extracts extracts exactly one valid JSON code block
3243
+ *
3244
+ * - When given string is a valid JSON as it is, it just returns it
3245
+ * - When there is no JSON code block the function throws a `ParseError`
3246
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3247
+ *
3248
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3249
+ * Note: There are multiple simmilar function:
3250
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3251
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3252
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3253
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3254
+ *
3255
+ * @public exported from `@promptbook/markdown-utils`
3256
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3257
+ */
3258
+ function extractJsonBlock(markdown) {
3259
+ if (isValidJsonString(markdown)) {
3260
+ return markdown;
3261
+ }
3262
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3263
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3264
+ var content = _a.content;
3265
+ return isValidJsonString(content);
3266
+ });
3267
+ if (jsonBlocks.length === 0) {
3268
+ throw new Error('There is no valid JSON block in the markdown');
3269
+ }
3270
+ if (jsonBlocks.length > 1) {
3271
+ throw new Error('There are multiple JSON code blocks in the markdown');
3272
+ }
3273
+ return jsonBlocks[0].content;
3274
+ }
3275
+ /**
3276
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3277
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3278
+ */
3279
+
3280
+ /**
3281
+ * Just says that the variable is not used but should be kept
3282
+ * No side effects.
3283
+ *
3284
+ * Note: It can be usefull for:
3285
+ *
3286
+ * 1) Suppressing eager optimization of unused imports
3287
+ * 2) Suppressing eslint errors of unused variables in the tests
3288
+ * 3) Keeping the type of the variable for type testing
3289
+ *
3290
+ * @param value any values
3291
+ * @returns void
3292
+ * @private within the repository
3293
+ */
3294
+ function keepUnused() {
3295
+ var valuesToKeep = [];
3296
+ for (var _i = 0; _i < arguments.length; _i++) {
3297
+ valuesToKeep[_i] = arguments[_i];
3298
+ }
3299
+ }
3300
+
3301
+ /**
3302
+ * Replaces parameters in template with values from parameters object
3303
+ *
3304
+ * @param template the template with parameters in {curly} braces
3305
+ * @param parameters the object with parameters
3306
+ * @returns the template with replaced parameters
3307
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3308
+ * @public exported from `@promptbook/utils`
3309
+ */
3310
+ function replaceParameters(template, parameters) {
3311
+ var e_1, _a;
3312
+ try {
3313
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3314
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3315
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3316
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3317
+ }
3318
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3319
+ // TODO: [🍵]
3320
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3321
+ }
3322
+ }
3323
+ }
3324
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3325
+ finally {
3326
+ try {
3327
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3328
+ }
3329
+ finally { if (e_1) throw e_1.error; }
3330
+ }
3331
+ var replacedTemplate = template;
3332
+ var match;
3333
+ var loopLimit = LOOP_LIMIT;
3334
+ var _loop_1 = function () {
3335
+ if (loopLimit-- < 0) {
3336
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3337
+ }
3338
+ var precol = match.groups.precol;
3339
+ var parameterName = match.groups.parameterName;
3340
+ if (parameterName === '') {
3341
+ return "continue";
3342
+ }
3343
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3344
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3345
+ }
3346
+ if (parameters[parameterName] === undefined) {
3347
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3348
+ }
3349
+ var parameterValue = parameters[parameterName];
3350
+ if (parameterValue === undefined) {
3351
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3352
+ }
3353
+ parameterValue = parameterValue.toString();
3354
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3355
+ parameterValue = parameterValue
3356
+ .split('\n')
3357
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3358
+ .join('\n');
3359
+ }
3360
+ replacedTemplate =
3361
+ replacedTemplate.substring(0, match.index + precol.length) +
3362
+ parameterValue +
3363
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3364
+ };
3365
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3366
+ .exec(replacedTemplate))) {
3367
+ _loop_1();
3368
+ }
3369
+ // [💫] Check if there are parameters that are not closed properly
3370
+ if (/{\w+$/.test(replacedTemplate)) {
3371
+ throw new PipelineExecutionError('Parameter is not closed');
3372
+ }
3373
+ // [💫] Check if there are parameters that are not opened properly
3374
+ if (/^\w+}/.test(replacedTemplate)) {
3375
+ throw new PipelineExecutionError('Parameter is not opened');
3376
+ }
3377
+ return replacedTemplate;
3378
+ }
3379
+
3380
+ /**
3381
+ * Counts number of characters in the text
3382
+ *
3383
+ * @public exported from `@promptbook/utils`
3384
+ */
3385
+ function countCharacters(text) {
3386
+ // Remove null characters
3387
+ text = text.replace(/\0/g, '');
3388
+ // Replace emojis (and also ZWJ sequence) with hyphens
3389
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3390
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3391
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3392
+ return text.length;
3393
+ }
3394
+
3395
+ /**
3396
+ * Counts number of lines in the text
3397
+ *
3398
+ * @public exported from `@promptbook/utils`
3399
+ */
3400
+ function countLines(text) {
3401
+ if (text === '') {
3402
+ return 0;
3403
+ }
3404
+ return text.split('\n').length;
3405
+ }
3406
+
3407
+ /**
3408
+ * Counts number of pages in the text
3409
+ *
3410
+ * @public exported from `@promptbook/utils`
3411
+ */
3412
+ function countPages(text) {
3413
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3414
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3415
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3416
+ return pageCount;
3417
+ }
3418
+
3419
+ /**
3420
+ * Counts number of paragraphs in the text
3421
+ *
3422
+ * @public exported from `@promptbook/utils`
3423
+ */
3424
+ function countParagraphs(text) {
3425
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3426
+ }
3427
+
3428
+ /**
3429
+ * Split text into sentences
3430
+ *
3431
+ * @public exported from `@promptbook/utils`
3432
+ */
3433
+ function splitIntoSentences(text) {
3434
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3435
+ }
3436
+ /**
3437
+ * Counts number of sentences in the text
3438
+ *
3439
+ * @public exported from `@promptbook/utils`
3440
+ */
3441
+ function countSentences(text) {
3442
+ return splitIntoSentences(text).length;
3443
+ }
3444
+
3445
+ /**
3446
+ * Counts number of words in the text
3447
+ *
3448
+ * @public exported from `@promptbook/utils`
3449
+ */
3450
+ function countWords(text) {
3451
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3452
+ text = removeDiacritics(text);
3453
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3454
+ }
3455
+
3456
+ /**
3457
+ * Index of all counter functions
3458
+ *
3459
+ * @public exported from `@promptbook/utils`
3460
+ */
3461
+ var CountUtils = {
3462
+ CHARACTERS: countCharacters,
3463
+ WORDS: countWords,
3464
+ SENTENCES: countSentences,
3465
+ PARAGRAPHS: countParagraphs,
3466
+ LINES: countLines,
3467
+ PAGES: countPages,
3468
+ };
3469
+ /**
3470
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3471
+ */
3472
+
3473
+ /**
3474
+ * Function checkExpectations will check if the expectations on given value are met
3475
+ *
3476
+ * Note: There are two simmilar functions:
3477
+ * - `checkExpectations` which throws an error if the expectations are not met
3478
+ * - `isPassingExpectations` which returns a boolean
3479
+ *
3480
+ * @throws {ExpectError} if the expectations are not met
3481
+ * @returns {void} Nothing
3482
+ * @private internal function of `createPipelineExecutor`
3483
+ */
3484
+ function checkExpectations(expectations, value) {
3485
+ var e_1, _a;
3486
+ try {
3487
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3488
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3489
+ var amount = CountUtils[unit.toUpperCase()](value);
3490
+ if (min && amount < min) {
3491
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3492
+ } /* not else */
3493
+ if (max && amount > max) {
3494
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3495
+ }
3496
+ }
3497
+ }
3498
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3499
+ finally {
3500
+ try {
3501
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3502
+ }
3503
+ finally { if (e_1) throw e_1.error; }
3504
+ }
3505
+ }
3506
+ /**
3507
+ * TODO: [💝] Unite object for expecting amount and format
3508
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3509
+ * Note: [💝] and [🤠] are interconnected together
3510
+ */
3511
+
3512
+ /**
3513
+ * @@@
3514
+ *
3515
+ * @private internal utility of `createPipelineExecutor`
3516
+ */
3517
+ function executeAttempts(options) {
3518
+ return __awaiter(this, void 0, void 0, function () {
3519
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3520
+ return __generator(this, function (_a) {
3521
+ switch (_a.label) {
3522
+ case 0:
3523
+ 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;
3524
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3525
+ $ongoingTemplateResult = {
3526
+ $result: null,
3527
+ $resultString: null,
3528
+ $expectError: null,
3529
+ $scriptPipelineExecutionErrors: [],
3530
+ };
3531
+ _loop_1 = function (attempt) {
3532
+ 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;
3533
+ var e_1, _r, e_3, _s, e_2, _t;
3534
+ return __generator(this, function (_u) {
3535
+ switch (_u.label) {
3536
+ case 0:
3537
+ isJokerAttempt = attempt < 0;
3538
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3539
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3540
+ if (isJokerAttempt && !jokerParameterName) {
3541
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3542
+ }
3543
+ $ongoingTemplateResult.$result = null;
3544
+ $ongoingTemplateResult.$resultString = null;
3545
+ $ongoingTemplateResult.$expectError = null;
3546
+ if (isJokerAttempt) {
3547
+ if (parameters[jokerParameterName] === undefined) {
3548
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3549
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3550
+ }
3551
+ else {
3552
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3553
+ }
3554
+ }
3555
+ _u.label = 1;
3556
+ case 1:
3557
+ _u.trys.push([1, 44, 45, 46]);
3558
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3559
+ _b = template.templateType;
3560
+ switch (_b) {
3561
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3562
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3563
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3564
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3565
+ }
3566
+ return [3 /*break*/, 25];
3567
+ case 2:
3568
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3569
+ return [3 /*break*/, 26];
3570
+ case 3:
3571
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3572
+ $ongoingTemplateResult.$prompt = {
3573
+ title: template.title,
3574
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3575
+ ? preparedPipeline.pipelineUrl
3576
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3577
+ parameters: parameters,
3578
+ content: preparedContent,
3579
+ modelRequirements: modelRequirements,
3580
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3581
+ var name = _a.name;
3582
+ return name === template.personaName;
3583
+ }) ||
3584
+ {})), template.expectations),
3585
+ format: template.format,
3586
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3587
+ }; // <- TODO: Not very good type guard
3588
+ _c = modelRequirements.modelVariant;
3589
+ switch (_c) {
3590
+ case 'CHAT': return [3 /*break*/, 4];
3591
+ case 'COMPLETION': return [3 /*break*/, 6];
3592
+ case 'EMBEDDING': return [3 /*break*/, 8];
3593
+ }
3594
+ return [3 /*break*/, 10];
3595
+ case 4:
3596
+ _d = $ongoingTemplateResult;
3597
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3598
+ case 5:
3599
+ _d.$chatResult = _u.sent();
3600
+ // TODO: [🍬] Destroy chatThread
3601
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3602
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3603
+ return [3 /*break*/, 11];
3604
+ case 6:
3605
+ _e = $ongoingTemplateResult;
3606
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3607
+ case 7:
3608
+ _e.$completionResult = _u.sent();
3609
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3610
+ $ongoingTemplateResult.$resultString =
3611
+ $ongoingTemplateResult.$completionResult.content;
3612
+ return [3 /*break*/, 11];
3613
+ case 8:
3614
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3615
+ _f = $ongoingTemplateResult;
3616
+ return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze($ongoingTemplateResult.$prompt))];
3617
+ case 9:
3618
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3619
+ _f.$embeddingResult = _u.sent();
3620
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$embeddingResult;
3621
+ $ongoingTemplateResult.$resultString =
3622
+ $ongoingTemplateResult.$embeddingResult.content.join(',');
3623
+ return [3 /*break*/, 11];
3624
+ 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 "); }));
3625
+ case 11: return [3 /*break*/, 26];
3626
+ case 12:
3627
+ if (arrayableToArray(tools.script).length === 0) {
3628
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3629
+ }
3630
+ if (!template.contentLanguage) {
3631
+ 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 "); }));
3632
+ }
3633
+ _u.label = 13;
3634
+ case 13:
3635
+ _u.trys.push([13, 20, 21, 22]);
3636
+ _g = (e_1 = void 0, __values(arrayableToArray(tools.script))), _h = _g.next();
3637
+ _u.label = 14;
3638
+ case 14:
3639
+ if (!!_h.done) return [3 /*break*/, 19];
3640
+ scriptTools = _h.value;
3641
+ _u.label = 15;
3642
+ case 15:
3643
+ _u.trys.push([15, 17, , 18]);
3644
+ _j = $ongoingTemplateResult;
3645
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3646
+ scriptLanguage: template.contentLanguage,
3647
+ script: preparedContent,
3648
+ parameters: parameters,
3649
+ }))];
3650
+ case 16:
3651
+ _j.$resultString = _u.sent();
3652
+ return [3 /*break*/, 19];
3653
+ case 17:
3654
+ error_1 = _u.sent();
3655
+ if (!(error_1 instanceof Error)) {
3656
+ throw error_1;
3657
+ }
3658
+ if (error_1 instanceof UnexpectedError) {
3659
+ throw error_1;
3660
+ }
3661
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3662
+ return [3 /*break*/, 18];
3663
+ case 18:
3664
+ _h = _g.next();
3665
+ return [3 /*break*/, 14];
3666
+ case 19: return [3 /*break*/, 22];
3667
+ case 20:
3668
+ e_1_1 = _u.sent();
3669
+ e_1 = { error: e_1_1 };
3670
+ return [3 /*break*/, 22];
3671
+ case 21:
3672
+ try {
3673
+ if (_h && !_h.done && (_r = _g.return)) _r.call(_g);
3674
+ }
3675
+ finally { if (e_1) throw e_1.error; }
3676
+ return [7 /*endfinally*/];
3677
+ case 22:
3678
+ if ($ongoingTemplateResult.$resultString !== null) {
3679
+ return [3 /*break*/, 26];
3680
+ }
3681
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3682
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3683
+ }
3684
+ else {
3685
+ 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
3686
+ .map(function (error) { return '- ' + error.message; })
3687
+ .join('\n\n')), "\n "); }));
3688
+ }
3689
+ case 23:
3690
+ if (tools.userInterface === undefined) {
3691
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3692
+ }
3693
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3694
+ _k = $ongoingTemplateResult;
3695
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3696
+ promptTitle: template.title,
3697
+ promptMessage: replaceParameters(template.description || '', parameters),
3698
+ defaultValue: replaceParameters(preparedContent, parameters),
3699
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3700
+ placeholder: undefined,
3701
+ priority: priority,
3702
+ }))];
3703
+ case 24:
3704
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3705
+ _k.$resultString = _u.sent();
3706
+ return [3 /*break*/, 26];
3707
+ case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3708
+ case 26:
3709
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 43];
3710
+ _u.label = 27;
3711
+ case 27:
3712
+ _u.trys.push([27, 41, 42, 43]);
3713
+ _l = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _m = _l.next();
3714
+ _u.label = 28;
3715
+ case 28:
3716
+ if (!!_m.done) return [3 /*break*/, 40];
3717
+ functionName = _m.value;
3718
+ postprocessingError = null;
3719
+ _u.label = 29;
3720
+ case 29:
3721
+ _u.trys.push([29, 36, 37, 38]);
3722
+ _o = (e_2 = void 0, __values(arrayableToArray(tools.script))), _p = _o.next();
3723
+ _u.label = 30;
3724
+ case 30:
3725
+ if (!!_p.done) return [3 /*break*/, 35];
3726
+ scriptTools = _p.value;
3727
+ _u.label = 31;
3728
+ case 31:
3729
+ _u.trys.push([31, 33, , 34]);
3730
+ _q = $ongoingTemplateResult;
3731
+ return [4 /*yield*/, scriptTools.execute({
3732
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3733
+ script: "".concat(functionName, "(resultString)"),
3734
+ parameters: {
3735
+ resultString: $ongoingTemplateResult.$resultString || '',
3736
+ // Note: No ...parametersForTemplate, because working with result only
3737
+ },
3738
+ })];
3739
+ case 32:
3740
+ _q.$resultString = _u.sent();
3741
+ postprocessingError = null;
3742
+ return [3 /*break*/, 35];
3743
+ case 33:
3744
+ error_2 = _u.sent();
3745
+ if (!(error_2 instanceof Error)) {
3746
+ throw error_2;
3747
+ }
3748
+ if (error_2 instanceof UnexpectedError) {
3749
+ throw error_2;
3750
+ }
3751
+ postprocessingError = error_2;
3752
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3753
+ return [3 /*break*/, 34];
3754
+ case 34:
3755
+ _p = _o.next();
3756
+ return [3 /*break*/, 30];
3757
+ case 35: return [3 /*break*/, 38];
3758
+ case 36:
3759
+ e_2_1 = _u.sent();
3760
+ e_2 = { error: e_2_1 };
3761
+ return [3 /*break*/, 38];
3762
+ case 37:
3763
+ try {
3764
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3765
+ }
3766
+ finally { if (e_2) throw e_2.error; }
3767
+ return [7 /*endfinally*/];
3768
+ case 38:
3769
+ if (postprocessingError) {
3770
+ throw postprocessingError;
3771
+ }
3772
+ _u.label = 39;
3773
+ case 39:
3774
+ _m = _l.next();
3775
+ return [3 /*break*/, 28];
3776
+ case 40: return [3 /*break*/, 43];
3777
+ case 41:
3778
+ e_3_1 = _u.sent();
3779
+ e_3 = { error: e_3_1 };
3780
+ return [3 /*break*/, 43];
3781
+ case 42:
3782
+ try {
3783
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3784
+ }
3785
+ finally { if (e_3) throw e_3.error; }
3786
+ return [7 /*endfinally*/];
3787
+ case 43:
3788
+ // TODO: [💝] Unite object for expecting amount and format
3789
+ if (template.format) {
3790
+ if (template.format === 'JSON') {
3791
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3792
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3793
+ try {
3794
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3574
3795
  }
3575
- else {
3576
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3796
+ catch (error) {
3797
+ keepUnused(error);
3798
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3799
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3577
3800
  }
3578
3801
  }
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) || '')
3802
+ }
3803
+ else {
3804
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3805
+ }
3806
+ }
3807
+ // TODO: [💝] Unite object for expecting amount and format
3808
+ if (template.expectations) {
3809
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3810
+ }
3811
+ return [2 /*return*/, "break-attempts"];
3812
+ case 44:
3813
+ error_3 = _u.sent();
3814
+ if (!(error_3 instanceof ExpectError)) {
3815
+ throw error_3;
3816
+ }
3817
+ $ongoingTemplateResult.$expectError = error_3;
3818
+ return [3 /*break*/, 46];
3819
+ case 45:
3820
+ if (!isJokerAttempt &&
3821
+ template.templateType === 'PROMPT_TEMPLATE' &&
3822
+ $ongoingTemplateResult.$prompt
3823
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3824
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3825
+ ) {
3826
+ // TODO: [🧠] Maybe put other templateTypes into report
3827
+ $executionReport.promptExecutions.push({
3828
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3829
+ result: $ongoingTemplateResult.$result || undefined,
3830
+ error: $ongoingTemplateResult.$expectError === null
3831
+ ? undefined
3832
+ : serializeError($ongoingTemplateResult.$expectError),
3833
+ });
3834
+ }
3835
+ return [7 /*endfinally*/];
3836
+ case 46:
3837
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3838
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3839
+ var _a, _b, _c;
3840
+ 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) || '')
3841
+ .split('\n')
3842
+ .map(function (line) { return "> ".concat(line); })
3843
+ .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) || '')
3844
+ .split('\n')
3845
+ .map(function (line) { return "> ".concat(line); })
3846
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3847
+ ? 'null'
3848
+ : $ongoingTemplateResult.$resultString
3612
3849
  .split('\n')
3613
3850
  .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*/];
3851
+ .join('\n')), "\n ---\n ");
3852
+ }));
3622
3853
  }
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 "); }));
3854
+ return [2 /*return*/];
3659
3855
  }
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*/];
3856
+ });
3857
+ };
3858
+ attempt = -jokerParameterNames.length;
3859
+ _a.label = 1;
3860
+ case 1:
3861
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3862
+ return [5 /*yield**/, _loop_1(attempt)];
3863
+ case 2:
3864
+ state_1 = _a.sent();
3865
+ switch (state_1) {
3866
+ case "break-attempts": return [3 /*break*/, 4];
3667
3867
  }
3668
- });
3669
- });
3868
+ _a.label = 3;
3869
+ case 3:
3870
+ attempt++;
3871
+ return [3 /*break*/, 1];
3872
+ case 4:
3873
+ if ($ongoingTemplateResult.$resultString === null) {
3874
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3875
+ }
3876
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3877
+ }
3878
+ });
3879
+ });
3880
+ }
3881
+ /**
3882
+ * TODO: Break into smaller functions
3883
+ */
3884
+
3885
+ /**
3886
+ * @@@
3887
+ *
3888
+ * @private internal utility of `createPipelineExecutor`
3889
+ */
3890
+ function executeFormatCells(options) {
3891
+ return __awaiter(this, void 0, void 0, function () {
3892
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, parameterValue, formatDefinition, subvalueDefinition, resultString;
3893
+ var _this = this;
3894
+ return __generator(this, function (_a) {
3895
+ switch (_a.label) {
3896
+ case 0:
3897
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification;
3898
+ if (template.foreach === undefined) {
3899
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3900
+ }
3901
+ if (jokerParameterNames.length !== 0) {
3902
+ 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 "); }));
3903
+ }
3904
+ parameterValue = parameters[template.foreach.parameterName] || '';
3905
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3906
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3907
+ });
3908
+ if (formatDefinition === undefined) {
3909
+ throw new UnexpectedError(
3910
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3911
+ 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; })
3912
+ .map(function (formatName) { return "- ".concat(formatName); })
3913
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3914
+ }
3915
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3916
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.cellName);
3917
+ });
3918
+ if (subvalueDefinition === undefined) {
3919
+ throw new UnexpectedError(
3920
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3921
+ 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
3922
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3923
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3924
+ .join('\n')), "\n\n [\u26F7] This should never happen because cell name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3925
+ }
3926
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3927
+ var mappedParameters, allSubparameters, subresultString;
3928
+ return __generator(this, function (_a) {
3929
+ switch (_a.label) {
3930
+ case 0:
3931
+ try {
3932
+ mappedParameters = mapAvailableToExpectedParameters({
3933
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3934
+ availableParameters: subparameters,
3935
+ });
3936
+ }
3937
+ catch (error) {
3938
+ if (!(error instanceof PipelineExecutionError)) {
3939
+ throw error;
3940
+ }
3941
+ 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 "); }));
3942
+ }
3943
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3944
+ // 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
3945
+ Object.freeze(allSubparameters);
3946
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3947
+ case 1:
3948
+ subresultString = _a.sent();
3949
+ return [2 /*return*/, subresultString];
3950
+ }
3951
+ });
3952
+ }); })];
3953
+ case 1:
3954
+ resultString = _a.sent();
3955
+ return [2 /*return*/, resultString];
3956
+ }
3957
+ });
3958
+ });
3959
+ }
3960
+ /**
3961
+ * TODO: !!!!!! Make pipelineIdentification more precise
3962
+ * TODO: !!!!!! How FOREACH execution looks in the report
3963
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
3964
+ * TODO: []
3965
+ */
3966
+
3967
+ /**
3968
+ * @@@
3969
+ *
3970
+ * @private internal utility of `createPipelineExecutor`
3971
+ */
3972
+ function getContextForTemplate(template) {
3973
+ return __awaiter(this, void 0, void 0, function () {
3974
+ return __generator(this, function (_a) {
3975
+ TODO_USE(template);
3976
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3977
+ });
3978
+ });
3979
+ }
3980
+
3981
+ /**
3982
+ * @@@
3983
+ *
3984
+ * @private internal utility of `createPipelineExecutor`
3985
+ */
3986
+ function getKnowledgeForTemplate(options) {
3987
+ return __awaiter(this, void 0, void 0, function () {
3988
+ var preparedPipeline, template;
3989
+ return __generator(this, function (_a) {
3990
+ preparedPipeline = options.preparedPipeline, template = options.template;
3991
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3992
+ TODO_USE(template);
3993
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3994
+ var content = _a.content;
3995
+ return "- ".concat(content);
3996
+ }).join('\n')];
3997
+ });
3998
+ });
3999
+ }
4000
+
4001
+ /**
4002
+ * @@@
4003
+ *
4004
+ * @private internal utility of `createPipelineExecutor`
4005
+ */
4006
+ function getSamplesForTemplate(template) {
4007
+ return __awaiter(this, void 0, void 0, function () {
4008
+ return __generator(this, function (_a) {
4009
+ // TODO: [♨] Implement Better - use real index and keyword search
4010
+ TODO_USE(template);
4011
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4012
+ });
4013
+ });
4014
+ }
4015
+
4016
+ /**
4017
+ * @@@
4018
+ *
4019
+ * @private internal utility of `createPipelineExecutor`
4020
+ */
4021
+ function getReservedParametersForTemplate(options) {
4022
+ return __awaiter(this, void 0, void 0, function () {
4023
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4024
+ var e_1, _a;
4025
+ return __generator(this, function (_b) {
4026
+ switch (_b.label) {
4027
+ case 0:
4028
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4029
+ return [4 /*yield*/, getContextForTemplate(template)];
4030
+ case 1:
4031
+ context = _b.sent();
4032
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4033
+ case 2:
4034
+ knowledge = _b.sent();
4035
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4036
+ case 3:
4037
+ samples = _b.sent();
4038
+ currentDate = new Date().toISOString();
4039
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4040
+ reservedParameters = {
4041
+ content: RESERVED_PARAMETER_RESTRICTED,
4042
+ context: context,
4043
+ knowledge: knowledge,
4044
+ samples: samples,
4045
+ currentDate: currentDate,
4046
+ modelName: modelName,
4047
+ };
4048
+ _loop_1 = function (parameterName) {
4049
+ if (reservedParameters[parameterName] === undefined) {
4050
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4051
+ }
4052
+ };
4053
+ try {
4054
+ // Note: Doublecheck that ALL reserved parameters are defined:
4055
+ 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()) {
4056
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4057
+ _loop_1(parameterName);
4058
+ }
4059
+ }
4060
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4061
+ finally {
4062
+ try {
4063
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4064
+ }
4065
+ finally { if (e_1) throw e_1.error; }
4066
+ }
4067
+ return [2 /*return*/, reservedParameters];
4068
+ }
4069
+ });
4070
+ });
4071
+ }
4072
+
4073
+ /**
4074
+ * @@@
4075
+ *
4076
+ * @private internal utility of `createPipelineExecutor`
4077
+ */
4078
+ function executeTemplate(options) {
4079
+ return __awaiter(this, void 0, void 0, function () {
4080
+ 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;
4081
+ var e_1, _f, _g;
4082
+ return __generator(this, function (_h) {
4083
+ switch (_h.label) {
4084
+ case 0:
4085
+ 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;
4086
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4087
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4088
+ title = currentTemplate.title;
4089
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4090
+ return [4 /*yield*/, onProgress({
4091
+ name: name,
4092
+ title: title,
4093
+ isStarted: false,
4094
+ isDone: false,
4095
+ templateType: currentTemplate.templateType,
4096
+ parameterName: currentTemplate.resultingParameterName,
4097
+ parameterValue: null,
4098
+ // <- [🍸]
4099
+ })];
4100
+ case 1:
4101
+ _h.sent();
4102
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4103
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4104
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4105
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4106
+ 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)
4107
+ .map(function (name) { return "{".concat(name, "}"); })
4108
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4109
+ .map(function (name) { return "{".concat(name, "}"); })
4110
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4111
+ }
4112
+ _b = (_a = Object).freeze;
4113
+ _c = [{}];
4114
+ return [4 /*yield*/, getReservedParametersForTemplate({
4115
+ preparedPipeline: preparedPipeline,
4116
+ template: currentTemplate,
4117
+ pipelineIdentification: pipelineIdentification,
4118
+ })];
4119
+ case 2:
4120
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4121
+ definedParameterNames = new Set(Object.keys(definedParameters));
4122
+ parameters = {};
4123
+ _loop_1 = function (parameterName) {
4124
+ // Situation: Parameter is defined and used
4125
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4126
+ parameters[parameterName] = definedParameters[parameterName];
4127
+ }
4128
+ // Situation: Parameter is defined but NOT used
4129
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4130
+ // Situation: Parameter is NOT defined BUT used
4131
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4132
+ // Houston, we have a problem
4133
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4134
+ 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 "); }));
4135
+ }
4136
+ };
4137
+ try {
4138
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4139
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4140
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4141
+ parameterName = _e.value;
4142
+ _loop_1(parameterName);
4143
+ }
4144
+ }
4145
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4146
+ finally {
4147
+ try {
4148
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4149
+ }
4150
+ finally { if (e_1) throw e_1.error; }
4151
+ }
4152
+ // 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
4153
+ Object.freeze(parameters);
4154
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4155
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4156
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4157
+ .split('{content}')
4158
+ .join(currentTemplate.content);
4159
+ return [4 /*yield*/, executeFormatCells({
4160
+ jokerParameterNames: jokerParameterNames,
4161
+ priority: priority,
4162
+ maxAttempts: maxAttempts,
4163
+ preparedContent: preparedContent,
4164
+ parameters: parameters,
4165
+ template: currentTemplate,
4166
+ preparedPipeline: preparedPipeline,
4167
+ tools: tools,
4168
+ llmTools: llmTools,
4169
+ settings: settings,
4170
+ $executionReport: $executionReport,
4171
+ pipelineIdentification: pipelineIdentification,
4172
+ })];
4173
+ case 3:
4174
+ resultString = _h.sent();
4175
+ return [4 /*yield*/, onProgress({
4176
+ name: name,
4177
+ title: title,
4178
+ isStarted: true,
4179
+ isDone: true,
4180
+ templateType: currentTemplate.templateType,
4181
+ parameterName: currentTemplate.resultingParameterName,
4182
+ parameterValue: resultString,
4183
+ // <- [🍸]
4184
+ })];
4185
+ case 4:
4186
+ _h.sent();
4187
+ return [2 /*return*/, Object.freeze((_g = {},
4188
+ _g[currentTemplate.resultingParameterName] =
4189
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4190
+ resultString,
4191
+ _g))];
4192
+ }
4193
+ });
4194
+ });
4195
+ }
4196
+ /**
4197
+ * TODO: [🤹‍♂️]
4198
+ */
4199
+
4200
+ /**
4201
+ * @@@
4202
+ *
4203
+ * @private internal utility of `createPipelineExecutor`
4204
+ */
4205
+ function filterJustOutputParameters(options) {
4206
+ var e_1, _a;
4207
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4208
+ var outputParameters = {};
4209
+ var _loop_1 = function (parameter) {
4210
+ if (parametersToPass[parameter.name] === undefined) {
4211
+ // [4]
4212
+ $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 "); })));
4213
+ return "continue";
4214
+ }
4215
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4216
+ };
4217
+ try {
4218
+ // Note: Filter ONLY output parameters
4219
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4220
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4221
+ var isOutput = _a.isOutput;
4222
+ return isOutput;
4223
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4224
+ var parameter = _c.value;
4225
+ _loop_1(parameter);
3670
4226
  }
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;
4227
+ }
4228
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4229
+ finally {
4230
+ try {
4231
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3700
4232
  }
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;
4233
+ finally { if (e_1) throw e_1.error; }
4234
+ }
4235
+ return outputParameters;
4236
+ }
4237
+
4238
+ /**
4239
+ * @@@
4240
+ *
4241
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4242
+ *
4243
+ * @private internal utility of `createPipelineExecutor`
4244
+ */
4245
+ function executePipeline(options) {
4246
+ return __awaiter(this, void 0, void 0, function () {
4247
+ 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
4248
  var e_1, _e, e_2, _f;
3703
4249
  return __generator(this, function (_g) {
3704
4250
  switch (_g.label) {
3705
4251
  case 0:
4252
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4253
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4254
+ preparedPipeline = options.preparedPipeline;
4255
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3706
4256
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3707
4257
  return [4 /*yield*/, preparePipeline(pipeline, {
3708
4258
  llmTools: llmTools,
@@ -3711,6 +4261,7 @@
3711
4261
  })];
3712
4262
  case 1:
3713
4263
  preparedPipeline = _g.sent();
4264
+ setPreparedPipeline(preparedPipeline);
3714
4265
  _g.label = 2;
3715
4266
  case 2:
3716
4267
  errors = [];
@@ -3780,7 +4331,7 @@
3780
4331
  return name === parameterName;
3781
4332
  });
3782
4333
  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 "); })));
4334
+ 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
4335
  return [3 /*break*/, 4];
3785
4336
  case 1:
3786
4337
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3792,10 +4343,10 @@
3792
4343
  // Note: Wait a short time to prevent race conditions
3793
4344
  _h.sent();
3794
4345
  _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 "); }), {
4346
+ 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
4347
  isSuccessful: false,
3797
4348
  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 "); }))
4349
+ 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
4350
  ], __read(errors), false).map(serializeError),
3800
4351
  warnings: warnings.map(serializeError),
3801
4352
  executionReport: executionReport,
@@ -3859,7 +4410,7 @@
3859
4410
  case 0:
3860
4411
  if (loopLimit-- < 0) {
3861
4412
  // 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 "); }));
4413
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3863
4414
  }
3864
4415
  currentTemplate = unresovedTemplates_1.find(function (template) {
3865
4416
  return template.dependentParameterNames.every(function (name) {
@@ -3869,29 +4420,52 @@
3869
4420
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3870
4421
  throw new UnexpectedError(
3871
4422
  // 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
4423
+ 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
4424
  .map(function (_a) {
3874
4425
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3875
4426
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3876
4427
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3877
4428
  .join(' and '));
3878
4429
  })
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 "); }));
4430
+ .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
4431
  case 1:
3881
4432
  if (!!currentTemplate) return [3 /*break*/, 3];
3882
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4433
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3883
4434
  case 2:
3884
- /* [5] */ _j.sent();
4435
+ /* [🤹‍♂️] */ _j.sent();
3885
4436
  return [3 /*break*/, 4];
3886
4437
  case 3:
3887
4438
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3888
- work_1 = executeSingleTemplate(currentTemplate)
3889
- .then(function () {
4439
+ work_1 = executeTemplate({
4440
+ currentTemplate: currentTemplate,
4441
+ preparedPipeline: preparedPipeline,
4442
+ parametersToPass: parametersToPass,
4443
+ tools: tools,
4444
+ llmTools: llmTools,
4445
+ onProgress: function (progress) {
4446
+ if (isReturned) {
4447
+ 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)
4448
+ .split('\n')
4449
+ .map(function (line) { return "> ".concat(line); })
4450
+ .join('\n')), "\n "); }));
4451
+ }
4452
+ if (onProgress) {
4453
+ onProgress(progress);
4454
+ }
4455
+ },
4456
+ settings: settings,
4457
+ $executionReport: executionReport,
4458
+ pipelineIdentification: pipelineIdentification,
4459
+ })
4460
+ .then(function (newParametersToPass) {
4461
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3890
4462
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3891
4463
  })
3892
4464
  .then(function () {
3893
4465
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3894
4466
  });
4467
+ // <- Note: Errors are catched here [3]
4468
+ // 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
4469
  resolving_1.push(work_1);
3896
4470
  _j.label = 4;
3897
4471
  case 4: return [2 /*return*/];
@@ -3918,7 +4492,12 @@
3918
4492
  var result = _a.result;
3919
4493
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3920
4494
  })), false));
3921
- outputParameters_1 = filterJustOutputParameters();
4495
+ outputParameters_1 = filterJustOutputParameters({
4496
+ preparedPipeline: preparedPipeline,
4497
+ parametersToPass: parametersToPass,
4498
+ $warnings: warnings,
4499
+ pipelineIdentification: pipelineIdentification,
4500
+ });
3922
4501
  isReturned = true;
3923
4502
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3924
4503
  // Note: Wait a short time to prevent race conditions
@@ -3941,7 +4520,12 @@
3941
4520
  var result = _a.result;
3942
4521
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3943
4522
  })), false));
3944
- outputParameters = filterJustOutputParameters();
4523
+ outputParameters = filterJustOutputParameters({
4524
+ preparedPipeline: preparedPipeline,
4525
+ parametersToPass: parametersToPass,
4526
+ $warnings: warnings,
4527
+ pipelineIdentification: pipelineIdentification,
4528
+ });
3945
4529
  isReturned = true;
3946
4530
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3947
4531
  // Note: Wait a short time to prevent race conditions
@@ -3961,22 +4545,62 @@
3961
4545
  })];
3962
4546
  }
3963
4547
  });
3964
- }); };
3965
- return pipelineExecutor;
4548
+ });
3966
4549
  }
4550
+
3967
4551
  /**
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
4552
+ * Creates executor function from pipeline and execution tools.
4553
+ *
4554
+ * @returns The executor function
4555
+ * @throws {PipelineLogicError} on logical error in the pipeline
4556
+ * @public exported from `@promptbook/core`
3979
4557
  */
4558
+ function createPipelineExecutor(options) {
4559
+ var _this = this;
4560
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4561
+ 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;
4562
+ validatePipeline(pipeline);
4563
+ var pipelineIdentification = (function () {
4564
+ // Note: This is a 😐 implementation of [🚞]
4565
+ var _ = [];
4566
+ if (pipeline.sourceFile !== undefined) {
4567
+ _.push("File: ".concat(pipeline.sourceFile));
4568
+ }
4569
+ if (pipeline.pipelineUrl !== undefined) {
4570
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4571
+ }
4572
+ return _.join('\n');
4573
+ })();
4574
+ var preparedPipeline;
4575
+ if (isPipelinePrepared(pipeline)) {
4576
+ preparedPipeline = pipeline;
4577
+ }
4578
+ else if (isNotPreparedWarningSupressed !== true) {
4579
+ 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 "); }));
4580
+ }
4581
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4582
+ return __generator(this, function (_a) {
4583
+ return [2 /*return*/, executePipeline({
4584
+ pipeline: pipeline,
4585
+ preparedPipeline: preparedPipeline,
4586
+ setPreparedPipeline: function (newPreparedPipeline) {
4587
+ preparedPipeline = newPreparedPipeline;
4588
+ },
4589
+ inputParameters: inputParameters,
4590
+ tools: tools,
4591
+ onProgress: onProgress,
4592
+ pipelineIdentification: pipelineIdentification,
4593
+ settings: {
4594
+ maxExecutionAttempts: maxExecutionAttempts,
4595
+ maxParallelCount: maxParallelCount,
4596
+ isVerbose: isVerbose,
4597
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4598
+ },
4599
+ })];
4600
+ });
4601
+ }); };
4602
+ return pipelineExecutor;
4603
+ }
3980
4604
 
3981
4605
  /**
3982
4606
  * @@@
@@ -5130,6 +5754,145 @@
5130
5754
  * TODO: [🌺] Use some intermediate util splitWords
5131
5755
  */
5132
5756
 
5757
+ /**
5758
+ * @@@
5759
+ *
5760
+ * @param text @@@
5761
+ * @param _isFirstLetterCapital @@@
5762
+ * @returns @@@
5763
+ * @example 'helloWorld'
5764
+ * @example 'iLovePromptbook'
5765
+ * @public exported from `@promptbook/utils`
5766
+ */
5767
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5768
+ var e_1, _a;
5769
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5770
+ var charType;
5771
+ var lastCharType = null;
5772
+ var normalizedName = '';
5773
+ try {
5774
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5775
+ var char = text_1_1.value;
5776
+ var normalizedChar = void 0;
5777
+ if (/^[a-z]$/.test(char)) {
5778
+ charType = 'LOWERCASE';
5779
+ normalizedChar = char;
5780
+ }
5781
+ else if (/^[A-Z]$/.test(char)) {
5782
+ charType = 'UPPERCASE';
5783
+ normalizedChar = char.toLowerCase();
5784
+ }
5785
+ else if (/^[0-9]$/.test(char)) {
5786
+ charType = 'NUMBER';
5787
+ normalizedChar = char;
5788
+ }
5789
+ else {
5790
+ charType = 'OTHER';
5791
+ normalizedChar = '';
5792
+ }
5793
+ if (!lastCharType) {
5794
+ if (_isFirstLetterCapital) {
5795
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5796
+ }
5797
+ }
5798
+ else if (charType !== lastCharType &&
5799
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5800
+ !(lastCharType === 'NUMBER') &&
5801
+ !(charType === 'NUMBER')) {
5802
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5803
+ }
5804
+ normalizedName += normalizedChar;
5805
+ lastCharType = charType;
5806
+ }
5807
+ }
5808
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5809
+ finally {
5810
+ try {
5811
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5812
+ }
5813
+ finally { if (e_1) throw e_1.error; }
5814
+ }
5815
+ return normalizedName;
5816
+ }
5817
+ /**
5818
+ * TODO: [🌺] Use some intermediate util splitWords
5819
+ */
5820
+
5821
+ /**
5822
+ * Function `validateParameterName` will @@@
5823
+ *
5824
+ * @param parameterName @@@
5825
+ * @returns @@@
5826
+ * @throws {ParseError} @@@
5827
+ * @private within the repository
5828
+ */
5829
+ function validateParameterName(parameterName) {
5830
+ var e_1, _a;
5831
+ var rawParameterName = parameterName;
5832
+ try {
5833
+ for (var _b = __values([
5834
+ ['`', '`'],
5835
+ ['{', '}'],
5836
+ ['[', ']'],
5837
+ ['(', ')'],
5838
+ ['<', '>'],
5839
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5840
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5841
+ if (parameterName.substring(0, 1) === start &&
5842
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5843
+ // <- TODO: More universal that 1 character
5844
+ ) {
5845
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5846
+ // <- TODO: More universal that 1 character
5847
+ }
5848
+ }
5849
+ }
5850
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5851
+ finally {
5852
+ try {
5853
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5854
+ }
5855
+ finally { if (e_1) throw e_1.error; }
5856
+ }
5857
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5858
+ try {
5859
+ /*
5860
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5861
+ if (parameterName.includes(' ')) {
5862
+ throw new ParseError(`Parameter name cannot contain spaces`);
5863
+ }
5864
+ */
5865
+ if (parameterName.includes('.')) {
5866
+ throw new ParseError("Parameter name cannot contain dots");
5867
+ }
5868
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5869
+ throw new ParseError("Parameter name cannot contain slashes");
5870
+ }
5871
+ if (parameterName.includes('(') ||
5872
+ parameterName.includes(')') ||
5873
+ parameterName.includes('{') ||
5874
+ parameterName.includes('}') ||
5875
+ parameterName.includes('[') ||
5876
+ parameterName.includes(']')) {
5877
+ throw new ParseError("Parameter name cannot contain braces");
5878
+ }
5879
+ parameterName = normalizeTo_camelCase(parameterName);
5880
+ if (parameterName === '') {
5881
+ throw new ParseError("Parameter name cannot be empty");
5882
+ }
5883
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5884
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5885
+ }
5886
+ }
5887
+ catch (error) {
5888
+ if (!(error instanceof ParseError)) {
5889
+ throw error;
5890
+ }
5891
+ 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 "); }));
5892
+ }
5893
+ return parameterName;
5894
+ }
5895
+
5133
5896
  /**
5134
5897
  * Parses the foreach command
5135
5898
  *
@@ -5164,62 +5927,66 @@
5164
5927
  * Example usages of the FOREACH command
5165
5928
  */
5166
5929
  examples: [
5167
- 'FOREACH List Line -> `{customer}`',
5168
- 'FOR List Line -> `{customer}`',
5169
- 'EACH List Line -> `{customer}`',
5930
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5931
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5932
+ 'EACH Csv Cell `{customers}` -> `{cell}`',
5170
5933
  // <- TODO: [🍭] !!!!!! More
5171
5934
  ],
5172
5935
  /**
5173
5936
  * Parses the FOREACH command
5174
5937
  */
5175
5938
  parse: function (input) {
5176
- var args = input.args, rawArgs = input.rawArgs;
5939
+ var args = input.args;
5177
5940
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5178
5941
  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)) {
5942
+ var parameterNameWrapped = args[2];
5943
+ var assignSign = args[3];
5944
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5945
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5946
+ });
5947
+ if (formatDefinition === undefined) {
5186
5948
  console.info({ args: args, formatName: formatName });
5187
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5949
+ 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; })
5950
+ .map(function (formatName) { return "- ".concat(formatName); })
5951
+ .join('\n')), "\n "); }));
5188
5952
  // <- TODO: [🏢] List all supported format names
5189
5953
  }
5190
- if (![
5191
- 'LINE',
5192
- 'ROW',
5193
- 'COLUMN',
5194
- 'CELL',
5195
- // <- TODO: [🏢] Unhardcode format cekks
5196
- ].includes(cellName)) {
5954
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5955
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(cellName);
5956
+ });
5957
+ if (subvalueDefinition === undefined) {
5197
5958
  console.info({ args: args, cellName: cellName });
5198
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5959
+ 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
5960
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5961
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5962
+ .join('\n')), "\n "); }));
5199
5963
  // <- TODO: [🏢] List all supported cell names for the format
5200
5964
  }
5201
5965
  if (assignSign !== '->') {
5202
5966
  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
5967
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5968
+ }
5969
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5970
+ if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5971
+ (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5972
+ 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));
5973
+ throw new ParseError("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5974
+ }
5975
+ var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5976
+ var subparameterNames = args
5977
+ .slice(4)
5978
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5979
+ .filter(function (parameterName) { return parameterName !== ''; })
5980
+ .map(validateParameterName);
5981
+ if (subparameterNames.length === 0) {
5982
+ throw new ParseError("FOREACH command must have at least one subparameter");
5217
5983
  }
5218
5984
  return {
5219
5985
  type: 'FOREACH',
5220
5986
  formatName: formatName,
5221
5987
  cellName: cellName,
5222
5988
  parameterName: parameterName,
5989
+ subparameterNames: subparameterNames,
5223
5990
  };
5224
5991
  },
5225
5992
  /**
@@ -5228,8 +5995,12 @@
5228
5995
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5229
5996
  */
5230
5997
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5231
- keepUnused(command, $templateJson, $pipelineJson);
5232
- // <- TODO: [🍭] !!!!!! Implement
5998
+ var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
5999
+ // TODO: !!!!!! Detect double use
6000
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
6001
+ $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterNames: subparameterNames };
6002
+ keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6003
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5233
6004
  },
5234
6005
  /**
5235
6006
  * Converts the FOREACH command back to string
@@ -5238,8 +6009,7 @@
5238
6009
  */
5239
6010
  stringify: function (command) {
5240
6011
  keepUnused(command);
5241
- return "";
5242
- // <- TODO: [🍭] !!!!!! Implement
6012
+ return "---"; // <- TODO: [🛋] Implement
5243
6013
  },
5244
6014
  /**
5245
6015
  * Reads the FOREACH command from the `TemplateJson`
@@ -5248,12 +6018,12 @@
5248
6018
  */
5249
6019
  takeFromTemplateJson: function ($templateJson) {
5250
6020
  keepUnused($templateJson);
5251
- return [];
5252
- // <- TODO: [🍭] !!!!!! Implement
6021
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5253
6022
  },
5254
6023
  };
5255
6024
  /**
5256
- * TODO: !!!!!! Comment console logs
6025
+ * TODO: !!!!!! Remove console logs
6026
+ * TODO: [🧠][🦥] Better (less confusing) name for "cell" / "subvalue" / "subparameter"
5257
6027
  * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5258
6028
  */
5259
6029
 
@@ -5364,6 +6134,7 @@
5364
6134
  */
5365
6135
  parse: function (input) {
5366
6136
  var args = input.args;
6137
+ // TODO: !!!!!! Replace with propper parameter name validation `validateParameterName`
5367
6138
  var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5368
6139
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5369
6140
  throw new ParseError("Invalid joker");
@@ -5493,6 +6264,7 @@
5493
6264
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5494
6265
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5495
6266
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6267
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5496
6268
  }
5497
6269
  else {
5498
6270
  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 ")));
@@ -7609,21 +8381,40 @@
7609
8381
  * @public exported from `@promptbook/core`
7610
8382
  */
7611
8383
  function usageToHuman(usage) {
7612
- var report = 'Usage:';
8384
+ var reportItems = [];
7613
8385
  var uncertainNumberToHuman = function (_a) {
7614
8386
  var value = _a.value, isUncertain = _a.isUncertain;
7615
8387
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7616
8388
  };
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);
8389
+ if (usage.price.value > 0.1
8390
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8391
+ ) {
8392
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8393
+ }
8394
+ else {
8395
+ reportItems.push("Negligible cost");
8396
+ }
8397
+ var worktime = usageToWorktime(usage);
8398
+ if (worktime.value > 0.5
8399
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8400
+ ) {
8401
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8402
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8403
+ }
8404
+ if (usage.output.charactersCount.value > 0) {
8405
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8406
+ }
8407
+ if (reportItems.length === 0) {
8408
+ // Note: For negligible usage, we report at least something
8409
+ reportItems.push('Negligible');
8410
+ }
8411
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7620
8412
  }
7621
8413
  /**
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
8414
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8415
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8416
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7625
8417
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7626
- * TODO: When negligible usage, report "Negligible" or just don't report it
7627
8418
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7628
8419
  * TODO: [🏛] Maybe make some markdown builder
7629
8420
  */
@@ -8427,70 +9218,6 @@
8427
9218
  * TODO: [🏛] This can be part of markdown builder
8428
9219
  */
8429
9220
 
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
9221
  /**
8495
9222
  * Creates a Mermaid graph based on the promptbook
8496
9223
  *
@@ -8547,6 +9274,9 @@
8547
9274
  return promptbookMermaid;
8548
9275
  }
8549
9276
  /**
9277
+ * TODO: !!!!!! FOREACH in mermaid graph
9278
+ * TODO: !!!!!! Knowledge in mermaid graph
9279
+ * TODO: !!!!!! Personas in mermaid graph
8550
9280
  * TODO: Maybe use some Mermaid package instead of string templating
8551
9281
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8552
9282
  */
@@ -9265,7 +9995,7 @@
9265
9995
  resultContent = contentBlock.text;
9266
9996
  // eslint-disable-next-line prefer-const
9267
9997
  complete = getCurrentIsoDate();
9268
- usage = computeAnthropicClaudeUsage(content, '', rawResponse);
9998
+ usage = computeAnthropicClaudeUsage(rawPromptContent || '', resultContent || '', rawResponse);
9269
9999
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('AnthropicClaudeExecutionTools ChatPromptResult', {
9270
10000
  content: resultContent,
9271
10001
  modelName: rawResponse.model,
@@ -10379,7 +11109,7 @@
10379
11109
  resultContent = rawResponse.choices[0].message.content;
10380
11110
  // eslint-disable-next-line prefer-const
10381
11111
  complete = getCurrentIsoDate();
10382
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11112
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10383
11113
  if (resultContent === null) {
10384
11114
  throw new PipelineExecutionError('No response message from OpenAI');
10385
11115
  }
@@ -10451,7 +11181,7 @@
10451
11181
  resultContent = rawResponse.choices[0].text;
10452
11182
  // eslint-disable-next-line prefer-const
10453
11183
  complete = getCurrentIsoDate();
10454
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11184
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10455
11185
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools CompletionPromptResult', {
10456
11186
  content: resultContent,
10457
11187
  modelName: rawResponse.model || modelName,
@@ -10511,7 +11241,9 @@
10511
11241
  resultContent = rawResponse.data[0].embedding;
10512
11242
  // eslint-disable-next-line prefer-const
10513
11243
  complete = getCurrentIsoDate();
10514
- usage = computeOpenAiUsage(content, '', rawResponse);
11244
+ usage = computeOpenAiUsage(content || '', '',
11245
+ // <- Note: Embedding does not have result content
11246
+ rawResponse);
10515
11247
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools EmbeddingPromptResult', {
10516
11248
  content: resultContent,
10517
11249
  modelName: rawResponse.model || modelName,