@promptbook/cli 0.69.0-1 → 0.69.0-4

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 (27) hide show
  1. package/esm/index.es.js +998 -906
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/src/_packages/core.index.d.ts +1 -1
  4. package/esm/typings/src/_packages/types.index.d.ts +6 -0
  5. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +2 -6
  6. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +26 -0
  7. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  8. package/esm/typings/src/config.d.ts +7 -1
  9. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  10. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  11. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +4 -0
  12. package/esm/typings/src/execution/createPipelineExecutor/CreatePipelineExecutorOptions.d.ts +20 -0
  13. package/esm/typings/src/execution/createPipelineExecutor/CreatePipelineExecutorSettings.d.ts +30 -0
  14. package/esm/typings/src/execution/createPipelineExecutor/createPipelineExecutor.d.ts +24 -0
  15. package/esm/typings/src/execution/createPipelineExecutor/executeSingleTemplate.d.ts +27 -0
  16. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +8 -0
  17. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +8 -0
  18. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +9 -0
  19. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +8 -0
  20. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +8 -0
  21. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  22. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  23. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  24. package/package.json +1 -1
  25. package/umd/index.umd.js +998 -906
  26. package/umd/index.umd.js.map +1 -1
  27. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
package/esm/index.es.js CHANGED
@@ -20,7 +20,7 @@ import OpenAI from 'openai';
20
20
  /**
21
21
  * The version of the Promptbook library
22
22
  */
23
- var PROMPTBOOK_VERSION = '0.69.0-0';
23
+ var PROMPTBOOK_VERSION = '0.69.0-3';
24
24
  // TODO: !!!! List here all the versions and annotate + put into script
25
25
 
26
26
  /*! *****************************************************************************
@@ -473,6 +473,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
473
473
  'samples',
474
474
  'modelName',
475
475
  'currentDate',
476
+ // <- TODO: !!!!! list here all command names
476
477
  // <- TODO: Add more like 'date', 'modelName',...
477
478
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
478
479
  ]);
@@ -507,6 +508,15 @@ var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
507
508
  * @public exported from `@promptbook/core`
508
509
  */
509
510
  var IS_VERBOSE = false;
511
+ /**
512
+ * @@@
513
+ *
514
+ * @private within the repository
515
+ */
516
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
517
+ /**/
518
+ // Note: In normal situations, we check the pipeline logic:
519
+ true);
510
520
  /**
511
521
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
512
522
  */
@@ -1040,7 +1050,7 @@ function forEachAsync(array, options, callbackfunction) {
1040
1050
  });
1041
1051
  }
1042
1052
 
1043
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-0",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1053
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-3",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-3",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-3",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-3",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1044
1054
 
1045
1055
  /**
1046
1056
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1247,6 +1257,26 @@ function isValidPipelineUrl(url) {
1247
1257
  * @public exported from `@promptbook/core`
1248
1258
  */
1249
1259
  function validatePipeline(pipeline) {
1260
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1261
+ validatePipelineCore(pipeline);
1262
+ }
1263
+ else {
1264
+ try {
1265
+ validatePipelineCore(pipeline);
1266
+ }
1267
+ catch (error) {
1268
+ if (!(error instanceof PipelineLogicError)) {
1269
+ throw error;
1270
+ }
1271
+ console.error(spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1272
+ }
1273
+ }
1274
+ return pipeline;
1275
+ }
1276
+ /**
1277
+ * @private internal function for `validatePipeline`
1278
+ */
1279
+ function validatePipelineCore(pipeline) {
1250
1280
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1251
1281
  var e_1, _a, e_2, _b, e_3, _c;
1252
1282
  var pipelineIdentification = (function () {
@@ -1445,7 +1475,6 @@ function validatePipeline(pipeline) {
1445
1475
  while (unresovedTemplates.length > 0) {
1446
1476
  _loop_3();
1447
1477
  }
1448
- return pipeline;
1449
1478
  }
1450
1479
  /**
1451
1480
  * TODO: [🧠] Work with promptbookVersion
@@ -2168,116 +2197,6 @@ function assertsExecutionSuccessful(executionResult) {
2168
2197
  * TODO: [🧠] Can this return type be better typed than void
2169
2198
  */
2170
2199
 
2171
- /**
2172
- * Parses the given script and returns the list of all used variables that are not defined in the script
2173
- *
2174
- * @param script from which to extract the variables
2175
- * @returns the list of variable names
2176
- * @throws {ParseError} if the script is invalid
2177
- * @public exported from `@promptbook/utils`
2178
- */
2179
- function extractVariables(script) {
2180
- var variables = new Set();
2181
- script = "(()=>{".concat(script, "})()");
2182
- try {
2183
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2184
- try {
2185
- eval(script);
2186
- }
2187
- catch (error) {
2188
- if (!(error instanceof ReferenceError)) {
2189
- throw error;
2190
- }
2191
- var undefinedName = error.message.split(' ')[0];
2192
- /*
2193
- Note: Parsing the error
2194
- [PipelineUrlError: thing is not defined]
2195
- */
2196
- if (!undefinedName) {
2197
- throw error;
2198
- }
2199
- if (script.includes(undefinedName + '(')) {
2200
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2201
- }
2202
- else {
2203
- variables.add(undefinedName);
2204
- script = "const ".concat(undefinedName, " = '';") + script;
2205
- }
2206
- }
2207
- }
2208
- catch (error) {
2209
- if (!(error instanceof Error)) {
2210
- throw error;
2211
- }
2212
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2213
- }
2214
- return variables;
2215
- }
2216
- /**
2217
- * TODO: [🔣] Support for multiple languages - python, java,...
2218
- */
2219
-
2220
- /**
2221
- * Parses the template and returns the set of all used parameters
2222
- *
2223
- * @param template the template with used parameters
2224
- * @returns the set of parameter names
2225
- * @throws {ParseError} if the script is invalid
2226
- * @public exported from `@promptbook/utils`
2227
- */
2228
- function extractParameterNamesFromTemplate(template) {
2229
- var e_1, _a, e_2, _b, e_3, _c;
2230
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2231
- var parameterNames = new Set();
2232
- try {
2233
- for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2234
- var parameterName = _e.value;
2235
- parameterNames.add(parameterName);
2236
- }
2237
- }
2238
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2239
- finally {
2240
- try {
2241
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2242
- }
2243
- finally { if (e_1) throw e_1.error; }
2244
- }
2245
- if (templateType === 'SCRIPT_TEMPLATE') {
2246
- try {
2247
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2248
- var parameterName = _g.value;
2249
- parameterNames.add(parameterName);
2250
- }
2251
- }
2252
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2253
- finally {
2254
- try {
2255
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2256
- }
2257
- finally { if (e_2) throw e_2.error; }
2258
- }
2259
- }
2260
- try {
2261
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2262
- var jokerName = _j.value;
2263
- parameterNames.add(jokerName);
2264
- }
2265
- }
2266
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2267
- finally {
2268
- try {
2269
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2270
- }
2271
- finally { if (e_3) throw e_3.error; }
2272
- }
2273
- parameterNames.delete('content');
2274
- // <- Note {websiteContent} is used in `preparedContent`
2275
- return parameterNames;
2276
- }
2277
- /**
2278
- * TODO: [🔣] If script require contentLanguage
2279
- */
2280
-
2281
2200
  /**
2282
2201
  * Serializes an error into a [🚉] JSON-serializable object
2283
2202
  *
@@ -2295,27 +2214,6 @@ function serializeError(error) {
2295
2214
  };
2296
2215
  }
2297
2216
 
2298
- /**
2299
- * Function isValidJsonString will tell you if the string is valid JSON or not
2300
- *
2301
- * @public exported from `@promptbook/utils`
2302
- */
2303
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2304
- try {
2305
- JSON.parse(value);
2306
- return true;
2307
- }
2308
- catch (error) {
2309
- if (!(error instanceof Error)) {
2310
- throw error;
2311
- }
2312
- if (error.message.includes('Unexpected token')) {
2313
- return false;
2314
- }
2315
- return false;
2316
- }
2317
- }
2318
-
2319
2217
  /**
2320
2218
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2321
2219
  *
@@ -2610,171 +2508,310 @@ function joinLlmExecutionTools() {
2610
2508
  */
2611
2509
 
2612
2510
  /**
2613
- * Extracts all code blocks from markdown.
2614
- *
2615
- * Note: There are multiple simmilar function:
2616
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2617
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2618
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2619
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2511
+ * Determine if the pipeline is fully prepared
2620
2512
  *
2621
- * @param markdown any valid markdown
2622
- * @returns code blocks with language and content
2623
- * @throws {ParseError} if block is not closed properly
2624
- * @public exported from `@promptbook/markdown-utils`
2513
+ * @public exported from `@promptbook/core`
2625
2514
  */
