@promptbook/core 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
@@ -10,7 +10,7 @@ import moment from 'moment';
10
10
  /**
11
11
  * The version of the Promptbook library
12
12
  */
13
- var PROMPTBOOK_VERSION = '0.69.0-1';
13
+ var PROMPTBOOK_VERSION = '0.69.0-3';
14
14
  // TODO: !!!! List here all the versions and annotate + put into script
15
15
 
16
16
  /*! *****************************************************************************
@@ -709,6 +709,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
709
709
  'samples',
710
710
  'modelName',
711
711
  'currentDate',
712
+ // <- TODO: !!!!! list here all command names
712
713
  // <- TODO: Add more like 'date', 'modelName',...
713
714
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
714
715
  ]);
@@ -1816,7 +1817,7 @@ function forEachAsync(array, options, callbackfunction) {
1816
1817
  });
1817
1818
  }
1818
1819
 
1819
- 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"}];
1820
+ 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"}];
1820
1821
 
1821
1822
  var defaultDiacriticsRemovalMap = [
1822
1823
  {
@@ -2344,124 +2345,6 @@ function assertsExecutionSuccessful(executionResult) {
2344
2345
  * TODO: [๐Ÿง ] Can this return type be better typed than void
2345
2346
  */
2346
2347
 
2347
- /**
2348
- * Parses the given script and returns the list of all used variables that are not defined in the script
2349
- *
2350
- * @param script from which to extract the variables
2351
- * @returns the list of variable names
2352
- * @throws {ParseError} if the script is invalid
2353
- * @public exported from `@promptbook/utils`
2354
- */
2355
- function extractVariables(script) {
2356
- var variables = new Set();
2357
- script = "(()=>{".concat(script, "})()");
2358
- try {
2359
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2360
- try {
2361
- eval(script);
2362
- }
2363
- catch (error) {
2364
- if (!(error instanceof ReferenceError)) {
2365
- throw error;
2366
- }
2367
- var undefinedName = error.message.split(' ')[0];
2368
- /*
2369
- Note: Parsing the error
2370
- [PipelineUrlError: thing is not defined]
2371
- */
2372
- if (!undefinedName) {
2373
- throw error;
2374
- }
2375
- if (script.includes(undefinedName + '(')) {
2376
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2377
- }
2378
- else {
2379
- variables.add(undefinedName);
2380
- script = "const ".concat(undefinedName, " = '';") + script;
2381
- }
2382
- }
2383
- }
2384
- catch (error) {
2385
- if (!(error instanceof Error)) {
2386
- throw error;
2387
- }
2388
- throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2389
- }
2390
- return variables;
2391
- }
2392
- /**
2393
- * TODO: [๐Ÿ”ฃ] Support for multiple languages - python, java,...
2394
- */
2395
-
2396
- /**
2397
- * Parses the template and returns the set of all used parameters
2398
- *
2399
- * @param template the template with used parameters
2400
- * @returns the set of parameter names
2401
- * @throws {ParseError} if the script is invalid
2402
- * @public exported from `@promptbook/utils`
2403
- */
2404
- function extractParameterNamesFromTemplate(template) {
2405
- var e_1, _a, e_2, _b, e_3, _c;
2406
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2407
- var parameterNames = new Set();
2408
- try {
2409
- 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()) {
2410
- var parameterName = _e.value;
2411
- parameterNames.add(parameterName);
2412
- }
2413
- }
2414
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2415
- finally {
2416
- try {
2417
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2418
- }
2419
- finally { if (e_1) throw e_1.error; }
2420
- }
2421
- if (templateType === 'SCRIPT_TEMPLATE') {
2422
- try {
2423
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2424
- var parameterName = _g.value;
2425
- parameterNames.add(parameterName);
2426
- }
2427
- }
2428
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2429
- finally {
2430
- try {
2431
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2432
- }
2433
- finally { if (e_2) throw e_2.error; }
2434
- }
2435
- }
2436
- try {
2437
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2438
- var jokerName = _j.value;
2439
- parameterNames.add(jokerName);
2440
- }
2441
- }
2442
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2443
- finally {
2444
- try {
2445
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2446
- }
2447
- finally { if (e_3) throw e_3.error; }
2448
- }
2449
- parameterNames.delete('content');
2450
- // <- Note {websiteContent} is used in `preparedContent`
2451
- // Note: [๐Ÿญ] Fixing dependent subparameterName from FOREACH command
2452
- if (foreach !== undefined) {
2453
- if (parameterNames.has(foreach.subparameterName)) {
2454
- parameterNames.delete(foreach.subparameterName);
2455
- parameterNames.add(foreach.parameterName);
2456
- // <- TODO: [๐ŸšŽ] Warn/logic error when `subparameterName` not used
2457
- }
2458
- }
2459
- return parameterNames;
2460
- }
2461
- /**
2462
- * TODO: [๐Ÿ”ฃ] If script require contentLanguage
2463
- */
2464
-
2465
2348
  /**
2466
2349
  * Serializes an error into a [๐Ÿš‰] JSON-serializable object
2467
2350
  *
@@ -2479,27 +2362,6 @@ function serializeError(error) {
2479
2362
  };
2480
2363
  }
2481
2364
 
2482
- /**
2483
- * Function isValidJsonString will tell you if the string is valid JSON or not
2484
- *
2485
- * @public exported from `@promptbook/utils`
2486
- */
2487
- function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
2488
- try {
2489
- JSON.parse(value);
2490
- return true;
2491
- }
2492
- catch (error) {
2493
- if (!(error instanceof Error)) {
2494
- throw error;
2495
- }
2496
- if (error.message.includes('Unexpected token')) {
2497
- return false;
2498
- }
2499
- return false;
2500
- }
2501
- }
2502
-
2503
2365
  /**
2504
2366
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2505
2367
  *
@@ -2793,122 +2655,6 @@ function joinLlmExecutionTools() {
2793
2655
  * TODO: [๐Ÿ‘ทโ€โ™‚๏ธ] @@@ Manual about construction of llmTools
2794
2656
  */
2795
2657
 
