@promptbook/node 0.69.0-2 โ†’ 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.
package/esm/index.es.js CHANGED
@@ -14,7 +14,7 @@ import * as dotenv from 'dotenv';
14
14
  /**
15
15
  * The version of the Promptbook library
16
16
  */
17
- var PROMPTBOOK_VERSION = '0.69.0-1';
17
+ var PROMPTBOOK_VERSION = '0.69.0-3';
18
18
  // TODO: !!!! List here all the versions and annotate + put into script
19
19
 
20
20
  /*! *****************************************************************************
@@ -404,6 +404,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
404
404
  'samples',
405
405
  'modelName',
406
406
  'currentDate',
407
+ // <- TODO: !!!!! list here all command names
407
408
  // <- TODO: Add more like 'date', 'modelName',...
408
409
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
409
410
  ]);
@@ -883,7 +884,7 @@ function forEachAsync(array, options, callbackfunction) {
883
884
  });
884
885
  }
885
886
 
886
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
887
+ 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"}];
887
888
 
888
889
  /**
889
890
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -2046,124 +2047,6 @@ function assertsExecutionSuccessful(executionResult) {
2046
2047
  * TODO: [๐Ÿง ] Can this return type be better typed than void
2047
2048
  */
2048
2049
 
2049
- /**
2050
- * Parses the given script and returns the list of all used variables that are not defined in the script
2051
- *
2052
- * @param script from which to extract the variables
2053
- * @returns the list of variable names
2054
- * @throws {ParseError} if the script is invalid
2055
- * @public exported from `@promptbook/utils`
2056
- */
2057
- function extractVariables(script) {
2058
- var variables = new Set();
2059
- script = "(()=>{".concat(script, "})()");
2060
- try {
2061
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2062
- try {
2063
- eval(script);
2064
- }
2065
- catch (error) {
2066
- if (!(error instanceof ReferenceError)) {
2067
- throw error;
2068
- }
2069
- var undefinedName = error.message.split(' ')[0];
2070
- /*
2071
- Note: Parsing the error
2072
- [PipelineUrlError: thing is not defined]
2073
- */
2074
- if (!undefinedName) {
2075
- throw error;
2076
- }
2077
- if (script.includes(undefinedName + '(')) {
2078
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2079
- }
2080
- else {
2081
- variables.add(undefinedName);
2082
- script = "const ".concat(undefinedName, " = '';") + script;
2083
- }
2084
- }
2085
- }
2086
- catch (error) {
2087
- if (!(error instanceof Error)) {
2088
- throw error;
2089
- }
2090
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2091
- }
2092
- return variables;
2093
- }
2094
- /**
2095
- * TODO: [๐Ÿ”ฃ] Support for multiple languages - python, java,...
2096
- */
2097
-
2098
- /**
2099
- * Parses the template and returns the set of all used parameters
2100
- *
2101
- * @param template the template with used parameters
2102
- * @returns the set of parameter names
2103
- * @throws {ParseError} if the script is invalid
2104
- * @public exported from `@promptbook/utils`
2105
- */
2106
- function extractParameterNamesFromTemplate(template) {
2107
- var e_1, _a, e_2, _b, e_3, _c;
2108
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2109
- var parameterNames = new Set();
2110
- try {
2111
- 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()) {
2112
- var parameterName = _e.value;
2113
- parameterNames.add(parameterName);
2114
- }
2115
- }
2116
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2117
- finally {
2118
- try {
2119
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2120
- }
2121
- finally { if (e_1) throw e_1.error; }
2122
- }
2123
- if (templateType === 'SCRIPT_TEMPLATE') {
2124
- try {
2125
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2126
- var parameterName = _g.value;
2127
- parameterNames.add(parameterName);
2128
- }
2129
- }
2130
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2131
- finally {
2132
- try {
2133
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2134
- }
2135
- finally { if (e_2) throw e_2.error; }
2136
- }
2137
- }
2138
- try {
2139
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2140
- var jokerName = _j.value;
2141
- parameterNames.add(jokerName);
2142
- }
2143
- }
2144
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2145
- finally {
2146
- try {
2147
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2148
- }
2149
- finally { if (e_3) throw e_3.error; }
2150
- }
2151
- parameterNames.delete('content');
2152
- // <- Note {websiteContent} is used in `preparedContent`
2153
- // Note: [๐Ÿญ] Fixing dependent subparameterName from FOREACH command
2154
- if (foreach !== undefined) {
2155
- if (parameterNames.has(foreach.subparameterName)) {
2156
- parameterNames.delete(foreach.subparameterName);
2157
- parameterNames.add(foreach.parameterName);
2158
- // <- TODO: [๐ŸšŽ] Warn/logic error when `subparameterName` not used
2159
- }
2160
- }
2161
- return parameterNames;
2162
- }
2163
- /**
2164
- * TODO: [๐Ÿ”ฃ] If script require contentLanguage
2165
- */
2166
-
2167
2050
  /**
2168
2051
  * Serializes an error into a [๐Ÿš‰] JSON-serializable object
2169
2052
  *
@@ -2181,27 +2064,6 @@ function serializeError(error) {
2181
2064
  };
2182
2065
  }
2183
2066
 
2184
- /**
2185
- * Function isValidJsonString will tell you if the string is valid JSON or not
2186
- *
2187
- * @public exported from `@promptbook/utils`
2188
- */
2189
- function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
2190
- try {
2191
- JSON.parse(value);
2192
- return true;
2193
- }
2194
- catch (error) {
2195
- if (!(error instanceof Error)) {
2196
- throw error;
2197
- }
2198
- if (error.message.includes('Unexpected token')) {
2199
- return false;
2200
- }
2201
- return false;
2202
- }
2203
- }
2204
-
2205
2067
  /**
2206
2068
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2207
2069
  *
@@ -2495,122 +2357,6 @@ function joinLlmExecutionTools() {
2495
2357
  * TODO: [๐Ÿ‘ทโ€โ™‚๏ธ] @@@ Manual about construction of llmTools
2496
2358
  */
2497
2359
 