2626
- function extractAllBlocksFromMarkdown(markdown) {
2627
- var e_1, _a;
2628
- var codeBlocks = [];
2629
- var lines = markdown.split('\n');
2630
- // Note: [0] Ensure that the last block notated by gt > will be closed
2631
- lines.push('');
2632
- var currentCodeBlock = null;
2633
- try {
2634
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2635
- var line = lines_1_1.value;
2636
- if (line.startsWith('> ') || line === '>') {
2637
- if (currentCodeBlock === null) {
2638
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2639
- } /* not else */
2640
- if (currentCodeBlock.blockNotation === '>') {
2641
- if (currentCodeBlock.content !== '') {
2642
- currentCodeBlock.content += '\n';
2643
- }
2644
- currentCodeBlock.content += line.slice(2);
2645
- }
2646
- }
2647
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2648
- codeBlocks.push(currentCodeBlock);
2649
- currentCodeBlock = null;
2650
- }
2651
- /* not else */
2652
- if (line.startsWith('```')) {
2653
- var language = line.slice(3).trim() || null;
2654
- if (currentCodeBlock === null) {
2655
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2656
- }
2657
- else {
2658
- if (language !== null) {
2659
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2660
- }
2661
- codeBlocks.push(currentCodeBlock);
2662
- currentCodeBlock = null;
2663
- }
2664
- }
2665
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2666
- if (currentCodeBlock.content !== '') {
2667
- currentCodeBlock.content += '\n';
2668
- }
2669
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2670
- }
2671
- }
2672
- }
2673
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2674
- finally {
2675
- try {
2676
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2677
- }
2678
- finally { if (e_1) throw e_1.error; }
2515
+ function isPipelinePrepared(pipeline) {
2516
+ // Note: Ignoring `pipeline.preparations` @@@
2517
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2518
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2519
+ return false;
2679
2520
  }
2680
- if (currentCodeBlock !== null) {
2681
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2521
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2522
+ return false;
2682
2523
  }
2683
- return codeBlocks;
2524
+ /*
2525
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2526
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2527
+ > return false;
2528
+ > }
2529
+ */
2530
+ return true;
2684
2531
  }
2685
2532
  /**
2686
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2533
+ * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2534
+ * TODO: [🐠] Maybe base this on `makeValidator`
2535
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2536
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2537
+ * - [🏍] ? Is context in each template
2538
+ * - [♨] Are samples prepared
2539
+ * - [♨] Are templates prepared
2687
2540
  */
2688
2541
 
2689
2542
  /**
2690
- * Extracts extracts exactly one valid JSON code block
2691
- *
2692
- * - When given string is a valid JSON as it is, it just returns it
2693
- * - When there is no JSON code block the function throws a `ParseError`
2694
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2543
+ * Takes an item or an array of items and returns an array of items
2695
2544
  *
2696
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2697
- * Note: There are multiple simmilar function:
2698
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2699
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2700
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2701
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2545
+ * 1) Any item except array and undefined returns array with that one item (also null)
2546
+ * 2) Undefined returns empty array
2547
+ * 3) Array returns itself
2702
2548
  *
2703
- * @public exported from `@promptbook/markdown-utils`
2704
- * @throws {ParseError} if there is no valid JSON block in the markdown
2549
+ * @private internal utility
2705
2550
  */
2706
- function extractJsonBlock(markdown) {
2707
- if (isValidJsonString(markdown)) {
2708
- return markdown;
2551
+ function arrayableToArray(input) {
2552
+ if (input === undefined) {
2553
+ return [];
2709
2554
  }
2710
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2711
- var jsonBlocks = codeBlocks.filter(function (_a) {
2712
- var content = _a.content;
2713
- return isValidJsonString(content);
2714
- });
2715
- if (jsonBlocks.length === 0) {
2716
- throw new Error('There is no valid JSON block in the markdown');
2555
+ if (input instanceof Array) {
2556
+ return input;
2717
2557
  }
2718
- if (jsonBlocks.length > 1) {
2719
- throw new Error('There are multiple JSON code blocks in the markdown');
2558
+ return [input];
2559
+ }
2560
+
2561
+ /**
2562
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2563
+ *
2564
+ * @param script from which to extract the variables
2565
+ * @returns the list of variable names
2566
+ * @throws {ParseError} if the script is invalid
2567
+ * @public exported from `@promptbook/utils`
2568
+ */
2569
+ function extractVariables(script) {
2570
+ var variables = new Set();
2571
+ script = "(()=>{".concat(script, "})()");
2572
+ try {
2573
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2574
+ try {
2575
+ eval(script);
2576
+ }
2577
+ catch (error) {
2578
+ if (!(error instanceof ReferenceError)) {
2579
+ throw error;
2580
+ }
2581
+ var undefinedName = error.message.split(' ')[0];
2582
+ /*
2583
+ Note: Parsing the error
2584
+ [PipelineUrlError: thing is not defined]
2585
+ */
2586
+ if (!undefinedName) {
2587
+ throw error;
2588
+ }
2589
+ if (script.includes(undefinedName + '(')) {
2590
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2591
+ }
2592
+ else {
2593
+ variables.add(undefinedName);
2594
+ script = "const ".concat(undefinedName, " = '';") + script;
2595
+ }
2596
+ }
2720
2597
  }
2721
- return jsonBlocks[0].content;
2598
+ catch (error) {
2599
+ if (!(error instanceof Error)) {
2600
+ throw error;
2601
+ }
2602
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2603
+ }
2604
+ return variables;
2722
2605
  }
2723
2606
  /**
2724
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2725
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2607
+ * TODO: [🔣] Support for multiple languages - python, java,...
2726
2608
  */
2727
2609
 
2728
2610
  /**
2729
- * Determine if the pipeline is fully prepared
2611
+ * Parses the template and returns the set of all used parameters
2730
2612
  *
2731
- * @public exported from `@promptbook/core`
2613
+ * @param template the template with used parameters
2614
+ * @returns the set of parameter names
2615
+ * @throws {ParseError} if the script is invalid
2616
+ * @public exported from `@promptbook/utils`
2732
2617
  */
2733
- function isPipelinePrepared(pipeline) {
2734
- // Note: Ignoring `pipeline.preparations` @@@
2735
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2736
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2737
- return false;
2618
+ function extractParameterNamesFromTemplate(template) {
2619
+ var e_1, _a, e_2, _b, e_3, _c;
2620
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2621
+ var parameterNames = new Set();
2622
+ try {
2623
+ 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()) {
2624
+ var parameterName = _e.value;
2625
+ parameterNames.add(parameterName);
2626
+ }
2738
2627
  }
2739
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2628
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2629
+ finally {
2630
+ try {
2631
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2632
+ }
2633
+ finally { if (e_1) throw e_1.error; }
2634
+ }
2635
+ if (templateType === 'SCRIPT_TEMPLATE') {
2636
+ try {
2637
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2638
+ var parameterName = _g.value;
2639
+ parameterNames.add(parameterName);
2640
+ }
2641
+ }
2642
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2643
+ finally {
2644
+ try {
2645
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2646
+ }
2647
+ finally { if (e_2) throw e_2.error; }
2648
+ }
2649
+ }
2650
+ try {
2651
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2652
+ var jokerName = _j.value;
2653
+ parameterNames.add(jokerName);
2654
+ }
2655
+ }
2656
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2657
+ finally {
2658
+ try {
2659
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2660
+ }
2661
+ finally { if (e_3) throw e_3.error; }
2662
+ }
2663
+ parameterNames.delete('content');
2664
+ // <- Note {websiteContent} is used in `preparedContent`
2665
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2666
+ if (foreach !== undefined) {
2667
+ if (parameterNames.has(foreach.subparameterName)) {
2668
+ parameterNames.delete(foreach.subparameterName);
2669
+ parameterNames.add(foreach.parameterName);
2670
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2671
+ }
2672
+ }
2673
+ return parameterNames;
2674
+ }
2675
+ /**
2676
+ * TODO: [🔣] If script require contentLanguage
2677
+ */
2678
+
2679
+ /**
2680
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2681
+ *
2682
+ * @public exported from `@promptbook/utils`
2683
+ */
2684
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2685
+ try {
2686
+ JSON.parse(value);
2687
+ return true;
2688
+ }
2689
+ catch (error) {
2690
+ if (!(error instanceof Error)) {
2691
+ throw error;
2692
+ }
2693
+ if (error.message.includes('Unexpected token')) {
2694
+ return false;
2695
+ }
2740
2696
  return false;
2741
2697
  }
2742
- /*
2743
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2744
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2745
- > return false;
2746
- > }
2747
- */
2748
- return true;
2749
2698
  }
2699
+
2750
2700
  /**
2751
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2752
- * TODO: [🐠] Maybe base this on `makeValidator`
2753
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2754
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2755
- * - [🏍] ? Is context in each template
2756
- * - [♨] Are samples prepared
2757
- * - [♨] Are templates prepared
2701
+ * Extracts all code blocks from markdown.
2702
+ *
2703
+ * Note: There are multiple simmilar function:
2704
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2705
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2706
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2707
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2708
+ *
2709
+ * @param markdown any valid markdown
2710
+ * @returns code blocks with language and content
2711
+ * @throws {ParseError} if block is not closed properly
2712
+ * @public exported from `@promptbook/markdown-utils`
2713
+ */
2714
+ function extractAllBlocksFromMarkdown(markdown) {
2715
+ var e_1, _a;
2716
+ var codeBlocks = [];
2717
+ var lines = markdown.split('\n');
2718
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2719
+ lines.push('');
2720
+ var currentCodeBlock = null;
2721
+ try {
2722
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2723
+ var line = lines_1_1.value;
2724
+ if (line.startsWith('> ') || line === '>') {
2725
+ if (currentCodeBlock === null) {
2726
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2727
+ } /* not else */
2728
+ if (currentCodeBlock.blockNotation === '>') {
2729
+ if (currentCodeBlock.content !== '') {
2730
+ currentCodeBlock.content += '\n';
2731
+ }
2732
+ currentCodeBlock.content += line.slice(2);
2733
+ }
2734
+ }
2735
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2736
+ codeBlocks.push(currentCodeBlock);
2737
+ currentCodeBlock = null;
2738
+ }
2739
+ /* not else */
2740
+ if (line.startsWith('```')) {
2741
+ var language = line.slice(3).trim() || null;
2742
+ if (currentCodeBlock === null) {
2743
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2744
+ }
2745
+ else {
2746
+ if (language !== null) {
2747
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2748
+ }
2749
+ codeBlocks.push(currentCodeBlock);
2750
+ currentCodeBlock = null;
2751
+ }
2752
+ }
2753
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2754
+ if (currentCodeBlock.content !== '') {
2755
+ currentCodeBlock.content += '\n';
2756
+ }
2757
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2758
+ }
2759
+ }
2760
+ }
2761
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2762
+ finally {
2763
+ try {
2764
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2765
+ }
2766
+ finally { if (e_1) throw e_1.error; }
2767
+ }
2768
+ if (currentCodeBlock !== null) {
2769
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2770
+ }
2771
+ return codeBlocks;
2772
+ }
2773
+ /**
2774
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2758
2775
  */
