@promptbook/cli 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
@@ -20,7 +20,7 @@ import OpenAI from 'openai';
20
20
  /**
21
21
  * The version of the Promptbook library
22
22
  */
23
- var PROMPTBOOK_VERSION = '0.69.0-1';
23
+ var PROMPTBOOK_VERSION = '0.69.0-3';
24
24
  // TODO: !!!! List here all the versions and annotate + put into script
25
25
 
26
26
  /*! *****************************************************************************
@@ -473,6 +473,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
473
473
  'samples',
474
474
  'modelName',
475
475
  'currentDate',
476
+ // <- TODO: !!!!! list here all command names
476
477
  // <- TODO: Add more like 'date', 'modelName',...
477
478
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
478
479
  ]);
@@ -1049,7 +1050,7 @@ function forEachAsync(array, options, callbackfunction) {
1049
1050
  });
1050
1051
  }
1051
1052
 
1052
- 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"}];
1053
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-3",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-3",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-3",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-3",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1053
1054
 
1054
1055
  /**
1055
1056
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -2196,124 +2197,6 @@ function assertsExecutionSuccessful(executionResult) {
2196
2197
  * TODO: [๐Ÿง ] Can this return type be better typed than void
2197
2198
  */
2198
2199
 
2199
- /**
2200
- * Parses the given script and returns the list of all used variables that are not defined in the script
2201
- *
2202
- * @param script from which to extract the variables
2203
- * @returns the list of variable names
2204
- * @throws {ParseError} if the script is invalid
2205
- * @public exported from `@promptbook/utils`
2206
- */
2207
- function extractVariables(script) {
2208
- var variables = new Set();
2209
- script = "(()=>{".concat(script, "})()");
2210
- try {
2211
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2212
- try {
2213
- eval(script);
2214
- }
2215
- catch (error) {
2216
- if (!(error instanceof ReferenceError)) {
2217
- throw error;
2218
- }
2219
- var undefinedName = error.message.split(' ')[0];
2220
- /*
2221
- Note: Parsing the error
2222
- [PipelineUrlError: thing is not defined]
2223
- */
2224
- if (!undefinedName) {
2225
- throw error;
2226
- }
2227
- if (script.includes(undefinedName + '(')) {
2228
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2229
- }
2230
- else {
2231
- variables.add(undefinedName);
2232
- script = "const ".concat(undefinedName, " = '';") + script;
2233
- }
2234
- }
2235
- }
2236
- catch (error) {
2237
- if (!(error instanceof Error)) {
2238
- throw error;
2239
- }
2240
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2241
- }
2242
- return variables;
2243
- }
2244
- /**
2245
- * TODO: [๐Ÿ”ฃ] Support for multiple languages - python, java,...
2246
- */
2247
-
2248
- /**
2249
- * Parses the template and returns the set of all used parameters
2250
- *
2251
- * @param template the template with used parameters
2252
- * @returns the set of parameter names
2253
- * @throws {ParseError} if the script is invalid
2254
- * @public exported from `@promptbook/utils`
2255
- */
2256
- function extractParameterNamesFromTemplate(template) {
2257
- var e_1, _a, e_2, _b, e_3, _c;
2258
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2259
- var parameterNames = new Set();
2260
- try {
2261
- 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()) {
2262
- var parameterName = _e.value;
2263
- parameterNames.add(parameterName);
2264
- }
2265
- }
2266
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2267
- finally {
2268
- try {
2269
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2270
- }
2271
- finally { if (e_1) throw e_1.error; }
2272
- }
2273
- if (templateType === 'SCRIPT_TEMPLATE') {
2274
- try {
2275
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2276
- var parameterName = _g.value;
2277
- parameterNames.add(parameterName);
2278
- }
2279
- }
2280
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2281
- finally {
2282
- try {
2283
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2284
- }
2285
- finally { if (e_2) throw e_2.error; }
2286
- }
2287
- }
2288
- try {
2289
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2290
- var jokerName = _j.value;
2291
- parameterNames.add(jokerName);
2292
- }
2293
- }
2294
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2295
- finally {
2296
- try {
2297
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2298
- }
2299
- finally { if (e_3) throw e_3.error; }
2300
- }
2301
- parameterNames.delete('content');
2302
- // <- Note {websiteContent} is used in `preparedContent`
2303
- // Note: [๐Ÿญ] Fixing dependent subparameterName from FOREACH command
2304
- if (foreach !== undefined) {
2305
- if (parameterNames.has(foreach.subparameterName)) {
2306
- parameterNames.delete(foreach.subparameterName);
2307
- parameterNames.add(foreach.parameterName);
2308
- // <- TODO: [๐ŸšŽ] Warn/logic error when `subparameterName` not used
2309
- }
2310
- }
2311
- return parameterNames;
2312
- }
2313
- /**
2314
- * TODO: [๐Ÿ”ฃ] If script require contentLanguage
2315
- */
2316
-
2317
2200
  /**
2318
2201
  * Serializes an error into a [๐Ÿš‰] JSON-serializable object
2319
2202
  *
@@ -2331,27 +2214,6 @@ function serializeError(error) {
2331
2214
  };
2332
2215
  }
2333
2216
 
2334
- /**
2335
- * Function isValidJsonString will tell you if the string is valid JSON or not
2336
- *
2337
- * @public exported from `@promptbook/utils`
2338
- */
2339
- function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
2340
- try {
2341
- JSON.parse(value);
2342
- return true;
2343
- }
2344
- catch (error) {
2345
- if (!(error instanceof Error)) {
2346
- throw error;
2347
- }
2348
- if (error.message.includes('Unexpected token')) {
2349
- return false;
2350
- }
2351
- return false;
2352
- }
2353
- }
2354
-
2355
2217
  /**
2356
2218
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2357
2219
  *
@@ -2645,122 +2507,6 @@ function joinLlmExecutionTools() {
2645
2507
  * TODO: [๐Ÿ‘ทโ€โ™‚๏ธ] @@@ Manual about construction of llmTools
2646
2508
  */
2647
2509
 