2498
- /**
2499
- * Extracts all code blocks from markdown.
2500
- *
2501
- * Note: There are multiple simmilar function:
2502
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2503
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2504
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2505
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2506
- *
2507
- * @param markdown any valid markdown
2508
- * @returns code blocks with language and content
2509
- * @throws {ParseError} if block is not closed properly
2510
- * @public exported from `@promptbook/markdown-utils`
2511
- */
2512
- function extractAllBlocksFromMarkdown(markdown) {
2513
- var e_1, _a;
2514
- var codeBlocks = [];
2515
- var lines = markdown.split('\n');
2516
- // Note: [0] Ensure that the last block notated by gt > will be closed
2517
- lines.push('');
2518
- var currentCodeBlock = null;
2519
- try {
2520
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2521
- var line = lines_1_1.value;
2522
- if (line.startsWith('> ') || line === '>') {
2523
- if (currentCodeBlock === null) {
2524
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2525
- } /* not else */
2526
- if (currentCodeBlock.blockNotation === '>') {
2527
- if (currentCodeBlock.content !== '') {
2528
- currentCodeBlock.content += '\n';
2529
- }
2530
- currentCodeBlock.content += line.slice(2);
2531
- }
2532
- }
2533
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2534
- codeBlocks.push(currentCodeBlock);
2535
- currentCodeBlock = null;
2536
- }
2537
- /* not else */
2538
- if (line.startsWith('```')) {
2539
- var language = line.slice(3).trim() || null;
2540
- if (currentCodeBlock === null) {
2541
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2542
- }
2543
- else {
2544
- if (language !== null) {
2545
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2546
- }
2547
- codeBlocks.push(currentCodeBlock);
2548
- currentCodeBlock = null;
2549
- }
2550
- }
2551
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2552
- if (currentCodeBlock.content !== '') {
2553
- currentCodeBlock.content += '\n';
2554
- }
2555
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2556
- }
2557
- }
2558
- }
2559
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2560
- finally {
2561
- try {
2562
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2563
- }
2564
- finally { if (e_1) throw e_1.error; }
2565
- }
2566
- if (currentCodeBlock !== null) {
2567
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2568
- }
2569
- return codeBlocks;
2570
- }
2571
- /**
2572
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2573
- */
2574
-
2575
- /**
2576
- * Extracts extracts exactly one valid JSON code block
2577
- *
2578
- * - When given string is a valid JSON as it is, it just returns it
2579
- * - When there is no JSON code block the function throws a `ParseError`
2580
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2581
- *
2582
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2583
- * Note: There are multiple simmilar function:
2584
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2585
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2586
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2587
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2588
- *
2589
- * @public exported from `@promptbook/markdown-utils`
2590
- * @throws {ParseError} if there is no valid JSON block in the markdown
2591
- */
2592
- function extractJsonBlock(markdown) {
2593
- if (isValidJsonString(markdown)) {
2594
- return markdown;
2595
- }
2596
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2597
- var jsonBlocks = codeBlocks.filter(function (_a) {
2598
- var content = _a.content;
2599
- return isValidJsonString(content);
2600
- });
2601
- if (jsonBlocks.length === 0) {
2602
- throw new Error('There is no valid JSON block in the markdown');
2603
- }
2604
- if (jsonBlocks.length > 1) {
2605
- throw new Error('There are multiple JSON code blocks in the markdown');
2606
- }
2607
- return jsonBlocks[0].content;
2608
- }
2609
- /**
2610
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2611
- * TODO: [๐Ÿข] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2612
- */
2613
-
2614
2360
  /**
2615
2361
  * Determine if the pipeline is fully prepared
2616
2362
  *
@@ -2663,40 +2409,278 @@ function arrayableToArray(input) {
2663
2409
  }
2664
2410
 
2665
2411
  /**
2666
- * Just says that the variable is not used but should be kept
2667
- * No side effects.
2412
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2668
2413
  *
2669
- * Note: It can be usefull for:
2414
+ * @param script from which to extract the variables
2415
+ * @returns the list of variable names
2416
+ * @throws {ParseError} if the script is invalid
2417
+ * @public exported from `@promptbook/utils`
2418
+ */
2419
+ function extractVariables(script) {
2420
+ var variables = new Set();
2421
+ script = "(()=>{".concat(script, "})()");
2422
+ try {
2423
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2424
+ try {
2425
+ eval(script);
2426
+ }
2427
+ catch (error) {
2428
+ if (!(error instanceof ReferenceError)) {
2429
+ throw error;
2430
+ }
2431
+ var undefinedName = error.message.split(' ')[0];
2432
+ /*
2433
+ Note: Parsing the error
2434
+ [PipelineUrlError: thing is not defined]
2435
+ */
2436
+ if (!undefinedName) {
2437
+ throw error;
2438
+ }
2439
+ if (script.includes(undefinedName + '(')) {
2440
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2441
+ }
2442
+ else {
2443
+ variables.add(undefinedName);
2444
+ script = "const ".concat(undefinedName, " = '';") + script;
2445
+ }
2446
+ }
2447
+ }
2448
+ catch (error) {
2449
+ if (!(error instanceof Error)) {
2450
+ throw error;
2451
+ }
2452
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2453
+ }
2454
+ return variables;
2455
+ }
2456
+ /**
2457
+ * TODO: [๐Ÿ”ฃ] Support for multiple languages - python, java,...
2458
+ */
2459
+
2460
+ /**
2461
+ * Parses the template and returns the set of all used parameters
2670
2462
  *
2671
- * 1) Suppressing eager optimization of unused imports
2672
- * 2) Suppressing eslint errors of unused variables in the tests
2673
- * 3) Keeping the type of the variable for type testing
2463
+ * @param template the template with used parameters
2464
+ * @returns the set of parameter names
2465
+ * @throws {ParseError} if the script is invalid
2466
+ * @public exported from `@promptbook/utils`
2467
+ */
2468
+ function extractParameterNamesFromTemplate(template) {
2469
+ var e_1, _a, e_2, _b, e_3, _c;
2470
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2471
+ var parameterNames = new Set();
2472
+ try {
2473
+ 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()) {
2474
+ var parameterName = _e.value;
2475
+ parameterNames.add(parameterName);
2476
+ }
2477
+ }
2478
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2479
+ finally {
2480
+ try {
2481
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2482
+ }
2483
+ finally { if (e_1) throw e_1.error; }
2484
+ }
2485
+ if (templateType === 'SCRIPT_TEMPLATE') {
2486
+ try {
2487
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2488
+ var parameterName = _g.value;
2489
+ parameterNames.add(parameterName);
2490
+ }
2491
+ }
2492
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2493
+ finally {
2494
+ try {
2495
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2496
+ }
2497
+ finally { if (e_2) throw e_2.error; }
2498
+ }
2499
+ }
2500
+ try {
2501
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2502
+ var jokerName = _j.value;
2503
+ parameterNames.add(jokerName);
2504
+ }
2505
+ }
2506
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2507
+ finally {
2508
+ try {
2509
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2510
+ }
2511
+ finally { if (e_3) throw e_3.error; }
2512
+ }
2513
+ parameterNames.delete('content');
2514
+ // <- Note {websiteContent} is used in `preparedContent`
2515
+ // Note: [๐Ÿญ] Fixing dependent subparameterName from FOREACH command
2516
+ if (foreach !== undefined) {
2517
+ if (parameterNames.has(foreach.subparameterName)) {
2518
+ parameterNames.delete(foreach.subparameterName);
2519
+ parameterNames.add(foreach.parameterName);
2520
+ // <- TODO: [๐ŸšŽ] Warn/logic error when `subparameterName` not used
2521
+ }
2522
+ }
2523
+ return parameterNames;
2524
+ }
2525
+ /**
2526
+ * TODO: [๐Ÿ”ฃ] If script require contentLanguage
2527
+ */
2528
+
2529
+ /**
2530
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2674
2531
  *
2675
- * @param value any values
2676
- * @returns void
2677
- * @private within the repository
2532
+ * @public exported from `@promptbook/utils`
2678
2533
  */
2679
- function keepUnused() {
2680
- var valuesToKeep = [];
2681
- for (var _i = 0; _i < arguments.length; _i++) {
2682
- valuesToKeep[_i] = arguments[_i];
2534
+ function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
2535
+ try {
2536
+ JSON.parse(value);
2537
+ return true;
2538
+ }
2539
+ catch (error) {
2540
+ if (!(error instanceof Error)) {
2541
+ throw error;
2542
+ }
2543
+ if (error.message.includes('Unexpected token')) {
2544
+ return false;
2545
+ }
2546
+ return false;
2683
2547
  }
2684
2548
  }
2685
2549
 
2686
2550
  /**
2687
- * Just marks a place of place where should be something implemented
2551
+ * Extracts all code blocks from markdown.
2552
+ *
2553
+ * Note: There are multiple simmilar function:
2554
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2555
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2556
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2557
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2558
+ *
2559
+ * @param markdown any valid markdown
2560
+ * @returns code blocks with language and content
2561
+ * @throws {ParseError} if block is not closed properly
2562
+ * @public exported from `@promptbook/markdown-utils`
2563
+ */
2564
+ function extractAllBlocksFromMarkdown(markdown) {
2565
+ var e_1, _a;
2566
+ var codeBlocks = [];
2567
+ var lines = markdown.split('\n');
2568
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2569
+ lines.push('');
2570
+ var currentCodeBlock = null;
2571
+ try {
2572
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2573
+ var line = lines_1_1.value;
2574
+ if (line.startsWith('> ') || line === '>') {
2575
+ if (currentCodeBlock === null) {
2576
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2577
+ } /* not else */
2578
+ if (currentCodeBlock.blockNotation === '>') {
2579
+ if (currentCodeBlock.content !== '') {
2580
+ currentCodeBlock.content += '\n';
2581
+ }
2582
+ currentCodeBlock.content += line.slice(2);
2583
+ }
2584
+ }
2585
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2586
+ codeBlocks.push(currentCodeBlock);
2587
+ currentCodeBlock = null;
2588
+ }
2589
+ /* not else */
2590
+ if (line.startsWith('```')) {
2591
+ var language = line.slice(3).trim() || null;
2592
+ if (currentCodeBlock === null) {
2593
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2594
+ }
2595
+ else {
2596
+ if (language !== null) {
2597
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2598
+ }
2599
+ codeBlocks.push(currentCodeBlock);
2600
+ currentCodeBlock = null;
2601
+ }
2602
+ }
2603
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2604
+ if (currentCodeBlock.content !== '') {
2605
+ currentCodeBlock.content += '\n';
2606
+ }
2607
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2608
+ }
2609
+ }
2610
+ }
2611
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2612
+ finally {
2613
+ try {
2614
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2615
+ }
2616
+ finally { if (e_1) throw e_1.error; }
2617
+ }
2618
+ if (currentCodeBlock !== null) {
2619
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2620
+ }
2621
+ return codeBlocks;
2622
+ }
2623
+ /**
2624
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2625
+ */
2626
+
2627
+ /**
2628
+ * Extracts extracts exactly one valid JSON code block
2629
+ *
2630
+ * - When given string is a valid JSON as it is, it just returns it
2631
+ * - When there is no JSON code block the function throws a `ParseError`
2632
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
2633
+ *
2634
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
2635
+ * Note: There are multiple simmilar function:
2636
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2637
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2638
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2639
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2640
+ *
2641
+ * @public exported from `@promptbook/markdown-utils`
2642
+ * @throws {ParseError} if there is no valid JSON block in the markdown
2643
+ */
2644
+ function extractJsonBlock(markdown) {
2645
+ if (isValidJsonString(markdown)) {
2646
+ return markdown;
2647
+ }
2648
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2649
+ var jsonBlocks = codeBlocks.filter(function (_a) {
2650
+ var content = _a.content;
2651
+ return isValidJsonString(content);
2652
+ });
2653
+ if (jsonBlocks.length === 0) {
2654
+ throw new Error('There is no valid JSON block in the markdown');
2655
+ }
2656
+ if (jsonBlocks.length > 1) {
2657
+ throw new Error('There are multiple JSON code blocks in the markdown');
2658
+ }
2659
+ return jsonBlocks[0].content;
2660
+ }
2661
+ /**
2662
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2663
+ * TODO: [๐Ÿข] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2664
+ */
2665
+
2666
+ /**
2667
+ * Just says that the variable is not used but should be kept
2688
2668
  * No side effects.
2689
2669
  *
2690
- * Note: It can be usefull suppressing eslint errors of unused variables
2670
+ * Note: It can be usefull for:
2671
+ *
2672
+ * 1) Suppressing eager optimization of unused imports
2673
+ * 2) Suppressing eslint errors of unused variables in the tests
2674
+ * 3) Keeping the type of the variable for type testing
2691
2675
  *
2692
2676
  * @param value any values
2693
2677
  * @returns void
2694
2678
  * @private within the repository
2695
2679
  */