2759
2776
 
2760
2777
  /**
2761
- * Takes an item or an array of items and returns an array of items
2778
+ * Extracts extracts exactly one valid JSON code block
2762
2779
  *
2763
- * 1) Any item except array and undefined returns array with that one item (also null)
2764
- * 2) Undefined returns empty array
2765
- * 3) Array returns itself
2780
+ * - When given string is a valid JSON as it is, it just returns it
2781
+ * - When there is no JSON code block the function throws a `ParseError`
2782
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
2766
2783
  *
2767
- * @private internal utility
2784
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
2785
+ * Note: There are multiple simmilar function:
2786
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2787
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2788
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2789
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2790
+ *
2791
+ * @public exported from `@promptbook/markdown-utils`
2792
+ * @throws {ParseError} if there is no valid JSON block in the markdown
2768
2793
  */
2769
- function arrayableToArray(input) {
2770
- if (input === undefined) {
2771
- return [];
2794
+ function extractJsonBlock(markdown) {
2795
+ if (isValidJsonString(markdown)) {
2796
+ return markdown;
2772
2797
  }
2773
- if (input instanceof Array) {
2774
- return input;
2798
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2799
+ var jsonBlocks = codeBlocks.filter(function (_a) {
2800
+ var content = _a.content;
2801
+ return isValidJsonString(content);
2802
+ });
2803
+ if (jsonBlocks.length === 0) {
2804
+ throw new Error('There is no valid JSON block in the markdown');
2775
2805
  }
2776
- return [input];
2806
+ if (jsonBlocks.length > 1) {
2807
+ throw new Error('There are multiple JSON code blocks in the markdown');
2808
+ }
2809
+ return jsonBlocks[0].content;
2777
2810
  }
2811
+ /**
2812
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2813
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2814
+ */
2778
2815
 
2779
2816
  /**
2780
2817
  * Just says that the variable is not used but should be kept
@@ -2797,23 +2834,6 @@ function keepUnused() {
2797
2834
  }
2798
2835
  }
2799
2836
 
2800
- /**
2801
- * Just marks a place of place where should be something implemented
2802
- * No side effects.
2803
- *
2804
- * Note: It can be usefull suppressing eslint errors of unused variables
2805
- *
2806
- * @param value any values
2807
- * @returns void
2808
- * @private within the repository
2809
- */
2810
- function TODO_USE() {
2811
- var value = [];
2812
- for (var _i = 0; _i < arguments.length; _i++) {
2813
- value[_i] = arguments[_i];
2814
- }
2815
- }
2816
-
2817
2837
  /**
2818
2838
  * Replaces parameters in template with values from parameters object
2819
2839
  *
@@ -3034,53 +3054,646 @@ function countSentences(text) {
3034
3054
  }
3035
3055
 
3036
3056
  /**
3037
- * Counts number of words in the text
3038
- *
3039
- * @public exported from `@promptbook/utils`
3057
+ * Counts number of words in the text
3058
+ *
3059
+ * @public exported from `@promptbook/utils`
3060
+ */
3061
+ function countWords(text) {
3062
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3063
+ text = removeDiacritics(text);
3064
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3065
+ }
3066
+
3067
+ /**
3068
+ * Index of all counter functions
3069
+ *
3070
+ * @public exported from `@promptbook/utils`
3071
+ */
3072
+ var CountUtils = {
3073
+ CHARACTERS: countCharacters,
3074
+ WORDS: countWords,
3075
+ SENTENCES: countSentences,
3076
+ PARAGRAPHS: countParagraphs,
3077
+ LINES: countLines,
3078
+ PAGES: countPages,
3079
+ };
3080
+
3081
+ /**
3082
+ * Function checkExpectations will check if the expectations on given value are met
3083
+ *
3084
+ * Note: There are two simmilar functions:
3085
+ * - `checkExpectations` which throws an error if the expectations are not met
3086
+ * - `isPassingExpectations` which returns a boolean
3087
+ *
3088
+ * @throws {ExpectError} if the expectations are not met
3089
+ * @returns {void} Nothing
3090
+ * @private internal function of `createPipelineExecutor`
3091
+ */
3092
+ function checkExpectations(expectations, value) {
3093
+ var e_1, _a;
3094
+ try {
3095
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3096
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3097
+ var amount = CountUtils[unit.toUpperCase()](value);
3098
+ if (min && amount < min) {
3099
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3100
+ } /* not else */
3101
+ if (max && amount > max) {
3102
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3103
+ }
3104
+ }
3105
+ }
3106
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3107
+ finally {
3108
+ try {
3109
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3110
+ }
3111
+ finally { if (e_1) throw e_1.error; }
3112
+ }
3113
+ }
3114
+ /**
3115
+ * TODO: [💝] Unite object for expecting amount and format
3116
+ */
3117
+
3118
+ /**
3119
+ * Just marks a place of place where should be something implemented
3120
+ * No side effects.
3121
+ *
3122
+ * Note: It can be usefull suppressing eslint errors of unused variables
3123
+ *
3124
+ * @param value any values
3125
+ * @returns void
3126
+ * @private within the repository
3127
+ */
3128
+ function TODO_USE() {
3129
+ var value = [];
3130
+ for (var _i = 0; _i < arguments.length; _i++) {
3131
+ value[_i] = arguments[_i];
3132
+ }
3133
+ }
3134
+
3135
+ /**
3136
+ * @private @@@
3137
+ */
3138
+ function getContextForTemplate(template) {
3139
+ return __awaiter(this, void 0, void 0, function () {
3140
+ return __generator(this, function (_a) {
3141
+ TODO_USE(template);
3142
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3143
+ });
3144
+ });
3145
+ }
3146
+
3147
+ /**
3148
+ * @private @@@
3149
+ */
3150
+ function getKnowledgeForTemplate(preparedPipeline, template) {
3151
+ return __awaiter(this, void 0, void 0, function () {
3152
+ return __generator(this, function (_a) {
3153
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3154
+ TODO_USE(template);
3155
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3156
+ var content = _a.content;
3157
+ return "- ".concat(content);
3158
+ }).join('\n')];
3159
+ });
3160
+ });
3161
+ }
3162
+
3163
+ /**
3164
+ * @private @@@
3165
+ */
3166
+ function getSamplesForTemplate(template) {
3167
+ return __awaiter(this, void 0, void 0, function () {
3168
+ return __generator(this, function (_a) {
3169
+ // TODO: [♨] Implement Better - use real index and keyword search
3170
+ TODO_USE(template);
3171
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3172
+ });
3173
+ });
3174
+ }
3175
+
3176
+ /**
3177
+ * @private @@@
3178
+ */
3179
+ function getReservedParametersForTemplate(preparedPipeline, template, pipelineIdentification) {
3180
+ return __awaiter(this, void 0, void 0, function () {
3181
+ var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3182
+ var e_1, _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(preparedPipeline, 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_1 = function (parameterName) {
3205
+ if (reservedParameters[parameterName] === undefined) {
3206
+ throw new UnexpectedError(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_1(parameterName);
3214
+ }
3215
+ }
3216
+ catch (e_1_1) { e_1 = { error: e_1_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_1) throw e_1.error; }
3222
+ }
3223
+ return [2 /*return*/, reservedParameters];
3224
+ }
3225
+ });
3226
+ });
3227
+ }
3228
+
3229
+ /**
3230
+ * @private @@@
3040
3231
  */