2648
- /**
2649
- * Extracts all code blocks from markdown.
2650
- *
2651
- * Note: There are multiple simmilar function:
2652
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2653
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2654
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2655
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2656
- *
2657
- * @param markdown any valid markdown
2658
- * @returns code blocks with language and content
2659
- * @throws {ParseError} if block is not closed properly
2660
- * @public exported from `@promptbook/markdown-utils`
2661
- */
2662
- function extractAllBlocksFromMarkdown(markdown) {
2663
- var e_1, _a;
2664
- var codeBlocks = [];
2665
- var lines = markdown.split('\n');
2666
- // Note: [0] Ensure that the last block notated by gt > will be closed
2667
- lines.push('');
2668
- var currentCodeBlock = null;
2669
- try {
2670
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2671
- var line = lines_1_1.value;
2672
- if (line.startsWith('> ') || line === '>') {
2673
- if (currentCodeBlock === null) {
2674
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2675
- } /* not else */
2676
- if (currentCodeBlock.blockNotation === '>') {
2677
- if (currentCodeBlock.content !== '') {
2678
- currentCodeBlock.content += '\n';
2679
- }
2680
- currentCodeBlock.content += line.slice(2);
2681
- }
2682
- }
2683
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2684
- codeBlocks.push(currentCodeBlock);
2685
- currentCodeBlock = null;
2686
- }
2687
- /* not else */
2688
- if (line.startsWith('```')) {
2689
- var language = line.slice(3).trim() || null;
2690
- if (currentCodeBlock === null) {
2691
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2692
- }
2693
- else {
2694
- if (language !== null) {
2695
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2696
- }
2697
- codeBlocks.push(currentCodeBlock);
2698
- currentCodeBlock = null;
2699
- }
2700
- }
2701
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2702
- if (currentCodeBlock.content !== '') {
2703
- currentCodeBlock.content += '\n';
2704
- }
2705
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2706
- }
2707
- }
2708
- }
2709
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2710
- finally {
2711
- try {
2712
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2713
- }
2714
- finally { if (e_1) throw e_1.error; }
2715
- }
2716
- if (currentCodeBlock !== null) {
2717
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2718
- }
2719
- return codeBlocks;
2720
- }
2721
- /**
2722
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2723
- */
2724
-
2725
- /**
2726
- * Extracts extracts exactly one valid JSON code block
2727
- *
2728
- * - When given string is a valid JSON as it is, it just returns it
2729
- * - When there is no JSON code block the function throws a `ParseError`
2730
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2731
- *
2732
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2733
- * Note: There are multiple simmilar function:
2734
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2735
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2736
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2737
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2738
- *
2739
- * @public exported from `@promptbook/markdown-utils`
2740
- * @throws {ParseError} if there is no valid JSON block in the markdown
2741
- */
2742
- function extractJsonBlock(markdown) {
2743
- if (isValidJsonString(markdown)) {
2744
- return markdown;
2745
- }
2746
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2747
- var jsonBlocks = codeBlocks.filter(function (_a) {
2748
- var content = _a.content;
2749
- return isValidJsonString(content);
2750
- });
2751
- if (jsonBlocks.length === 0) {
2752
- throw new Error('There is no valid JSON block in the markdown');
2753
- }
2754
- if (jsonBlocks.length > 1) {
2755
- throw new Error('There are multiple JSON code blocks in the markdown');
2756
- }
2757
- return jsonBlocks[0].content;
2758
- }
2759
- /**
2760
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2761
- * TODO: [๐Ÿข] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2762
- */
2763
-
2764
2510
  /**
2765
2511
  * Determine if the pipeline is fully prepared
2766
2512
  *
@@ -2813,40 +2559,278 @@ function arrayableToArray(input) {
2813
2559
  }
2814
2560
 
2815
2561
  /**
2816
- * Just says that the variable is not used but should be kept
2817
- * No side effects.
2562
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2818
2563
  *
2819
- * Note: It can be usefull for:
2564
+ * @param script from which to extract the variables
2565
+ * @returns the list of variable names
2566
+ * @throws {ParseError} if the script is invalid
2567
+ * @public exported from `@promptbook/utils`
2568
+ */
2569
+ function extractVariables(script) {
2570
+ var variables = new Set();
2571
+ script = "(()=>{".concat(script, "})()");
2572
+ try {
2573
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2574
+ try {
2575
+ eval(script);
2576
+ }
2577
+ catch (error) {
2578
+ if (!(error instanceof ReferenceError)) {
2579
+ throw error;
2580
+ }
2581
+ var undefinedName = error.message.split(' ')[0];
2582
+ /*
2583
+ Note: Parsing the error
2584
+ [PipelineUrlError: thing is not defined]
2585
+ */
2586
+ if (!undefinedName) {
2587
+ throw error;
2588
+ }
2589
+ if (script.includes(undefinedName + '(')) {
2590
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2591
+ }
2592
+ else {
2593
+ variables.add(undefinedName);
2594
+ script = "const ".concat(undefinedName, " = '';") + script;
2595
+ }
2596
+ }
2597
+ }
2598
+ catch (error) {
2599
+ if (!(error instanceof Error)) {
2600
+ throw error;
2601
+ }
2602
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2603
+ }
2604
+ return variables;
2605
+ }
2606
+ /**
2607
+ * TODO: [๐Ÿ”ฃ] Support for multiple languages - python, java,...
2608
+ */
2609
+
2610
+ /**
2611
+ * Parses the template and returns the set of all used parameters
2820
2612
  *
2821
- * 1) Suppressing eager optimization of unused imports
2822
- * 2) Suppressing eslint errors of unused variables in the tests
2823
- * 3) Keeping the type of the variable for type testing
2613
+ * @param template the template with used parameters
2614
+ * @returns the set of parameter names
2615
+ * @throws {ParseError} if the script is invalid
2616
+ * @public exported from `@promptbook/utils`
2617
+ */
2618
+ function extractParameterNamesFromTemplate(template) {
2619
+ var e_1, _a, e_2, _b, e_3, _c;
2620
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2621
+ var parameterNames = new Set();
2622
+ try {
2623
+ for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2624
+ var parameterName = _e.value;
2625
+ parameterNames.add(parameterName);
2626
+ }
2627
+ }
2628
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2629
+ finally {
2630
+ try {
2631
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2632
+ }
2633
+ finally { if (e_1) throw e_1.error; }
2634
+ }
2635
+ if (templateType === 'SCRIPT_TEMPLATE') {
2636
+ try {
2637
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2638
+ var parameterName = _g.value;
2639
+ parameterNames.add(parameterName);
2640
+ }
2641
+ }
2642
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2643
+ finally {
2644
+ try {
2645
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2646
+ }
2647
+ finally { if (e_2) throw e_2.error; }
2648
+ }
2649
+ }
2650
+ try {
2651
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2652
+ var jokerName = _j.value;
2653
+ parameterNames.add(jokerName);
2654
+ }
2655
+ }
2656
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2657
+ finally {
2658
+ try {
2659
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2660
+ }
2661
+ finally { if (e_3) throw e_3.error; }
2662
+ }
2663
+ parameterNames.delete('content');
2664
+ // <- Note {websiteContent} is used in `preparedContent`
2665
+ // Note: [๐Ÿญ] Fixing dependent subparameterName from FOREACH command
2666
+ if (foreach !== undefined) {
2667
+ if (parameterNames.has(foreach.subparameterName)) {
2668
+ parameterNames.delete(foreach.subparameterName);
2669
+ parameterNames.add(foreach.parameterName);
2670
+ // <- TODO: [๐ŸšŽ] Warn/logic error when `subparameterName` not used
2671
+ }
2672
+ }
2673
+ return parameterNames;
2674
+ }
2675
+ /**
2676
+ * TODO: [๐Ÿ”ฃ] If script require contentLanguage
2677
+ */
2678
+
2679
+ /**
2680
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2824
2681
  *
2825
- * @param value any values
2826
- * @returns void
2827
- * @private within the repository
2682
+ * @public exported from `@promptbook/utils`
2828
2683
  */
2829
- function keepUnused() {
2830
- var valuesToKeep = [];
2831
- for (var _i = 0; _i < arguments.length; _i++) {
2832
- valuesToKeep[_i] = arguments[_i];
2684
+ function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
2685
+ try {
2686
+ JSON.parse(value);
2687
+ return true;
2688
+ }
2689
+ catch (error) {
2690
+ if (!(error instanceof Error)) {
2691
+ throw error;
2692
+ }
2693
+ if (error.message.includes('Unexpected token')) {
2694
+ return false;
2695
+ }
2696
+ return false;
2833
2697
  }
2834
2698
  }
2835
2699
 
2836
2700
  /**
2837
- * Just marks a place of place where should be something implemented
2701
+ * Extracts all code blocks from markdown.
2702
+ *
2703
+ * Note: There are multiple simmilar function:
2704
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2705
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2706
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2707
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2708
+ *
2709
+ * @param markdown any valid markdown
2710
+ * @returns code blocks with language and content
2711
+ * @throws {ParseError} if block is not closed properly
2712
+ * @public exported from `@promptbook/markdown-utils`
2713
+ */
2714
+ function extractAllBlocksFromMarkdown(markdown) {
2715
+ var e_1, _a;
2716
+ var codeBlocks = [];
2717
+ var lines = markdown.split('\n');
2718
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2719
+ lines.push('');
2720
+ var currentCodeBlock = null;
2721
+ try {
2722
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2723
+ var line = lines_1_1.value;
2724
+ if (line.startsWith('> ') || line === '>') {
2725
+ if (currentCodeBlock === null) {
2726
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2727
+ } /* not else */
2728
+ if (currentCodeBlock.blockNotation === '>') {
2729
+ if (currentCodeBlock.content !== '') {
2730
+ currentCodeBlock.content += '\n';
2731
+ }
2732
+ currentCodeBlock.content += line.slice(2);
2733
+ }
2734
+ }
2735
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2736
+ codeBlocks.push(currentCodeBlock);
2737
+ currentCodeBlock = null;
2738
+ }
2739
+ /* not else */
2740
+ if (line.startsWith('```')) {
2741
+ var language = line.slice(3).trim() || null;
2742
+ if (currentCodeBlock === null) {
2743
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2744
+ }
2745
+ else {
2746
+ if (language !== null) {
2747
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2748
+ }
2749
+ codeBlocks.push(currentCodeBlock);
2750
+ currentCodeBlock = null;
2751
+ }
2752
+ }
2753
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2754
+ if (currentCodeBlock.content !== '') {
2755
+ currentCodeBlock.content += '\n';
2756
+ }
2757
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2758
+ }
2759
+ }
2760
+ }
2761
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2762
+ finally {
2763
+ try {
2764
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2765
+ }
2766
+ finally { if (e_1) throw e_1.error; }
2767
+ }
2768
+ if (currentCodeBlock !== null) {
2769
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2770
+ }
2771
+ return codeBlocks;
2772
+ }
2773
+ /**
2774
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2775
+ */
2776
+
2777
+ /**
2778
+ * Extracts extracts exactly one valid JSON code block
2779
+ *
2780
+ * - When given string is a valid JSON as it is, it just returns it
2781
+ * - When there is no JSON code block the function throws a `ParseError`
2782
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
2783
+ *
2784
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
2785
+ * Note: There are multiple simmilar function:
2786
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2787
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2788
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2789
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2790
+ *
2791
+ * @public exported from `@promptbook/markdown-utils`
2792
+ * @throws {ParseError} if there is no valid JSON block in the markdown
2793
+ */
2794
+ function extractJsonBlock(markdown) {
2795
+ if (isValidJsonString(markdown)) {
2796
+ return markdown;
2797
+ }
2798
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2799
+ var jsonBlocks = codeBlocks.filter(function (_a) {
2800
+ var content = _a.content;
2801
+ return isValidJsonString(content);
2802
+ });
2803
+ if (jsonBlocks.length === 0) {
2804
+ throw new Error('There is no valid JSON block in the markdown');
2805
+ }
2806
+ if (jsonBlocks.length > 1) {
2807
+ throw new Error('There are multiple JSON code blocks in the markdown');
2808
+ }
2809
+ return jsonBlocks[0].content;
2810
+ }
2811
+ /**
2812
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2813
+ * TODO: [๐Ÿข] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2814
+ */
2815
+
2816
+ /**
2817
+ * Just says that the variable is not used but should be kept
2838
2818
  * No side effects.
2839
2819
  *
2840
- * Note: It can be usefull suppressing eslint errors of unused variables
2820
+ * Note: It can be usefull for:
2821
+ *
2822
+ * 1) Suppressing eager optimization of unused imports
2823
+ * 2) Suppressing eslint errors of unused variables in the tests
2824
+ * 3) Keeping the type of the variable for type testing
2841
2825
  *
2842
2826
  * @param value any values
2843
2827
  * @returns void
2844
2828
  * @private within the repository
2845
2829
  */