2696
- function TODO_USE() {
2697
- var value = [];
2680
+ function keepUnused() {
2681
+ var valuesToKeep = [];
2698
2682
  for (var _i = 0; _i < arguments.length; _i++) {
2699
- value[_i] = arguments[_i];
2683
+ valuesToKeep[_i] = arguments[_i];
2700
2684
  }
2701
2685
  }
2702
2686
 
@@ -2920,53 +2904,646 @@ function countSentences(text) {
2920
2904
  }
2921
2905
 
2922
2906
  /**
2923
- * Counts number of words in the text
2924
- *
2925
- * @public exported from `@promptbook/utils`
2907
+ * Counts number of words in the text
2908
+ *
2909
+ * @public exported from `@promptbook/utils`
2910
+ */
2911
+ function countWords(text) {
2912
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
2913
+ text = removeDiacritics(text);
2914
+ return text.split(/[^a-zะฐ-ั0-9]+/i).filter(function (word) { return word.length > 0; }).length;
2915
+ }
2916
+
2917
+ /**
2918
+ * Index of all counter functions
2919
+ *
2920
+ * @public exported from `@promptbook/utils`
2921
+ */
2922
+ var CountUtils = {
2923
+ CHARACTERS: countCharacters,
2924
+ WORDS: countWords,
2925
+ SENTENCES: countSentences,
2926
+ PARAGRAPHS: countParagraphs,
2927
+ LINES: countLines,
2928
+ PAGES: countPages,
2929
+ };
2930
+
2931
+ /**
2932
+ * Function checkExpectations will check if the expectations on given value are met
2933
+ *
2934
+ * Note: There are two simmilar functions:
2935
+ * - `checkExpectations` which throws an error if the expectations are not met
2936
+ * - `isPassingExpectations` which returns a boolean
2937
+ *
2938
+ * @throws {ExpectError} if the expectations are not met
2939
+ * @returns {void} Nothing
2940
+ * @private internal function of `createPipelineExecutor`
2941
+ */
2942
+ function checkExpectations(expectations, value) {
2943
+ var e_1, _a;
2944
+ try {
2945
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
2946
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
2947
+ var amount = CountUtils[unit.toUpperCase()](value);
2948
+ if (min && amount < min) {
2949
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2950
+ } /* not else */
2951
+ if (max && amount > max) {
2952
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2953
+ }
2954
+ }
2955
+ }
2956
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2957
+ finally {
2958
+ try {
2959
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2960
+ }
2961
+ finally { if (e_1) throw e_1.error; }
2962
+ }
2963
+ }
2964
+ /**
2965
+ * TODO: [๐Ÿ’] Unite object for expecting amount and format
2966
+ */
2967
+
2968
+ /**
2969
+ * Just marks a place of place where should be something implemented
2970
+ * No side effects.
2971
+ *
2972
+ * Note: It can be usefull suppressing eslint errors of unused variables
2973
+ *
2974
+ * @param value any values
2975
+ * @returns void
2976
+ * @private within the repository
2977
+ */
2978
+ function TODO_USE() {
2979
+ var value = [];
2980
+ for (var _i = 0; _i < arguments.length; _i++) {
2981
+ value[_i] = arguments[_i];
2982
+ }
2983
+ }
2984
+
2985
+ /**
2986
+ * @private @@@
2987
+ */
2988
+ function getContextForTemplate(template) {
2989
+ return __awaiter(this, void 0, void 0, function () {
2990
+ return __generator(this, function (_a) {
2991
+ TODO_USE(template);
2992
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [๐Ÿ] Implement */];
2993
+ });
2994
+ });
2995
+ }
2996
+
2997
+ /**
2998
+ * @private @@@
2999
+ */
3000
+ function getKnowledgeForTemplate(preparedPipeline, template) {
3001
+ return __awaiter(this, void 0, void 0, function () {
3002
+ return __generator(this, function (_a) {
3003
+ // TODO: [โ™จ] Implement Better - use real index and keyword search from `template` and {samples}
3004
+ TODO_USE(template);
3005
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3006
+ var content = _a.content;
3007
+ return "- ".concat(content);
3008
+ }).join('\n')];
3009
+ });
3010
+ });
3011
+ }
3012
+
3013
+ /**
3014
+ * @private @@@
3015
+ */
3016
+ function getSamplesForTemplate(template) {
3017
+ return __awaiter(this, void 0, void 0, function () {
3018
+ return __generator(this, function (_a) {
3019
+ // TODO: [โ™จ] Implement Better - use real index and keyword search
3020
+ TODO_USE(template);
3021
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [โ™จ] Implement */];
3022
+ });
3023
+ });
3024
+ }
3025
+
3026
+ /**
3027
+ * @private @@@
3028
+ */
3029
+ function getReservedParametersForTemplate(preparedPipeline, template, pipelineIdentification) {
3030
+ return __awaiter(this, void 0, void 0, function () {
3031
+ var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3032
+ var e_1, _a;
3033
+ return __generator(this, function (_b) {
3034
+ switch (_b.label) {
3035
+ case 0: return [4 /*yield*/, getContextForTemplate(template)];
3036
+ case 1:
3037
+ context = _b.sent();
3038
+ return [4 /*yield*/, getKnowledgeForTemplate(preparedPipeline, template)];
3039
+ case 2:
3040
+ knowledge = _b.sent();
3041
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3042
+ case 3:
3043
+ samples = _b.sent();
3044
+ currentDate = new Date().toISOString();
3045
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3046
+ reservedParameters = {
3047
+ content: RESERVED_PARAMETER_RESTRICTED,
3048
+ context: context,
3049
+ knowledge: knowledge,
3050
+ samples: samples,
3051
+ currentDate: currentDate,
3052
+ modelName: modelName,
3053
+ };
3054
+ _loop_1 = function (parameterName) {
3055
+ if (reservedParameters[parameterName] === undefined) {
3056
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3057
+ }
3058
+ };
3059
+ try {
3060
+ // Note: Doublecheck that ALL reserved parameters are defined:
3061
+ 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()) {
3062
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3063
+ _loop_1(parameterName);
3064
+ }
3065
+ }
3066
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3067
+ finally {
3068
+ try {
3069
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3070
+ }
3071
+ finally { if (e_1) throw e_1.error; }
3072
+ }
3073
+ return [2 /*return*/, reservedParameters];
3074
+ }
3075
+ });
3076
+ });
3077
+ }
3078
+
3079
+ /**
3080
+ * @private @@@
2926
3081
  */