2796
- /**
2797
- * Extracts all code blocks from markdown.
2798
- *
2799
- * Note: There are multiple simmilar function:
2800
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2801
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2802
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2803
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2804
- *
2805
- * @param markdown any valid markdown
2806
- * @returns code blocks with language and content
2807
- * @throws {ParseError} if block is not closed properly
2808
- * @public exported from `@promptbook/markdown-utils`
2809
- */
2810
- function extractAllBlocksFromMarkdown(markdown) {
2811
- var e_1, _a;
2812
- var codeBlocks = [];
2813
- var lines = markdown.split('\n');
2814
- // Note: [0] Ensure that the last block notated by gt > will be closed
2815
- lines.push('');
2816
- var currentCodeBlock = null;
2817
- try {
2818
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2819
- var line = lines_1_1.value;
2820
- if (line.startsWith('> ') || line === '>') {
2821
- if (currentCodeBlock === null) {
2822
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2823
- } /* not else */
2824
- if (currentCodeBlock.blockNotation === '>') {
2825
- if (currentCodeBlock.content !== '') {
2826
- currentCodeBlock.content += '\n';
2827
- }
2828
- currentCodeBlock.content += line.slice(2);
2829
- }
2830
- }
2831
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2832
- codeBlocks.push(currentCodeBlock);
2833
- currentCodeBlock = null;
2834
- }
2835
- /* not else */
2836
- if (line.startsWith('```')) {
2837
- var language = line.slice(3).trim() || null;
2838
- if (currentCodeBlock === null) {
2839
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2840
- }
2841
- else {
2842
- if (language !== null) {
2843
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2844
- }
2845
- codeBlocks.push(currentCodeBlock);
2846
- currentCodeBlock = null;
2847
- }
2848
- }
2849
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2850
- if (currentCodeBlock.content !== '') {
2851
- currentCodeBlock.content += '\n';
2852
- }
2853
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2854
- }
2855
- }
2856
- }
2857
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2858
- finally {
2859
- try {
2860
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2861
- }
2862
- finally { if (e_1) throw e_1.error; }
2863
- }
2864
- if (currentCodeBlock !== null) {
2865
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2866
- }
2867
- return codeBlocks;
2868
- }
2869
- /**
2870
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2871
- */
2872
-
2873
- /**
2874
- * Extracts extracts exactly one valid JSON code block
2875
- *
2876
- * - When given string is a valid JSON as it is, it just returns it
2877
- * - When there is no JSON code block the function throws a `ParseError`
2878
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2879
- *
2880
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2881
- * Note: There are multiple simmilar function:
2882
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2883
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2884
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2885
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2886
- *
2887
- * @public exported from `@promptbook/markdown-utils`
2888
- * @throws {ParseError} if there is no valid JSON block in the markdown
2889
- */
2890
- function extractJsonBlock(markdown) {
2891
- if (isValidJsonString(markdown)) {
2892
- return markdown;
2893
- }
2894
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2895
- var jsonBlocks = codeBlocks.filter(function (_a) {
2896
- var content = _a.content;
2897
- return isValidJsonString(content);
2898
- });
2899
- if (jsonBlocks.length === 0) {
2900
- throw new Error('There is no valid JSON block in the markdown');
2901
- }
2902
- if (jsonBlocks.length > 1) {
2903
- throw new Error('There are multiple JSON code blocks in the markdown');
2904
- }
2905
- return jsonBlocks[0].content;
2906
- }
2907
- /**
2908
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2909
- * TODO: [๐Ÿข] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2910
- */
2911
-
2912
2658
  /**
2913
2659
  * Determine if the pipeline is fully prepared
2914
2660
  *
@@ -2961,40 +2707,278 @@ function arrayableToArray(input) {
2961
2707
  }
2962
2708
 
2963
2709
  /**
2964
- * Just says that the variable is not used but should be kept
2965
- * No side effects.
2710
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2966
2711
  *
2967
- * Note: It can be usefull for:
2712
+ * @param script from which to extract the variables
2713
+ * @returns the list of variable names
2714
+ * @throws {ParseError} if the script is invalid
2715
+ * @public exported from `@promptbook/utils`
2716
+ */
2717
+ function extractVariables(script) {
2718
+ var variables = new Set();
2719
+ script = "(()=>{".concat(script, "})()");
2720
+ try {
2721
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2722
+ try {
2723
+ eval(script);
2724
+ }
2725
+ catch (error) {
2726
+ if (!(error instanceof ReferenceError)) {
2727
+ throw error;
2728
+ }
2729
+ var undefinedName = error.message.split(' ')[0];
2730
+ /*
2731
+ Note: Parsing the error
2732
+ [PipelineUrlError: thing is not defined]
2733
+ */
2734
+ if (!undefinedName) {
2735
+ throw error;
2736
+ }
2737
+ if (script.includes(undefinedName + '(')) {
2738
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2739
+ }
2740
+ else {
2741
+ variables.add(undefinedName);
2742
+ script = "const ".concat(undefinedName, " = '';") + script;
2743
+ }
2744
+ }
2745
+ }
2746
+ catch (error) {
2747
+ if (!(error instanceof Error)) {
2748
+ throw error;
2749
+ }
2750
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2751
+ }
2752
+ return variables;
2753
+ }
2754
+ /**
2755
+ * TODO: [๐Ÿ”ฃ] Support for multiple languages - python, java,...
2756
+ */
2757
+
2758
+ /**
2759
+ * Parses the template and returns the set of all used parameters
2968
2760
  *
2969
- * 1) Suppressing eager optimization of unused imports
2970
- * 2) Suppressing eslint errors of unused variables in the tests
2971
- * 3) Keeping the type of the variable for type testing
2761
+ * @param template the template with used parameters
2762
+ * @returns the set of parameter names
2763
+ * @throws {ParseError} if the script is invalid
2764
+ * @public exported from `@promptbook/utils`
2765
+ */
2766
+ function extractParameterNamesFromTemplate(template) {
2767
+ var e_1, _a, e_2, _b, e_3, _c;
2768
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2769
+ var parameterNames = new Set();
2770
+ try {
2771
+ 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()) {
2772
+ var parameterName = _e.value;
2773
+ parameterNames.add(parameterName);
2774
+ }
2775
+ }
2776
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2777
+ finally {
2778
+ try {
2779
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2780
+ }
2781
+ finally { if (e_1) throw e_1.error; }
2782
+ }
2783
+ if (templateType === 'SCRIPT_TEMPLATE') {
2784
+ try {
2785
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2786
+ var parameterName = _g.value;
2787
+ parameterNames.add(parameterName);
2788
+ }
2789
+ }
2790
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2791
+ finally {
2792
+ try {
2793
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2794
+ }
2795
+ finally { if (e_2) throw e_2.error; }
2796
+ }
2797
+ }
2798
+ try {
2799
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2800
+ var jokerName = _j.value;
2801
+ parameterNames.add(jokerName);
2802
+ }
2803
+ }
2804
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2805
+ finally {
2806
+ try {
2807
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2808
+ }
2809
+ finally { if (e_3) throw e_3.error; }
2810
+ }
2811
+ parameterNames.delete('content');
2812
+ // <- Note {websiteContent} is used in `preparedContent`
2813
+ // Note: [๐Ÿญ] Fixing dependent subparameterName from FOREACH command
2814
+ if (foreach !== undefined) {
2815
+ if (parameterNames.has(foreach.subparameterName)) {
2816
+ parameterNames.delete(foreach.subparameterName);
2817
+ parameterNames.add(foreach.parameterName);
2818
+ // <- TODO: [๐ŸšŽ] Warn/logic error when `subparameterName` not used
2819
+ }
2820
+ }
2821
+ return parameterNames;
2822
+ }
2823
+ /**
2824
+ * TODO: [๐Ÿ”ฃ] If script require contentLanguage
2825
+ */
2826
+
2827
+ /**
2828
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2972
2829
  *
2973
- * @param value any values
2974
- * @returns void
2975
- * @private within the repository
2830
+ * @public exported from `@promptbook/utils`
2976
2831
  */
2977
- function keepUnused() {
2978
- var valuesToKeep = [];
2979
- for (var _i = 0; _i < arguments.length; _i++) {
2980
- valuesToKeep[_i] = arguments[_i];
2832
+ function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
2833
+ try {
2834
+ JSON.parse(value);
2835
+ return true;
2836
+ }
2837
+ catch (error) {
2838
+ if (!(error instanceof Error)) {
2839
+ throw error;
2840
+ }
2841
+ if (error.message.includes('Unexpected token')) {
2842
+ return false;
2843
+ }
2844
+ return false;
2981
2845
  }
2982
2846
  }
2983
2847
 
2984
2848
  /**
2985
- * Just marks a place of place where should be something implemented
2849
+ * Extracts all code blocks from markdown.
2850
+ *
2851
+ * Note: There are multiple simmilar function:
2852
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2853
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2854
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2855
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2856
+ *
2857
+ * @param markdown any valid markdown
2858
+ * @returns code blocks with language and content
2859
+ * @throws {ParseError} if block is not closed properly
2860
+ * @public exported from `@promptbook/markdown-utils`
2861
+ */
2862
+ function extractAllBlocksFromMarkdown(markdown) {
2863
+ var e_1, _a;
2864
+ var codeBlocks = [];
2865
+ var lines = markdown.split('\n');
2866
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2867
+ lines.push('');
2868
+ var currentCodeBlock = null;
2869
+ try {
2870
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2871
+ var line = lines_1_1.value;
2872
+ if (line.startsWith('> ') || line === '>') {
2873
+ if (currentCodeBlock === null) {
2874
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2875
+ } /* not else */
2876
+ if (currentCodeBlock.blockNotation === '>') {
2877
+ if (currentCodeBlock.content !== '') {
2878
+ currentCodeBlock.content += '\n';
2879
+ }
2880
+ currentCodeBlock.content += line.slice(2);
2881
+ }
2882
+ }
2883
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2884
+ codeBlocks.push(currentCodeBlock);
2885
+ currentCodeBlock = null;
2886
+ }
2887
+ /* not else */
2888
+ if (line.startsWith('```')) {
2889
+ var language = line.slice(3).trim() || null;
2890
+ if (currentCodeBlock === null) {
2891
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2892
+ }
2893
+ else {
2894
+ if (language !== null) {
2895
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2896
+ }
2897
+ codeBlocks.push(currentCodeBlock);
2898
+ currentCodeBlock = null;
2899
+ }
2900
+ }
2901
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2902
+ if (currentCodeBlock.content !== '') {
2903
+ currentCodeBlock.content += '\n';
2904
+ }
2905
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2906
+ }
2907
+ }
2908
+ }
2909
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2910
+ finally {
2911
+ try {
2912
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2913
+ }
2914
+ finally { if (e_1) throw e_1.error; }
2915
+ }
2916
+ if (currentCodeBlock !== null) {
2917
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2918
+ }
2919
+ return codeBlocks;
2920
+ }
2921
+ /**
2922
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2923
+ */
2924
+
2925
+ /**
2926
+ * Extracts extracts exactly one valid JSON code block
2927
+ *
2928
+ * - When given string is a valid JSON as it is, it just returns it
2929
+ * - When there is no JSON code block the function throws a `ParseError`
2930
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
2931
+ *
2932
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
2933
+ * Note: There are multiple simmilar function:
2934
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2935
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2936
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2937
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2938
+ *
2939
+ * @public exported from `@promptbook/markdown-utils`
2940
+ * @throws {ParseError} if there is no valid JSON block in the markdown
2941
+ */
2942
+ function extractJsonBlock(markdown) {
2943
+ if (isValidJsonString(markdown)) {
2944
+ return markdown;
2945
+ }
2946
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2947
+ var jsonBlocks = codeBlocks.filter(function (_a) {
2948
+ var content = _a.content;
2949
+ return isValidJsonString(content);
2950
+ });
2951
+ if (jsonBlocks.length === 0) {
2952
+ throw new Error('There is no valid JSON block in the markdown');
2953
+ }
2954
+ if (jsonBlocks.length > 1) {
2955
+ throw new Error('There are multiple JSON code blocks in the markdown');
2956
+ }
2957
+ return jsonBlocks[0].content;
2958
+ }
2959
+ /**
2960
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2961
+ * TODO: [๐Ÿข] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2962
+ */
2963
+
2964
+ /**
2965
+ * Just says that the variable is not used but should be kept
2986
2966
  * No side effects.
2987
2967
  *
2988
- * Note: It can be usefull suppressing eslint errors of unused variables
2968
+ * Note: It can be usefull for:
2969
+ *
2970
+ * 1) Suppressing eager optimization of unused imports
2971
+ * 2) Suppressing eslint errors of unused variables in the tests
2972
+ * 3) Keeping the type of the variable for type testing
2989
2973
  *
2990
2974
  * @param value any values
2991
2975
  * @returns void
2992
2976
  * @private within the repository
2993
2977
  */