3041
- function countWords(text) {
3042
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3043
- text = removeDiacritics(text);
3044
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3232
+ function executeSingleTemplate(options) {
3233
+ return __awaiter(this, void 0, void 0, function () {
3234
+ var currentTemplate, preparedPipeline, parametersToPass, tools, llmTools, onProgress, maxExecutionAttempts, $executionReport, pipelineIdentification, name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_2, attempt, state_1;
3235
+ var e_1, _f, _g;
3236
+ return __generator(this, function (_h) {
3237
+ switch (_h.label) {
3238
+ case 0:
3239
+ currentTemplate = options.currentTemplate, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, llmTools = options.llmTools, onProgress = options.onProgress, maxExecutionAttempts = options.maxExecutionAttempts, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3240
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3241
+ title = currentTemplate.title;
3242
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3243
+ return [4 /*yield*/, onProgress({
3244
+ name: name,
3245
+ title: title,
3246
+ isStarted: false,
3247
+ isDone: false,
3248
+ templateType: currentTemplate.templateType,
3249
+ parameterName: currentTemplate.resultingParameterName,
3250
+ parameterValue: null,
3251
+ // <- [🍸]
3252
+ })];
3253
+ case 1:
3254
+ _h.sent();
3255
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3256
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3257
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3258
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3259
+ .map(function (name) { return "{".concat(name, "}"); })
3260
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3261
+ .map(function (name) { return "{".concat(name, "}"); })
3262
+ .join(', '), "\n\n "); }));
3263
+ }
3264
+ _b = (_a = Object).freeze;
3265
+ _c = [{}];
3266
+ return [4 /*yield*/, getReservedParametersForTemplate(preparedPipeline, currentTemplate, pipelineIdentification)];
3267
+ case 2:
3268
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3269
+ definedParameterNames = new Set(Object.keys(definedParameters));
3270
+ parameters = {};
3271
+ _loop_1 = function (parameterName) {
3272
+ // Situation: Parameter is defined and used
3273
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3274
+ parameters[parameterName] = definedParameters[parameterName];
3275
+ }
3276
+ // Situation: Parameter is defined but NOT used
3277
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3278
+ // Situation: Parameter is NOT defined BUT used
3279
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3280
+ // Houston, we have a problem
3281
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3282
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3283
+ }
3284
+ };
3285
+ try {
3286
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3287
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3288
+ parameterName = _e.value;
3289
+ _loop_1(parameterName);
3290
+ }
3291
+ }
3292
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3293
+ finally {
3294
+ try {
3295
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3296
+ }
3297
+ finally { if (e_1) throw e_1.error; }
3298
+ }
3299
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3300
+ Object.freeze(parameters);
3301
+ result = null;
3302
+ resultString = null;
3303
+ expectError = null;
3304
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3305
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3306
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3307
+ .split('{content}')
3308
+ .join(currentTemplate.content);
3309
+ _loop_2 = function (attempt) {
3310
+ var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_1, e_2_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_2, e_3_1, e_4_1, error_3;
3311
+ var e_2, _s, e_4, _t, e_3, _u;
3312
+ return __generator(this, function (_v) {
3313
+ switch (_v.label) {
3314
+ case 0:
3315
+ isJokerAttempt = attempt < 0;
3316
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3317
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3318
+ if (isJokerAttempt && !jokerParameterName) {
3319
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3320
+ }
3321
+ result = null;
3322
+ resultString = null;
3323
+ expectError = null;
3324
+ if (isJokerAttempt) {
3325
+ if (parameters[jokerParameterName] === undefined) {
3326
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3327
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3328
+ }
3329
+ else {
3330
+ resultString = parameters[jokerParameterName];
3331
+ }
3332
+ }
3333
+ _v.label = 1;
3334
+ case 1:
3335
+ _v.trys.push([1, 44, 45, 46]);
3336
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3337
+ _j = currentTemplate.templateType;
3338
+ switch (_j) {
3339
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3340
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3341
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3342
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3343
+ }
3344
+ return [3 /*break*/, 25];
3345
+ case 2:
3346
+ resultString = replaceParameters(preparedContent, parameters);
3347
+ return [3 /*break*/, 26];
3348
+ case 3:
3349
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3350
+ prompt = {
3351
+ title: currentTemplate.title,
3352
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3353
+ ? preparedPipeline.pipelineUrl
3354
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3355
+ parameters: parameters,
3356
+ content: preparedContent,
3357
+ modelRequirements: modelRequirements,
3358
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3359
+ var name = _a.name;
3360
+ return name === currentTemplate.personaName;
3361
+ }) || {})), currentTemplate.expectations),
3362
+ format: currentTemplate.format,
3363
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3364
+ }; // <- TODO: Not very good type guard
3365
+ _k = modelRequirements.modelVariant;
3366
+ switch (_k) {
3367
+ case 'CHAT': return [3 /*break*/, 4];
3368
+ case 'COMPLETION': return [3 /*break*/, 6];
3369
+ case 'EMBEDDING': return [3 /*break*/, 8];
3370
+ }
3371
+ return [3 /*break*/, 10];
3372
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3373
+ case 5:
3374
+ chatResult = _v.sent();
3375
+ // TODO: [🍬] Destroy chatThread
3376
+ result = chatResult;
3377
+ resultString = chatResult.content;
3378
+ return [3 /*break*/, 11];
3379
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3380
+ case 7:
3381
+ completionResult = _v.sent();
3382
+ result = completionResult;
3383
+ resultString = completionResult.content;
3384
+ return [3 /*break*/, 11];
3385
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3386
+ case 9:
3387
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3388
+ embeddingResult = _v.sent();
3389
+ result = embeddingResult;
3390
+ resultString = embeddingResult.content.join(',');
3391
+ return [3 /*break*/, 11];
3392
+ case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3393
+ case 11: return [3 /*break*/, 26];
3394
+ case 12:
3395
+ if (arrayableToArray(tools.script).length === 0) {
3396
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3397
+ }
3398
+ if (!currentTemplate.contentLanguage) {
3399
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3400
+ }
3401
+ // TODO: DRY [1]
3402
+ scriptPipelineExecutionErrors = [];
3403
+ _v.label = 13;
3404
+ case 13:
3405
+ _v.trys.push([13, 20, 21, 22]);
3406
+ _l = (e_2 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3407
+ _v.label = 14;
3408
+ case 14:
3409
+ if (!!_m.done) return [3 /*break*/, 19];
3410
+ scriptTools = _m.value;
3411
+ _v.label = 15;
3412
+ case 15:
3413
+ _v.trys.push([15, 17, , 18]);
3414
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3415
+ scriptLanguage: currentTemplate.contentLanguage,
3416
+ script: preparedContent,
3417
+ parameters: parameters,
3418
+ }))];
3419
+ case 16:
3420
+ resultString = _v.sent();
3421
+ return [3 /*break*/, 19];
3422
+ case 17:
3423
+ error_1 = _v.sent();
3424
+ if (!(error_1 instanceof Error)) {
3425
+ throw error_1;
3426
+ }
3427
+ if (error_1 instanceof UnexpectedError) {
3428
+ throw error_1;
3429
+ }
3430
+ scriptPipelineExecutionErrors.push(error_1);
3431
+ return [3 /*break*/, 18];
3432
+ case 18:
3433
+ _m = _l.next();
3434
+ return [3 /*break*/, 14];
3435
+ case 19: return [3 /*break*/, 22];
3436
+ case 20:
3437
+ e_2_1 = _v.sent();
3438
+ e_2 = { error: e_2_1 };
3439
+ return [3 /*break*/, 22];
3440
+ case 21:
3441
+ try {
3442
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3443
+ }
3444
+ finally { if (e_2) throw e_2.error; }
3445
+ return [7 /*endfinally*/];
3446
+ case 22:
3447
+ if (resultString !== null) {
3448
+ return [3 /*break*/, 26];
3449
+ }
3450
+ if (scriptPipelineExecutionErrors.length === 1) {
3451
+ throw scriptPipelineExecutionErrors[0];
3452
+ }
3453
+ else {
3454
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3455
+ .map(function (error) { return '- ' + error.message; })
3456
+ .join('\n\n')), "\n "); }));
3457
+ }
3458
+ case 23:
3459
+ if (tools.userInterface === undefined) {
3460
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3461
+ }
3462
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3463
+ promptTitle: currentTemplate.title,
3464
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3465
+ defaultValue: replaceParameters(preparedContent, parameters),
3466
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3467
+ placeholder: undefined,
3468
+ priority: priority,
3469
+ }))];
3470
+ case 24:
3471
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3472
+ resultString = _v.sent();
3473
+ return [3 /*break*/, 26];
3474
+ case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3475
+ case 26:
3476
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3477
+ _v.label = 27;
3478
+ case 27:
3479
+ _v.trys.push([27, 41, 42, 43]);
3480
+ _o = (e_4 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3481
+ _v.label = 28;
3482
+ case 28:
3483
+ if (!!_p.done) return [3 /*break*/, 40];
3484
+ functionName = _p.value;
3485
+ // TODO: DRY [1]
3486
+ scriptPipelineExecutionErrors = [];
3487
+ postprocessingError = null;
3488
+ _v.label = 29;
3489
+ case 29:
3490
+ _v.trys.push([29, 36, 37, 38]);
3491
+ _q = (e_3 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3492
+ _v.label = 30;
3493
+ case 30:
3494
+ if (!!_r.done) return [3 /*break*/, 35];
3495
+ scriptTools = _r.value;
3496
+ _v.label = 31;
3497
+ case 31:
3498
+ _v.trys.push([31, 33, , 34]);
3499
+ return [4 /*yield*/, scriptTools.execute({
3500
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3501
+ script: "".concat(functionName, "(resultString)"),
3502
+ parameters: {
3503
+ resultString: resultString || '',
3504
+ // Note: No ...parametersForTemplate, because working with result only
3505
+ },
3506
+ })];
3507
+ case 32:
3508
+ resultString = _v.sent();
3509
+ postprocessingError = null;
3510
+ return [3 /*break*/, 35];
3511
+ case 33:
3512
+ error_2 = _v.sent();
3513
+ if (!(error_2 instanceof Error)) {
3514
+ throw error_2;
3515
+ }
3516
+ if (error_2 instanceof UnexpectedError) {
3517
+ throw error_2;
3518
+ }
3519
+ postprocessingError = error_2;
3520
+ scriptPipelineExecutionErrors.push(error_2);
3521
+ return [3 /*break*/, 34];
3522
+ case 34:
3523
+ _r = _q.next();
3524
+ return [3 /*break*/, 30];
3525
+ case 35: return [3 /*break*/, 38];
3526
+ case 36:
3527
+ e_3_1 = _v.sent();
3528
+ e_3 = { error: e_3_1 };
3529
+ return [3 /*break*/, 38];
3530
+ case 37:
3531
+ try {
3532
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3533
+ }
3534
+ finally { if (e_3) throw e_3.error; }
3535
+ return [7 /*endfinally*/];
3536
+ case 38:
3537
+ if (postprocessingError) {
3538
+ throw postprocessingError;
3539
+ }
3540
+ _v.label = 39;
3541
+ case 39:
3542
+ _p = _o.next();
3543
+ return [3 /*break*/, 28];
3544
+ case 40: return [3 /*break*/, 43];
3545
+ case 41:
3546
+ e_4_1 = _v.sent();
3547
+ e_4 = { error: e_4_1 };
3548
+ return [3 /*break*/, 43];
3549
+ case 42:
3550
+ try {
3551
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3552
+ }
3553
+ finally { if (e_4) throw e_4.error; }
3554
+ return [7 /*endfinally*/];
3555
+ case 43:
3556
+ // TODO: [💝] Unite object for expecting amount and format
3557
+ if (currentTemplate.format) {
3558
+ if (currentTemplate.format === 'JSON') {
3559
+ if (!isValidJsonString(resultString || '')) {
3560
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3561
+ try {
3562
+ resultString = extractJsonBlock(resultString || '');
3563
+ }
3564
+ catch (error) {
3565
+ keepUnused(error);
3566
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3567
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3568
+ }
3569
+ }
3570
+ }
3571
+ else {
3572
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3573
+ }
3574
+ }
3575
+ // TODO: [💝] Unite object for expecting amount and format
3576
+ if (currentTemplate.expectations) {
3577
+ checkExpectations(currentTemplate.expectations, resultString || '');
3578
+ }
3579
+ return [2 /*return*/, "break-attempts"];
3580
+ case 44:
3581
+ error_3 = _v.sent();
3582
+ if (!(error_3 instanceof ExpectError)) {
3583
+ throw error_3;
3584
+ }
3585
+ expectError = error_3;
3586
+ return [3 /*break*/, 46];
3587
+ case 45:
3588
+ if (!isJokerAttempt &&
3589
+ currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3590
+ prompt
3591
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3592
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3593
+ ) {
3594
+ // TODO: [🧠] Maybe put other templateTypes into report
3595
+ $executionReport.promptExecutions.push({
3596
+ prompt: __assign({}, prompt),
3597
+ result: result || undefined,
3598
+ error: expectError === null ? undefined : serializeError(expectError),
3599
+ });
3600
+ }
3601
+ return [7 /*endfinally*/];
3602
+ case 46:
3603
+ if (expectError !== null && attempt === maxAttempts - 1) {
3604
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3605
+ .split('\n')
3606
+ .map(function (line) { return "> ".concat(line); })
3607
+ .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) || '')
3608
+ .split('\n')
3609
+ .map(function (line) { return "> ".concat(line); })
3610
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3611
+ ? 'null'
3612
+ : resultString
3613
+ .split('\n')
3614
+ .map(function (line) { return "> ".concat(line); })
3615
+ .join('\n')), "\n ---\n "); }));
3616
+ }
3617
+ return [2 /*return*/];
3618
+ }
3619
+ });
3620
+ };
3621
+ attempt = -jokerParameterNames.length;
3622
+ _h.label = 3;
3623
+ case 3:
3624
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 6];
3625
+ return [5 /*yield**/, _loop_2(attempt)];
3626
+ case 4:
3627
+ state_1 = _h.sent();
3628
+ switch (state_1) {
3629
+ case "break-attempts": return [3 /*break*/, 6];
3630
+ }
3631
+ _h.label = 5;
3632
+ case 5:
3633
+ attempt++;
3634
+ return [3 /*break*/, 3];
3635
+ case 6:
3636
+ //------------------------------------
3637
+ /*
3638
+
3639
+
3640
+
3641
+
3642
+
3643
+
3644
+
3645
+
3646
+
3647
+ */
3648
+ //------------------------------------
3649
+ if (resultString === null) {
3650
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3651
+ }
3652
+ return [4 /*yield*/, onProgress({
3653
+ name: name,
3654
+ title: title,
3655
+ isStarted: true,
3656
+ isDone: true,
3657
+ templateType: currentTemplate.templateType,
3658
+ parameterName: currentTemplate.resultingParameterName,
3659
+ parameterValue: resultString,
3660
+ // <- [🍸]
3661
+ })];
3662
+ case 7:
3663
+ _h.sent();
3664
+ return [2 /*return*/, Object.freeze((_g = {},
3665
+ _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */,
3666
+ _g))];
3667
+ }
3668
+ });
3669
+ });
3045
3670
  }