2927
- function countWords(text) {
2928
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
2929
- text = removeDiacritics(text);
2930
- return text.split(/[^a-zะฐ-ั0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3082
+ function executeSingleTemplate(options) {
3083
+ return __awaiter(this, void 0, void 0, function () {
3084
+ 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;
3085
+ var e_1, _f, _g;
3086
+ return __generator(this, function (_h) {
3087
+ switch (_h.label) {
3088
+ case 0:
3089
+ 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;
3090
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3091
+ title = currentTemplate.title;
3092
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3093
+ return [4 /*yield*/, onProgress({
3094
+ name: name,
3095
+ title: title,
3096
+ isStarted: false,
3097
+ isDone: false,
3098
+ templateType: currentTemplate.templateType,
3099
+ parameterName: currentTemplate.resultingParameterName,
3100
+ parameterValue: null,
3101
+ // <- [๐Ÿธ]
3102
+ })];
3103
+ case 1:
3104
+ _h.sent();
3105
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3106
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3107
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3108
+ 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)
3109
+ .map(function (name) { return "{".concat(name, "}"); })
3110
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3111
+ .map(function (name) { return "{".concat(name, "}"); })
3112
+ .join(', '), "\n\n "); }));
3113
+ }
3114
+ _b = (_a = Object).freeze;
3115
+ _c = [{}];
3116
+ return [4 /*yield*/, getReservedParametersForTemplate(preparedPipeline, currentTemplate, pipelineIdentification)];
3117
+ case 2:
3118
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3119
+ definedParameterNames = new Set(Object.keys(definedParameters));
3120
+ parameters = {};
3121
+ _loop_1 = function (parameterName) {
3122
+ // Situation: Parameter is defined and used
3123
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3124
+ parameters[parameterName] = definedParameters[parameterName];
3125
+ }
3126
+ // Situation: Parameter is defined but NOT used
3127
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3128
+ // Situation: Parameter is NOT defined BUT used
3129
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3130
+ // Houston, we have a problem
3131
+ // Note: Checking part is also done in `validatePipeline`, but itโ€™s good to doublecheck
3132
+ 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 "); }));
3133
+ }
3134
+ };
3135
+ try {
3136
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3137
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3138
+ parameterName = _e.value;
3139
+ _loop_1(parameterName);
3140
+ }
3141
+ }
3142
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3143
+ finally {
3144
+ try {
3145
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3146
+ }
3147
+ finally { if (e_1) throw e_1.error; }
3148
+ }
3149
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3150
+ Object.freeze(parameters);
3151
+ result = null;
3152
+ resultString = null;
3153
+ expectError = null;
3154
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3155
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3156
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3157
+ .split('{content}')
3158
+ .join(currentTemplate.content);
3159
+ _loop_2 = function (attempt) {
3160
+ 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;
3161
+ var e_2, _s, e_4, _t, e_3, _u;
3162
+ return __generator(this, function (_v) {
3163
+ switch (_v.label) {
3164
+ case 0:
3165
+ isJokerAttempt = attempt < 0;
3166
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3167
+ // TODO: [๐Ÿง ] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3168
+ if (isJokerAttempt && !jokerParameterName) {
3169
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3170
+ }
3171
+ result = null;
3172
+ resultString = null;
3173
+ expectError = null;
3174
+ if (isJokerAttempt) {
3175
+ if (parameters[jokerParameterName] === undefined) {
3176
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3177
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3178
+ }
3179
+ else {
3180
+ resultString = parameters[jokerParameterName];
3181
+ }
3182
+ }
3183
+ _v.label = 1;
3184
+ case 1:
3185
+ _v.trys.push([1, 44, 45, 46]);
3186
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3187
+ _j = currentTemplate.templateType;
3188
+ switch (_j) {
3189
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3190
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3191
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3192
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3193
+ }
3194
+ return [3 /*break*/, 25];
3195
+ case 2:
3196
+ resultString = replaceParameters(preparedContent, parameters);
3197
+ return [3 /*break*/, 26];
3198
+ case 3:
3199
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3200
+ prompt = {
3201
+ title: currentTemplate.title,
3202
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3203
+ ? preparedPipeline.pipelineUrl
3204
+ : 'anonymous' /* <- TODO: [๐Ÿง ] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3205
+ parameters: parameters,
3206
+ content: preparedContent,
3207
+ modelRequirements: modelRequirements,
3208
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3209
+ var name = _a.name;
3210
+ return name === currentTemplate.personaName;
3211
+ }) || {})), currentTemplate.expectations),
3212
+ format: currentTemplate.format,
3213
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3214
+ }; // <- TODO: Not very good type guard
3215
+ _k = modelRequirements.modelVariant;
3216
+ switch (_k) {
3217
+ case 'CHAT': return [3 /*break*/, 4];
3218
+ case 'COMPLETION': return [3 /*break*/, 6];
3219
+ case 'EMBEDDING': return [3 /*break*/, 8];
3220
+ }
3221
+ return [3 /*break*/, 10];
3222
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3223
+ case 5:
3224
+ chatResult = _v.sent();
3225
+ // TODO: [๐Ÿฌ] Destroy chatThread
3226
+ result = chatResult;
3227
+ resultString = chatResult.content;
3228
+ return [3 /*break*/, 11];
3229
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3230
+ case 7:
3231
+ completionResult = _v.sent();
3232
+ result = completionResult;
3233
+ resultString = completionResult.content;
3234
+ return [3 /*break*/, 11];
3235
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3236
+ case 9:
3237
+ // TODO: [๐Ÿง ] This is weird, embedding model can not be used such a way in the pipeline
3238
+ embeddingResult = _v.sent();
3239
+ result = embeddingResult;
3240
+ resultString = embeddingResult.content.join(',');
3241
+ return [3 /*break*/, 11];
3242
+ case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3243
+ case 11: return [3 /*break*/, 26];
3244
+ case 12:
3245
+ if (arrayableToArray(tools.script).length === 0) {
3246
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3247
+ }
3248
+ if (!currentTemplate.contentLanguage) {
3249
+ 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 "); }));
3250
+ }
3251
+ // TODO: DRY [1]
3252
+ scriptPipelineExecutionErrors = [];
3253
+ _v.label = 13;
3254
+ case 13:
3255
+ _v.trys.push([13, 20, 21, 22]);
3256
+ _l = (e_2 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3257
+ _v.label = 14;
3258
+ case 14:
3259
+ if (!!_m.done) return [3 /*break*/, 19];
3260
+ scriptTools = _m.value;
3261
+ _v.label = 15;
3262
+ case 15:
3263
+ _v.trys.push([15, 17, , 18]);
3264
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3265
+ scriptLanguage: currentTemplate.contentLanguage,
3266
+ script: preparedContent,
3267
+ parameters: parameters,
3268
+ }))];
3269
+ case 16:
3270
+ resultString = _v.sent();
3271
+ return [3 /*break*/, 19];
3272
+ case 17:
3273
+ error_1 = _v.sent();
3274
+ if (!(error_1 instanceof Error)) {
3275
+ throw error_1;
3276
+ }
3277
+ if (error_1 instanceof UnexpectedError) {
3278
+ throw error_1;
3279
+ }
3280
+ scriptPipelineExecutionErrors.push(error_1);
3281
+ return [3 /*break*/, 18];
3282
+ case 18:
3283
+ _m = _l.next();
3284
+ return [3 /*break*/, 14];
3285
+ case 19: return [3 /*break*/, 22];
3286
+ case 20:
3287
+ e_2_1 = _v.sent();
3288
+ e_2 = { error: e_2_1 };
3289
+ return [3 /*break*/, 22];
3290
+ case 21:
3291
+ try {
3292
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3293
+ }
3294
+ finally { if (e_2) throw e_2.error; }
3295
+ return [7 /*endfinally*/];
3296
+ case 22:
3297
+ if (resultString !== null) {
3298
+ return [3 /*break*/, 26];
3299
+ }
3300
+ if (scriptPipelineExecutionErrors.length === 1) {
3301
+ throw scriptPipelineExecutionErrors[0];
3302
+ }
3303
+ else {
3304
+ 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
3305
+ .map(function (error) { return '- ' + error.message; })
3306
+ .join('\n\n')), "\n "); }));
3307
+ }
3308
+ case 23:
3309
+ if (tools.userInterface === undefined) {
3310
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3311
+ }
3312
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3313
+ promptTitle: currentTemplate.title,
3314
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3315
+ defaultValue: replaceParameters(preparedContent, parameters),
3316
+ // TODO: [๐Ÿง ] !! Figure out how to define placeholder in .ptbk.md file
3317
+ placeholder: undefined,
3318
+ priority: priority,
3319
+ }))];
3320
+ case 24:
3321
+ // TODO: [๐ŸŒน] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3322
+ resultString = _v.sent();
3323
+ return [3 /*break*/, 26];
3324
+ case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3325
+ case 26:
3326
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3327
+ _v.label = 27;
3328
+ case 27:
3329
+ _v.trys.push([27, 41, 42, 43]);
3330
+ _o = (e_4 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3331
+ _v.label = 28;
3332
+ case 28:
3333
+ if (!!_p.done) return [3 /*break*/, 40];
3334
+ functionName = _p.value;
3335
+ // TODO: DRY [1]
3336
+ scriptPipelineExecutionErrors = [];
3337
+ postprocessingError = null;
3338
+ _v.label = 29;
3339
+ case 29:
3340
+ _v.trys.push([29, 36, 37, 38]);
3341
+ _q = (e_3 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3342
+ _v.label = 30;
3343
+ case 30:
3344
+ if (!!_r.done) return [3 /*break*/, 35];
3345
+ scriptTools = _r.value;
3346
+ _v.label = 31;
3347
+ case 31:
3348
+ _v.trys.push([31, 33, , 34]);
3349
+ return [4 /*yield*/, scriptTools.execute({
3350
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3351
+ script: "".concat(functionName, "(resultString)"),
3352
+ parameters: {
3353
+ resultString: resultString || '',
3354
+ // Note: No ...parametersForTemplate, because working with result only
3355
+ },
3356
+ })];
3357
+ case 32:
3358
+ resultString = _v.sent();
3359
+ postprocessingError = null;
3360
+ return [3 /*break*/, 35];
3361
+ case 33:
3362
+ error_2 = _v.sent();
3363
+ if (!(error_2 instanceof Error)) {
3364
+ throw error_2;
3365
+ }
3366
+ if (error_2 instanceof UnexpectedError) {
3367
+ throw error_2;
3368
+ }
3369
+ postprocessingError = error_2;
3370
+ scriptPipelineExecutionErrors.push(error_2);
3371
+ return [3 /*break*/, 34];
3372
+ case 34:
3373
+ _r = _q.next();
3374
+ return [3 /*break*/, 30];
3375
+ case 35: return [3 /*break*/, 38];
3376
+ case 36:
3377
+ e_3_1 = _v.sent();
3378
+ e_3 = { error: e_3_1 };
3379
+ return [3 /*break*/, 38];
3380
+ case 37:
3381
+ try {
3382
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3383
+ }
3384
+ finally { if (e_3) throw e_3.error; }
3385
+ return [7 /*endfinally*/];
3386
+ case 38:
3387
+ if (postprocessingError) {
3388
+ throw postprocessingError;
3389
+ }
3390
+ _v.label = 39;
3391
+ case 39:
3392
+ _p = _o.next();
3393
+ return [3 /*break*/, 28];
3394
+ case 40: return [3 /*break*/, 43];
3395
+ case 41:
3396
+ e_4_1 = _v.sent();
3397
+ e_4 = { error: e_4_1 };
3398
+ return [3 /*break*/, 43];
3399
+ case 42:
3400
+ try {
3401
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3402
+ }
3403
+ finally { if (e_4) throw e_4.error; }
3404
+ return [7 /*endfinally*/];
3405
+ case 43:
3406
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
3407
+ if (currentTemplate.format) {
3408
+ if (currentTemplate.format === 'JSON') {
3409
+ if (!isValidJsonString(resultString || '')) {
3410
+ // TODO: [๐Ÿข] Do more universally via `FormatDefinition`
3411
+ try {
3412
+ resultString = extractJsonBlock(resultString || '');
3413
+ }
3414
+ catch (error) {
3415
+ keepUnused(error);
3416
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3417
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3418
+ }
3419
+ }
3420
+ }
3421
+ else {
3422
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3423
+ }
3424
+ }
3425
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
3426
+ if (currentTemplate.expectations) {
3427
+ checkExpectations(currentTemplate.expectations, resultString || '');
3428
+ }
3429
+ return [2 /*return*/, "break-attempts"];
3430
+ case 44:
3431
+ error_3 = _v.sent();
3432
+ if (!(error_3 instanceof ExpectError)) {
3433
+ throw error_3;
3434
+ }
3435
+ expectError = error_3;
3436
+ return [3 /*break*/, 46];
3437
+ case 45:
3438
+ if (!isJokerAttempt &&
3439
+ currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3440
+ prompt
3441
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3442
+ // In that case we donโ€™t want to make a report about it because itโ€™s not a llm execution error
3443
+ ) {
3444
+ // TODO: [๐Ÿง ] Maybe put other templateTypes into report
3445
+ $executionReport.promptExecutions.push({
3446
+ prompt: __assign({}, prompt),
3447
+ result: result || undefined,
3448
+ error: expectError === null ? undefined : serializeError(expectError),
3449
+ });
3450
+ }
3451
+ return [7 /*endfinally*/];
3452
+ case 46:
3453
+ if (expectError !== null && attempt === maxAttempts - 1) {
3454
+ 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
3455
+ .split('\n')
3456
+ .map(function (line) { return "> ".concat(line); })
3457
+ .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) || '')
3458
+ .split('\n')
3459
+ .map(function (line) { return "> ".concat(line); })
3460
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3461
+ ? 'null'
3462
+ : resultString
3463
+ .split('\n')
3464
+ .map(function (line) { return "> ".concat(line); })
3465
+ .join('\n')), "\n ---\n "); }));
3466
+ }
3467
+ return [2 /*return*/];
3468
+ }
3469
+ });
3470
+ };
3471
+ attempt = -jokerParameterNames.length;
3472
+ _h.label = 3;
3473
+ case 3:
3474
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 6];
3475
+ return [5 /*yield**/, _loop_2(attempt)];
3476
+ case 4:
3477
+ state_1 = _h.sent();
3478
+ switch (state_1) {
3479
+ case "break-attempts": return [3 /*break*/, 6];
3480
+ }
3481
+ _h.label = 5;
3482
+ case 5:
3483
+ attempt++;
3484
+ return [3 /*break*/, 3];
3485
+ case 6:
3486
+ //------------------------------------
3487
+ /*
3488
+
3489
+
3490
+
3491
+
3492
+
3493
+
3494
+
3495
+
3496
+
3497
+ */
3498
+ //------------------------------------
3499
+ if (resultString === null) {
3500
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3501
+ }
3502
+ return [4 /*yield*/, onProgress({
3503
+ name: name,
3504
+ title: title,
3505
+ isStarted: true,
3506
+ isDone: true,
3507
+ templateType: currentTemplate.templateType,
3508
+ parameterName: currentTemplate.resultingParameterName,
3509
+ parameterValue: resultString,
3510
+ // <- [๐Ÿธ]
3511
+ })];
3512
+ case 7:
3513
+ _h.sent();
3514
+ return [2 /*return*/, Object.freeze((_g = {},
3515
+ _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */,
3516
+ _g))];
3517
+ }
3518
+ });
3519
+ });
2931
3520
  }