2846
- function TODO_USE() {
2847
- var value = [];
2830
+ function keepUnused() {
2831
+ var valuesToKeep = [];
2848
2832
  for (var _i = 0; _i < arguments.length; _i++) {
2849
- value[_i] = arguments[_i];
2833
+ valuesToKeep[_i] = arguments[_i];
2850
2834
  }
2851
2835
  }
2852
2836
 
@@ -3070,53 +3054,646 @@ function countSentences(text) {
3070
3054
  }
3071
3055
 
3072
3056
  /**
3073
- * Counts number of words in the text
3074
- *
3075
- * @public exported from `@promptbook/utils`
3057
+ * Counts number of words in the text
3058
+ *
3059
+ * @public exported from `@promptbook/utils`
3060
+ */
3061
+ function countWords(text) {
3062
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3063
+ text = removeDiacritics(text);
3064
+ return text.split(/[^a-zะฐ-ั0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3065
+ }
3066
+
3067
+ /**
3068
+ * Index of all counter functions
3069
+ *
3070
+ * @public exported from `@promptbook/utils`
3071
+ */
3072
+ var CountUtils = {
3073
+ CHARACTERS: countCharacters,
3074
+ WORDS: countWords,
3075
+ SENTENCES: countSentences,
3076
+ PARAGRAPHS: countParagraphs,
3077
+ LINES: countLines,
3078
+ PAGES: countPages,
3079
+ };
3080
+
3081
+ /**
3082
+ * Function checkExpectations will check if the expectations on given value are met
3083
+ *
3084
+ * Note: There are two simmilar functions:
3085
+ * - `checkExpectations` which throws an error if the expectations are not met
3086
+ * - `isPassingExpectations` which returns a boolean
3087
+ *
3088
+ * @throws {ExpectError} if the expectations are not met
3089
+ * @returns {void} Nothing
3090
+ * @private internal function of `createPipelineExecutor`
3091
+ */
3092
+ function checkExpectations(expectations, value) {
3093
+ var e_1, _a;
3094
+ try {
3095
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3096
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3097
+ var amount = CountUtils[unit.toUpperCase()](value);
3098
+ if (min && amount < min) {
3099
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3100
+ } /* not else */
3101
+ if (max && amount > max) {
3102
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3103
+ }
3104
+ }
3105
+ }
3106
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3107
+ finally {
3108
+ try {
3109
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3110
+ }
3111
+ finally { if (e_1) throw e_1.error; }
3112
+ }
3113
+ }
3114
+ /**
3115
+ * TODO: [๐Ÿ’] Unite object for expecting amount and format
3116
+ */
3117
+
3118
+ /**
3119
+ * Just marks a place of place where should be something implemented
3120
+ * No side effects.
3121
+ *
3122
+ * Note: It can be usefull suppressing eslint errors of unused variables
3123
+ *
3124
+ * @param value any values
3125
+ * @returns void
3126
+ * @private within the repository
3127
+ */
3128
+ function TODO_USE() {
3129
+ var value = [];
3130
+ for (var _i = 0; _i < arguments.length; _i++) {
3131
+ value[_i] = arguments[_i];
3132
+ }
3133
+ }
3134
+
3135
+ /**
3136
+ * @private @@@
3137
+ */
3138
+ function getContextForTemplate(template) {
3139
+ return __awaiter(this, void 0, void 0, function () {
3140
+ return __generator(this, function (_a) {
3141
+ TODO_USE(template);
3142
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [๐Ÿ] Implement */];
3143
+ });
3144
+ });
3145
+ }
3146
+
3147
+ /**
3148
+ * @private @@@
3149
+ */
3150
+ function getKnowledgeForTemplate(preparedPipeline, template) {
3151
+ return __awaiter(this, void 0, void 0, function () {
3152
+ return __generator(this, function (_a) {
3153
+ // TODO: [โ™จ] Implement Better - use real index and keyword search from `template` and {samples}
3154
+ TODO_USE(template);
3155
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3156
+ var content = _a.content;
3157
+ return "- ".concat(content);
3158
+ }).join('\n')];
3159
+ });
3160
+ });
3161
+ }
3162
+
3163
+ /**
3164
+ * @private @@@
3165
+ */
3166
+ function getSamplesForTemplate(template) {
3167
+ return __awaiter(this, void 0, void 0, function () {
3168
+ return __generator(this, function (_a) {
3169
+ // TODO: [โ™จ] Implement Better - use real index and keyword search
3170
+ TODO_USE(template);
3171
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [โ™จ] Implement */];
3172
+ });
3173
+ });
3174
+ }
3175
+
3176
+ /**
3177
+ * @private @@@
3178
+ */
3179
+ function getReservedParametersForTemplate(preparedPipeline, template, pipelineIdentification) {
3180
+ return __awaiter(this, void 0, void 0, function () {
3181
+ var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3182
+ var e_1, _a;
3183
+ return __generator(this, function (_b) {
3184
+ switch (_b.label) {
3185
+ case 0: return [4 /*yield*/, getContextForTemplate(template)];
3186
+ case 1:
3187
+ context = _b.sent();
3188
+ return [4 /*yield*/, getKnowledgeForTemplate(preparedPipeline, template)];
3189
+ case 2:
3190
+ knowledge = _b.sent();
3191
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3192
+ case 3:
3193
+ samples = _b.sent();
3194
+ currentDate = new Date().toISOString();
3195
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3196
+ reservedParameters = {
3197
+ content: RESERVED_PARAMETER_RESTRICTED,
3198
+ context: context,
3199
+ knowledge: knowledge,
3200
+ samples: samples,
3201
+ currentDate: currentDate,
3202
+ modelName: modelName,
3203
+ };
3204
+ _loop_1 = function (parameterName) {
3205
+ if (reservedParameters[parameterName] === undefined) {
3206
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3207
+ }
3208
+ };
3209
+ try {
3210
+ // Note: Doublecheck that ALL reserved parameters are defined:
3211
+ for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3212
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3213
+ _loop_1(parameterName);
3214
+ }
3215
+ }
3216
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3217
+ finally {
3218
+ try {
3219
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3220
+ }
3221
+ finally { if (e_1) throw e_1.error; }
3222
+ }
3223
+ return [2 /*return*/, reservedParameters];
3224
+ }
3225
+ });
3226
+ });
3227
+ }
3228
+
3229
+ /**
3230
+ * @private @@@
3076
3231
  */