3046
-
3047
3671
  /**
3048
- * Index of all counter functions
3049
- *
3050
- * @public exported from `@promptbook/utils`
3672
+ * TODO: [🤹‍♂️]
3051
3673
  */
3052
- var CountUtils = {
3053
- CHARACTERS: countCharacters,
3054
- WORDS: countWords,
3055
- SENTENCES: countSentences,
3056
- PARAGRAPHS: countParagraphs,
3057
- LINES: countLines,
3058
- PAGES: countPages,
3059
- };
3060
3674
 
3061
3675
  /**
3062
- * Function checkExpectations will check if the expectations on given value are met
3063
- *
3064
- * Note: There are two simmilar functions:
3065
- * - `checkExpectations` which throws an error if the expectations are not met
3066
- * - `isPassingExpectations` which returns a boolean
3067
- *
3068
- * @throws {ExpectError} if the expectations are not met
3069
- * @returns {void} Nothing
3070
- * @private internal function of `createPipelineExecutor`
3676
+ * @private @@@
3071
3677
  */
3072
- function checkExpectations(expectations, value) {
3678
+ function filterJustOutputParameters(preparedPipeline, parametersToPass, $warnings, pipelineIdentification) {
3073
3679
  var e_1, _a;
3680
+ var outputParameters = {};
3681
+ var _loop_1 = function (parameter) {
3682
+ if (parametersToPass[parameter.name] === undefined) {
3683
+ // [4]
3684
+ $warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3685
+ return "continue";
3686
+ }
3687
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3688
+ };
3074
3689
  try {
3075
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3076
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3077
- var amount = CountUtils[unit.toUpperCase()](value);
3078
- if (min && amount < min) {
3079
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3080
- } /* not else */
3081
- if (max && amount > max) {
3082
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3083
- }
3690
+ // Note: Filter ONLY output parameters
3691
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3692
+ var isOutput = _a.isOutput;
3693
+ return isOutput;
3694
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
3695
+ var parameter = _c.value;
3696
+ _loop_1(parameter);
3084
3697
  }
3085
3698
  }
3086
3699
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3090,10 +3703,8 @@ function checkExpectations(expectations, value) {
3090
3703
  }
3091
3704
  finally { if (e_1) throw e_1.error; }
3092
3705
  }