2994
- function TODO_USE() {
2995
- var value = [];
2978
+ function keepUnused() {
2979
+ var valuesToKeep = [];
2996
2980
  for (var _i = 0; _i < arguments.length; _i++) {
2997
- value[_i] = arguments[_i];
2981
+ valuesToKeep[_i] = arguments[_i];
2998
2982
  }
2999
2983
  }
3000
2984
 
@@ -3218,53 +3202,668 @@ function countSentences(text) {
3218
3202
  }
3219
3203
 
3220
3204
  /**
3221
- * Counts number of words in the text
3222
- *
3223
- * @public exported from `@promptbook/utils`
3205
+ * Counts number of words in the text
3206
+ *
3207
+ * @public exported from `@promptbook/utils`
3208
+ */
3209
+ function countWords(text) {
3210
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3211
+ text = removeDiacritics(text);
3212
+ return text.split(/[^a-zะฐ-ั0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3213
+ }
3214
+
3215
+ /**
3216
+ * Index of all counter functions
3217
+ *
3218
+ * @public exported from `@promptbook/utils`
3219
+ */
3220
+ var CountUtils = {
3221
+ CHARACTERS: countCharacters,
3222
+ WORDS: countWords,
3223
+ SENTENCES: countSentences,
3224
+ PARAGRAPHS: countParagraphs,
3225
+ LINES: countLines,
3226
+ PAGES: countPages,
3227
+ };
3228
+
3229
+ /**
3230
+ * Function checkExpectations will check if the expectations on given value are met
3231
+ *
3232
+ * Note: There are two simmilar functions:
3233
+ * - `checkExpectations` which throws an error if the expectations are not met
3234
+ * - `isPassingExpectations` which returns a boolean
3235
+ *
3236
+ * @throws {ExpectError} if the expectations are not met
3237
+ * @returns {void} Nothing
3238
+ * @private internal function of `createPipelineExecutor`
3239
+ */
3240
+ function checkExpectations(expectations, value) {
3241
+ var e_1, _a;
3242
+ try {
3243
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3244
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3245
+ var amount = CountUtils[unit.toUpperCase()](value);
3246
+ if (min && amount < min) {
3247
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3248
+ } /* not else */
3249
+ if (max && amount > max) {
3250
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3251
+ }
3252
+ }
3253
+ }
3254
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3255
+ finally {
3256
+ try {
3257
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3258
+ }
3259
+ finally { if (e_1) throw e_1.error; }
3260
+ }
3261
+ }
3262
+ /**
3263
+ * Function checkExpectations will check if the expectations on given value are met
3264
+ *
3265
+ * Note: There are two simmilar functions:
3266
+ * - `checkExpectations` which throws an error if the expectations are not met
3267
+ * - `isPassingExpectations` which returns a boolean
3268
+ *
3269
+ * @returns {boolean} True if the expectations are met
3270
+ * @public exported from `@promptbook/core`
3271
+ */
3272
+ function isPassingExpectations(expectations, value) {
3273
+ try {
3274
+ checkExpectations(expectations, value);
3275
+ return true;
3276
+ }
3277
+ catch (error) {
3278
+ if (!(error instanceof ExpectError)) {
3279
+ throw error;
3280
+ }
3281
+ return false;
3282
+ }
3283
+ }
3284
+ /**
3285
+ * TODO: [๐Ÿ’] Unite object for expecting amount and format
3286
+ */
3287
+
3288
+ /**
3289
+ * Just marks a place of place where should be something implemented
3290
+ * No side effects.
3291
+ *
3292
+ * Note: It can be usefull suppressing eslint errors of unused variables
3293
+ *
3294
+ * @param value any values
3295
+ * @returns void
3296
+ * @private within the repository
3297
+ */
3298
+ function TODO_USE() {
3299
+ var value = [];
3300
+ for (var _i = 0; _i < arguments.length; _i++) {
3301
+ value[_i] = arguments[_i];
3302
+ }
3303
+ }
3304
+
3305
+ /**
3306
+ * @private @@@
3307
+ */
3308
+ function getContextForTemplate(template) {
3309
+ return __awaiter(this, void 0, void 0, function () {
3310
+ return __generator(this, function (_a) {
3311
+ TODO_USE(template);
3312
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [๐Ÿ] Implement */];
3313
+ });
3314
+ });
3315
+ }
3316
+
3317
+ /**
3318
+ * @private @@@
3319
+ */
3320
+ function getKnowledgeForTemplate(preparedPipeline, template) {
3321
+ return __awaiter(this, void 0, void 0, function () {
3322
+ return __generator(this, function (_a) {
3323
+ // TODO: [โ™จ] Implement Better - use real index and keyword search from `template` and {samples}
3324
+ TODO_USE(template);
3325
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3326
+ var content = _a.content;
3327
+ return "- ".concat(content);
3328
+ }).join('\n')];
3329
+ });
3330
+ });
3331
+ }
3332
+
3333
+ /**
3334
+ * @private @@@
3335
+ */
3336
+ function getSamplesForTemplate(template) {
3337
+ return __awaiter(this, void 0, void 0, function () {
3338
+ return __generator(this, function (_a) {
3339
+ // TODO: [โ™จ] Implement Better - use real index and keyword search
3340
+ TODO_USE(template);
3341
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [โ™จ] Implement */];
3342
+ });
3343
+ });
3344
+ }
3345
+
3346
+ /**
3347
+ * @private @@@
3348
+ */
3349
+ function getReservedParametersForTemplate(preparedPipeline, template, pipelineIdentification) {
3350
+ return __awaiter(this, void 0, void 0, function () {
3351
+ var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3352
+ var e_1, _a;
3353
+ return __generator(this, function (_b) {
3354
+ switch (_b.label) {
3355
+ case 0: return [4 /*yield*/, getContextForTemplate(template)];
3356
+ case 1:
3357
+ context = _b.sent();
3358
+ return [4 /*yield*/, getKnowledgeForTemplate(preparedPipeline, template)];
3359
+ case 2:
3360
+ knowledge = _b.sent();
3361
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3362
+ case 3:
3363
+ samples = _b.sent();
3364
+ currentDate = new Date().toISOString();
3365
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3366
+ reservedParameters = {
3367
+ content: RESERVED_PARAMETER_RESTRICTED,
3368
+ context: context,
3369
+ knowledge: knowledge,
3370
+ samples: samples,
3371
+ currentDate: currentDate,
3372
+ modelName: modelName,
3373
+ };
3374
+ _loop_1 = function (parameterName) {
3375
+ if (reservedParameters[parameterName] === undefined) {
3376
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3377
+ }
3378
+ };
3379
+ try {
3380
+ // Note: Doublecheck that ALL reserved parameters are defined:
3381
+ 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()) {
3382
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3383
+ _loop_1(parameterName);
3384
+ }
3385
+ }
3386
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3387
+ finally {
3388
+ try {
3389
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3390
+ }
3391
+ finally { if (e_1) throw e_1.error; }
3392
+ }
3393
+ return [2 /*return*/, reservedParameters];
3394
+ }
3395
+ });
3396
+ });
3397
+ }
3398
+
3399
+ /**
3400
+ * @private @@@
3224
3401
  */