3077
- function countWords(text) {
3078
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3079
- text = removeDiacritics(text);
3080
- return text.split(/[^a-zะฐ-ั0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3232
+ function executeSingleTemplate(options) {
3233
+ return __awaiter(this, void 0, void 0, function () {
3234
+ var currentTemplate, preparedPipeline, parametersToPass, tools, llmTools, onProgress, maxExecutionAttempts, $executionReport, pipelineIdentification, name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_2, attempt, state_1;
3235
+ var e_1, _f, _g;
3236
+ return __generator(this, function (_h) {
3237
+ switch (_h.label) {
3238
+ case 0:
3239
+ currentTemplate = options.currentTemplate, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, llmTools = options.llmTools, onProgress = options.onProgress, maxExecutionAttempts = options.maxExecutionAttempts, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3240
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3241
+ title = currentTemplate.title;
3242
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3243
+ return [4 /*yield*/, onProgress({
3244
+ name: name,
3245
+ title: title,
3246
+ isStarted: false,
3247
+ isDone: false,
3248
+ templateType: currentTemplate.templateType,
3249
+ parameterName: currentTemplate.resultingParameterName,
3250
+ parameterValue: null,
3251
+ // <- [๐Ÿธ]
3252
+ })];
3253
+ case 1:
3254
+ _h.sent();
3255
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3256
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3257
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3258
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3259
+ .map(function (name) { return "{".concat(name, "}"); })
3260
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3261
+ .map(function (name) { return "{".concat(name, "}"); })
3262
+ .join(', '), "\n\n "); }));
3263
+ }
3264
+ _b = (_a = Object).freeze;
3265
+ _c = [{}];
3266
+ return [4 /*yield*/, getReservedParametersForTemplate(preparedPipeline, currentTemplate, pipelineIdentification)];
3267
+ case 2:
3268
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3269
+ definedParameterNames = new Set(Object.keys(definedParameters));
3270
+ parameters = {};
3271
+ _loop_1 = function (parameterName) {
3272
+ // Situation: Parameter is defined and used
3273
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3274
+ parameters[parameterName] = definedParameters[parameterName];
3275
+ }
3276
+ // Situation: Parameter is defined but NOT used
3277
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3278
+ // Situation: Parameter is NOT defined BUT used
3279
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3280
+ // Houston, we have a problem
3281
+ // Note: Checking part is also done in `validatePipeline`, but itโ€™s good to doublecheck
3282
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3283
+ }
3284
+ };
3285
+ try {
3286
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3287
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3288
+ parameterName = _e.value;
3289
+ _loop_1(parameterName);
3290
+ }
3291
+ }
3292
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3293
+ finally {
3294
+ try {
3295
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3296
+ }
3297
+ finally { if (e_1) throw e_1.error; }
3298
+ }
3299
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3300
+ Object.freeze(parameters);
3301
+ result = null;
3302
+ resultString = null;
3303
+ expectError = null;
3304
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3305
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3306
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3307
+ .split('{content}')
3308
+ .join(currentTemplate.content);
3309
+ _loop_2 = function (attempt) {
3310
+ var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_1, e_2_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_2, e_3_1, e_4_1, error_3;
3311
+ var e_2, _s, e_4, _t, e_3, _u;
3312
+ return __generator(this, function (_v) {
3313
+ switch (_v.label) {
3314
+ case 0:
3315
+ isJokerAttempt = attempt < 0;
3316
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3317
+ // TODO: [๐Ÿง ] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3318
+ if (isJokerAttempt && !jokerParameterName) {
3319
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3320
+ }
3321
+ result = null;
3322
+ resultString = null;
3323
+ expectError = null;
3324
+ if (isJokerAttempt) {
3325
+ if (parameters[jokerParameterName] === undefined) {
3326
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3327
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3328
+ }
3329
+ else {
3330
+ resultString = parameters[jokerParameterName];
3331
+ }
3332
+ }
3333
+ _v.label = 1;
3334
+ case 1:
3335
+ _v.trys.push([1, 44, 45, 46]);
3336
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3337
+ _j = currentTemplate.templateType;
3338
+ switch (_j) {
3339
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3340
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3341
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3342
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3343
+ }
3344
+ return [3 /*break*/, 25];
3345
+ case 2:
3346
+ resultString = replaceParameters(preparedContent, parameters);
3347
+ return [3 /*break*/, 26];
3348
+ case 3:
3349
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3350
+ prompt = {
3351
+ title: currentTemplate.title,
3352
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3353
+ ? preparedPipeline.pipelineUrl
3354
+ : 'anonymous' /* <- TODO: [๐Ÿง ] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3355
+ parameters: parameters,
3356
+ content: preparedContent,
3357
+ modelRequirements: modelRequirements,
3358
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3359
+ var name = _a.name;
3360
+ return name === currentTemplate.personaName;
3361
+ }) || {})), currentTemplate.expectations),
3362
+ format: currentTemplate.format,
3363
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3364
+ }; // <- TODO: Not very good type guard
3365
+ _k = modelRequirements.modelVariant;
3366
+ switch (_k) {
3367
+ case 'CHAT': return [3 /*break*/, 4];
3368
+ case 'COMPLETION': return [3 /*break*/, 6];
3369
+ case 'EMBEDDING': return [3 /*break*/, 8];
3370
+ }
3371
+ return [3 /*break*/, 10];
3372
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3373
+ case 5:
3374
+ chatResult = _v.sent();
3375
+ // TODO: [๐Ÿฌ] Destroy chatThread
3376
+ result = chatResult;
3377
+ resultString = chatResult.content;
3378
+ return [3 /*break*/, 11];
3379
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3380
+ case 7:
3381
+ completionResult = _v.sent();
3382
+ result = completionResult;
3383
+ resultString = completionResult.content;
3384
+ return [3 /*break*/, 11];
3385
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3386
+ case 9:
3387
+ // TODO: [๐Ÿง ] This is weird, embedding model can not be used such a way in the pipeline
3388
+ embeddingResult = _v.sent();
3389
+ result = embeddingResult;
3390
+ resultString = embeddingResult.content.join(',');
3391
+ return [3 /*break*/, 11];
3392
+ case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3393
+ case 11: return [3 /*break*/, 26];
3394
+ case 12:
3395
+ if (arrayableToArray(tools.script).length === 0) {
3396
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3397
+ }
3398
+ if (!currentTemplate.contentLanguage) {
3399
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3400
+ }
3401
+ // TODO: DRY [1]
3402
+ scriptPipelineExecutionErrors = [];
3403
+ _v.label = 13;
3404
+ case 13:
3405
+ _v.trys.push([13, 20, 21, 22]);
3406
+ _l = (e_2 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3407
+ _v.label = 14;
3408
+ case 14:
3409
+ if (!!_m.done) return [3 /*break*/, 19];
3410
+ scriptTools = _m.value;
3411
+ _v.label = 15;
3412
+ case 15:
3413
+ _v.trys.push([15, 17, , 18]);
3414
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3415
+ scriptLanguage: currentTemplate.contentLanguage,
3416
+ script: preparedContent,
3417
+ parameters: parameters,
3418
+ }))];
3419
+ case 16:
3420
+ resultString = _v.sent();
3421
+ return [3 /*break*/, 19];
3422
+ case 17:
3423
+ error_1 = _v.sent();
3424
+ if (!(error_1 instanceof Error)) {
3425
+ throw error_1;
3426
+ }
3427
+ if (error_1 instanceof UnexpectedError) {
3428
+ throw error_1;
3429
+ }
3430
+ scriptPipelineExecutionErrors.push(error_1);
3431
+ return [3 /*break*/, 18];
3432
+ case 18:
3433
+ _m = _l.next();
3434
+ return [3 /*break*/, 14];
3435
+ case 19: return [3 /*break*/, 22];
3436
+ case 20:
3437
+ e_2_1 = _v.sent();
3438
+ e_2 = { error: e_2_1 };
3439
+ return [3 /*break*/, 22];
3440
+ case 21:
3441
+ try {
3442
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3443
+ }
3444
+ finally { if (e_2) throw e_2.error; }
3445
+ return [7 /*endfinally*/];
3446
+ case 22:
3447
+ if (resultString !== null) {
3448
+ return [3 /*break*/, 26];
3449
+ }
3450
+ if (scriptPipelineExecutionErrors.length === 1) {
3451
+ throw scriptPipelineExecutionErrors[0];
3452
+ }
3453
+ else {
3454
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3455
+ .map(function (error) { return '- ' + error.message; })
3456
+ .join('\n\n')), "\n "); }));
3457
+ }
3458
+ case 23:
3459
+ if (tools.userInterface === undefined) {
3460
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3461
+ }
3462
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3463
+ promptTitle: currentTemplate.title,
3464
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3465
+ defaultValue: replaceParameters(preparedContent, parameters),
3466
+ // TODO: [๐Ÿง ] !! Figure out how to define placeholder in .ptbk.md file
3467
+ placeholder: undefined,
3468
+ priority: priority,
3469
+ }))];
3470
+ case 24:
3471
+ // TODO: [๐ŸŒน] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3472
+ resultString = _v.sent();
3473
+ return [3 /*break*/, 26];
3474
+ case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3475
+ case 26:
3476
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3477
+ _v.label = 27;
3478
+ case 27:
3479
+ _v.trys.push([27, 41, 42, 43]);
3480
+ _o = (e_4 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3481
+ _v.label = 28;
3482
+ case 28:
3483
+ if (!!_p.done) return [3 /*break*/, 40];
3484
+ functionName = _p.value;
3485
+ // TODO: DRY [1]
3486
+ scriptPipelineExecutionErrors = [];
3487
+ postprocessingError = null;
3488
+ _v.label = 29;
3489
+ case 29:
3490
+ _v.trys.push([29, 36, 37, 38]);
3491
+ _q = (e_3 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3492
+ _v.label = 30;
3493
+ case 30:
3494
+ if (!!_r.done) return [3 /*break*/, 35];
3495
+ scriptTools = _r.value;
3496
+ _v.label = 31;
3497
+ case 31:
3498
+ _v.trys.push([31, 33, , 34]);
3499
+ return [4 /*yield*/, scriptTools.execute({
3500
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3501
+ script: "".concat(functionName, "(resultString)"),
3502
+ parameters: {
3503
+ resultString: resultString || '',
3504
+ // Note: No ...parametersForTemplate, because working with result only
3505
+ },
3506
+ })];
3507
+ case 32:
3508
+ resultString = _v.sent();
3509
+ postprocessingError = null;
3510
+ return [3 /*break*/, 35];
3511
+ case 33:
3512
+ error_2 = _v.sent();
3513
+ if (!(error_2 instanceof Error)) {
3514
+ throw error_2;
3515
+ }
3516
+ if (error_2 instanceof UnexpectedError) {
3517
+ throw error_2;
3518
+ }
3519
+ postprocessingError = error_2;
3520
+ scriptPipelineExecutionErrors.push(error_2);
3521
+ return [3 /*break*/, 34];
3522
+ case 34:
3523
+ _r = _q.next();
3524
+ return [3 /*break*/, 30];
3525
+ case 35: return [3 /*break*/, 38];
3526
+ case 36:
3527
+ e_3_1 = _v.sent();
3528
+ e_3 = { error: e_3_1 };
3529
+ return [3 /*break*/, 38];
3530
+ case 37:
3531
+ try {
3532
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3533
+ }
3534
+ finally { if (e_3) throw e_3.error; }
3535
+ return [7 /*endfinally*/];
3536
+ case 38:
3537
+ if (postprocessingError) {
3538
+ throw postprocessingError;
3539
+ }
3540
+ _v.label = 39;
3541
+ case 39:
3542
+ _p = _o.next();
3543
+ return [3 /*break*/, 28];
3544
+ case 40: return [3 /*break*/, 43];
3545
+ case 41:
3546
+ e_4_1 = _v.sent();
3547
+ e_4 = { error: e_4_1 };
3548
+ return [3 /*break*/, 43];
3549
+ case 42:
3550
+ try {
3551
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3552
+ }
3553
+ finally { if (e_4) throw e_4.error; }
3554
+ return [7 /*endfinally*/];
3555
+ case 43:
3556
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
3557
+ if (currentTemplate.format) {
3558
+ if (currentTemplate.format === 'JSON') {
3559
+ if (!isValidJsonString(resultString || '')) {
3560
+ // TODO: [๐Ÿข] Do more universally via `FormatDefinition`
3561
+ try {
3562
+ resultString = extractJsonBlock(resultString || '');
3563
+ }
3564
+ catch (error) {
3565
+ keepUnused(error);
3566
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3567
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3568
+ }
3569
+ }
3570
+ }
3571
+ else {
3572
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3573
+ }
3574
+ }
3575
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
3576
+ if (currentTemplate.expectations) {
3577
+ checkExpectations(currentTemplate.expectations, resultString || '');
3578
+ }
3579
+ return [2 /*return*/, "break-attempts"];
3580
+ case 44:
3581
+ error_3 = _v.sent();
3582
+ if (!(error_3 instanceof ExpectError)) {
3583
+ throw error_3;
3584
+ }
3585
+ expectError = error_3;
3586
+ return [3 /*break*/, 46];
3587
+ case 45:
3588
+ if (!isJokerAttempt &&
3589
+ currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3590
+ prompt
3591
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3592
+ // In that case we donโ€™t want to make a report about it because itโ€™s not a llm execution error
3593
+ ) {
3594
+ // TODO: [๐Ÿง ] Maybe put other templateTypes into report
3595
+ $executionReport.promptExecutions.push({
3596
+ prompt: __assign({}, prompt),
3597
+ result: result || undefined,
3598
+ error: expectError === null ? undefined : serializeError(expectError),
3599
+ });
3600
+ }
3601
+ return [7 /*endfinally*/];
3602
+ case 46:
3603
+ if (expectError !== null && attempt === maxAttempts - 1) {
3604
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3605
+ .split('\n')
3606
+ .map(function (line) { return "> ".concat(line); })
3607
+ .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3608
+ .split('\n')
3609
+ .map(function (line) { return "> ".concat(line); })
3610
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3611
+ ? 'null'
3612
+ : resultString
3613
+ .split('\n')
3614
+ .map(function (line) { return "> ".concat(line); })
3615
+ .join('\n')), "\n ---\n "); }));
3616
+ }
3617
+ return [2 /*return*/];
3618
+ }
3619
+ });
3620
+ };
3621
+ attempt = -jokerParameterNames.length;
3622
+ _h.label = 3;
3623
+ case 3:
3624
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 6];
3625
+ return [5 /*yield**/, _loop_2(attempt)];
3626
+ case 4:
3627
+ state_1 = _h.sent();
3628
+ switch (state_1) {
3629
+ case "break-attempts": return [3 /*break*/, 6];
3630
+ }
3631
+ _h.label = 5;
3632
+ case 5:
3633
+ attempt++;
3634
+ return [3 /*break*/, 3];
3635
+ case 6:
3636
+ //------------------------------------
3637
+ /*
3638
+
3639
+
3640
+
3641
+
3642
+
3643
+
3644
+
3645
+
3646
+
3647
+ */
3648
+ //------------------------------------
3649
+ if (resultString === null) {
3650
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3651
+ }
3652
+ return [4 /*yield*/, onProgress({
3653
+ name: name,
3654
+ title: title,
3655
+ isStarted: true,
3656
+ isDone: true,
3657
+ templateType: currentTemplate.templateType,
3658
+ parameterName: currentTemplate.resultingParameterName,
3659
+ parameterValue: resultString,
3660
+ // <- [๐Ÿธ]
3661
+ })];
3662
+ case 7:
3663
+ _h.sent();
3664
+ return [2 /*return*/, Object.freeze((_g = {},
3665
+ _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */,
3666
+ _g))];
3667
+ }
3668
+ });
3669
+ });
3081
3670
  }