3706
+ return outputParameters;
3093
3707
  }
3094
- /**
3095
- * TODO: [💝] Unite object for expecting amount and format
3096
- */
3097
3708
 
3098
3709
  /**
3099
3710
  * Creates executor function from pipeline and execution tools.
@@ -3127,558 +3738,6 @@ function createPipelineExecutor(options) {
3127
3738
  console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3128
3739
  }
3129
3740
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3130
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3131
- function getContextForTemplate(template) {
3132
- return __awaiter(this, void 0, void 0, function () {
3133
- return __generator(this, function (_a) {
3134
- TODO_USE(template);
3135
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3136
- });
3137
- });
3138
- }
3139
- function getKnowledgeForTemplate(template) {
3140
- return __awaiter(this, void 0, void 0, function () {
3141
- return __generator(this, function (_a) {
3142
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3143
- TODO_USE(template);
3144
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3145
- var content = _a.content;
3146
- return "- ".concat(content);
3147
- }).join('\n')];
3148
- });
3149
- });
3150
- }
3151
- function getSamplesForTemplate(template) {
3152
- return __awaiter(this, void 0, void 0, function () {
3153
- return __generator(this, function (_a) {
3154
- // TODO: [♨] Implement Better - use real index and keyword search
3155
- TODO_USE(template);
3156
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3157
- });
3158
- });
3159
- }
3160
- function getReservedParametersForTemplate(template) {
3161
- return __awaiter(this, void 0, void 0, function () {
3162
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3163
- var e_3, _a;
3164
- return __generator(this, function (_b) {
3165
- switch (_b.label) {
3166
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3167
- case 1:
3168
- context = _b.sent();
3169
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3170
- case 2:
3171
- knowledge = _b.sent();
3172
- return [4 /*yield*/, getSamplesForTemplate(template)];
3173
- case 3:
3174
- samples = _b.sent();
3175
- currentDate = new Date().toISOString();
3176
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3177
- reservedParameters = {
3178
- content: RESERVED_PARAMETER_RESTRICTED,
3179
- context: context,
3180
- knowledge: knowledge,
3181
- samples: samples,
3182
- currentDate: currentDate,
3183
- modelName: modelName,
3184
- };
3185
- _loop_3 = function (parameterName) {
3186
- if (reservedParameters[parameterName] === undefined) {
3187
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3188
- }
3189
- };
3190
- try {
3191
- // Note: Doublecheck that ALL reserved parameters are defined:
3192
- for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3193
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3194
- _loop_3(parameterName);
3195
- }
3196
- }
3197
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3198
- finally {
3199
- try {
3200
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3201
- }
3202
- finally { if (e_3) throw e_3.error; }
3203
- }
3204
- return [2 /*return*/, reservedParameters];
3205
- }
3206
- });
3207
- });
3208
- }
3209
- function executeSingleTemplate(currentTemplate) {
3210
- return __awaiter(this, void 0, void 0, function () {
3211
- var name, title, priority, progress_1, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_4, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_5, attempt, state_2, progress_2;
3212
- var e_4, _f, _g;
3213
- return __generator(this, function (_h) {
3214
- switch (_h.label) {
3215
- case 0:
3216
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3217
- title = currentTemplate.title;
3218
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3219
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3220
- progress_1 = {
3221
- name: name,
3222
- title: title,
3223
- isStarted: false,
3224
- isDone: false,
3225
- templateType: currentTemplate.templateType,
3226
- parameterName: currentTemplate.resultingParameterName,
3227
- parameterValue: null,
3228
- // <- [3]
3229
- };
3230
- if (isReturned) {
3231
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3232
- .split('\n')
3233
- .map(function (line) { return "> ".concat(line); })
3234
- .join('\n')), "\n "); }));
3235
- }
3236
- return [4 /*yield*/, onProgress(progress_1)];
3237
- case 1:
3238
- _h.sent();
3239
- _h.label = 2;
3240
- case 2:
3241
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3242
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3243
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3244
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3245
- .map(function (name) { return "{".concat(name, "}"); })
3246
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3247
- .map(function (name) { return "{".concat(name, "}"); })
3248
- .join(', '), "\n\n "); }));
3249
- }
3250
- _b = (_a = Object).freeze;
3251
- _c = [{}];
3252
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3253
- case 3:
3254
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3255
- definedParameterNames = new Set(Object.keys(definedParameters));
3256
- parameters = {};
3257
- _loop_4 = function (parameterName) {
3258
- // Situation: Parameter is defined and used
3259
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3260
- parameters[parameterName] = definedParameters[parameterName];
3261
- }
3262
- // Situation: Parameter is defined but NOT used
3263
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3264
- // Situation: Parameter is NOT defined BUT used
3265
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3266
- // Houston, we have a problem
3267
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3268
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3269
- }
3270
- };
3271
- try {
3272
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3273
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3274
- parameterName = _e.value;
3275
- _loop_4(parameterName);
3276
- }
3277
- }
3278
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3279
- finally {
3280
- try {
3281
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3282
- }
3283
- finally { if (e_4) throw e_4.error; }
3284
- }
3285
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3286
- Object.freeze(parameters);
3287
- result = null;
3288
- resultString = null;
3289
- expectError = null;
3290
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3291
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3292
- preparedContent = (currentTemplate.preparedContent || '{content}')
3293
- .split('{content}')
3294
- .join(currentTemplate.content);
3295
- _loop_5 = function (attempt) {
3296
- var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_2, e_5_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_3, e_6_1, e_7_1, error_4;
3297
- var e_5, _s, e_7, _t, e_6, _u;
3298
- return __generator(this, function (_v) {
3299
- switch (_v.label) {
3300
- case 0:
3301
- isJokerAttempt = attempt < 0;
3302
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3303
- if (isJokerAttempt && !jokerParameterName) {
3304
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3305
- }
3306
- result = null;
3307
- resultString = null;
3308
- expectError = null;
3309
- if (isJokerAttempt) {
3310
- if (parameters[jokerParameterName] === undefined) {
3311
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3312
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3313
- }
3314
- else {
3315
- resultString = parameters[jokerParameterName];
3316
- }
3317
- }
3318
- _v.label = 1;
3319
- case 1:
3320
- _v.trys.push([1, 44, 45, 46]);
3321
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3322
- _j = currentTemplate.templateType;
3323
- switch (_j) {
3324
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3325
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3326
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3327
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3328
- }
3329
- return [3 /*break*/, 25];
3330
- case 2:
3331
- resultString = replaceParameters(preparedContent, parameters);
3332
- return [3 /*break*/, 26];
3333
- case 3:
3334
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3335
- prompt = {
3336
- title: currentTemplate.title,
3337
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3338
- ? preparedPipeline.pipelineUrl
3339
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3340
- parameters: parameters,
3341
- content: preparedContent,
3342
- modelRequirements: modelRequirements,
3343
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3344
- var name = _a.name;
3345
- return name === currentTemplate.personaName;
3346
- }) || {})), currentTemplate.expectations),
3347
- format: currentTemplate.format,
3348
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3349
- }; // <- TODO: Not very good type guard
3350
- _k = modelRequirements.modelVariant;
3351
- switch (_k) {
3352
- case 'CHAT': return [3 /*break*/, 4];
3353
- case 'COMPLETION': return [3 /*break*/, 6];
3354
- case 'EMBEDDING': return [3 /*break*/, 8];
3355
- }
3356
- return [3 /*break*/, 10];
3357
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3358
- case 5:
3359
- chatResult = _v.sent();
3360
- // TODO: [🍬] Destroy chatThread
3361
- result = chatResult;
3362
- resultString = chatResult.content;
3363
- return [3 /*break*/, 11];
3364
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3365
- case 7:
3366
- completionResult = _v.sent();
3367
- result = completionResult;
3368
- resultString = completionResult.content;
3369
- return [3 /*break*/, 11];
3370
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3371
- case 9:
3372
- embeddingResult = _v.sent();
3373
- result = embeddingResult;
3374
- resultString = embeddingResult.content.join(',');
3375
- return [3 /*break*/, 11];
3376
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3377
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3378
- case 11: return [3 /*break*/, 26];
3379
- case 12:
3380
- if (arrayableToArray(tools.script).length === 0) {
3381
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3382
- }
3383
- if (!currentTemplate.contentLanguage) {
3384
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3385
- }
3386
- // TODO: DRY [1]
3387
- scriptPipelineExecutionErrors = [];
3388
- _v.label = 13;
3389
- case 13:
3390
- _v.trys.push([13, 20, 21, 22]);
3391
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3392
- _v.label = 14;
3393
- case 14:
3394
- if (!!_m.done) return [3 /*break*/, 19];
3395
- scriptTools = _m.value;
3396
- _v.label = 15;
3397
- case 15:
3398
- _v.trys.push([15, 17, , 18]);
3399
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3400
- scriptLanguage: currentTemplate.contentLanguage,
3401
- script: preparedContent,
3402
- parameters: parameters,
3403
- }))];
3404
- case 16:
3405
- resultString = _v.sent();
3406
- return [3 /*break*/, 19];
3407
- case 17:
3408
- error_2 = _v.sent();
3409
- if (!(error_2 instanceof Error)) {
3410
- throw error_2;
3411
- }
3412
- if (error_2 instanceof UnexpectedError) {
3413
- throw error_2;
3414
- }
3415
- scriptPipelineExecutionErrors.push(error_2);
3416
- return [3 /*break*/, 18];
3417
- case 18:
3418
- _m = _l.next();
3419
- return [3 /*break*/, 14];
3420
- case 19: return [3 /*break*/, 22];
3421
- case 20:
3422
- e_5_1 = _v.sent();
3423
- e_5 = { error: e_5_1 };
3424
- return [3 /*break*/, 22];
3425
- case 21:
3426
- try {
3427
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3428
- }
3429
- finally { if (e_5) throw e_5.error; }
3430
- return [7 /*endfinally*/];
3431
- case 22:
3432
- if (resultString !== null) {
3433
- return [3 /*break*/, 26];
3434
- }
3435
- if (scriptPipelineExecutionErrors.length === 1) {
3436
- throw scriptPipelineExecutionErrors[0];
3437
- }
3438
- else {
3439
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3440
- .map(function (error) { return '- ' + error.message; })
3441
- .join('\n\n')), "\n "); }));
3442
- }
3443
- case 23:
3444
- if (tools.userInterface === undefined) {
3445
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3446
- }
3447
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3448
- promptTitle: currentTemplate.title,
3449
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3450
- defaultValue: replaceParameters(preparedContent, parameters),
3451
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3452
- placeholder: undefined,
3453
- priority: priority,
3454
- }))];
3455
- case 24:
3456
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3457
- resultString = _v.sent();
3458
- return [3 /*break*/, 26];
3459
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3460
- case 26:
3461
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3462
- _v.label = 27;
3463
- case 27:
3464
- _v.trys.push([27, 41, 42, 43]);
3465
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3466
- _v.label = 28;
3467
- case 28:
3468
- if (!!_p.done) return [3 /*break*/, 40];
3469
- functionName = _p.value;
3470
- // TODO: DRY [1]
3471
- scriptPipelineExecutionErrors = [];
3472
- postprocessingError = null;
3473
- _v.label = 29;
3474
- case 29:
3475
- _v.trys.push([29, 36, 37, 38]);
3476
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3477
- _v.label = 30;
3478
- case 30:
3479
- if (!!_r.done) return [3 /*break*/, 35];
3480
- scriptTools = _r.value;
3481
- _v.label = 31;
3482
- case 31:
3483
- _v.trys.push([31, 33, , 34]);
3484
- return [4 /*yield*/, scriptTools.execute({
3485
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3486
- script: "".concat(functionName, "(resultString)"),
3487
- parameters: {
3488
- resultString: resultString || '',
3489
- // Note: No ...parametersForTemplate, because working with result only
3490
- },
3491
- })];
3492
- case 32:
3493
- resultString = _v.sent();
3494
- postprocessingError = null;
3495
- return [3 /*break*/, 35];
3496
- case 33:
3497
- error_3 = _v.sent();
3498
- if (!(error_3 instanceof Error)) {
3499
- throw error_3;
3500
- }
3501
- if (error_3 instanceof UnexpectedError) {
3502
- throw error_3;
3503
- }
3504
- postprocessingError = error_3;
3505
- scriptPipelineExecutionErrors.push(error_3);
3506
- return [3 /*break*/, 34];
3507
- case 34:
3508
- _r = _q.next();
3509
- return [3 /*break*/, 30];
3510
- case 35: return [3 /*break*/, 38];
3511
- case 36:
3512
- e_6_1 = _v.sent();
3513
- e_6 = { error: e_6_1 };
3514
- return [3 /*break*/, 38];
3515
- case 37:
3516
- try {
3517
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3518
- }
3519
- finally { if (e_6) throw e_6.error; }
3520
- return [7 /*endfinally*/];
3521
- case 38:
3522
- if (postprocessingError) {
3523
- throw postprocessingError;
3524
- }
3525
- _v.label = 39;
3526
- case 39:
3527
- _p = _o.next();
3528
- return [3 /*break*/, 28];
3529
- case 40: return [3 /*break*/, 43];
3530
- case 41:
3531
- e_7_1 = _v.sent();
3532
- e_7 = { error: e_7_1 };
3533
- return [3 /*break*/, 43];
3534
- case 42:
3535
- try {
3536
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3537
- }
3538
- finally { if (e_7) throw e_7.error; }
3539
- return [7 /*endfinally*/];
3540
- case 43:
3541
- // TODO: [💝] Unite object for expecting amount and format
3542
- if (currentTemplate.format) {
3543
- if (currentTemplate.format === 'JSON') {
3544
- if (!isValidJsonString(resultString || '')) {
3545
- // TODO: [🏢] Do more universally via `FormatDefinition`
3546
- try {
3547
- resultString = extractJsonBlock(resultString || '');
3548
- }
3549
- catch (error) {
3550
- keepUnused(error);
3551
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3552
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3553
- }
3554
- }
3555
- }
3556
- else {
3557
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3558
- }
3559
- }
3560
- // TODO: [💝] Unite object for expecting amount and format
3561
- if (currentTemplate.expectations) {
3562
- checkExpectations(currentTemplate.expectations, resultString || '');
3563
- }
3564
- return [2 /*return*/, "break-attempts"];
3565
- case 44:
3566
- error_4 = _v.sent();
3567
- if (!(error_4 instanceof ExpectError)) {
3568
- throw error_4;
3569
- }
3570
- expectError = error_4;
3571
- return [3 /*break*/, 46];
3572
- case 45:
3573
- if (!isJokerAttempt &&
3574
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3575
- prompt
3576
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3577
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3578
- ) {
3579
- // TODO: [🧠] Maybe put other templateTypes into report
3580
- executionReport.promptExecutions.push({
3581
- prompt: __assign({}, prompt),
3582
- result: result || undefined,
3583
- error: expectError === null ? undefined : serializeError(expectError),
3584
- });
3585
- }
3586
- return [7 /*endfinally*/];
3587
- case 46:
3588
- if (expectError !== null && attempt === maxAttempts - 1) {
3589
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3590
- .split('\n')
3591
- .map(function (line) { return "> ".concat(line); })
3592
- .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3593
- .split('\n')
3594
- .map(function (line) { return "> ".concat(line); })
3595
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3596
- ? 'null'
3597
- : resultString
3598
- .split('\n')
3599
- .map(function (line) { return "> ".concat(line); })
3600
- .join('\n')), "\n ---\n "); }));
3601
- }
3602
- return [2 /*return*/];
3603
- }
3604
- });
3605
- };
3606
- attempt = -jokerParameterNames.length;
3607
- _h.label = 4;
3608
- case 4:
3609
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3610
- return [5 /*yield**/, _loop_5(attempt)];
3611
- case 5:
3612
- state_2 = _h.sent();
3613
- switch (state_2) {
3614
- case "break-attempts": return [3 /*break*/, 7];
3615
- }
3616
- _h.label = 6;
3617
- case 6:
3618
- attempt++;
3619
- return [3 /*break*/, 4];
3620
- case 7:
3621
- if (resultString === null) {
3622
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3623
- }
3624
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3625
- progress_2 = {
3626
- name: name,
3627
- title: title,
3628
- isStarted: true,
3629
- isDone: true,
3630
- templateType: currentTemplate.templateType,
3631
- parameterName: currentTemplate.resultingParameterName,
3632
- parameterValue: resultString,
3633
- // <- [3]
3634
- };
3635
- if (isReturned) {
3636
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3637
- .split('\n')
3638
- .map(function (line) { return "> ".concat(line); })
3639
- .join('\n')), "\n\n "); }));
3640
- }
3641
- return [4 /*yield*/, onProgress(progress_2)];
3642
- case 8:
3643
- _h.sent();
3644
- _h.label = 9;
3645
- case 9:
3646
- parametersToPass = Object.freeze(__assign(__assign({}, parametersToPass), (_g = {}, _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _g)));
3647
- return [2 /*return*/];
3648
- }
3649
- });
3650
- });
3651
- }
3652
- function filterJustOutputParameters() {
3653
- var e_8, _a;
3654
- var outputParameters = {};
3655
- var _loop_6 = function (parameter) {
3656
- if (parametersToPass[parameter.name] === undefined) {
3657
- // [4]
3658
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3659
- return "continue";
3660
- }
3661
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3662
- };
3663
- try {
3664
- // Note: Filter ONLY output parameters
3665
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3666
- var isOutput = _a.isOutput;
3667
- return isOutput;
3668
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3669
- var parameter = _c.value;
3670
- _loop_6(parameter);
3671
- }
3672
- }
3673
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3674
- finally {
3675
- try {
3676
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3677
- }
3678
- finally { if (e_8) throw e_8.error; }
3679
- }
3680
- return outputParameters;
3681
- }
3682
3741
  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;