3225
- function countWords(text) {
3226
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3227
- text = removeDiacritics(text);
3228
- return text.split(/[^a-zะฐ-ั0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3402
+ function executeSingleTemplate(options) {
3403
+ return __awaiter(this, void 0, void 0, function () {
3404
+ 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;
3405
+ var e_1, _f, _g;
3406
+ return __generator(this, function (_h) {
3407
+ switch (_h.label) {
3408
+ case 0:
3409
+ 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;
3410
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3411
+ title = currentTemplate.title;
3412
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3413
+ return [4 /*yield*/, onProgress({
3414
+ name: name,
3415
+ title: title,
3416
+ isStarted: false,
3417
+ isDone: false,
3418
+ templateType: currentTemplate.templateType,
3419
+ parameterName: currentTemplate.resultingParameterName,
3420
+ parameterValue: null,
3421
+ // <- [๐Ÿธ]
3422
+ })];
3423
+ case 1:
3424
+ _h.sent();
3425
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3426
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3427
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3428
+ throw new UnexpectedError(spaceTrim$1(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)
3429
+ .map(function (name) { return "{".concat(name, "}"); })
3430
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3431
+ .map(function (name) { return "{".concat(name, "}"); })
3432
+ .join(', '), "\n\n "); }));
3433
+ }
3434
+ _b = (_a = Object).freeze;
3435
+ _c = [{}];
3436
+ return [4 /*yield*/, getReservedParametersForTemplate(preparedPipeline, currentTemplate, pipelineIdentification)];
3437
+ case 2:
3438
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3439
+ definedParameterNames = new Set(Object.keys(definedParameters));
3440
+ parameters = {};
3441
+ _loop_1 = function (parameterName) {
3442
+ // Situation: Parameter is defined and used
3443
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3444
+ parameters[parameterName] = definedParameters[parameterName];
3445
+ }
3446
+ // Situation: Parameter is defined but NOT used
3447
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3448
+ // Situation: Parameter is NOT defined BUT used
3449
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3450
+ // Houston, we have a problem
3451
+ // Note: Checking part is also done in `validatePipeline`, but itโ€™s good to doublecheck
3452
+ throw new UnexpectedError(spaceTrim$1(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 "); }));
3453
+ }
3454
+ };
3455
+ try {
3456
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3457
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3458
+ parameterName = _e.value;
3459
+ _loop_1(parameterName);
3460
+ }
3461
+ }
3462
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3463
+ finally {
3464
+ try {
3465
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3466
+ }
3467
+ finally { if (e_1) throw e_1.error; }
3468
+ }
3469
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3470
+ Object.freeze(parameters);
3471
+ result = null;
3472
+ resultString = null;
3473
+ expectError = null;
3474
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3475
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3476
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3477
+ .split('{content}')
3478
+ .join(currentTemplate.content);
3479
+ _loop_2 = function (attempt) {
3480
+ 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;
3481
+ var e_2, _s, e_4, _t, e_3, _u;
3482
+ return __generator(this, function (_v) {
3483
+ switch (_v.label) {
3484
+ case 0:
3485
+ isJokerAttempt = attempt < 0;
3486
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3487
+ // TODO: [๐Ÿง ] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3488
+ if (isJokerAttempt && !jokerParameterName) {
3489
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3490
+ }
3491
+ result = null;
3492
+ resultString = null;
3493
+ expectError = null;
3494
+ if (isJokerAttempt) {
3495
+ if (parameters[jokerParameterName] === undefined) {
3496
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3497
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3498
+ }
3499
+ else {
3500
+ resultString = parameters[jokerParameterName];
3501
+ }
3502
+ }
3503
+ _v.label = 1;
3504
+ case 1:
3505
+ _v.trys.push([1, 44, 45, 46]);
3506
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3507
+ _j = currentTemplate.templateType;
3508
+ switch (_j) {
3509
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3510
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3511
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3512
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3513
+ }
3514
+ return [3 /*break*/, 25];
3515
+ case 2:
3516
+ resultString = replaceParameters(preparedContent, parameters);
3517
+ return [3 /*break*/, 26];
3518
+ case 3:
3519
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3520
+ prompt = {
3521
+ title: currentTemplate.title,
3522
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3523
+ ? preparedPipeline.pipelineUrl
3524
+ : 'anonymous' /* <- TODO: [๐Ÿง ] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3525
+ parameters: parameters,
3526
+ content: preparedContent,
3527
+ modelRequirements: modelRequirements,
3528
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3529
+ var name = _a.name;
3530
+ return name === currentTemplate.personaName;
3531
+ }) || {})), currentTemplate.expectations),
3532
+ format: currentTemplate.format,
3533
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3534
+ }; // <- TODO: Not very good type guard
3535
+ _k = modelRequirements.modelVariant;
3536
+ switch (_k) {
3537
+ case 'CHAT': return [3 /*break*/, 4];
3538
+ case 'COMPLETION': return [3 /*break*/, 6];
3539
+ case 'EMBEDDING': return [3 /*break*/, 8];
3540
+ }
3541
+ return [3 /*break*/, 10];
3542
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3543
+ case 5:
3544
+ chatResult = _v.sent();
3545
+ // TODO: [๐Ÿฌ] Destroy chatThread
3546
+ result = chatResult;
3547
+ resultString = chatResult.content;
3548
+ return [3 /*break*/, 11];
3549
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3550
+ case 7:
3551
+ completionResult = _v.sent();
3552
+ result = completionResult;
3553
+ resultString = completionResult.content;
3554
+ return [3 /*break*/, 11];
3555
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3556
+ case 9:
3557
+ // TODO: [๐Ÿง ] This is weird, embedding model can not be used such a way in the pipeline
3558
+ embeddingResult = _v.sent();
3559
+ result = embeddingResult;
3560
+ resultString = embeddingResult.content.join(',');
3561
+ return [3 /*break*/, 11];
3562
+ case 10: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3563
+ case 11: return [3 /*break*/, 26];
3564
+ case 12:
3565
+ if (arrayableToArray(tools.script).length === 0) {
3566
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3567
+ }
3568
+ if (!currentTemplate.contentLanguage) {
3569
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3570
+ }
3571
+ // TODO: DRY [1]
3572
+ scriptPipelineExecutionErrors = [];
3573
+ _v.label = 13;
3574
+ case 13:
3575
+ _v.trys.push([13, 20, 21, 22]);
3576
+ _l = (e_2 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3577
+ _v.label = 14;
3578
+ case 14:
3579
+ if (!!_m.done) return [3 /*break*/, 19];
3580
+ scriptTools = _m.value;
3581
+ _v.label = 15;
3582
+ case 15:
3583
+ _v.trys.push([15, 17, , 18]);
3584
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3585
+ scriptLanguage: currentTemplate.contentLanguage,
3586
+ script: preparedContent,
3587
+ parameters: parameters,
3588
+ }))];
3589
+ case 16:
3590
+ resultString = _v.sent();
3591
+ return [3 /*break*/, 19];
3592
+ case 17:
3593
+ error_1 = _v.sent();
3594
+ if (!(error_1 instanceof Error)) {
3595
+ throw error_1;
3596
+ }
3597
+ if (error_1 instanceof UnexpectedError) {
3598
+ throw error_1;
3599
+ }
3600
+ scriptPipelineExecutionErrors.push(error_1);
3601
+ return [3 /*break*/, 18];
3602
+ case 18:
3603
+ _m = _l.next();
3604
+ return [3 /*break*/, 14];
3605
+ case 19: return [3 /*break*/, 22];
3606
+ case 20:
3607
+ e_2_1 = _v.sent();
3608
+ e_2 = { error: e_2_1 };
3609
+ return [3 /*break*/, 22];
3610
+ case 21:
3611
+ try {
3612
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3613
+ }
3614
+ finally { if (e_2) throw e_2.error; }
3615
+ return [7 /*endfinally*/];
3616
+ case 22:
3617
+ if (resultString !== null) {
3618
+ return [3 /*break*/, 26];
3619
+ }
3620
+ if (scriptPipelineExecutionErrors.length === 1) {
3621
+ throw scriptPipelineExecutionErrors[0];
3622
+ }
3623
+ else {
3624
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3625
+ .map(function (error) { return '- ' + error.message; })
3626
+ .join('\n\n')), "\n "); }));
3627
+ }
3628
+ case 23:
3629
+ if (tools.userInterface === undefined) {
3630
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3631
+ }
3632
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3633
+ promptTitle: currentTemplate.title,
3634
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3635
+ defaultValue: replaceParameters(preparedContent, parameters),
3636
+ // TODO: [๐Ÿง ] !! Figure out how to define placeholder in .ptbk.md file
3637
+ placeholder: undefined,
3638
+ priority: priority,
3639
+ }))];
3640
+ case 24:
3641
+ // TODO: [๐ŸŒน] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3642
+ resultString = _v.sent();
3643
+ return [3 /*break*/, 26];
3644
+ case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3645
+ case 26:
3646
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3647
+ _v.label = 27;
3648
+ case 27:
3649
+ _v.trys.push([27, 41, 42, 43]);
3650
+ _o = (e_4 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3651
+ _v.label = 28;
3652
+ case 28:
3653
+ if (!!_p.done) return [3 /*break*/, 40];
3654
+ functionName = _p.value;
3655
+ // TODO: DRY [1]
3656
+ scriptPipelineExecutionErrors = [];
3657
+ postprocessingError = null;
3658
+ _v.label = 29;
3659
+ case 29:
3660
+ _v.trys.push([29, 36, 37, 38]);
3661
+ _q = (e_3 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3662
+ _v.label = 30;
3663
+ case 30:
3664
+ if (!!_r.done) return [3 /*break*/, 35];
3665
+ scriptTools = _r.value;
3666
+ _v.label = 31;
3667
+ case 31:
3668
+ _v.trys.push([31, 33, , 34]);
3669
+ return [4 /*yield*/, scriptTools.execute({
3670
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3671
+ script: "".concat(functionName, "(resultString)"),
3672
+ parameters: {
3673
+ resultString: resultString || '',
3674
+ // Note: No ...parametersForTemplate, because working with result only
3675
+ },
3676
+ })];
3677
+ case 32:
3678
+ resultString = _v.sent();
3679
+ postprocessingError = null;
3680
+ return [3 /*break*/, 35];
3681
+ case 33:
3682
+ error_2 = _v.sent();
3683
+ if (!(error_2 instanceof Error)) {
3684
+ throw error_2;
3685
+ }
3686
+ if (error_2 instanceof UnexpectedError) {
3687
+ throw error_2;
3688
+ }
3689
+ postprocessingError = error_2;
3690
+ scriptPipelineExecutionErrors.push(error_2);
3691
+ return [3 /*break*/, 34];
3692
+ case 34:
3693
+ _r = _q.next();
3694
+ return [3 /*break*/, 30];
3695
+ case 35: return [3 /*break*/, 38];
3696
+ case 36:
3697
+ e_3_1 = _v.sent();
3698
+ e_3 = { error: e_3_1 };
3699
+ return [3 /*break*/, 38];
3700
+ case 37:
3701
+ try {
3702
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3703
+ }
3704
+ finally { if (e_3) throw e_3.error; }
3705
+ return [7 /*endfinally*/];
3706
+ case 38:
3707
+ if (postprocessingError) {
3708
+ throw postprocessingError;
3709
+ }
3710
+ _v.label = 39;
3711
+ case 39:
3712
+ _p = _o.next();
3713
+ return [3 /*break*/, 28];
3714
+ case 40: return [3 /*break*/, 43];
3715
+ case 41:
3716
+ e_4_1 = _v.sent();
3717
+ e_4 = { error: e_4_1 };
3718
+ return [3 /*break*/, 43];
3719
+ case 42:
3720
+ try {
3721
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3722
+ }
3723
+ finally { if (e_4) throw e_4.error; }
3724
+ return [7 /*endfinally*/];
3725
+ case 43:
3726
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
3727
+ if (currentTemplate.format) {
3728
+ if (currentTemplate.format === 'JSON') {
3729
+ if (!isValidJsonString(resultString || '')) {
3730
+ // TODO: [๐Ÿข] Do more universally via `FormatDefinition`
3731
+ try {
3732
+ resultString = extractJsonBlock(resultString || '');
3733
+ }
3734
+ catch (error) {
3735
+ keepUnused(error);
3736
+ throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3737
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3738
+ }
3739
+ }
3740
+ }
3741
+ else {
3742
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3743
+ }
3744
+ }
3745
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
3746
+ if (currentTemplate.expectations) {
3747
+ checkExpectations(currentTemplate.expectations, resultString || '');
3748
+ }
3749
+ return [2 /*return*/, "break-attempts"];
3750
+ case 44:
3751
+ error_3 = _v.sent();
3752
+ if (!(error_3 instanceof ExpectError)) {
3753
+ throw error_3;
3754
+ }
3755
+ expectError = error_3;
3756
+ return [3 /*break*/, 46];
3757
+ case 45:
3758
+ if (!isJokerAttempt &&
3759
+ currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3760
+ prompt
3761
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3762
+ // In that case we donโ€™t want to make a report about it because itโ€™s not a llm execution error
3763
+ ) {
3764
+ // TODO: [๐Ÿง ] Maybe put other templateTypes into report
3765
+ $executionReport.promptExecutions.push({
3766
+ prompt: __assign({}, prompt),
3767
+ result: result || undefined,
3768
+ error: expectError === null ? undefined : serializeError(expectError),
3769
+ });
3770
+ }
3771
+ return [7 /*endfinally*/];
3772
+ case 46:
3773
+ if (expectError !== null && attempt === maxAttempts - 1) {
3774
+ throw new PipelineExecutionError(spaceTrim$1(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
3775
+ .split('\n')
3776
+ .map(function (line) { return "> ".concat(line); })
3777
+ .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) || '')
3778
+ .split('\n')
3779
+ .map(function (line) { return "> ".concat(line); })
3780
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3781
+ ? 'null'
3782
+ : resultString
3783
+ .split('\n')
3784
+ .map(function (line) { return "> ".concat(line); })
3785
+ .join('\n')), "\n ---\n "); }));
3786
+ }
3787
+ return [2 /*return*/];
3788
+ }
3789
+ });
3790
+ };
3791
+ attempt = -jokerParameterNames.length;
3792
+ _h.label = 3;
3793
+ case 3:
3794
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 6];
3795
+ return [5 /*yield**/, _loop_2(attempt)];
3796
+ case 4:
3797
+ state_1 = _h.sent();
3798
+ switch (state_1) {
3799
+ case "break-attempts": return [3 /*break*/, 6];
3800
+ }
3801
+ _h.label = 5;
3802
+ case 5:
3803
+ attempt++;
3804
+ return [3 /*break*/, 3];
3805
+ case 6:
3806
+ //------------------------------------
3807
+ /*
3808
+
3809
+
3810
+
3811
+
3812
+
3813
+
3814
+
3815
+
3816
+
3817
+ */
3818
+ //------------------------------------
3819
+ if (resultString === null) {
3820
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3821
+ }
3822
+ return [4 /*yield*/, onProgress({
3823
+ name: name,
3824
+ title: title,
3825
+ isStarted: true,
3826
+ isDone: true,
3827
+ templateType: currentTemplate.templateType,
3828
+ parameterName: currentTemplate.resultingParameterName,
3829
+ parameterValue: resultString,
3830
+ // <- [๐Ÿธ]
3831
+ })];
3832
+ case 7:
3833
+ _h.sent();
3834
+ return [2 /*return*/, Object.freeze((_g = {},
3835
+ _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */,
3836
+ _g))];
3837
+ }
3838
+ });
3839
+ });
3229
3840
  }