3082
-
3083
3671
  /**
3084
- * Index of all counter functions
3085
- *
3086
- * @public exported from `@promptbook/utils`
3672
+ * TODO: [๐Ÿคนโ€โ™‚๏ธ]
3087
3673
  */
3088
- var CountUtils = {
3089
- CHARACTERS: countCharacters,
3090
- WORDS: countWords,
3091
- SENTENCES: countSentences,
3092
- PARAGRAPHS: countParagraphs,
3093
- LINES: countLines,
3094
- PAGES: countPages,
3095
- };
3096
3674
 
3097
3675
  /**
3098
- * Function checkExpectations will check if the expectations on given value are met
3099
- *
3100
- * Note: There are two simmilar functions:
3101
- * - `checkExpectations` which throws an error if the expectations are not met
3102
- * - `isPassingExpectations` which returns a boolean
3103
- *
3104
- * @throws {ExpectError} if the expectations are not met
3105
- * @returns {void} Nothing
3106
- * @private internal function of `createPipelineExecutor`
3676
+ * @private @@@
3107
3677
  */
3108
- function checkExpectations(expectations, value) {
3678
+ function filterJustOutputParameters(preparedPipeline, parametersToPass, $warnings, pipelineIdentification) {
3109
3679
  var e_1, _a;
3680
+ var outputParameters = {};
3681
+ var _loop_1 = function (parameter) {
3682
+ if (parametersToPass[parameter.name] === undefined) {
3683
+ // [4]
3684
+ $warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3685
+ return "continue";
3686
+ }
3687
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3688
+ };
3110
3689
  try {
3111
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3112
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3113
- var amount = CountUtils[unit.toUpperCase()](value);
3114
- if (min && amount < min) {
3115
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3116
- } /* not else */
3117
- if (max && amount > max) {
3118
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3119
- }
3690
+ // Note: Filter ONLY output parameters
3691
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3692
+ var isOutput = _a.isOutput;
3693
+ return isOutput;
3694
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
3695
+ var parameter = _c.value;
3696
+ _loop_1(parameter);
3120
3697
  }
3121
3698
  }
3122
3699
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3126,10 +3703,8 @@ function checkExpectations(expectations, value) {
3126
3703
  }
3127
3704
  finally { if (e_1) throw e_1.error; }
3128
3705
  }
