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