2932
-
2933
3521
  /**
2934
- * Index of all counter functions
2935
- *
2936
- * @public exported from `@promptbook/utils`
3522
+ * TODO: [๐Ÿคนโ€โ™‚๏ธ]
2937
3523
  */
2938
- var CountUtils = {
2939
- CHARACTERS: countCharacters,
2940
- WORDS: countWords,
2941
- SENTENCES: countSentences,
2942
- PARAGRAPHS: countParagraphs,
2943
- LINES: countLines,
2944
- PAGES: countPages,
2945
- };
2946
3524
 
2947
3525
  /**
2948
- * Function checkExpectations will check if the expectations on given value are met
2949
- *
2950
- * Note: There are two simmilar functions:
2951
- * - `checkExpectations` which throws an error if the expectations are not met
2952
- * - `isPassingExpectations` which returns a boolean
2953
- *
2954
- * @throws {ExpectError} if the expectations are not met
2955
- * @returns {void} Nothing
2956
- * @private internal function of `createPipelineExecutor`
3526
+ * @private @@@
2957
3527
  */
2958
- function checkExpectations(expectations, value) {
3528
+ function filterJustOutputParameters(preparedPipeline, parametersToPass, $warnings, pipelineIdentification) {
2959
3529
  var e_1, _a;
3530
+ var outputParameters = {};
3531
+ var _loop_1 = function (parameter) {
3532
+ if (parametersToPass[parameter.name] === undefined) {
3533
+ // [4]
3534
+ $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 "); })));
3535
+ return "continue";
3536
+ }
3537
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3538
+ };
2960
3539
  try {
2961
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
2962
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
2963
- var amount = CountUtils[unit.toUpperCase()](value);
2964
- if (min && amount < min) {
2965
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2966
- } /* not else */
2967
- if (max && amount > max) {
2968
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2969
- }
3540
+ // Note: Filter ONLY output parameters
3541
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3542
+ var isOutput = _a.isOutput;
3543
+ return isOutput;
3544
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
3545
+ var parameter = _c.value;
3546
+ _loop_1(parameter);
2970
3547
  }
2971
3548
  }
2972
3549
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -2976,10 +3553,8 @@ function checkExpectations(expectations, value) {
2976
3553
  }
2977
3554
  finally { if (e_1) throw e_1.error; }
2978
3555
  }