3706
+ return outputParameters;
3129
3707
  }
3130
- /**
3131
- * TODO: [๐Ÿ’] Unite object for expecting amount and format
3132
- */
3133
3708
 
3134
3709
  /**
3135
3710
  * Creates executor function from pipeline and execution tools.
@@ -3163,572 +3738,6 @@ function createPipelineExecutor(options) {
3163
3738
  console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3164
3739
  }
3165
3740
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3166
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3167
- function getContextForTemplate(template) {
3168
- return __awaiter(this, void 0, void 0, function () {
3169
- return __generator(this, function (_a) {
3170
- TODO_USE(template);
3171
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [๐Ÿ] Implement */];
3172
- });
3173
- });
3174
- }
3175
- function getKnowledgeForTemplate(template) {
3176
- return __awaiter(this, void 0, void 0, function () {
3177
- return __generator(this, function (_a) {
3178
- // TODO: [โ™จ] Implement Better - use real index and keyword search from `template` and {samples}
3179
- TODO_USE(template);
3180
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3181
- var content = _a.content;
3182
- return "- ".concat(content);
3183
- }).join('\n')];
3184
- });
3185
- });
3186
- }
3187
- function getSamplesForTemplate(template) {
3188
- return __awaiter(this, void 0, void 0, function () {
3189
- return __generator(this, function (_a) {
3190
- // TODO: [โ™จ] Implement Better - use real index and keyword search
3191
- TODO_USE(template);
3192
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [โ™จ] Implement */];
3193
- });
3194
- });
3195
- }
3196
- function getReservedParametersForTemplate(template) {
3197
- return __awaiter(this, void 0, void 0, function () {
3198
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3199
- var e_3, _a;
3200
- return __generator(this, function (_b) {
3201
- switch (_b.label) {
3202
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3203
- case 1:
3204
- context = _b.sent();
3205
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3206
- case 2:
3207
- knowledge = _b.sent();
3208
- return [4 /*yield*/, getSamplesForTemplate(template)];
3209
- case 3:
3210
- samples = _b.sent();
3211
- currentDate = new Date().toISOString();
3212
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3213
- reservedParameters = {
3214
- content: RESERVED_PARAMETER_RESTRICTED,
3215
- context: context,
3216
- knowledge: knowledge,
3217
- samples: samples,
3218
- currentDate: currentDate,
3219
- modelName: modelName,
3220
- };
3221
- _loop_3 = function (parameterName) {
3222
- if (reservedParameters[parameterName] === undefined) {
3223
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3224
- }
3225
- };
3226
- try {
3227
- // Note: Doublecheck that ALL reserved parameters are defined:
3228
- 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()) {
3229
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3230
- _loop_3(parameterName);
3231
- }
3232
- }
3233
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3234
- finally {
3235
- try {
3236
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3237
- }
3238
- finally { if (e_3) throw e_3.error; }
3239
- }
3240
- return [2 /*return*/, reservedParameters];
3241
- }
3242
- });
3243
- });
3244
- }
3245
- function executeSingleTemplate(currentTemplate) {
3246
- return __awaiter(this, void 0, void 0, function () {
3247
- 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;
3248
- var e_4, _f, _g;
3249
- return __generator(this, function (_h) {
3250
- switch (_h.label) {
3251
- case 0:
3252
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3253
- title = currentTemplate.title;
3254
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3255
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3256
- progress_1 = {
3257
- name: name,
3258
- title: title,
3259
- isStarted: false,
3260
- isDone: false,
3261
- templateType: currentTemplate.templateType,
3262
- parameterName: currentTemplate.resultingParameterName,
3263
- parameterValue: null,
3264
- // <- [3]
3265
- };
3266
- if (isReturned) {
3267
- 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)
3268
- .split('\n')
3269
- .map(function (line) { return "> ".concat(line); })
3270
- .join('\n')), "\n "); }));
3271
- }
3272
- return [4 /*yield*/, onProgress(progress_1)];
3273
- case 1:
3274
- _h.sent();
3275
- _h.label = 2;
3276
- case 2:
3277
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3278
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3279
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3280
- 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)
3281
- .map(function (name) { return "{".concat(name, "}"); })
3282
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3283
- .map(function (name) { return "{".concat(name, "}"); })
3284
- .join(', '), "\n\n "); }));
3285
- }
3286
- _b = (_a = Object).freeze;
3287
- _c = [{}];
3288
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3289
- case 3:
3290
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3291
- definedParameterNames = new Set(Object.keys(definedParameters));
3292
- parameters = {};
3293
- _loop_4 = function (parameterName) {
3294
- // Situation: Parameter is defined and used
3295
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3296
- parameters[parameterName] = definedParameters[parameterName];
3297
- }
3298
- // Situation: Parameter is defined but NOT used
3299
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3300
- // Situation: Parameter is NOT defined BUT used
3301
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3302
- // Houston, we have a problem
3303
- // Note: Checking part is also done in `validatePipeline`, but itโ€™s good to doublecheck
3304
- 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 "); }));
3305
- }
3306
- };
3307
- try {
3308
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3309
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3310
- parameterName = _e.value;
3311
- _loop_4(parameterName);
3312
- }
3313
- }
3314
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3315
- finally {
3316
- try {
3317
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3318
- }
3319
- finally { if (e_4) throw e_4.error; }
3320
- }
3321
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3322
- Object.freeze(parameters);
3323
- result = null;
3324
- resultString = null;
3325
- expectError = null;
3326
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3327
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3328
- preparedContent = (currentTemplate.preparedContent || '{content}')
3329
- .split('{content}')
3330
- .join(currentTemplate.content);
3331
- _loop_5 = function (attempt) {
3332
- 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;
3333
- var e_5, _s, e_7, _t, e_6, _u;
3334
- return __generator(this, function (_v) {
3335
- switch (_v.label) {
3336
- case 0:
3337
- isJokerAttempt = attempt < 0;
3338
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3339
- // TODO: [๐Ÿง ] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3340
- if (isJokerAttempt && !jokerParameterName) {
3341
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3342
- }
3343
- result = null;
3344
- resultString = null;
3345
- expectError = null;
3346
- if (isJokerAttempt) {
3347
- if (parameters[jokerParameterName] === undefined) {
3348
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3349
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3350
- }
3351
- else {
3352
- resultString = parameters[jokerParameterName];
3353
- }
3354
- }
3355
- _v.label = 1;
3356
- case 1:
3357
- _v.trys.push([1, 44, 45, 46]);
3358
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3359
- _j = currentTemplate.templateType;
3360
- switch (_j) {
3361
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3362
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3363
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3364
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3365
- }
3366
- return [3 /*break*/, 25];
3367
- case 2:
3368
- resultString = replaceParameters(preparedContent, parameters);
3369
- return [3 /*break*/, 26];
3370
- case 3:
3371
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3372
- prompt = {
3373
- title: currentTemplate.title,
3374
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3375
- ? preparedPipeline.pipelineUrl
3376
- : 'anonymous' /* <- TODO: [๐Ÿง ] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3377
- parameters: parameters,
3378
- content: preparedContent,
3379
- modelRequirements: modelRequirements,
3380
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3381
- var name = _a.name;
3382
- return name === currentTemplate.personaName;
3383
- }) || {})), currentTemplate.expectations),
3384
- format: currentTemplate.format,
3385
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3386
- }; // <- TODO: Not very good type guard
3387
- _k = modelRequirements.modelVariant;
3388
- switch (_k) {
3389
- case 'CHAT': return [3 /*break*/, 4];
3390
- case 'COMPLETION': return [3 /*break*/, 6];
3391
- case 'EMBEDDING': return [3 /*break*/, 8];
3392
- }
3393
- return [3 /*break*/, 10];
3394
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3395
- case 5:
3396
- chatResult = _v.sent();
3397
- // TODO: [๐Ÿฌ] Destroy chatThread
3398
- result = chatResult;
3399
- resultString = chatResult.content;
3400
- return [3 /*break*/, 11];
3401
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3402
- case 7:
3403
- completionResult = _v.sent();
3404
- result = completionResult;
3405
- resultString = completionResult.content;
3406
- return [3 /*break*/, 11];
3407
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3408
- case 9:
3409
- embeddingResult = _v.sent();
3410
- result = embeddingResult;
3411
- resultString = embeddingResult.content.join(',');
3412
- return [3 /*break*/, 11];
3413
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3414
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3415
- case 11: return [3 /*break*/, 26];
3416
- case 12:
3417
- if (arrayableToArray(tools.script).length === 0) {
3418
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3419
- }
3420
- if (!currentTemplate.contentLanguage) {
3421
- 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 "); }));
3422
- }
3423
- // TODO: DRY [1]
3424
- scriptPipelineExecutionErrors = [];
3425
- _v.label = 13;
3426
- case 13:
3427
- _v.trys.push([13, 20, 21, 22]);
3428
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3429
- _v.label = 14;
3430
- case 14:
3431
- if (!!_m.done) return [3 /*break*/, 19];
3432
- scriptTools = _m.value;
3433
- _v.label = 15;
3434
- case 15:
3435
- _v.trys.push([15, 17, , 18]);
3436
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3437
- scriptLanguage: currentTemplate.contentLanguage,
3438
- script: preparedContent,
3439
- parameters: parameters,
3440
- }))];
3441
- case 16:
3442
- resultString = _v.sent();
3443
- return [3 /*break*/, 19];
3444
- case 17:
3445
- error_2 = _v.sent();
3446
- if (!(error_2 instanceof Error)) {
3447
- throw error_2;
3448
- }
3449
- if (error_2 instanceof UnexpectedError) {
3450
- throw error_2;
3451
- }
3452
- scriptPipelineExecutionErrors.push(error_2);
3453
- return [3 /*break*/, 18];
3454
- case 18:
3455
- _m = _l.next();
3456
- return [3 /*break*/, 14];
3457
- case 19: return [3 /*break*/, 22];
3458
- case 20:
3459
- e_5_1 = _v.sent();
3460
- e_5 = { error: e_5_1 };
3461
- return [3 /*break*/, 22];
3462
- case 21:
3463
- try {
3464
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3465
- }
3466
- finally { if (e_5) throw e_5.error; }
3467
- return [7 /*endfinally*/];
3468
- case 22:
3469
- if (resultString !== null) {
3470
- return [3 /*break*/, 26];
3471
- }
3472
- if (scriptPipelineExecutionErrors.length === 1) {
3473
- throw scriptPipelineExecutionErrors[0];
3474
- }
3475
- else {
3476
- 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
3477
- .map(function (error) { return '- ' + error.message; })
3478
- .join('\n\n')), "\n "); }));
3479
- }
3480
- case 23:
3481
- if (tools.userInterface === undefined) {
3482
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3483
- }
3484
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3485
- promptTitle: currentTemplate.title,
3486
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3487
- defaultValue: replaceParameters(preparedContent, parameters),
3488
- // TODO: [๐Ÿง ] !! Figure out how to define placeholder in .ptbk.md file
3489
- placeholder: undefined,
3490
- priority: priority,
3491
- }))];
3492
- case 24:
3493
- // TODO: [๐ŸŒน] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3494
- resultString = _v.sent();
3495
- return [3 /*break*/, 26];
3496
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3497
- case 26:
3498
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3499
- _v.label = 27;
3500
- case 27:
3501
- _v.trys.push([27, 41, 42, 43]);
3502
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3503
- _v.label = 28;
3504
- case 28:
3505
- if (!!_p.done) return [3 /*break*/, 40];
3506
- functionName = _p.value;
3507
- // TODO: DRY [1]
3508
- scriptPipelineExecutionErrors = [];
3509
- postprocessingError = null;
3510
- _v.label = 29;
3511
- case 29:
3512
- _v.trys.push([29, 36, 37, 38]);
3513
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3514
- _v.label = 30;
3515
- case 30:
3516
- if (!!_r.done) return [3 /*break*/, 35];
3517
- scriptTools = _r.value;
3518
- _v.label = 31;
3519
- case 31:
3520
- _v.trys.push([31, 33, , 34]);
3521
- return [4 /*yield*/, scriptTools.execute({
3522
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3523
- script: "".concat(functionName, "(resultString)"),
3524
- parameters: {
3525
- resultString: resultString || '',
3526
- // Note: No ...parametersForTemplate, because working with result only
3527
- },
3528
- })];
3529
- case 32:
3530
- resultString = _v.sent();
3531
- postprocessingError = null;
3532
- return [3 /*break*/, 35];
3533
- case 33:
3534
- error_3 = _v.sent();
3535
- if (!(error_3 instanceof Error)) {
3536
- throw error_3;
3537
- }
3538
- if (error_3 instanceof UnexpectedError) {
3539
- throw error_3;
3540
- }
3541
- postprocessingError = error_3;
3542
- scriptPipelineExecutionErrors.push(error_3);
3543
- return [3 /*break*/, 34];
3544
- case 34:
3545
- _r = _q.next();
3546
- return [3 /*break*/, 30];
3547
- case 35: return [3 /*break*/, 38];
3548
- case 36:
3549
- e_6_1 = _v.sent();
3550
- e_6 = { error: e_6_1 };
3551
- return [3 /*break*/, 38];
3552
- case 37:
3553
- try {
3554
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3555
- }
3556
- finally { if (e_6) throw e_6.error; }
3557
- return [7 /*endfinally*/];
3558
- case 38:
3559
- if (postprocessingError) {
3560
- throw postprocessingError;
3561
- }
3562
- _v.label = 39;
3563
- case 39:
3564
- _p = _o.next();
3565
- return [3 /*break*/, 28];
3566
- case 40: return [3 /*break*/, 43];
3567
- case 41:
3568
- e_7_1 = _v.sent();
3569
- e_7 = { error: e_7_1 };
3570
- return [3 /*break*/, 43];
3571
- case 42:
3572
- try {
3573
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3574
- }
3575
- finally { if (e_7) throw e_7.error; }
3576
- return [7 /*endfinally*/];
3577
- case 43:
3578
- // TODO: [๐Ÿ’] Unite object for expecting amount and format
3579
- if (currentTemplate.format) {
3580
- if (currentTemplate.format === 'JSON') {
3581
- if (!isValidJsonString(resultString || '')) {
3582
- // TODO: [๐Ÿข] Do more universally via `FormatDefinition`
3583
- try {
3584
- resultString = extractJsonBlock(resultString || '');
3585
- }
3586
- catch (error) {
3587
- keepUnused(error);
3588
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3589
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3590
- }
3591
- }
3592
- }
3593
- else {
3594
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3595
- }
3596
- }
3597
- // TODO: [๐Ÿ’] Unite object for expecting amount and format
3598
- if (currentTemplate.expectations) {
3599
- checkExpectations(currentTemplate.expectations, resultString || '');
3600
- }
3601
- return [2 /*return*/, "break-attempts"];
3602
- case 44:
3603
- error_4 = _v.sent();
3604
- if (!(error_4 instanceof ExpectError)) {
3605
- throw error_4;
3606
- }
3607
- expectError = error_4;
3608
- return [3 /*break*/, 46];
3609
- case 45:
3610
- if (!isJokerAttempt &&
3611
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3612
- prompt
3613
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3614
- // In that case we donโ€™t want to make a report about it because itโ€™s not a llm execution error
3615
- ) {
3616
- // TODO: [๐Ÿง ] Maybe put other templateTypes into report
3617
- executionReport.promptExecutions.push({
3618
- prompt: __assign({}, prompt),
3619
- result: result || undefined,
3620
- error: expectError === null ? undefined : serializeError(expectError),
3621
- });
3622
- }
3623
- return [7 /*endfinally*/];
3624
- case 46:
3625
- if (expectError !== null && attempt === maxAttempts - 1) {
3626
- 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
3627
- .split('\n')
3628
- .map(function (line) { return "> ".concat(line); })
3629
- .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) || '')
3630
- .split('\n')
3631
- .map(function (line) { return "> ".concat(line); })
3632
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3633
- ? 'null'
3634
- : resultString
3635
- .split('\n')
3636
- .map(function (line) { return "> ".concat(line); })
3637
- .join('\n')), "\n ---\n "); }));
3638
- }
3639
- return [2 /*return*/];
3640
- }
3641
- });
3642
- };
3643
- attempt = -jokerParameterNames.length;
3644
- _h.label = 4;
3645
- case 4:
3646
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3647
- return [5 /*yield**/, _loop_5(attempt)];
3648
- case 5:
3649
- state_2 = _h.sent();
3650
- switch (state_2) {
3651
- case "break-attempts": return [3 /*break*/, 7];
3652
- }
3653
- _h.label = 6;
3654
- case 6:
3655
- attempt++;
3656
- return [3 /*break*/, 4];
3657
- case 7:
3658
- //------------------------------------
3659
- /*
3660
-
3661
-
3662
-
3663
-
3664
-
3665
-
3666
-
3667
-
3668
-
3669
- */
3670
- //------------------------------------
3671
- if (resultString === null) {
3672
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3673
- }
3674
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3675
- progress_2 = {
3676
- name: name,
3677
- title: title,
3678
- isStarted: true,
3679
- isDone: true,
3680
- templateType: currentTemplate.templateType,
3681
- parameterName: currentTemplate.resultingParameterName,
3682
- parameterValue: resultString,
3683
- // <- [3]
3684
- };
3685
- if (isReturned) {
3686
- 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)
3687
- .split('\n')
3688
- .map(function (line) { return "> ".concat(line); })
3689
- .join('\n')), "\n\n "); }));
3690
- }
3691
- return [4 /*yield*/, onProgress(progress_2)];
3692
- case 8:
3693
- _h.sent();
3694
- _h.label = 9;
3695
- case 9:
3696
- 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)));
3697
- return [2 /*return*/];
3698
- }
3699
- });
3700
- });
3701
- }
3702
- function filterJustOutputParameters() {
3703
- var e_8, _a;
3704
- var outputParameters = {};
3705
- var _loop_6 = function (parameter) {
3706
- if (parametersToPass[parameter.name] === undefined) {
3707
- // [4]
3708
- 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 "); })));
3709
- return "continue";
3710
- }
3711
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3712
- };
3713
- try {
3714
- // Note: Filter ONLY output parameters
3715
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3716
- var isOutput = _a.isOutput;
3717
- return isOutput;
3718
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3719
- var parameter = _c.value;
3720
- _loop_6(parameter);
3721
- }
3722
- }
3723
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3724
- finally {
3725
- try {
3726
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3727
- }
3728
- finally { if (e_8) throw e_8.error; }
3729
- }
3730
- return outputParameters;
3731
- }
3732
3741
  var errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