3683
3742
  var e_1, _e, e_2, _f;
3684
3743
  return __generator(this, function (_g) {
@@ -3860,14 +3919,35 @@ function createPipelineExecutor(options) {
3860
3919
  .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
3861
3920
  case 1:
3862
3921
  if (!!currentTemplate) return [3 /*break*/, 3];
3863
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
3922
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3864
3923
  case 2:
3865
- /* [5] */ _j.sent();
3924
+ /* [🤹‍♂️] */ _j.sent();
3866
3925
  return [3 /*break*/, 4];
3867
3926
  case 3:
3868
3927
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3869
- work_1 = executeSingleTemplate(currentTemplate)
3870
- .then(function () {
3928
+ work_1 = executeSingleTemplate({
3929
+ currentTemplate: currentTemplate,
3930
+ preparedPipeline: preparedPipeline,
3931
+ parametersToPass: parametersToPass,
3932
+ tools: tools,
3933
+ llmTools: llmTools,
3934
+ onProgress: function (progress) {
3935
+ if (isReturned) {
3936
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
3937
+ .split('\n')
3938
+ .map(function (line) { return "> ".concat(line); })
3939
+ .join('\n')), "\n "); }));
3940
+ }
3941
+ if (onProgress) {
3942
+ onProgress(progress);
3943
+ }
3944
+ },
3945
+ maxExecutionAttempts: maxExecutionAttempts,
3946
+ $executionReport: executionReport,
3947
+ pipelineIdentification: pipelineIdentification,
3948
+ })
3949
+ .then(function (newParametersToPass) {
3950
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3871
3951
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3872
3952
  })