3556
+ return outputParameters;
2979
3557
  }
2980
- /**
2981
- * TODO: [๐Ÿ’] Unite object for expecting amount and format
2982
- */
2983
3558
 
2984
3559
  /**
2985
3560
  * Creates executor function from pipeline and execution tools.
@@ -3013,572 +3588,6 @@ function createPipelineExecutor(options) {
3013
3588
  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 "); }));
3014
3589
  }
3015
3590
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3016
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3017
- function getContextForTemplate(template) {
3018
- return __awaiter(this, void 0, void 0, function () {
3019
- return __generator(this, function (_a) {
3020
- TODO_USE(template);
3021
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [๐Ÿ] Implement */];
3022
- });
3023
- });
3024
- }
3025
- function getKnowledgeForTemplate(template) {
3026
- return __awaiter(this, void 0, void 0, function () {
3027
- return __generator(this, function (_a) {
3028
- // TODO: [โ™จ] Implement Better - use real index and keyword search from `template` and {samples}
3029
- TODO_USE(template);
3030
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3031
- var content = _a.content;
3032
- return "- ".concat(content);
3033
- }).join('\n')];
3034
- });
3035
- });
3036
- }
3037
- function getSamplesForTemplate(template) {
3038
- return __awaiter(this, void 0, void 0, function () {
3039
- return __generator(this, function (_a) {
3040
- // TODO: [โ™จ] Implement Better - use real index and keyword search
3041
- TODO_USE(template);
3042
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [โ™จ] Implement */];
3043
- });
3044
- });
3045
- }
3046
- function getReservedParametersForTemplate(template) {
3047
- return __awaiter(this, void 0, void 0, function () {
3048
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3049
- var e_3, _a;
3050
- return __generator(this, function (_b) {
3051
- switch (_b.label) {
3052
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3053
- case 1:
3054
- context = _b.sent();
3055
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3056
- case 2:
3057
- knowledge = _b.sent();
3058
- return [4 /*yield*/, getSamplesForTemplate(template)];
3059
- case 3:
3060
- samples = _b.sent();
3061
- currentDate = new Date().toISOString();
3062
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3063
- reservedParameters = {
3064
- content: RESERVED_PARAMETER_RESTRICTED,
3065
- context: context,
3066
- knowledge: knowledge,
3067
- samples: samples,
3068
- currentDate: currentDate,
3069
- modelName: modelName,
3070
- };
3071
- _loop_3 = function (parameterName) {
3072
- if (reservedParameters[parameterName] === undefined) {
3073
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3074
- }
3075
- };
3076
- try {
3077
- // Note: Doublecheck that ALL reserved parameters are defined:
3078
- 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()) {
3079
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3080
- _loop_3(parameterName);
3081
- }
3082
- }
3083
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3084
- finally {
3085
- try {
3086
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3087
- }
3088
- finally { if (e_3) throw e_3.error; }
3089
- }
3090
- return [2 /*return*/, reservedParameters];
3091
- }
3092
- });
3093
- });
3094
- }
3095
- function executeSingleTemplate(currentTemplate) {
3096
- return __awaiter(this, void 0, void 0, function () {
3097
- 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;
3098
- var e_4, _f, _g;
3099
- return __generator(this, function (_h) {
3100
- switch (_h.label) {
3101
- case 0:
3102
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3103
- title = currentTemplate.title;
3104
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3105
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3106
- progress_1 = {
3107
- name: name,
3108
- title: title,
3109
- isStarted: false,
3110
- isDone: false,
3111
- templateType: currentTemplate.templateType,
3112
- parameterName: currentTemplate.resultingParameterName,
3113
- parameterValue: null,
3114
- // <- [3]
3115
- };
3116
- if (isReturned) {
3117
- 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)
3118
- .split('\n')
3119
- .map(function (line) { return "> ".concat(line); })
3120
- .join('\n')), "\n "); }));
3121
- }
3122
- return [4 /*yield*/, onProgress(progress_1)];
3123
- case 1:
3124
- _h.sent();
3125
- _h.label = 2;
3126
- case 2:
3127
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3128
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3129
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3130
- 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)
3131
- .map(function (name) { return "{".concat(name, "}"); })
3132
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3133
- .map(function (name) { return "{".concat(name, "}"); })
3134
- .join(', '), "\n\n "); }));
3135
- }
3136
- _b = (_a = Object).freeze;
3137
- _c = [{}];
3138
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3139
- case 3:
3140
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3141
- definedParameterNames = new Set(Object.keys(definedParameters));
3142
- parameters = {};
3143
- _loop_4 = function (parameterName) {
3144
- // Situation: Parameter is defined and used
3145
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3146
- parameters[parameterName] = definedParameters[parameterName];
3147
- }
3148
- // Situation: Parameter is defined but NOT used
3149
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3150
- // Situation: Parameter is NOT defined BUT used
3151
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3152
- // Houston, we have a problem
3153
- // Note: Checking part is also done in `validatePipeline`, but itโ€™s good to doublecheck
3154
- 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 "); }));
3155
- }
3156
- };
3157
- try {
3158
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3159
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3160
- parameterName = _e.value;
3161
- _loop_4(parameterName);
3162
- }
3163
- }
3164
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3165
- finally {
3166
- try {
3167
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3168
- }
3169
- finally { if (e_4) throw e_4.error; }
3170
- }
3171
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3172
- Object.freeze(parameters);
3173
- result = null;
3174
- resultString = null;
3175
- expectError = null;
3176
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3177
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3178
- preparedContent = (currentTemplate.preparedContent || '{content}')
3179
- .split('{content}')
3180
- .join(currentTemplate.content);
3181
- _loop_5 = function (attempt) {
3182
- 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;
3183
- var e_5, _s, e_7, _t, e_6, _u;
3184
- return __generator(this, function (_v) {
3185
- switch (_v.label) {
3186
- case 0:
3187
- isJokerAttempt = attempt < 0;
3188
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3189
- // TODO: [๐Ÿง ] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3190
- if (isJokerAttempt && !jokerParameterName) {
3191
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3192
- }
3193
- result = null;
3194
- resultString = null;
3195
- expectError = null;
3196
- if (isJokerAttempt) {
3197
- if (parameters[jokerParameterName] === undefined) {
3198
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3199
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3200
- }
3201
- else {
3202
- resultString = parameters[jokerParameterName];
3203
- }
3204
- }
3205
- _v.label = 1;
3206
- case 1:
3207
- _v.trys.push([1, 44, 45, 46]);
3208
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3209
- _j = currentTemplate.templateType;
3210
- switch (_j) {
3211
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3212
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3213
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3214
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3215
- }
3216
- return [3 /*break*/, 25];
3217
- case 2:
3218
- resultString = replaceParameters(preparedContent, parameters);
3219
- return [3 /*break*/, 26];
3220
- case 3:
3221
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3222
- prompt = {
3223
- title: currentTemplate.title,
3224
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3225
- ? preparedPipeline.pipelineUrl
3226
- : 'anonymous' /* <- TODO: [๐Ÿง ] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3227
- parameters: parameters,
3228
- content: preparedContent,
3229
- modelRequirements: modelRequirements,
3230
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3231
- var name = _a.name;
3232
- return name === currentTemplate.personaName;
3233
- }) || {})), currentTemplate.expectations),
3234
- format: currentTemplate.format,
3235
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3236
- }; // <- TODO: Not very good type guard
3237
- _k = modelRequirements.modelVariant;
3238
- switch (_k) {
3239
- case 'CHAT': return [3 /*break*/, 4];
3240
- case 'COMPLETION': return [3 /*break*/, 6];
3241
- case 'EMBEDDING': return [3 /*break*/, 8];
3242
- }
3243
- return [3 /*break*/, 10];
3244
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3245
- case 5:
3246
- chatResult = _v.sent();
3247
- // TODO: [๐Ÿฌ] Destroy chatThread
3248
- result = chatResult;
3249
- resultString = chatResult.content;
3250
- return [3 /*break*/, 11];
3251
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3252
- case 7:
3253
- completionResult = _v.sent();
3254
- result = completionResult;
3255
- resultString = completionResult.content;
3256
- return [3 /*break*/, 11];
3257
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3258
- case 9:
3259
- embeddingResult = _v.sent();
3260
- result = embeddingResult;
3261
- resultString = embeddingResult.content.join(',');
3262
- return [3 /*break*/, 11];
3263
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3264
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3265
- case 11: return [3 /*break*/, 26];
3266
- case 12:
3267
- if (arrayableToArray(tools.script).length === 0) {
3268
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3269
- }
3270
- if (!currentTemplate.contentLanguage) {
3271
- 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 "); }));
3272
- }
3273
- // TODO: DRY [1]
3274
- scriptPipelineExecutionErrors = [];
3275
- _v.label = 13;
3276
- case 13:
3277
- _v.trys.push([13, 20, 21, 22]);
3278
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3279
- _v.label = 14;
3280
- case 14:
3281
- if (!!_m.done) return [3 /*break*/, 19];
3282
- scriptTools = _m.value;
3283
- _v.label = 15;
3284
- case 15:
3285
- _v.trys.push([15, 17, , 18]);
3286
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3287
- scriptLanguage: currentTemplate.contentLanguage,
3288
- script: preparedContent,
3289
- parameters: parameters,
3290
- }))];
3291
- case 16:
3292
- resultString = _v.sent();
3293
- return [3 /*break*/, 19];
3294
- case 17:
3295
- error_2 = _v.sent();
3296
- if (!(error_2 instanceof Error)) {
3297
- throw error_2;
3298
- }
3299
- if (error_2 instanceof UnexpectedError) {
3300
- throw error_2;
3301
- }
3302
- scriptPipelineExecutionErrors.push(error_2);
3303
- return [3 /*break*/, 18];
3304
- case 18:
3305
- _m = _l.next();
3306
- return [3 /*break*/, 14];
3307
- case 19: return [3 /*break*/, 22];
3308
- case 20:
3309
- e_5_1 = _v.sent();
3310
- e_5 = { error: e_5_1 };
3311
- return [3 /*break*/, 22];
3312
- case 21:
3313
- try {
3314
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3315
- }
3316
- finally { if (e_5) throw e_5.error; }
3317
- return [7 /*endfinally*/];
3318
- case 22:
3319
- if (resultString !== null) {
3320
- return [3 /*break*/, 26];
3321
- }
3322
- if (scriptPipelineExecutionErrors.length === 1) {
3323
- throw scriptPipelineExecutionErrors[0];
3324
- }
3325
- else {
3326
- 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
3327
- .map(function (error) { return '- ' + error.message; })
3328
- .join('\n\n')), "\n "); }));
3329
- }
3330
- case 23:
3331
- if (tools.userInterface === undefined) {
3332
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3333
- }
3334
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3335
- promptTitle: currentTemplate.title,
3336
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3337
- defaultValue: replaceParameters(preparedContent, parameters),
3338
- // TODO: [๐Ÿง ] !! Figure out how to define placeholder in .ptbk.md file
3339
- placeholder: undefined,
3340
- priority: priority,
3341
- }))];
3342
- case 24:
3343
- // TODO: [๐ŸŒน] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3344
- resultString = _v.sent();
3345
- return [3 /*break*/, 26];
3346
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3347
- case 26:
3348
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3349
- _v.label = 27;
3350
- case 27:
3351
- _v.trys.push([27, 41, 42, 43]);
3352
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3353
- _v.label = 28;
3354
- case 28:
3355
- if (!!_p.done) return [3 /*break*/, 40];
3356
- functionName = _p.value;
3357
- // TODO: DRY [1]
3358
- scriptPipelineExecutionErrors = [];
3359
- postprocessingError = null;
3360
- _v.label = 29;
3361
- case 29:
3362
- _v.trys.push([29, 36, 37, 38]);
3363
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3364
- _v.label = 30;
3365
- case 30:
3366
- if (!!_r.done) return [3 /*break*/, 35];
3367
- scriptTools = _r.value;
3368
- _v.label = 31;
3369
- case 31:
3370
- _v.trys.push([31, 33, , 34]);
3371
- return [4 /*yield*/, scriptTools.execute({
3372
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3373
- script: "".concat(functionName, "(resultString)"),
3374
- parameters: {
3375
- resultString: resultString || '',
3376
- // Note: No ...parametersForTemplate, because working with result only
3377
- },
3378
- })];
3379
- case 32:
3380
- resultString = _v.sent();
3381
- postprocessingError = null;
3382
- return [3 /*break*/, 35];
3383
- case 33:
3384
- error_3 = _v.sent();
3385
- if (!(error_3 instanceof Error)) {
3386
- throw error_3;
3387
- }
3388
- if (error_3 instanceof UnexpectedError) {
3389
- throw error_3;
3390
- }
3391
- postprocessingError = error_3;
3392
- scriptPipelineExecutionErrors.push(error_3);
3393
- return [3 /*break*/, 34];
3394
- case 34:
3395
- _r = _q.next();
3396
- return [3 /*break*/, 30];
3397
- case 35: return [3 /*break*/, 38];
3398
- case 36:
3399
- e_6_1 = _v.sent();
3400
- e_6 = { error: e_6_1 };
3401
- return [3 /*break*/, 38];
3402
- case 37:
3403
- try {
3404
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3405
- }
3406
- finally { if (e_6) throw e_6.error; }
3407
- return [7 /*endfinally*/];
3408
- case 38:
3409
- if (postprocessingError) {
3410
- throw postprocessingError;
3411
- }
3412
- _v.label = 39;
3413
- case 39:
3414
- _p = _o.next();
3415
- return [3 /*break*/, 28];
3416
- case 40: return [3 /*break*/, 43];
3417
- case 41:
3418
- e_7_1 = _v.sent();
3419
- e_7 = { error: e_7_1 };
3420
- return [3 /*break*/, 43];
3421
- case 42:
3422
- try {
3423
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3424
- }
3425
- finally { if (e_7) throw e_7.error; }
3426
- return [7 /*endfinally*/];
3427
- case 43:
3428
- // TODO: [๐Ÿ’] Unite object for expecting amount and format
3429
- if (currentTemplate.format) {
3430
- if (currentTemplate.format === 'JSON') {
3431
- if (!isValidJsonString(resultString || '')) {
3432
- // TODO: [๐Ÿข] Do more universally via `FormatDefinition`
3433
- try {
3434
- resultString = extractJsonBlock(resultString || '');
3435
- }
3436
- catch (error) {
3437
- keepUnused(error);
3438
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3439
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3440
- }
3441
- }
3442
- }
3443
- else {
3444
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3445
- }
3446
- }
3447
- // TODO: [๐Ÿ’] Unite object for expecting amount and format
3448
- if (currentTemplate.expectations) {
3449
- checkExpectations(currentTemplate.expectations, resultString || '');
3450
- }
3451
- return [2 /*return*/, "break-attempts"];
3452
- case 44:
3453
- error_4 = _v.sent();
3454
- if (!(error_4 instanceof ExpectError)) {
3455
- throw error_4;
3456
- }
3457
- expectError = error_4;
3458
- return [3 /*break*/, 46];
3459
- case 45:
3460
- if (!isJokerAttempt &&
3461
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3462
- prompt
3463
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3464
- // In that case we donโ€™t want to make a report about it because itโ€™s not a llm execution error
3465
- ) {
3466
- // TODO: [๐Ÿง ] Maybe put other templateTypes into report
3467
- executionReport.promptExecutions.push({
3468
- prompt: __assign({}, prompt),
3469
- result: result || undefined,
3470
- error: expectError === null ? undefined : serializeError(expectError),
3471
- });
3472
- }
3473
- return [7 /*endfinally*/];
3474
- case 46:
3475
- if (expectError !== null && attempt === maxAttempts - 1) {
3476
- 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
3477
- .split('\n')
3478
- .map(function (line) { return "> ".concat(line); })
3479
- .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) || '')
3480
- .split('\n')
3481
- .map(function (line) { return "> ".concat(line); })
3482
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3483
- ? 'null'
3484
- : resultString
3485
- .split('\n')
3486
- .map(function (line) { return "> ".concat(line); })
3487
- .join('\n')), "\n ---\n "); }));
3488
- }
3489
- return [2 /*return*/];
3490
- }
3491
- });
3492
- };
3493
- attempt = -jokerParameterNames.length;
3494
- _h.label = 4;
3495
- case 4:
3496
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3497
- return [5 /*yield**/, _loop_5(attempt)];
3498
- case 5:
3499
- state_2 = _h.sent();
3500
- switch (state_2) {
3501
- case "break-attempts": return [3 /*break*/, 7];
3502
- }
3503
- _h.label = 6;
3504
- case 6:
3505
- attempt++;
3506
- return [3 /*break*/, 4];
3507
- case 7:
3508
- //------------------------------------
3509
- /*
3510
-
3511
-
3512
-
3513
-
3514
-
3515
-
3516
-
3517
-
3518
-
3519
- */
3520
- //------------------------------------
3521
- if (resultString === null) {
3522
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3523
- }
3524
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3525
- progress_2 = {
3526
- name: name,
3527
- title: title,
3528
- isStarted: true,
3529
- isDone: true,
3530
- templateType: currentTemplate.templateType,
3531
- parameterName: currentTemplate.resultingParameterName,
3532
- parameterValue: resultString,
3533
- // <- [3]
3534
- };
3535
- if (isReturned) {
3536
- 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)
3537
- .split('\n')
3538
- .map(function (line) { return "> ".concat(line); })
3539
- .join('\n')), "\n\n "); }));
3540
- }
3541
- return [4 /*yield*/, onProgress(progress_2)];
3542
- case 8:
3543
- _h.sent();
3544
- _h.label = 9;
3545
- case 9:
3546
- 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)));
3547
- return [2 /*return*/];
3548
- }
3549
- });
3550
- });
3551
- }
3552
- function filterJustOutputParameters() {
3553
- var e_8, _a;
3554
- var outputParameters = {};
3555
- var _loop_6 = function (parameter) {
3556
- if (parametersToPass[parameter.name] === undefined) {
3557
- // [4]
3558
- 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 "); })));
3559
- return "continue";
3560
- }
3561
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3562
- };
3563
- try {
3564
- // Note: Filter ONLY output parameters
3565
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3566
- var isOutput = _a.isOutput;
3567
- return isOutput;
3568
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3569
- var parameter = _c.value;
3570
- _loop_6(parameter);
3571
- }
3572
- }
3573
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3574
- finally {
3575
- try {
3576
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3577
- }
3578
- finally { if (e_8) throw e_8.error; }
3579
- }
3580
- return outputParameters;
3581
- }
3582
3591
  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;