3230
-
3231
3841
  /**
3232
- * Index of all counter functions
3233
- *
3234
- * @public exported from `@promptbook/utils`
3842
+ * TODO: [๐Ÿคนโ€โ™‚๏ธ]
3235
3843
  */
3236
- var CountUtils = {
3237
- CHARACTERS: countCharacters,
3238
- WORDS: countWords,
3239
- SENTENCES: countSentences,
3240
- PARAGRAPHS: countParagraphs,
3241
- LINES: countLines,
3242
- PAGES: countPages,
3243
- };
3244
3844
 
3245
3845
  /**
3246
- * Function checkExpectations will check if the expectations on given value are met
3247
- *
3248
- * Note: There are two simmilar functions:
3249
- * - `checkExpectations` which throws an error if the expectations are not met
3250
- * - `isPassingExpectations` which returns a boolean
3251
- *
3252
- * @throws {ExpectError} if the expectations are not met
3253
- * @returns {void} Nothing
3254
- * @private internal function of `createPipelineExecutor`
3846
+ * @private @@@
3255
3847
  */
3256
- function checkExpectations(expectations, value) {
3848
+ function filterJustOutputParameters(preparedPipeline, parametersToPass, $warnings, pipelineIdentification) {
3257
3849
  var e_1, _a;
3850
+ var outputParameters = {};
3851
+ var _loop_1 = function (parameter) {
3852
+ if (parametersToPass[parameter.name] === undefined) {
3853
+ // [4]
3854
+ $warnings.push(new PipelineExecutionError(spaceTrim$1(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 "); })));
3855
+ return "continue";
3856
+ }
3857
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3858
+ };
3258
3859
  try {
3259
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3260
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3261
- var amount = CountUtils[unit.toUpperCase()](value);
3262
- if (min && amount < min) {
3263
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3264
- } /* not else */
3265
- if (max && amount > max) {
3266
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3267
- }
3860
+ // Note: Filter ONLY output parameters
3861
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3862
+ var isOutput = _a.isOutput;
3863
+ return isOutput;
3864
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
3865
+ var parameter = _c.value;
3866
+ _loop_1(parameter);
3268
3867
  }
3269
3868
  }
3270
3869
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3274,32 +3873,8 @@ function checkExpectations(expectations, value) {
3274
3873
  }
3275
3874
  finally { if (e_1) throw e_1.error; }
3276
3875
  }
3876
+ return outputParameters;
3277
3877
  }
3278
- /**
3279
- * Function checkExpectations will check if the expectations on given value are met
3280
- *
3281
- * Note: There are two simmilar functions:
3282
- * - `checkExpectations` which throws an error if the expectations are not met
3283
- * - `isPassingExpectations` which returns a boolean
3284
- *
3285
- * @returns {boolean} True if the expectations are met
3286
- * @public exported from `@promptbook/core`
3287
- */
3288
- function isPassingExpectations(expectations, value) {
3289
- try {
3290
- checkExpectations(expectations, value);
3291
- return true;
3292
- }
3293
- catch (error) {
3294
- if (!(error instanceof ExpectError)) {
3295
- throw error;
3296
- }
3297
- return false;
3298
- }
3299
- }
3300
- /**
3301
- * TODO: [๐Ÿ’] Unite object for expecting amount and format
3302
- */
3303
3878
 
3304
3879
  /**
3305
3880
  * Creates executor function from pipeline and execution tools.
@@ -3333,572 +3908,6 @@ function createPipelineExecutor(options) {
3333
3908
  console.warn(spaceTrim$1(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 "); }));
3334
3909
  }
3335
3910
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3336
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3337
- function getContextForTemplate(template) {
3338
- return __awaiter(this, void 0, void 0, function () {
3339
- return __generator(this, function (_a) {
3340
- TODO_USE(template);
3341
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [๐Ÿ] Implement */];
3342
- });
3343
- });
3344
- }
3345
- function getKnowledgeForTemplate(template) {
3346
- return __awaiter(this, void 0, void 0, function () {
3347
- return __generator(this, function (_a) {
3348
- // TODO: [โ™จ] Implement Better - use real index and keyword search from `template` and {samples}
3349
- TODO_USE(template);
3350
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3351
- var content = _a.content;
3352
- return "- ".concat(content);
3353
- }).join('\n')];
3354
- });
3355
- });
3356
- }
3357
- function getSamplesForTemplate(template) {
3358
- return __awaiter(this, void 0, void 0, function () {
3359
- return __generator(this, function (_a) {
3360
- // TODO: [โ™จ] Implement Better - use real index and keyword search
3361
- TODO_USE(template);
3362
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [โ™จ] Implement */];
3363
- });
3364
- });
3365
- }
3366
- function getReservedParametersForTemplate(template) {
3367
- return __awaiter(this, void 0, void 0, function () {
3368
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3369
- var e_3, _a;
3370
- return __generator(this, function (_b) {
3371
- switch (_b.label) {
3372
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3373
- case 1:
3374
- context = _b.sent();
3375
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3376
- case 2:
3377
- knowledge = _b.sent();
3378
- return [4 /*yield*/, getSamplesForTemplate(template)];
3379
- case 3:
3380
- samples = _b.sent();
3381
- currentDate = new Date().toISOString();
3382
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3383
- reservedParameters = {
3384
- content: RESERVED_PARAMETER_RESTRICTED,
3385
- context: context,
3386
- knowledge: knowledge,
3387
- samples: samples,
3388
- currentDate: currentDate,
3389
- modelName: modelName,
3390
- };
3391
- _loop_3 = function (parameterName) {
3392
- if (reservedParameters[parameterName] === undefined) {
3393
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3394
- }
3395
- };
3396
- try {
3397
- // Note: Doublecheck that ALL reserved parameters are defined:
3398
- 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()) {
3399
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3400
- _loop_3(parameterName);
3401
- }
3402
- }
3403
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3404
- finally {
3405
- try {
3406
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3407
- }
3408
- finally { if (e_3) throw e_3.error; }
3409
- }
3410
- return [2 /*return*/, reservedParameters];
3411
- }
3412
- });
3413
- });
3414
- }
3415
- function executeSingleTemplate(currentTemplate) {
3416
- return __awaiter(this, void 0, void 0, function () {
3417
- 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;
3418
- var e_4, _f, _g;
3419
- return __generator(this, function (_h) {
3420
- switch (_h.label) {
3421
- case 0:
3422
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3423
- title = currentTemplate.title;
3424
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3425
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3426
- progress_1 = {
3427
- name: name,
3428
- title: title,
3429
- isStarted: false,
3430
- isDone: false,
3431
- templateType: currentTemplate.templateType,
3432
- parameterName: currentTemplate.resultingParameterName,
3433
- parameterValue: null,
3434
- // <- [3]
3435
- };
3436
- if (isReturned) {
3437
- throw new UnexpectedError(spaceTrim$1(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)
3438
- .split('\n')
3439
- .map(function (line) { return "> ".concat(line); })
3440
- .join('\n')), "\n "); }));
3441
- }
3442
- return [4 /*yield*/, onProgress(progress_1)];
3443
- case 1:
3444
- _h.sent();
3445
- _h.label = 2;
3446
- case 2:
3447
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3448
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3449
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3450
- throw new UnexpectedError(spaceTrim$1(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)
3451
- .map(function (name) { return "{".concat(name, "}"); })
3452
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3453
- .map(function (name) { return "{".concat(name, "}"); })
3454
- .join(', '), "\n\n "); }));
3455
- }
3456
- _b = (_a = Object).freeze;
3457
- _c = [{}];
3458
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3459
- case 3:
3460
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3461
- definedParameterNames = new Set(Object.keys(definedParameters));
3462
- parameters = {};
3463
- _loop_4 = function (parameterName) {
3464
- // Situation: Parameter is defined and used
3465
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3466
- parameters[parameterName] = definedParameters[parameterName];
3467
- }
3468
- // Situation: Parameter is defined but NOT used
3469
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3470
- // Situation: Parameter is NOT defined BUT used
3471
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3472
- // Houston, we have a problem
3473
- // Note: Checking part is also done in `validatePipeline`, but itโ€™s good to doublecheck
3474
- throw new UnexpectedError(spaceTrim$1(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 "); }));
3475
- }
3476
- };
3477
- try {
3478
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3479
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3480
- parameterName = _e.value;
3481
- _loop_4(parameterName);
3482
- }
3483
- }
3484
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3485
- finally {
3486
- try {
3487
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3488
- }
3489
- finally { if (e_4) throw e_4.error; }
3490
- }
3491
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3492
- Object.freeze(parameters);
3493
- result = null;
3494
- resultString = null;
3495
- expectError = null;
3496
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3497
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3498
- preparedContent = (currentTemplate.preparedContent || '{content}')
3499
- .split('{content}')
3500
- .join(currentTemplate.content);
3501
- _loop_5 = function (attempt) {
3502
- 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;
3503
- var e_5, _s, e_7, _t, e_6, _u;
3504
- return __generator(this, function (_v) {
3505
- switch (_v.label) {
3506
- case 0:
3507
- isJokerAttempt = attempt < 0;
3508
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3509
- // TODO: [๐Ÿง ] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3510
- if (isJokerAttempt && !jokerParameterName) {
3511
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3512
- }
3513
- result = null;
3514
- resultString = null;
3515
- expectError = null;
3516
- if (isJokerAttempt) {
3517
- if (parameters[jokerParameterName] === undefined) {
3518
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3519
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3520
- }
3521
- else {
3522
- resultString = parameters[jokerParameterName];
3523
- }
3524
- }
3525
- _v.label = 1;
3526
- case 1:
3527
- _v.trys.push([1, 44, 45, 46]);
3528
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3529
- _j = currentTemplate.templateType;
3530
- switch (_j) {
3531
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3532
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3533
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3534
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3535
- }
3536
- return [3 /*break*/, 25];
3537
- case 2:
3538
- resultString = replaceParameters(preparedContent, parameters);
3539
- return [3 /*break*/, 26];
3540
- case 3:
3541
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3542
- prompt = {
3543
- title: currentTemplate.title,
3544
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3545
- ? preparedPipeline.pipelineUrl
3546
- : 'anonymous' /* <- TODO: [๐Ÿง ] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3547
- parameters: parameters,
3548
- content: preparedContent,
3549
- modelRequirements: modelRequirements,
3550
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3551
- var name = _a.name;
3552
- return name === currentTemplate.personaName;
3553
- }) || {})), currentTemplate.expectations),
3554
- format: currentTemplate.format,
3555
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3556
- }; // <- TODO: Not very good type guard
3557
- _k = modelRequirements.modelVariant;
3558
- switch (_k) {
3559
- case 'CHAT': return [3 /*break*/, 4];
3560
- case 'COMPLETION': return [3 /*break*/, 6];
3561
- case 'EMBEDDING': return [3 /*break*/, 8];
3562
- }
3563
- return [3 /*break*/, 10];
3564
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3565
- case 5:
3566
- chatResult = _v.sent();
3567
- // TODO: [๐Ÿฌ] Destroy chatThread
3568
- result = chatResult;
3569
- resultString = chatResult.content;
3570
- return [3 /*break*/, 11];
3571
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3572
- case 7:
3573
- completionResult = _v.sent();
3574
- result = completionResult;
3575
- resultString = completionResult.content;
3576
- return [3 /*break*/, 11];
3577
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3578
- case 9:
3579
- embeddingResult = _v.sent();
3580
- result = embeddingResult;
3581
- resultString = embeddingResult.content.join(',');
3582
- return [3 /*break*/, 11];
3583
- case 10: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3584
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3585
- case 11: return [3 /*break*/, 26];
3586
- case 12:
3587
- if (arrayableToArray(tools.script).length === 0) {
3588
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3589
- }
3590
- if (!currentTemplate.contentLanguage) {
3591
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3592
- }
3593
- // TODO: DRY [1]
3594
- scriptPipelineExecutionErrors = [];
3595
- _v.label = 13;
3596
- case 13:
3597
- _v.trys.push([13, 20, 21, 22]);
3598
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3599
- _v.label = 14;
3600
- case 14:
3601
- if (!!_m.done) return [3 /*break*/, 19];
3602
- scriptTools = _m.value;
3603
- _v.label = 15;
3604
- case 15:
3605
- _v.trys.push([15, 17, , 18]);
3606
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3607
- scriptLanguage: currentTemplate.contentLanguage,
3608
- script: preparedContent,
3609
- parameters: parameters,
3610
- }))];
3611
- case 16:
3612
- resultString = _v.sent();
3613
- return [3 /*break*/, 19];
3614
- case 17:
3615
- error_2 = _v.sent();
3616
- if (!(error_2 instanceof Error)) {
3617
- throw error_2;
3618
- }
3619
- if (error_2 instanceof UnexpectedError) {
3620
- throw error_2;
3621
- }
3622
- scriptPipelineExecutionErrors.push(error_2);
3623
- return [3 /*break*/, 18];
3624
- case 18:
3625
- _m = _l.next();
3626
- return [3 /*break*/, 14];
3627
- case 19: return [3 /*break*/, 22];
3628
- case 20:
3629
- e_5_1 = _v.sent();
3630
- e_5 = { error: e_5_1 };
3631
- return [3 /*break*/, 22];
3632
- case 21:
3633
- try {
3634
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3635
- }
3636
- finally { if (e_5) throw e_5.error; }
3637
- return [7 /*endfinally*/];
3638
- case 22:
3639
- if (resultString !== null) {
3640
- return [3 /*break*/, 26];
3641
- }
3642
- if (scriptPipelineExecutionErrors.length === 1) {
3643
- throw scriptPipelineExecutionErrors[0];
3644
- }
3645
- else {
3646
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3647
- .map(function (error) { return '- ' + error.message; })
3648
- .join('\n\n')), "\n "); }));
3649
- }
3650
- case 23:
3651
- if (tools.userInterface === undefined) {
3652
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3653
- }
3654
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3655
- promptTitle: currentTemplate.title,
3656
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3657
- defaultValue: replaceParameters(preparedContent, parameters),
3658
- // TODO: [๐Ÿง ] !! Figure out how to define placeholder in .ptbk.md file
3659
- placeholder: undefined,
3660
- priority: priority,
3661
- }))];
3662
- case 24:
3663
- // TODO: [๐ŸŒน] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3664
- resultString = _v.sent();
3665
- return [3 /*break*/, 26];
3666
- case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3667
- case 26:
3668
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3669
- _v.label = 27;
3670
- case 27:
3671
- _v.trys.push([27, 41, 42, 43]);
3672
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3673
- _v.label = 28;
3674
- case 28:
3675
- if (!!_p.done) return [3 /*break*/, 40];
3676
- functionName = _p.value;
3677
- // TODO: DRY [1]
3678
- scriptPipelineExecutionErrors = [];
3679
- postprocessingError = null;
3680
- _v.label = 29;
3681
- case 29:
3682
- _v.trys.push([29, 36, 37, 38]);
3683
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3684
- _v.label = 30;
3685
- case 30:
3686
- if (!!_r.done) return [3 /*break*/, 35];
3687
- scriptTools = _r.value;
3688
- _v.label = 31;
3689
- case 31:
3690
- _v.trys.push([31, 33, , 34]);
3691
- return [4 /*yield*/, scriptTools.execute({
3692
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3693
- script: "".concat(functionName, "(resultString)"),
3694
- parameters: {
3695
- resultString: resultString || '',
3696
- // Note: No ...parametersForTemplate, because working with result only
3697
- },
3698
- })];
3699
- case 32:
3700
- resultString = _v.sent();
3701
- postprocessingError = null;
3702
- return [3 /*break*/, 35];
3703
- case 33:
3704
- error_3 = _v.sent();
3705
- if (!(error_3 instanceof Error)) {
3706
- throw error_3;
3707
- }
3708
- if (error_3 instanceof UnexpectedError) {
3709
- throw error_3;
3710
- }
3711
- postprocessingError = error_3;
3712
- scriptPipelineExecutionErrors.push(error_3);
3713
- return [3 /*break*/, 34];
3714
- case 34:
3715
- _r = _q.next();
3716
- return [3 /*break*/, 30];
3717
- case 35: return [3 /*break*/, 38];
3718
- case 36:
3719
- e_6_1 = _v.sent();
3720
- e_6 = { error: e_6_1 };
3721
- return [3 /*break*/, 38];
3722
- case 37:
3723
- try {
3724
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3725
- }
3726
- finally { if (e_6) throw e_6.error; }
3727
- return [7 /*endfinally*/];
3728
- case 38:
3729
- if (postprocessingError) {
3730
- throw postprocessingError;
3731
- }
3732
- _v.label = 39;
3733
- case 39:
3734
- _p = _o.next();
3735
- return [3 /*break*/, 28];
3736
- case 40: return [3 /*break*/, 43];
3737
- case 41:
3738
- e_7_1 = _v.sent();
3739
- e_7 = { error: e_7_1 };
3740
- return [3 /*break*/, 43];
3741
- case 42:
3742
- try {
3743
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3744
- }
3745
- finally { if (e_7) throw e_7.error; }
3746
- return [7 /*endfinally*/];
3747
- case 43:
3748
- // TODO: [๐Ÿ’] Unite object for expecting amount and format
3749
- if (currentTemplate.format) {
3750
- if (currentTemplate.format === 'JSON') {
3751
- if (!isValidJsonString(resultString || '')) {
3752
- // TODO: [๐Ÿข] Do more universally via `FormatDefinition`
3753
- try {
3754
- resultString = extractJsonBlock(resultString || '');
3755
- }
3756
- catch (error) {
3757
- keepUnused(error);
3758
- throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3759
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3760
- }
3761
- }
3762
- }
3763
- else {
3764
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3765
- }
3766
- }
3767
- // TODO: [๐Ÿ’] Unite object for expecting amount and format
3768
- if (currentTemplate.expectations) {
3769
- checkExpectations(currentTemplate.expectations, resultString || '');
3770
- }
3771
- return [2 /*return*/, "break-attempts"];
3772
- case 44:
3773
- error_4 = _v.sent();
3774
- if (!(error_4 instanceof ExpectError)) {
3775
- throw error_4;
3776
- }
3777
- expectError = error_4;
3778
- return [3 /*break*/, 46];
3779
- case 45:
3780
- if (!isJokerAttempt &&
3781
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3782
- prompt
3783
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3784
- // In that case we donโ€™t want to make a report about it because itโ€™s not a llm execution error
3785
- ) {
3786
- // TODO: [๐Ÿง ] Maybe put other templateTypes into report
3787
- executionReport.promptExecutions.push({
3788
- prompt: __assign({}, prompt),
3789
- result: result || undefined,
3790
- error: expectError === null ? undefined : serializeError(expectError),
3791
- });
3792
- }
3793
- return [7 /*endfinally*/];
3794
- case 46:
3795
- if (expectError !== null && attempt === maxAttempts - 1) {
3796
- throw new PipelineExecutionError(spaceTrim$1(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
3797
- .split('\n')
3798
- .map(function (line) { return "> ".concat(line); })
3799
- .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) || '')
3800
- .split('\n')
3801
- .map(function (line) { return "> ".concat(line); })
3802
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3803
- ? 'null'
3804
- : resultString
3805
- .split('\n')
3806
- .map(function (line) { return "> ".concat(line); })
3807
- .join('\n')), "\n ---\n "); }));
3808
- }
3809
- return [2 /*return*/];
3810
- }
3811
- });
3812
- };
3813
- attempt = -jokerParameterNames.length;
3814
- _h.label = 4;
3815
- case 4:
3816
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3817
- return [5 /*yield**/, _loop_5(attempt)];
3818
- case 5:
3819
- state_2 = _h.sent();
3820
- switch (state_2) {
3821
- case "break-attempts": return [3 /*break*/, 7];
3822
- }
3823
- _h.label = 6;
3824
- case 6:
3825
- attempt++;
3826
- return [3 /*break*/, 4];
3827
- case 7:
3828
- //------------------------------------
3829
- /*
3830
-
3831
-
3832
-
3833
-
3834
-
3835
-
3836
-
3837
-
3838
-
3839
- */
3840
- //------------------------------------
3841
- if (resultString === null) {
3842
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3843
- }
3844
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3845
- progress_2 = {
3846
- name: name,
3847
- title: title,
3848
- isStarted: true,
3849
- isDone: true,
3850
- templateType: currentTemplate.templateType,
3851
- parameterName: currentTemplate.resultingParameterName,
3852
- parameterValue: resultString,
3853
- // <- [3]
3854
- };
3855
- if (isReturned) {
3856
- throw new UnexpectedError(spaceTrim$1(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)
3857
- .split('\n')
3858
- .map(function (line) { return "> ".concat(line); })
3859
- .join('\n')), "\n\n "); }));
3860
- }
3861
- return [4 /*yield*/, onProgress(progress_2)];
3862
- case 8:
3863
- _h.sent();
3864
- _h.label = 9;
3865
- case 9:
3866
- 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)));
3867
- return [2 /*return*/];
3868
- }
3869
- });
3870
- });
3871
- }
3872
- function filterJustOutputParameters() {
3873
- var e_8, _a;
3874
- var outputParameters = {};
3875
- var _loop_6 = function (parameter) {
3876
- if (parametersToPass[parameter.name] === undefined) {
3877
- // [4]
3878
- warnings.push(new PipelineExecutionError(spaceTrim$1(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 "); })));
3879
- return "continue";
3880
- }
3881
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3882
- };
3883
- try {
3884
- // Note: Filter ONLY output parameters
3885
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3886
- var isOutput = _a.isOutput;
3887
- return isOutput;
3888
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3889
- var parameter = _c.value;
3890
- _loop_6(parameter);
3891
- }
3892
- }
3893
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3894
- finally {
3895
- try {
3896
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3897
- }
3898
- finally { if (e_8) throw e_8.error; }
3899
- }
3900
- return outputParameters;
3901
- }
3902
3911
  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;
3903
3912
  var e_1, _e, e_2, _f;
3904
3913
  return __generator(this, function (_g) {
@@ -4080,14 +4089,35 @@ function createPipelineExecutor(options) {
4080
4089
  .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 "); }));
4081
4090
  case 1:
4082
4091
  if (!!currentTemplate) return [3 /*break*/, 3];
4083
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4092
+ /* [๐Ÿคนโ€โ™‚๏ธ] */ return [4 /*yield*/, Promise.race(resolving_1)];
4084
4093
  case 2:
4085
- /* [5] */ _j.sent();
4094
+ /* [๐Ÿคนโ€โ™‚๏ธ] */ _j.sent();
4086
4095
  return [3 /*break*/, 4];
4087
4096
  case 3:
4088
4097
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4089
- work_1 = executeSingleTemplate(currentTemplate)
4090
- .then(function () {
4098
+ work_1 = executeSingleTemplate({
4099
+ currentTemplate: currentTemplate,
4100
+ preparedPipeline: preparedPipeline,
4101
+ parametersToPass: parametersToPass,
4102
+ tools: tools,
4103
+ llmTools: llmTools,
4104
+ onProgress: function (progress) {
4105
+ if (isReturned) {
4106
+ throw new UnexpectedError(spaceTrim$1(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)
4107
+ .split('\n')
4108
+ .map(function (line) { return "> ".concat(line); })
4109
+ .join('\n')), "\n "); }));
4110
+ }
4111
+ if (onProgress) {
4112
+ onProgress(progress);
4113
+ }
4114
+ },
4115
+ maxExecutionAttempts: maxExecutionAttempts,
4116
+ $executionReport: executionReport,
4117
+ pipelineIdentification: pipelineIdentification,
4118
+ })
4119
+ .then(function (newParametersToPass) {
4120
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4091
4121
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4092
4122
  })
4093
4123
  .then(function () {
@@ -4119,7 +4149,7 @@ function createPipelineExecutor(options) {
4119
4149
  var result = _a.result;
4120
4150
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4121
4151
  })), false));
4122
- outputParameters_1 = filterJustOutputParameters();
4152
+ outputParameters_1 = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
4123
4153
  isReturned = true;
4124
4154
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4125
4155
  // Note: Wait a short time to prevent race conditions
@@ -4142,7 +4172,7 @@ function createPipelineExecutor(options) {
4142
4172
  var result = _a.result;
4143
4173
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4144
4174
  })), false));