3733
3742
  var e_1, _e, e_2, _f;
3734
3743
  return __generator(this, function (_g) {
@@ -3910,14 +3919,35 @@ function createPipelineExecutor(options) {
3910
3919
  .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
3911
3920
  case 1:
3912
3921
  if (!!currentTemplate) return [3 /*break*/, 3];
3913
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
3922
+ /* [๐Ÿคนโ€โ™‚๏ธ] */ return [4 /*yield*/, Promise.race(resolving_1)];
3914
3923
  case 2:
3915
- /* [5] */ _j.sent();
3924
+ /* [๐Ÿคนโ€โ™‚๏ธ] */ _j.sent();
3916
3925
  return [3 /*break*/, 4];
3917
3926
  case 3:
3918
3927
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3919
- work_1 = executeSingleTemplate(currentTemplate)
3920
- .then(function () {
3928
+ work_1 = executeSingleTemplate({
3929
+ currentTemplate: currentTemplate,
3930
+ preparedPipeline: preparedPipeline,
3931
+ parametersToPass: parametersToPass,
3932
+ tools: tools,
3933
+ llmTools: llmTools,
3934
+ onProgress: function (progress) {
3935
+ if (isReturned) {
3936
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
3937
+ .split('\n')
3938
+ .map(function (line) { return "> ".concat(line); })
3939
+ .join('\n')), "\n "); }));
3940
+ }
3941
+ if (onProgress) {
3942
+ onProgress(progress);
3943
+ }
3944
+ },
3945
+ maxExecutionAttempts: maxExecutionAttempts,
3946
+ $executionReport: executionReport,
3947
+ pipelineIdentification: pipelineIdentification,
3948
+ })
3949
+ .then(function (newParametersToPass) {
3950
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3921
3951
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3922
3952
  })