3583
3592
  var e_1, _e, e_2, _f;
3584
3593
  return __generator(this, function (_g) {
@@ -3760,14 +3769,35 @@ function createPipelineExecutor(options) {
3760
3769
  .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 "); }));
3761
3770
  case 1:
3762
3771
  if (!!currentTemplate) return [3 /*break*/, 3];
3763
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
3772
+ /* [๐Ÿคนโ€โ™‚๏ธ] */ return [4 /*yield*/, Promise.race(resolving_1)];
3764
3773
  case 2:
3765
- /* [5] */ _j.sent();
3774
+ /* [๐Ÿคนโ€โ™‚๏ธ] */ _j.sent();
3766
3775
  return [3 /*break*/, 4];
3767
3776
  case 3:
3768
3777
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3769
- work_1 = executeSingleTemplate(currentTemplate)
3770
- .then(function () {
3778
+ work_1 = executeSingleTemplate({
3779
+ currentTemplate: currentTemplate,
3780
+ preparedPipeline: preparedPipeline,
3781
+ parametersToPass: parametersToPass,
3782
+ tools: tools,
3783
+ llmTools: llmTools,
3784
+ onProgress: function (progress) {
3785
+ if (isReturned) {
3786
+ 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)
3787
+ .split('\n')
3788
+ .map(function (line) { return "> ".concat(line); })
3789
+ .join('\n')), "\n "); }));
3790
+ }
3791
+ if (onProgress) {
3792
+ onProgress(progress);
3793
+ }
3794
+ },
3795
+ maxExecutionAttempts: maxExecutionAttempts,
3796
+ $executionReport: executionReport,
3797
+ pipelineIdentification: pipelineIdentification,
3798
+ })
3799
+ .then(function (newParametersToPass) {
3800
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3771
3801
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3772
3802
  })