4145
- outputParameters = filterJustOutputParameters();
4175
+ outputParameters = filterJustOutputParameters(preparedPipeline, parametersToPass, warnings, pipelineIdentification);
4146
4176
  isReturned = true;
4147
4177
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4148
4178
  // Note: Wait a short time to prevent race conditions
@@ -4166,6 +4196,7 @@ function createPipelineExecutor(options) {
4166
4196
  return pipelineExecutor;
4167
4197
  }
4168
4198
  /**
4199
+ * TODO: [๐Ÿคนโ€โ™‚๏ธ] Make some smarter system for limiting concurrent executions MAX_PARALLEL_TOTAL, MAX_PARALLEL_PER_LLM
4169
4200
  * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4170
4201
  * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4171
4202
  * TODO: [๐Ÿง ][๐ŸŒณ] Use here `countTotalUsage` and put preparation and prepared pipiline to report
@@ -4174,7 +4205,7 @@ function createPipelineExecutor(options) {
4174
4205
  * TODO: [๐Ÿง ] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4175
4206
  * TODO: [๐Ÿ‘ง] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4176
4207
  * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4177
- * TODO: [๐Ÿง ][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4208
+ * TODO: [๐Ÿง ][๐Ÿธ] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4178
4209
  * TODO: [๐Ÿ› ] Actions, instruments (and maybe knowledge) => Functions and tools
4179
4210
  * TODO: [๐Ÿง ][๐Ÿ’ท] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4180
4211
  */
@@ -5416,6 +5447,8 @@ var foreachCommandParser = {
5416
5447
  */
5417
5448
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5418
5449
  var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5450
+ // TODO: !!!!!! Detect double use
5451
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
5419
5452
  $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5420
5453
  keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
5421
5454
  // Note: [๐Ÿญ] FOREACH apply has some sideeffects on different places in codebase