3923
3953
  .then(function () {
@@ -3949,7 +3979,7 @@ function createPipelineExecutor(options) {
3949
3979
  var result = _a.result;
3950
3980
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3951
3981
  })), false));
3952
- outputParameters_1 = filterJustOutputParameters();
3982
+ outputParameters_1 = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
3953
3983
  isReturned = true;
3954
3984
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3955
3985
  // Note: Wait a short time to prevent race conditions
@@ -3972,7 +4002,7 @@ function createPipelineExecutor(options) {
3972
4002
  var result = _a.result;
3973
4003
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3974
4004
  })), false));
3975
- outputParameters = filterJustOutputParameters();
4005
+ outputParameters = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
3976
4006
  isReturned = true;
3977
4007
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3978
4008
  // Note: Wait a short time to prevent race conditions
@@ -3996,6 +4026,7 @@ function createPipelineExecutor(options) {
3996
4026
  return pipelineExecutor;
3997
4027
  }
3998
4028
  /**
4029
+ * TODO: [๐Ÿคนโ€โ™‚๏ธ] Make some smarter system for limiting concurrent executions MAX_PARALLEL_TOTAL, MAX_PARALLEL_PER_LLM
3999
4030
  * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4000
4031
  * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4001
4032
  * TODO: [๐Ÿง ][๐ŸŒณ] Use here `countTotalUsage` and put preparation and prepared pipiline to report
@@ -4004,7 +4035,7 @@ function createPipelineExecutor(options) {
4004
4035
  * TODO: [๐Ÿง ] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4005
4036
  * TODO: [๐Ÿ‘ง] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4006
4037
  * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4007
- * TODO: [๐Ÿง ][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4038
+ * TODO: [๐Ÿง ][๐Ÿธ] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4008
4039
  * TODO: [๐Ÿ› ] Actions, instruments (and maybe knowledge) => Functions and tools
4009
4040
  * TODO: [๐Ÿง ][๐Ÿ’ท] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4010
4041
  */
@@ -5264,6 +5295,8 @@ var foreachCommandParser = {
5264
5295
  */
5265
5296
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5266
5297
  var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5298
+ // TODO: !!!!!! Detect double use
5299
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
5267
5300
  $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5268
5301
  keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
5269
5302
  // Note: [๐Ÿญ] FOREACH apply has some sideeffects on different places in codebase