3773
3803
  .then(function () {
@@ -3799,7 +3829,7 @@ function createPipelineExecutor(options) {
3799
3829
  var result = _a.result;
3800
3830
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3801
3831
  })), false));
3802
- outputParameters_1 = filterJustOutputParameters();
3832
+ outputParameters_1 = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
3803
3833
  isReturned = true;
3804
3834
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3805
3835
  // Note: Wait a short time to prevent race conditions
@@ -3822,7 +3852,7 @@ function createPipelineExecutor(options) {
3822
3852
  var result = _a.result;
3823
3853
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3824
3854
  })), false));
3825
- outputParameters = filterJustOutputParameters();
3855
+ outputParameters = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
3826
3856
  isReturned = true;
3827
3857
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3828
3858
  // Note: Wait a short time to prevent race conditions
@@ -3846,6 +3876,7 @@ function createPipelineExecutor(options) {
3846
3876
  return pipelineExecutor;
3847
3877
  }
3848
3878
  /**
3879
+ * TODO: [๐Ÿคนโ€โ™‚๏ธ] Make some smarter system for limiting concurrent executions MAX_PARALLEL_TOTAL, MAX_PARALLEL_PER_LLM
3849
3880
  * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3850
3881
  * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3851
3882
  * TODO: [๐Ÿง ][๐ŸŒณ] Use here `countTotalUsage` and put preparation and prepared pipiline to report
@@ -3854,7 +3885,7 @@ function createPipelineExecutor(options) {
3854
3885
  * TODO: [๐Ÿง ] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3855
3886
  * TODO: [๐Ÿ‘ง] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3856
3887
  * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3857
- * TODO: [๐Ÿง ][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3888
+ * TODO: [๐Ÿง ][๐Ÿธ] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3858
3889
  * TODO: [๐Ÿ› ] Actions, instruments (and maybe knowledge) => Functions and tools
3859
3890
  * TODO: [๐Ÿง ][๐Ÿ’ท] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
3860
3891
  */
@@ -5114,6 +5145,8 @@ var foreachCommandParser = {
5114
5145
  */
5115
5146
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5116
5147
  var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5148
+ // TODO: !!!!!! Detect double use
5149
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
5117
5150
  $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5118
5151
  keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
5119
5152
  // Note: [๐Ÿญ] FOREACH apply has some sideeffects on different places in codebase