3873
3953
  .then(function () {
@@ -3899,7 +3979,7 @@ function createPipelineExecutor(options) {
3899
3979
  var result = _a.result;
3900
3980
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3901
3981
  })), false));
3902
- outputParameters_1 = filterJustOutputParameters();
3982
+ outputParameters_1 = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
3903
3983
  isReturned = true;
3904
3984
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3905
3985
  // Note: Wait a short time to prevent race conditions
@@ -3922,7 +4002,7 @@ function createPipelineExecutor(options) {
3922
4002
  var result = _a.result;
3923
4003
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3924
4004
  })), false));
3925
- outputParameters = filterJustOutputParameters();
4005
+ outputParameters = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
3926
4006
  isReturned = true;
3927
4007
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3928
4008
  // Note: Wait a short time to prevent race conditions
@@ -3946,6 +4026,7 @@ function createPipelineExecutor(options) {
3946
4026
  return pipelineExecutor;
3947
4027
  }
3948
4028
  /**
4029
+ * TODO: [🤹‍♂️] Make some smarter system for limiting concurrent executions MAX_PARALLEL_TOTAL, MAX_PARALLEL_PER_LLM
3949
4030
  * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3950
4031
  * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3951
4032
  * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
@@ -3954,7 +4035,7 @@ function createPipelineExecutor(options) {
3954
4035
  * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3955
4036
  * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3956
4037
  * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3957
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4038
+ * TODO: [🧠][🍸] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3958
4039
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3959
4040
  * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
3960
4041
  */
@@ -5145,20 +5226,21 @@ var foreachCommandParser = {
5145
5226
  * Example usages of the FOREACH command
5146
5227
  */
5147
5228
  examples: [
5148
- 'FOREACH List Line -> `{customer}`',
5149
- 'FOR List Line -> `{customer}`',
5150
- 'EACH List Line -> `{customer}`',
5229
+ 'FOREACH List Line `{customers}` -> `{customer}`',
5230
+ 'FOR List Line `{customers}` -> `{customer}`',
5231
+ 'EACH List Line `{customers}` -> `{customer}`',
5151
5232
  // <- TODO: [🍭] !!!!!! More
5152
5233
  ],
5153
5234
  /**
5154
5235
  * Parses the FOREACH command
5155
5236
  */
5156
5237
  parse: function (input) {
5157
- var args = input.args, rawArgs = input.rawArgs;
5238
+ var args = input.args;
5158
5239
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5159
5240
  var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5160
- var assignSign = args[2];
5161
- var parameter = args[3];
5241
+ var parameterNameWrapped = args[2];
5242
+ var assignSign = args[3];
5243
+ var subparameterNameWrapped = args[4];
5162
5244
  if (![
5163
5245
  'LIST',
5164
5246
  'CSV',
@@ -5173,7 +5255,7 @@ var foreachCommandParser = {
5173
5255
  'ROW',
5174
5256
  'COLUMN',
5175
5257
  'CELL',
5176
- // <- TODO: [🏢] Unhardcode format cekks
5258
+ // <- TODO: [🏢] Unhardcode format cells
5177
5259
  ].includes(cellName)) {
5178
5260
  console.info({ args: args, cellName: cellName });
5179
5261
  throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
@@ -5183,24 +5265,27 @@ var foreachCommandParser = {
5183
5265
  console.info({ args: args, assignSign: assignSign });
5184
5266
  throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5185
5267
  }
5186
- var parameterNames = extractParameterNames(parameter || rawArgs);
5187
- if (parameterNames.size !== 1) {
5188
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5189
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5190
- }
5191
- var parameterName = parameterNames.values().next().value;
5192
- if (typeof parameterName !== 'string'
5193
- // <- TODO: !!!!!! Replace with propper parameter name validation
5194
- ) {
5195
- console.info({ args: args, parameterName: parameterName });
5196
- throw new Error("Invalid parameter name");
5197
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
5198
- }
5268
+ // TODO: !!!!!! Replace with propper parameter name validation
5269
+ if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5270
+ (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5271
+ 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));
5272
+ throw new Error("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5273
+ }
5274
+ var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5275
+ // TODO: !!!!!! Replace with propper parameter name validation
5276
+ if ((subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(0, 1)) !== '{' ||
5277
+ (subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(subparameterNameWrapped.length - 1, subparameterNameWrapped.length)) !==
5278
+ '}') {
5279
+ console.info({ args: args, subparameterNameWrapped: subparameterNameWrapped });
5280
+ throw new Error("!!!!!! 2 Here will be error (with rules and precise error) from validateParameterName");
5281
+ }
5282
+ var subparameterName = subparameterNameWrapped.substring(1, subparameterNameWrapped.length - 1);
5199
5283
  return {
5200
5284
  type: 'FOREACH',
5201
5285
  formatName: formatName,
5202
5286
  cellName: cellName,
5203
5287
  parameterName: parameterName,
5288
+ subparameterName: subparameterName,
5204
5289
  };
5205
5290
  },
5206
5291
  /**
@@ -5209,8 +5294,12 @@ var foreachCommandParser = {
5209
5294
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5210
5295
  */
5211
5296
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5212
- keepUnused(command, $templateJson, $pipelineJson);
5213
- // <- TODO: [🍭] !!!!!! Implement
5297
+ var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5298
+ // TODO: !!!!!! Detect double use
5299
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
5300
+ $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5301
+ keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
5302
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5214
5303
  },
5215
5304
  /**
5216
5305
  * Converts the FOREACH command back to string
@@ -5219,8 +5308,7 @@ var foreachCommandParser = {
5219
5308
  */
5220
5309
  stringify: function (command) {
5221
5310
  keepUnused(command);
5222
- return "";
5223
- // <- TODO: [🍭] !!!!!! Implement
5311
+ return "---"; // <- TODO: [🛋] Implement
5224
5312
  },
5225
5313
  /**
5226
5314
  * Reads the FOREACH command from the `TemplateJson`
@@ -5229,8 +5317,7 @@ var foreachCommandParser = {
5229
5317
  */
5230
5318
  takeFromTemplateJson: function ($templateJson) {
5231
5319
  keepUnused($templateJson);
5232
- return [];
5233
- // <- TODO: [🍭] !!!!!! Implement
5320
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5234
5321
  },
5235
5322
  };
5236
5323
  /**
@@ -5345,6 +5432,7 @@ var jokerCommandParser = {
5345
5432
  */
5346
5433
  parse: function (input) {
5347
5434
  var args = input.args;
5435
+ // TODO: !!!!!! Replace with propper parameter name validation
5348
5436
  var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5349
5437
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5350
5438
  throw new ParseError("Invalid joker");
@@ -5474,6 +5562,7 @@ var modelCommandParser = {
5474
5562
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5475
5563
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5476
5564
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
5565
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5477
5566
  }
5478
5567
  else {
5479
5568
  throw new ParseError(spaceTrim$1("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -8528,6 +8617,9 @@ function renderPromptbookMermaid(pipelineJson, options) {
8528
8617
  return promptbookMermaid;
8529
8618
  }
8530
8619
  /**
8620
+ * TODO: !!!!!! FOREACH in mermaid graph
8621
+ * TODO: !!!!!! Knowledge in mermaid graph
8622
+ * TODO: !!!!!! Personas in mermaid graph
8531
8623
  * TODO: Maybe use some Mermaid package instead of string templating
8532
8624
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8533
8625
  */