@promptbook/core 0.69.0-2 → 0.69.0-5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/esm/index.es.js +985 -899
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/src/_packages/core.index.d.ts +1 -1
  4. package/esm/typings/src/_packages/types.index.d.ts +4 -0
  5. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  6. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +5 -3
  7. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  8. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +30 -0
  9. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  10. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  11. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  12. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCell.d.ts +30 -0
  13. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempt.d.ts +30 -0
  14. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  15. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  16. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  17. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  18. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  19. package/package.json +1 -1
  20. package/umd/index.umd.js +985 -899
  21. package/umd/index.umd.js.map +1 -1
  22. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
package/esm/index.es.js CHANGED
@@ -10,7 +10,7 @@ import moment from 'moment';
10
10
  /**
11
11
  * The version of the Promptbook library
12
12
  */
13
- var PROMPTBOOK_VERSION = '0.69.0-1';
13
+ var PROMPTBOOK_VERSION = '0.69.0-4';
14
14
  // TODO: !!!! List here all the versions and annotate + put into script
15
15
 
16
16
  /*! *****************************************************************************
@@ -709,6 +709,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
709
709
  'samples',
710
710
  'modelName',
711
711
  'currentDate',
712
+ // <- TODO: !!!!! list here all command names
712
713
  // <- TODO: Add more like 'date', 'modelName',...
713
714
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
714
715
  ]);
@@ -1014,12 +1015,12 @@ function validatePipelineCore(pipeline) {
1014
1015
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1015
1016
  if (!Array.isArray(pipeline.parameters)) {
1016
1017
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1017
- throw new ParseError(spaceTrim$1(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1018
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1018
1019
  }
1019
1020
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1020
1021
  if (!Array.isArray(pipeline.templates)) {
1021
1022
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1022
- throw new ParseError(spaceTrim$1(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1023
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1023
1024
  }
1024
1025
  var _loop_1 = function (parameter) {
1025
1026
  if (parameter.isInput && parameter.isOutput) {
@@ -1816,7 +1817,7 @@ function forEachAsync(array, options, callbackfunction) {
1816
1817
  });
1817
1818
  }
1818
1819
 
1819
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1820
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-4",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-4",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-4",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-4",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1820
1821
 
1821
1822
  var defaultDiacriticsRemovalMap = [
1822
1823
  {
@@ -2345,160 +2346,36 @@ function assertsExecutionSuccessful(executionResult) {
2345
2346
  */
2346
2347
 
2347
2348
  /**
2348
- * Parses the given script and returns the list of all used variables that are not defined in the script
2349
- *
2350
- * @param script from which to extract the variables
2351
- * @returns the list of variable names
2352
- * @throws {ParseError} if the script is invalid
2353
- * @public exported from `@promptbook/utils`
2354
- */
2355
- function extractVariables(script) {
2356
- var variables = new Set();
2357
- script = "(()=>{".concat(script, "})()");
2358
- try {
2359
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2360
- try {
2361
- eval(script);
2362
- }
2363
- catch (error) {
2364
- if (!(error instanceof ReferenceError)) {
2365
- throw error;
2366
- }
2367
- var undefinedName = error.message.split(' ')[0];
2368
- /*
2369
- Note: Parsing the error
2370
- [PipelineUrlError: thing is not defined]
2371
- */
2372
- if (!undefinedName) {
2373
- throw error;
2374
- }
2375
- if (script.includes(undefinedName + '(')) {
2376
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2377
- }
2378
- else {
2379
- variables.add(undefinedName);
2380
- script = "const ".concat(undefinedName, " = '';") + script;
2381
- }
2382
- }
2383
- }
2384
- catch (error) {
2385
- if (!(error instanceof Error)) {
2386
- throw error;
2387
- }
2388
- throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2389
- }
2390
- return variables;
2391
- }
2392
- /**
2393
- * TODO: [🔣] Support for multiple languages - python, java,...
2394
- */
2395
-
2396
- /**
2397
- * Parses the template and returns the set of all used parameters
2349
+ * Determine if the pipeline is fully prepared
2398
2350
  *
2399
- * @param template the template with used parameters
2400
- * @returns the set of parameter names
2401
- * @throws {ParseError} if the script is invalid
2402
- * @public exported from `@promptbook/utils`
2351
+ * @public exported from `@promptbook/core`
2403
2352
  */
2404
- function extractParameterNamesFromTemplate(template) {
2405
- var e_1, _a, e_2, _b, e_3, _c;
2406
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2407
- var parameterNames = new Set();
2408
- try {
2409
- for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2410
- var parameterName = _e.value;
2411
- parameterNames.add(parameterName);
2412
- }
2413
- }
2414
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2415
- finally {
2416
- try {
2417
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2418
- }
2419
- finally { if (e_1) throw e_1.error; }
2420
- }
2421
- if (templateType === 'SCRIPT_TEMPLATE') {
2422
- try {
2423
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2424
- var parameterName = _g.value;
2425
- parameterNames.add(parameterName);
2426
- }
2427
- }
2428
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2429
- finally {
2430
- try {
2431
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2432
- }
2433
- finally { if (e_2) throw e_2.error; }
2434
- }
2435
- }
2436
- try {
2437
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2438
- var jokerName = _j.value;
2439
- parameterNames.add(jokerName);
2440
- }
2441
- }
2442
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2443
- finally {
2444
- try {
2445
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2446
- }
2447
- finally { if (e_3) throw e_3.error; }
2448
- }
2449
- parameterNames.delete('content');
2450
- // <- Note {websiteContent} is used in `preparedContent`
2451
- // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2452
- if (foreach !== undefined) {
2453
- if (parameterNames.has(foreach.subparameterName)) {
2454
- parameterNames.delete(foreach.subparameterName);
2455
- parameterNames.add(foreach.parameterName);
2456
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2457
- }
2353
+ function isPipelinePrepared(pipeline) {
2354
+ // Note: Ignoring `pipeline.preparations` @@@
2355
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2356
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2357
+ return false;
2458
2358
  }
2459
- return parameterNames;
2460
- }
2461
- /**
2462
- * TODO: [🔣] If script require contentLanguage
2463
- */
2464
-
2465
- /**
2466
- * Serializes an error into a [🚉] JSON-serializable object
2467
- *
2468
- * @public exported from `@promptbook/utils`
2469
- */
2470
- function serializeError(error) {
2471
- var name = error.name, message = error.message, stack = error.stack;
2472
- if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2473
- throw new UnexpectedError(spaceTrim(function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2359
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2360
+ return false;
2474
2361
  }
2475
- return {
2476
- name: name,
2477
- message: message,
2478
- stack: stack,
2479
- };
2362
+ /*
2363
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2364
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2365
+ > return false;
2366
+ > }
2367
+ */
2368
+ return true;
2480
2369
  }
2481
-
2482
2370
  /**
2483
- * Function isValidJsonString will tell you if the string is valid JSON or not
2484
- *
2485
- * @public exported from `@promptbook/utils`
2371
+ * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2372
+ * TODO: [🐠] Maybe base this on `makeValidator`
2373
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2374
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2375
+ * - [🏍] ? Is context in each template
2376
+ * - [♨] Are samples prepared
2377
+ * - [♨] Are templates prepared
2486
2378
  */
2487
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2488
- try {
2489
- JSON.parse(value);
2490
- return true;
2491
- }
2492
- catch (error) {
2493
- if (!(error instanceof Error)) {
2494
- throw error;
2495
- }
2496
- if (error.message.includes('Unexpected token')) {
2497
- return false;
2498
- }
2499
- return false;
2500
- }
2501
- }
2502
2379
 
2503
2380
  /**
2504
2381
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
@@ -2794,87 +2671,262 @@ function joinLlmExecutionTools() {
2794
2671
  */
2795
2672
 
2796
2673
  /**
2797
- * Extracts all code blocks from markdown.
2798
- *
2799
- * Note: There are multiple simmilar function:
2800
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2801
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2802
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2803
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2674
+ * Serializes an error into a [🚉] JSON-serializable object
2804
2675
  *
2805
- * @param markdown any valid markdown
2806
- * @returns code blocks with language and content
2807
- * @throws {ParseError} if block is not closed properly
2808
- * @public exported from `@promptbook/markdown-utils`
2676
+ * @public exported from `@promptbook/utils`
2809
2677
  */
2810
- function extractAllBlocksFromMarkdown(markdown) {
2811
- var e_1, _a;
2812
- var codeBlocks = [];
2813
- var lines = markdown.split('\n');
2814
- // Note: [0] Ensure that the last block notated by gt > will be closed
2815
- lines.push('');
2816
- var currentCodeBlock = null;
2817
- try {
2818
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2819
- var line = lines_1_1.value;
2820
- if (line.startsWith('> ') || line === '>') {
2821
- if (currentCodeBlock === null) {
2822
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2823
- } /* not else */
2824
- if (currentCodeBlock.blockNotation === '>') {
2825
- if (currentCodeBlock.content !== '') {
2826
- currentCodeBlock.content += '\n';
2827
- }
2828
- currentCodeBlock.content += line.slice(2);
2829
- }
2830
- }
2831
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2832
- codeBlocks.push(currentCodeBlock);
2833
- currentCodeBlock = null;
2834
- }
2835
- /* not else */
2836
- if (line.startsWith('```')) {
2837
- var language = line.slice(3).trim() || null;
2838
- if (currentCodeBlock === null) {
2839
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2840
- }
2841
- else {
2842
- if (language !== null) {
2843
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2844
- }
2845
- codeBlocks.push(currentCodeBlock);
2846
- currentCodeBlock = null;
2847
- }
2848
- }
2849
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2850
- if (currentCodeBlock.content !== '') {
2851
- currentCodeBlock.content += '\n';
2852
- }
2853
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2854
- }
2855
- }
2856
- }
2857
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2858
- finally {
2859
- try {
2860
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2861
- }
2862
- finally { if (e_1) throw e_1.error; }
2863
- }
2864
- if (currentCodeBlock !== null) {
2865
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2678
+ function serializeError(error) {
2679
+ var name = error.name, message = error.message, stack = error.stack;
2680
+ if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2681
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2866
2682
  }
2867
- return codeBlocks;
2683
+ return {
2684
+ name: name,
2685
+ message: message,
2686
+ stack: stack,
2687
+ };
2868
2688
  }
2869
- /**
2870
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2871
- */
2872
2689
 
2873
2690
  /**
2874
- * Extracts extracts exactly one valid JSON code block
2691
+ * Takes an item or an array of items and returns an array of items
2875
2692
  *
2876
- * - When given string is a valid JSON as it is, it just returns it
2877
- * - When there is no JSON code block the function throws a `ParseError`
2693
+ * 1) Any item except array and undefined returns array with that one item (also null)
2694
+ * 2) Undefined returns empty array
2695
+ * 3) Array returns itself
2696
+ *
2697
+ * @private internal utility
2698
+ */
2699
+ function arrayableToArray(input) {
2700
+ if (input === undefined) {
2701
+ return [];
2702
+ }
2703
+ if (input instanceof Array) {
2704
+ return input;
2705
+ }
2706
+ return [input];
2707
+ }
2708
+
2709
+ /**
2710
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2711
+ *
2712
+ * @param script from which to extract the variables
2713
+ * @returns the list of variable names
2714
+ * @throws {ParseError} if the script is invalid
2715
+ * @public exported from `@promptbook/utils`
2716
+ */
2717
+ function extractVariables(script) {
2718
+ var variables = new Set();
2719
+ script = "(()=>{".concat(script, "})()");
2720
+ try {
2721
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2722
+ try {
2723
+ eval(script);
2724
+ }
2725
+ catch (error) {
2726
+ if (!(error instanceof ReferenceError)) {
2727
+ throw error;
2728
+ }
2729
+ var undefinedName = error.message.split(' ')[0];
2730
+ /*
2731
+ Note: Parsing the error
2732
+ [PipelineUrlError: thing is not defined]
2733
+ */
2734
+ if (!undefinedName) {
2735
+ throw error;
2736
+ }
2737
+ if (script.includes(undefinedName + '(')) {
2738
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2739
+ }
2740
+ else {
2741
+ variables.add(undefinedName);
2742
+ script = "const ".concat(undefinedName, " = '';") + script;
2743
+ }
2744
+ }
2745
+ }
2746
+ catch (error) {
2747
+ if (!(error instanceof Error)) {
2748
+ throw error;
2749
+ }
2750
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2751
+ }
2752
+ return variables;
2753
+ }
2754
+ /**
2755
+ * TODO: [🔣] Support for multiple languages - python, java,...
2756
+ */
2757
+
2758
+ /**
2759
+ * Parses the template and returns the set of all used parameters
2760
+ *
2761
+ * @param template the template with used parameters
2762
+ * @returns the set of parameter names
2763
+ * @throws {ParseError} if the script is invalid
2764
+ * @public exported from `@promptbook/utils`
2765
+ */
2766
+ function extractParameterNamesFromTemplate(template) {
2767
+ var e_1, _a, e_2, _b, e_3, _c;
2768
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2769
+ var parameterNames = new Set();
2770
+ try {
2771
+ for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2772
+ var parameterName = _e.value;
2773
+ parameterNames.add(parameterName);
2774
+ }
2775
+ }
2776
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2777
+ finally {
2778
+ try {
2779
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2780
+ }
2781
+ finally { if (e_1) throw e_1.error; }
2782
+ }
2783
+ if (templateType === 'SCRIPT_TEMPLATE') {
2784
+ try {
2785
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2786
+ var parameterName = _g.value;
2787
+ parameterNames.add(parameterName);
2788
+ }
2789
+ }
2790
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2791
+ finally {
2792
+ try {
2793
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2794
+ }
2795
+ finally { if (e_2) throw e_2.error; }
2796
+ }
2797
+ }
2798
+ try {
2799
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2800
+ var jokerName = _j.value;
2801
+ parameterNames.add(jokerName);
2802
+ }
2803
+ }
2804
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2805
+ finally {
2806
+ try {
2807
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2808
+ }
2809
+ finally { if (e_3) throw e_3.error; }
2810
+ }
2811
+ parameterNames.delete('content');
2812
+ // <- Note {websiteContent} is used in `preparedContent`
2813
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2814
+ if (foreach !== undefined) {
2815
+ if (parameterNames.has(foreach.subparameterName)) {
2816
+ parameterNames.delete(foreach.subparameterName);
2817
+ parameterNames.add(foreach.parameterName);
2818
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2819
+ }
2820
+ }
2821
+ return parameterNames;
2822
+ }
2823
+ /**
2824
+ * TODO: [🔣] If script require contentLanguage
2825
+ */
2826
+
2827
+ /**
2828
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2829
+ *
2830
+ * @public exported from `@promptbook/utils`
2831
+ */
2832
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2833
+ try {
2834
+ JSON.parse(value);
2835
+ return true;
2836
+ }
2837
+ catch (error) {
2838
+ if (!(error instanceof Error)) {
2839
+ throw error;
2840
+ }
2841
+ if (error.message.includes('Unexpected token')) {
2842
+ return false;
2843
+ }
2844
+ return false;
2845
+ }
2846
+ }
2847
+
2848
+ /**
2849
+ * Extracts all code blocks from markdown.
2850
+ *
2851
+ * Note: There are multiple simmilar function:
2852
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2853
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2854
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2855
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2856
+ *
2857
+ * @param markdown any valid markdown
2858
+ * @returns code blocks with language and content
2859
+ * @throws {ParseError} if block is not closed properly
2860
+ * @public exported from `@promptbook/markdown-utils`
2861
+ */
2862
+ function extractAllBlocksFromMarkdown(markdown) {
2863
+ var e_1, _a;
2864
+ var codeBlocks = [];
2865
+ var lines = markdown.split('\n');
2866
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2867
+ lines.push('');
2868
+ var currentCodeBlock = null;
2869
+ try {
2870
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2871
+ var line = lines_1_1.value;
2872
+ if (line.startsWith('> ') || line === '>') {
2873
+ if (currentCodeBlock === null) {
2874
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2875
+ } /* not else */
2876
+ if (currentCodeBlock.blockNotation === '>') {
2877
+ if (currentCodeBlock.content !== '') {
2878
+ currentCodeBlock.content += '\n';
2879
+ }
2880
+ currentCodeBlock.content += line.slice(2);
2881
+ }
2882
+ }
2883
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2884
+ codeBlocks.push(currentCodeBlock);
2885
+ currentCodeBlock = null;
2886
+ }
2887
+ /* not else */
2888
+ if (line.startsWith('```')) {
2889
+ var language = line.slice(3).trim() || null;
2890
+ if (currentCodeBlock === null) {
2891
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2892
+ }
2893
+ else {
2894
+ if (language !== null) {
2895
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2896
+ }
2897
+ codeBlocks.push(currentCodeBlock);
2898
+ currentCodeBlock = null;
2899
+ }
2900
+ }
2901
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2902
+ if (currentCodeBlock.content !== '') {
2903
+ currentCodeBlock.content += '\n';
2904
+ }
2905
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2906
+ }
2907
+ }
2908
+ }
2909
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2910
+ finally {
2911
+ try {
2912
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2913
+ }
2914
+ finally { if (e_1) throw e_1.error; }
2915
+ }
2916
+ if (currentCodeBlock !== null) {
2917
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2918
+ }
2919
+ return codeBlocks;
2920
+ }
2921
+ /**
2922
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2923
+ */
2924
+
2925
+ /**
2926
+ * Extracts extracts exactly one valid JSON code block
2927
+ *
2928
+ * - When given string is a valid JSON as it is, it just returns it
2929
+ * - When there is no JSON code block the function throws a `ParseError`
2878
2930
  * - When there are multiple JSON code blocks the function throws a `ParseError`
2879
2931
  *
2880
2932
  * Note: It is not important if marked as ```json BUT if it is VALID JSON
@@ -2909,57 +2961,6 @@ function extractJsonBlock(markdown) {
2909
2961
  * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2910
2962
  */
2911
2963
 
2912
- /**
2913
- * Determine if the pipeline is fully prepared
2914
- *
2915
- * @public exported from `@promptbook/core`
2916
- */
2917
- function isPipelinePrepared(pipeline) {
2918
- // Note: Ignoring `pipeline.preparations` @@@
2919
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2920
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2921
- return false;
2922
- }
2923
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2924
- return false;
2925
- }
2926
- /*
2927
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2928
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2929
- > return false;
2930
- > }
2931
- */
2932
- return true;
2933
- }
2934
- /**
2935
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2936
- * TODO: [🐠] Maybe base this on `makeValidator`
2937
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2938
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2939
- * - [🏍] ? Is context in each template
2940
- * - [♨] Are samples prepared
2941
- * - [♨] Are templates prepared
2942
- */
2943
-
2944
- /**
2945
- * Takes an item or an array of items and returns an array of items
2946
- *
2947
- * 1) Any item except array and undefined returns array with that one item (also null)
2948
- * 2) Undefined returns empty array
2949
- * 3) Array returns itself
2950
- *
2951
- * @private internal utility
2952
- */
2953
- function arrayableToArray(input) {
2954
- if (input === undefined) {
2955
- return [];
2956
- }
2957
- if (input instanceof Array) {
2958
- return input;
2959
- }
2960
- return [input];
2961
- }
2962
-
2963
2964
  /**
2964
2965
  * Just says that the variable is not used but should be kept
2965
2966
  * No side effects.
@@ -2981,23 +2982,6 @@ function keepUnused() {
2981
2982
  }
2982
2983
  }
2983
2984
 
2984
- /**
2985
- * Just marks a place of place where should be something implemented
2986
- * No side effects.
2987
- *
2988
- * Note: It can be usefull suppressing eslint errors of unused variables
2989
- *
2990
- * @param value any values
2991
- * @returns void
2992
- * @private within the repository
2993
- */
2994
- function TODO_USE() {
2995
- var value = [];
2996
- for (var _i = 0; _i < arguments.length; _i++) {
2997
- value[_i] = arguments[_i];
2998
- }
2999
- }
3000
-
3001
2985
  /**
3002
2986
  * Replaces parameters in template with values from parameters object
3003
2987
  *
@@ -3297,536 +3281,549 @@ function isPassingExpectations(expectations, value) {
3297
3281
  return false;
3298
3282
  }
3299
3283
  }
3300
- /**
3301
- * TODO: [💝] Unite object for expecting amount and format
3302
- */
3284
+ /**
3285
+ * TODO: [💝] Unite object for expecting amount and format
3286
+ */
3287
+
3288
+ /**
3289
+ * Just marks a place of place where should be something implemented
3290
+ * No side effects.
3291
+ *
3292
+ * Note: It can be usefull suppressing eslint errors of unused variables
3293
+ *
3294
+ * @param value any values
3295
+ * @returns void
3296
+ * @private within the repository
3297
+ */
3298
+ function TODO_USE() {
3299
+ var value = [];
3300
+ for (var _i = 0; _i < arguments.length; _i++) {
3301
+ value[_i] = arguments[_i];
3302
+ }
3303
+ }
3304
+
3305
+ /**
3306
+ * @@@
3307
+ *
3308
+ * @private internal utility of `createPipelineExecutor`
3309
+ */
3310
+ function getContextForTemplate(template) {
3311
+ return __awaiter(this, void 0, void 0, function () {
3312
+ return __generator(this, function (_a) {
3313
+ TODO_USE(template);
3314
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3315
+ });
3316
+ });
3317
+ }
3318
+
3319
+ /**
3320
+ * @@@
3321
+ *
3322
+ * @private internal utility of `createPipelineExecutor`
3323
+ */
3324
+ function getKnowledgeForTemplate(options) {
3325
+ return __awaiter(this, void 0, void 0, function () {
3326
+ var preparedPipeline, template;
3327
+ return __generator(this, function (_a) {
3328
+ preparedPipeline = options.preparedPipeline, template = options.template;
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
+ * @@@
3341
+ *
3342
+ * @private internal utility of `createPipelineExecutor`
3343
+ */
3344
+ function getSamplesForTemplate(template) {
3345
+ return __awaiter(this, void 0, void 0, function () {
3346
+ return __generator(this, function (_a) {
3347
+ // TODO: [♨] Implement Better - use real index and keyword search
3348
+ TODO_USE(template);
3349
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3350
+ });
3351
+ });
3352
+ }
3353
+
3354
+ /**
3355
+ * @@@
3356
+ *
3357
+ * @private internal utility of `createPipelineExecutor`
3358
+ */
3359
+ function getReservedParametersForTemplate(options) {
3360
+ return __awaiter(this, void 0, void 0, function () {
3361
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3362
+ var e_1, _a;
3363
+ return __generator(this, function (_b) {
3364
+ switch (_b.label) {
3365
+ case 0:
3366
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
3367
+ return [4 /*yield*/, getContextForTemplate(template)];
3368
+ case 1:
3369
+ context = _b.sent();
3370
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
3371
+ case 2:
3372
+ knowledge = _b.sent();
3373
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3374
+ case 3:
3375
+ samples = _b.sent();
3376
+ currentDate = new Date().toISOString();
3377
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3378
+ reservedParameters = {
3379
+ content: RESERVED_PARAMETER_RESTRICTED,
3380
+ context: context,
3381
+ knowledge: knowledge,
3382
+ samples: samples,
3383
+ currentDate: currentDate,
3384
+ modelName: modelName,
3385
+ };
3386
+ _loop_1 = function (parameterName) {
3387
+ if (reservedParameters[parameterName] === undefined) {
3388
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3389
+ }
3390
+ };
3391
+ try {
3392
+ // Note: Doublecheck that ALL reserved parameters are defined:
3393
+ 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()) {
3394
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3395
+ _loop_1(parameterName);
3396
+ }
3397
+ }
3398
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3399
+ finally {
3400
+ try {
3401
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3402
+ }
3403
+ finally { if (e_1) throw e_1.error; }
3404
+ }
3405
+ return [2 /*return*/, reservedParameters];
3406
+ }
3407
+ });
3408
+ });
3409
+ }
3303
3410
 
3304
3411
  /**
3305
- * Creates executor function from pipeline and execution tools.
3412
+ * @@@
3306
3413
  *
3307
- * @returns The executor function
3308
- * @throws {PipelineLogicError} on logical error in the pipeline
3309
- * @public exported from `@promptbook/core`
3414
+ * @private internal utility of `createPipelineExecutor`
3310
3415
  */
3311
- function createPipelineExecutor(options) {
3312
- var _this = this;
3313
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3314
- var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
3315
- validatePipeline(pipeline);
3316
- var pipelineIdentification = (function () {
3317
- // Note: This is a 😐 implementation of [🚞]
3318
- var _ = [];
3319
- if (pipeline.sourceFile !== undefined) {
3320
- _.push("File: ".concat(pipeline.sourceFile));
3321
- }
3322
- if (pipeline.pipelineUrl !== undefined) {
3323
- _.push("Url: ".concat(pipeline.pipelineUrl));
3324
- }
3325
- return _.join('\n');
3326
- })();
3327
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3328
- var preparedPipeline;
3329
- if (isPipelinePrepared(pipeline)) {
3330
- preparedPipeline = pipeline;
3331
- }
3332
- else if (isNotPreparedWarningSupressed !== true) {
3333
- console.warn(spaceTrim$1(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3334
- }
3335
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3336
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3337
- function getContextForTemplate(template) {
3338
- return __awaiter(this, void 0, void 0, function () {
3339
- return __generator(this, function (_a) {
3340
- TODO_USE(template);
3341
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3342
- });
3343
- });
3344
- }
3345
- function getKnowledgeForTemplate(template) {
3346
- return __awaiter(this, void 0, void 0, function () {
3347
- return __generator(this, function (_a) {
3348
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3349
- TODO_USE(template);
3350
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3351
- var content = _a.content;
3352
- return "- ".concat(content);
3353
- }).join('\n')];
3354
- });
3355
- });
3356
- }
3357
- function getSamplesForTemplate(template) {
3358
- return __awaiter(this, void 0, void 0, function () {
3359
- return __generator(this, function (_a) {
3360
- // TODO: [♨] Implement Better - use real index and keyword search
3361
- TODO_USE(template);
3362
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3363
- });
3364
- });
3365
- }
3366
- function getReservedParametersForTemplate(template) {
3367
- return __awaiter(this, void 0, void 0, function () {
3368
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3369
- var e_3, _a;
3370
- return __generator(this, function (_b) {
3371
- switch (_b.label) {
3372
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3373
- case 1:
3374
- context = _b.sent();
3375
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3376
- case 2:
3377
- knowledge = _b.sent();
3378
- return [4 /*yield*/, getSamplesForTemplate(template)];
3379
- case 3:
3380
- samples = _b.sent();
3381
- currentDate = new Date().toISOString();
3382
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3383
- reservedParameters = {
3384
- content: RESERVED_PARAMETER_RESTRICTED,
3385
- context: context,
3386
- knowledge: knowledge,
3387
- samples: samples,
3388
- currentDate: currentDate,
3389
- modelName: modelName,
3390
- };
3391
- _loop_3 = function (parameterName) {
3392
- if (reservedParameters[parameterName] === undefined) {
3393
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3394
- }
3395
- };
3396
- try {
3397
- // Note: Doublecheck that ALL reserved parameters are defined:
3398
- for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3399
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3400
- _loop_3(parameterName);
3401
- }
3402
- }
3403
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3404
- finally {
3405
- try {
3406
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3407
- }
3408
- finally { if (e_3) throw e_3.error; }
3409
- }
3410
- return [2 /*return*/, reservedParameters];
3416
+ function executeTemplate(options) {
3417
+ return __awaiter(this, void 0, void 0, function () {
3418
+ var currentTemplate, preparedPipeline, parametersToPass, tools, llmTools, onProgress, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, 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;
3419
+ var e_1, _f, _g;
3420
+ return __generator(this, function (_h) {
3421
+ switch (_h.label) {
3422
+ case 0:
3423
+ currentTemplate = options.currentTemplate, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, llmTools = options.llmTools, onProgress = options.onProgress, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3424
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3425
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3426
+ title = currentTemplate.title;
3427
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3428
+ return [4 /*yield*/, onProgress({
3429
+ name: name,
3430
+ title: title,
3431
+ isStarted: false,
3432
+ isDone: false,
3433
+ templateType: currentTemplate.templateType,
3434
+ parameterName: currentTemplate.resultingParameterName,
3435
+ parameterValue: null,
3436
+ // <- [🍸]
3437
+ })];
3438
+ case 1:
3439
+ _h.sent();
3440
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3441
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3442
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3443
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3444
+ .map(function (name) { return "{".concat(name, "}"); })
3445
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3446
+ .map(function (name) { return "{".concat(name, "}"); })
3447
+ .join(', '), "\n\n "); }));
3411
3448
  }
3412
- });
3413
- });
3414
- }
3415
- function executeSingleTemplate(currentTemplate) {
3416
- return __awaiter(this, void 0, void 0, function () {
3417
- var name, title, priority, progress_1, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_4, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_5, attempt, state_2, progress_2;
3418
- var e_4, _f, _g;
3419
- return __generator(this, function (_h) {
3420
- switch (_h.label) {
3421
- case 0:
3422
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3423
- title = currentTemplate.title;
3424
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3425
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3426
- progress_1 = {
3427
- name: name,
3428
- title: title,
3429
- isStarted: false,
3430
- isDone: false,
3431
- templateType: currentTemplate.templateType,
3432
- parameterName: currentTemplate.resultingParameterName,
3433
- parameterValue: null,
3434
- // <- [3]
3435
- };
3436
- if (isReturned) {
3437
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3438
- .split('\n')
3439
- .map(function (line) { return "> ".concat(line); })
3440
- .join('\n')), "\n "); }));
3441
- }
3442
- return [4 /*yield*/, onProgress(progress_1)];
3443
- case 1:
3444
- _h.sent();
3445
- _h.label = 2;
3446
- case 2:
3447
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3448
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3449
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3450
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3451
- .map(function (name) { return "{".concat(name, "}"); })
3452
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3453
- .map(function (name) { return "{".concat(name, "}"); })
3454
- .join(', '), "\n\n "); }));
3455
- }
3456
- _b = (_a = Object).freeze;
3457
- _c = [{}];
3458
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3459
- case 3:
3460
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3461
- definedParameterNames = new Set(Object.keys(definedParameters));
3462
- parameters = {};
3463
- _loop_4 = function (parameterName) {
3464
- // Situation: Parameter is defined and used
3465
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3466
- parameters[parameterName] = definedParameters[parameterName];
3467
- }
3468
- // Situation: Parameter is defined but NOT used
3469
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3470
- // Situation: Parameter is NOT defined BUT used
3471
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3472
- // Houston, we have a problem
3473
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3474
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3475
- }
3476
- };
3477
- try {
3478
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3479
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3480
- parameterName = _e.value;
3481
- _loop_4(parameterName);
3482
- }
3483
- }
3484
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3485
- finally {
3486
- try {
3487
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3488
- }
3489
- finally { if (e_4) throw e_4.error; }
3490
- }
3491
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3492
- Object.freeze(parameters);
3493
- result = null;
3494
- resultString = null;
3495
- expectError = null;
3496
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3497
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3498
- preparedContent = (currentTemplate.preparedContent || '{content}')
3499
- .split('{content}')
3500
- .join(currentTemplate.content);
3501
- _loop_5 = function (attempt) {
3502
- var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_2, e_5_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_3, e_6_1, e_7_1, error_4;
3503
- var e_5, _s, e_7, _t, e_6, _u;
3504
- return __generator(this, function (_v) {
3505
- switch (_v.label) {
3506
- case 0:
3507
- isJokerAttempt = attempt < 0;
3508
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3509
- // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3510
- if (isJokerAttempt && !jokerParameterName) {
3511
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3512
- }
3513
- result = null;
3514
- resultString = null;
3515
- expectError = null;
3516
- if (isJokerAttempt) {
3517
- if (parameters[jokerParameterName] === undefined) {
3518
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3519
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3520
- }
3521
- else {
3522
- resultString = parameters[jokerParameterName];
3523
- }
3524
- }
3525
- _v.label = 1;
3526
- case 1:
3527
- _v.trys.push([1, 44, 45, 46]);
3528
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3529
- _j = currentTemplate.templateType;
3530
- switch (_j) {
3531
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3532
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3533
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3534
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3535
- }
3536
- return [3 /*break*/, 25];
3537
- case 2:
3538
- resultString = replaceParameters(preparedContent, parameters);
3539
- return [3 /*break*/, 26];
3540
- case 3:
3541
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3542
- prompt = {
3543
- title: currentTemplate.title,
3544
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3545
- ? preparedPipeline.pipelineUrl
3546
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3547
- parameters: parameters,
3548
- content: preparedContent,
3549
- modelRequirements: modelRequirements,
3550
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3551
- var name = _a.name;
3552
- return name === currentTemplate.personaName;
3553
- }) || {})), currentTemplate.expectations),
3554
- format: currentTemplate.format,
3555
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3556
- }; // <- TODO: Not very good type guard
3557
- _k = modelRequirements.modelVariant;
3558
- switch (_k) {
3559
- case 'CHAT': return [3 /*break*/, 4];
3560
- case 'COMPLETION': return [3 /*break*/, 6];
3561
- case 'EMBEDDING': return [3 /*break*/, 8];
3562
- }
3563
- return [3 /*break*/, 10];
3564
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3565
- case 5:
3566
- chatResult = _v.sent();
3567
- // TODO: [🍬] Destroy chatThread
3568
- result = chatResult;
3569
- resultString = chatResult.content;
3570
- return [3 /*break*/, 11];
3571
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3572
- case 7:
3573
- completionResult = _v.sent();
3574
- result = completionResult;
3575
- resultString = completionResult.content;
3576
- return [3 /*break*/, 11];
3577
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3578
- case 9:
3579
- embeddingResult = _v.sent();
3580
- result = embeddingResult;
3581
- resultString = embeddingResult.content.join(',');
3582
- return [3 /*break*/, 11];
3583
- case 10: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3584
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3585
- case 11: return [3 /*break*/, 26];
3586
- case 12:
3587
- if (arrayableToArray(tools.script).length === 0) {
3588
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3589
- }
3590
- if (!currentTemplate.contentLanguage) {
3591
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3592
- }
3593
- // TODO: DRY [1]
3594
- scriptPipelineExecutionErrors = [];
3595
- _v.label = 13;
3596
- case 13:
3597
- _v.trys.push([13, 20, 21, 22]);
3598
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3599
- _v.label = 14;
3600
- case 14:
3601
- if (!!_m.done) return [3 /*break*/, 19];
3602
- scriptTools = _m.value;
3603
- _v.label = 15;
3604
- case 15:
3605
- _v.trys.push([15, 17, , 18]);
3606
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3607
- scriptLanguage: currentTemplate.contentLanguage,
3608
- script: preparedContent,
3609
- parameters: parameters,
3610
- }))];
3611
- case 16:
3612
- resultString = _v.sent();
3613
- return [3 /*break*/, 19];
3614
- case 17:
3615
- error_2 = _v.sent();
3616
- if (!(error_2 instanceof Error)) {
3617
- throw error_2;
3618
- }
3619
- if (error_2 instanceof UnexpectedError) {
3620
- throw error_2;
3621
- }
3622
- scriptPipelineExecutionErrors.push(error_2);
3623
- return [3 /*break*/, 18];
3624
- case 18:
3625
- _m = _l.next();
3626
- return [3 /*break*/, 14];
3627
- case 19: return [3 /*break*/, 22];
3628
- case 20:
3629
- e_5_1 = _v.sent();
3630
- e_5 = { error: e_5_1 };
3631
- return [3 /*break*/, 22];
3632
- case 21:
3633
- try {
3634
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3635
- }
3636
- finally { if (e_5) throw e_5.error; }
3637
- return [7 /*endfinally*/];
3638
- case 22:
3639
- if (resultString !== null) {
3640
- return [3 /*break*/, 26];
3641
- }
3642
- if (scriptPipelineExecutionErrors.length === 1) {
3643
- throw scriptPipelineExecutionErrors[0];
3644
- }
3645
- else {
3646
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3647
- .map(function (error) { return '- ' + error.message; })
3648
- .join('\n\n')), "\n "); }));
3649
- }
3650
- case 23:
3651
- if (tools.userInterface === undefined) {
3652
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3653
- }
3654
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3655
- promptTitle: currentTemplate.title,
3656
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3657
- defaultValue: replaceParameters(preparedContent, parameters),
3658
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3659
- placeholder: undefined,
3660
- priority: priority,
3661
- }))];
3662
- case 24:
3663
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3664
- resultString = _v.sent();
3665
- return [3 /*break*/, 26];
3666
- case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3667
- case 26:
3668
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3669
- _v.label = 27;
3670
- case 27:
3671
- _v.trys.push([27, 41, 42, 43]);
3672
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3673
- _v.label = 28;
3674
- case 28:
3675
- if (!!_p.done) return [3 /*break*/, 40];
3676
- functionName = _p.value;
3677
- // TODO: DRY [1]
3678
- scriptPipelineExecutionErrors = [];
3679
- postprocessingError = null;
3680
- _v.label = 29;
3681
- case 29:
3682
- _v.trys.push([29, 36, 37, 38]);
3683
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3684
- _v.label = 30;
3685
- case 30:
3686
- if (!!_r.done) return [3 /*break*/, 35];
3687
- scriptTools = _r.value;
3688
- _v.label = 31;
3689
- case 31:
3690
- _v.trys.push([31, 33, , 34]);
3691
- return [4 /*yield*/, scriptTools.execute({
3692
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3693
- script: "".concat(functionName, "(resultString)"),
3694
- parameters: {
3695
- resultString: resultString || '',
3696
- // Note: No ...parametersForTemplate, because working with result only
3697
- },
3698
- })];
3699
- case 32:
3700
- resultString = _v.sent();
3701
- postprocessingError = null;
3702
- return [3 /*break*/, 35];
3703
- case 33:
3704
- error_3 = _v.sent();
3705
- if (!(error_3 instanceof Error)) {
3706
- throw error_3;
3707
- }
3708
- if (error_3 instanceof UnexpectedError) {
3709
- throw error_3;
3710
- }
3711
- postprocessingError = error_3;
3712
- scriptPipelineExecutionErrors.push(error_3);
3713
- return [3 /*break*/, 34];
3714
- case 34:
3715
- _r = _q.next();
3716
- return [3 /*break*/, 30];
3717
- case 35: return [3 /*break*/, 38];
3718
- case 36:
3719
- e_6_1 = _v.sent();
3720
- e_6 = { error: e_6_1 };
3721
- return [3 /*break*/, 38];
3722
- case 37:
3723
- try {
3724
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3725
- }
3726
- finally { if (e_6) throw e_6.error; }
3727
- return [7 /*endfinally*/];
3728
- case 38:
3729
- if (postprocessingError) {
3730
- throw postprocessingError;
3731
- }
3732
- _v.label = 39;
3733
- case 39:
3734
- _p = _o.next();
3735
- return [3 /*break*/, 28];
3736
- case 40: return [3 /*break*/, 43];
3737
- case 41:
3738
- e_7_1 = _v.sent();
3739
- e_7 = { error: e_7_1 };
3740
- return [3 /*break*/, 43];
3741
- case 42:
3742
- try {
3743
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3744
- }
3745
- finally { if (e_7) throw e_7.error; }
3746
- return [7 /*endfinally*/];
3747
- case 43:
3748
- // TODO: [💝] Unite object for expecting amount and format
3749
- if (currentTemplate.format) {
3750
- if (currentTemplate.format === 'JSON') {
3751
- if (!isValidJsonString(resultString || '')) {
3752
- // TODO: [🏢] Do more universally via `FormatDefinition`
3753
- try {
3754
- resultString = extractJsonBlock(resultString || '');
3755
- }
3756
- catch (error) {
3757
- keepUnused(error);
3758
- throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3759
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3760
- }
3761
- }
3449
+ _b = (_a = Object).freeze;
3450
+ _c = [{}];
3451
+ return [4 /*yield*/, getReservedParametersForTemplate({
3452
+ preparedPipeline: preparedPipeline,
3453
+ template: currentTemplate,
3454
+ pipelineIdentification: pipelineIdentification,
3455
+ })];
3456
+ case 2:
3457
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3458
+ definedParameterNames = new Set(Object.keys(definedParameters));
3459
+ parameters = {};
3460
+ _loop_1 = function (parameterName) {
3461
+ // Situation: Parameter is defined and used
3462
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3463
+ parameters[parameterName] = definedParameters[parameterName];
3464
+ }
3465
+ // Situation: Parameter is defined but NOT used
3466
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3467
+ // Situation: Parameter is NOT defined BUT used
3468
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3469
+ // Houston, we have a problem
3470
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3471
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3472
+ }
3473
+ };
3474
+ try {
3475
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3476
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3477
+ parameterName = _e.value;
3478
+ _loop_1(parameterName);
3479
+ }
3480
+ }
3481
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3482
+ finally {
3483
+ try {
3484
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3485
+ }
3486
+ finally { if (e_1) throw e_1.error; }
3487
+ }
3488
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3489
+ Object.freeze(parameters);
3490
+ result = null;
3491
+ resultString = null;
3492
+ expectError = null;
3493
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3494
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3495
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3496
+ .split('{content}')
3497
+ .join(currentTemplate.content);
3498
+ _loop_2 = function (attempt) {
3499
+ 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;
3500
+ var e_2, _s, e_4, _t, e_3, _u;
3501
+ return __generator(this, function (_v) {
3502
+ switch (_v.label) {
3503
+ case 0:
3504
+ isJokerAttempt = attempt < 0;
3505
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3506
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3507
+ if (isJokerAttempt && !jokerParameterName) {
3508
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3509
+ }
3510
+ result = null;
3511
+ resultString = null;
3512
+ expectError = null;
3513
+ if (isJokerAttempt) {
3514
+ if (parameters[jokerParameterName] === undefined) {
3515
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3516
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3517
+ }
3518
+ else {
3519
+ resultString = parameters[jokerParameterName];
3520
+ }
3521
+ }
3522
+ _v.label = 1;
3523
+ case 1:
3524
+ _v.trys.push([1, 44, 45, 46]);
3525
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3526
+ _j = currentTemplate.templateType;
3527
+ switch (_j) {
3528
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3529
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3530
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3531
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3532
+ }
3533
+ return [3 /*break*/, 25];
3534
+ case 2:
3535
+ resultString = replaceParameters(preparedContent, parameters);
3536
+ return [3 /*break*/, 26];
3537
+ case 3:
3538
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3539
+ prompt = {
3540
+ title: currentTemplate.title,
3541
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3542
+ ? preparedPipeline.pipelineUrl
3543
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3544
+ parameters: parameters,
3545
+ content: preparedContent,
3546
+ modelRequirements: modelRequirements,
3547
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3548
+ var name = _a.name;
3549
+ return name === currentTemplate.personaName;
3550
+ }) || {})), currentTemplate.expectations),
3551
+ format: currentTemplate.format,
3552
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3553
+ }; // <- TODO: Not very good type guard
3554
+ _k = modelRequirements.modelVariant;
3555
+ switch (_k) {
3556
+ case 'CHAT': return [3 /*break*/, 4];
3557
+ case 'COMPLETION': return [3 /*break*/, 6];
3558
+ case 'EMBEDDING': return [3 /*break*/, 8];
3559
+ }
3560
+ return [3 /*break*/, 10];
3561
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3562
+ case 5:
3563
+ chatResult = _v.sent();
3564
+ // TODO: [🍬] Destroy chatThread
3565
+ result = chatResult;
3566
+ resultString = chatResult.content;
3567
+ return [3 /*break*/, 11];
3568
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3569
+ case 7:
3570
+ completionResult = _v.sent();
3571
+ result = completionResult;
3572
+ resultString = completionResult.content;
3573
+ return [3 /*break*/, 11];
3574
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3575
+ case 9:
3576
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3577
+ embeddingResult = _v.sent();
3578
+ result = embeddingResult;
3579
+ resultString = embeddingResult.content.join(',');
3580
+ return [3 /*break*/, 11];
3581
+ case 10: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3582
+ case 11: return [3 /*break*/, 26];
3583
+ case 12:
3584
+ if (arrayableToArray(tools.script).length === 0) {
3585
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3586
+ }
3587
+ if (!currentTemplate.contentLanguage) {
3588
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3589
+ }
3590
+ // TODO: DRY [1]
3591
+ scriptPipelineExecutionErrors = [];
3592
+ _v.label = 13;
3593
+ case 13:
3594
+ _v.trys.push([13, 20, 21, 22]);
3595
+ _l = (e_2 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3596
+ _v.label = 14;
3597
+ case 14:
3598
+ if (!!_m.done) return [3 /*break*/, 19];
3599
+ scriptTools = _m.value;
3600
+ _v.label = 15;
3601
+ case 15:
3602
+ _v.trys.push([15, 17, , 18]);
3603
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3604
+ scriptLanguage: currentTemplate.contentLanguage,
3605
+ script: preparedContent,
3606
+ parameters: parameters,
3607
+ }))];
3608
+ case 16:
3609
+ resultString = _v.sent();
3610
+ return [3 /*break*/, 19];
3611
+ case 17:
3612
+ error_1 = _v.sent();
3613
+ if (!(error_1 instanceof Error)) {
3614
+ throw error_1;
3615
+ }
3616
+ if (error_1 instanceof UnexpectedError) {
3617
+ throw error_1;
3618
+ }
3619
+ scriptPipelineExecutionErrors.push(error_1);
3620
+ return [3 /*break*/, 18];
3621
+ case 18:
3622
+ _m = _l.next();
3623
+ return [3 /*break*/, 14];
3624
+ case 19: return [3 /*break*/, 22];
3625
+ case 20:
3626
+ e_2_1 = _v.sent();
3627
+ e_2 = { error: e_2_1 };
3628
+ return [3 /*break*/, 22];
3629
+ case 21:
3630
+ try {
3631
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3632
+ }
3633
+ finally { if (e_2) throw e_2.error; }
3634
+ return [7 /*endfinally*/];
3635
+ case 22:
3636
+ if (resultString !== null) {
3637
+ return [3 /*break*/, 26];
3638
+ }
3639
+ if (scriptPipelineExecutionErrors.length === 1) {
3640
+ throw scriptPipelineExecutionErrors[0];
3641
+ }
3642
+ else {
3643
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3644
+ .map(function (error) { return '- ' + error.message; })
3645
+ .join('\n\n')), "\n "); }));
3646
+ }
3647
+ case 23:
3648
+ if (tools.userInterface === undefined) {
3649
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3650
+ }
3651
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3652
+ promptTitle: currentTemplate.title,
3653
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3654
+ defaultValue: replaceParameters(preparedContent, parameters),
3655
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3656
+ placeholder: undefined,
3657
+ priority: priority,
3658
+ }))];
3659
+ case 24:
3660
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3661
+ resultString = _v.sent();
3662
+ return [3 /*break*/, 26];
3663
+ case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3664
+ case 26:
3665
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3666
+ _v.label = 27;
3667
+ case 27:
3668
+ _v.trys.push([27, 41, 42, 43]);
3669
+ _o = (e_4 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3670
+ _v.label = 28;
3671
+ case 28:
3672
+ if (!!_p.done) return [3 /*break*/, 40];
3673
+ functionName = _p.value;
3674
+ // TODO: DRY [1]
3675
+ scriptPipelineExecutionErrors = [];
3676
+ postprocessingError = null;
3677
+ _v.label = 29;
3678
+ case 29:
3679
+ _v.trys.push([29, 36, 37, 38]);
3680
+ _q = (e_3 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3681
+ _v.label = 30;
3682
+ case 30:
3683
+ if (!!_r.done) return [3 /*break*/, 35];
3684
+ scriptTools = _r.value;
3685
+ _v.label = 31;
3686
+ case 31:
3687
+ _v.trys.push([31, 33, , 34]);
3688
+ return [4 /*yield*/, scriptTools.execute({
3689
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3690
+ script: "".concat(functionName, "(resultString)"),
3691
+ parameters: {
3692
+ resultString: resultString || '',
3693
+ // Note: No ...parametersForTemplate, because working with result only
3694
+ },
3695
+ })];
3696
+ case 32:
3697
+ resultString = _v.sent();
3698
+ postprocessingError = null;
3699
+ return [3 /*break*/, 35];
3700
+ case 33:
3701
+ error_2 = _v.sent();
3702
+ if (!(error_2 instanceof Error)) {
3703
+ throw error_2;
3704
+ }
3705
+ if (error_2 instanceof UnexpectedError) {
3706
+ throw error_2;
3707
+ }
3708
+ postprocessingError = error_2;
3709
+ scriptPipelineExecutionErrors.push(error_2);
3710
+ return [3 /*break*/, 34];
3711
+ case 34:
3712
+ _r = _q.next();
3713
+ return [3 /*break*/, 30];
3714
+ case 35: return [3 /*break*/, 38];
3715
+ case 36:
3716
+ e_3_1 = _v.sent();
3717
+ e_3 = { error: e_3_1 };
3718
+ return [3 /*break*/, 38];
3719
+ case 37:
3720
+ try {
3721
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3722
+ }
3723
+ finally { if (e_3) throw e_3.error; }
3724
+ return [7 /*endfinally*/];
3725
+ case 38:
3726
+ if (postprocessingError) {
3727
+ throw postprocessingError;
3728
+ }
3729
+ _v.label = 39;
3730
+ case 39:
3731
+ _p = _o.next();
3732
+ return [3 /*break*/, 28];
3733
+ case 40: return [3 /*break*/, 43];
3734
+ case 41:
3735
+ e_4_1 = _v.sent();
3736
+ e_4 = { error: e_4_1 };
3737
+ return [3 /*break*/, 43];
3738
+ case 42:
3739
+ try {
3740
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3741
+ }
3742
+ finally { if (e_4) throw e_4.error; }
3743
+ return [7 /*endfinally*/];
3744
+ case 43:
3745
+ // TODO: [💝] Unite object for expecting amount and format
3746
+ if (currentTemplate.format) {
3747
+ if (currentTemplate.format === 'JSON') {
3748
+ if (!isValidJsonString(resultString || '')) {
3749
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3750
+ try {
3751
+ resultString = extractJsonBlock(resultString || '');
3762
3752
  }
3763
- else {
3764
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3753
+ catch (error) {
3754
+ keepUnused(error);
3755
+ throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3756
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3765
3757
  }
3766
3758
  }
3767
- // TODO: [💝] Unite object for expecting amount and format
3768
- if (currentTemplate.expectations) {
3769
- checkExpectations(currentTemplate.expectations, resultString || '');
3770
- }
3771
- return [2 /*return*/, "break-attempts"];
3772
- case 44:
3773
- error_4 = _v.sent();
3774
- if (!(error_4 instanceof ExpectError)) {
3775
- throw error_4;
3776
- }
3777
- expectError = error_4;
3778
- return [3 /*break*/, 46];
3779
- case 45:
3780
- if (!isJokerAttempt &&
3781
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3782
- prompt
3783
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3784
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3785
- ) {
3786
- // TODO: [🧠] Maybe put other templateTypes into report
3787
- executionReport.promptExecutions.push({
3788
- prompt: __assign({}, prompt),
3789
- result: result || undefined,
3790
- error: expectError === null ? undefined : serializeError(expectError),
3791
- });
3792
- }
3793
- return [7 /*endfinally*/];
3794
- case 46:
3795
- if (expectError !== null && attempt === maxAttempts - 1) {
3796
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3797
- .split('\n')
3798
- .map(function (line) { return "> ".concat(line); })
3799
- .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3800
- .split('\n')
3801
- .map(function (line) { return "> ".concat(line); })
3802
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3803
- ? 'null'
3804
- : resultString
3805
- .split('\n')
3806
- .map(function (line) { return "> ".concat(line); })
3807
- .join('\n')), "\n ---\n "); }));
3808
- }
3809
- return [2 /*return*/];
3759
+ }
3760
+ else {
3761
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3762
+ }
3810
3763
  }
3811
- });
3812
- };
3813
- attempt = -jokerParameterNames.length;
3814
- _h.label = 4;
3815
- case 4:
3816
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3817
- return [5 /*yield**/, _loop_5(attempt)];
3818
- case 5:
3819
- state_2 = _h.sent();
3820
- switch (state_2) {
3821
- case "break-attempts": return [3 /*break*/, 7];
3764
+ // TODO: [💝] Unite object for expecting amount and format
3765
+ if (currentTemplate.expectations) {
3766
+ checkExpectations(currentTemplate.expectations, resultString || '');
3767
+ }
3768
+ return [2 /*return*/, "break-attempts"];
3769
+ case 44:
3770
+ error_3 = _v.sent();
3771
+ if (!(error_3 instanceof ExpectError)) {
3772
+ throw error_3;
3773
+ }
3774
+ expectError = error_3;
3775
+ return [3 /*break*/, 46];
3776
+ case 45:
3777
+ if (!isJokerAttempt &&
3778
+ currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3779
+ prompt
3780
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3781
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3782
+ ) {
3783
+ // TODO: [🧠] Maybe put other templateTypes into report
3784
+ $executionReport.promptExecutions.push({
3785
+ prompt: __assign({}, prompt),
3786
+ result: result || undefined,
3787
+ error: expectError === null ? undefined : serializeError(expectError),
3788
+ });
3789
+ }
3790
+ return [7 /*endfinally*/];
3791
+ case 46:
3792
+ if (expectError !== null && attempt === maxAttempts - 1) {
3793
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3794
+ .split('\n')
3795
+ .map(function (line) { return "> ".concat(line); })
3796
+ .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) || '')
3797
+ .split('\n')
3798
+ .map(function (line) { return "> ".concat(line); })
3799
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3800
+ ? 'null'
3801
+ : resultString
3802
+ .split('\n')
3803
+ .map(function (line) { return "> ".concat(line); })
3804
+ .join('\n')), "\n ---\n "); }));
3805
+ }
3806
+ return [2 /*return*/];
3822
3807
  }
3823
- _h.label = 6;
3824
- case 6:
3825
- attempt++;
3826
- return [3 /*break*/, 4];
3827
- case 7:
3828
- //------------------------------------
3829
- /*
3808
+ });
3809
+ };
3810
+ attempt = -jokerParameterNames.length;
3811
+ _h.label = 3;
3812
+ case 3:
3813
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 6];
3814
+ return [5 /*yield**/, _loop_2(attempt)];
3815
+ case 4:
3816
+ state_1 = _h.sent();
3817
+ switch (state_1) {
3818
+ case "break-attempts": return [3 /*break*/, 6];
3819
+ }
3820
+ _h.label = 5;
3821
+ case 5:
3822
+ attempt++;
3823
+ return [3 /*break*/, 3];
3824
+ case 6:
3825
+ //------------------------------------
3826
+ /*
3830
3827
 
3831
3828
 
3832
3829
 
@@ -3836,74 +3833,89 @@ function createPipelineExecutor(options) {
3836
3833
 
3837
3834
 
3838
3835
 
3839
- */
3840
- //------------------------------------
3841
- if (resultString === null) {
3842
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3843
- }
3844
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3845
- progress_2 = {
3846
- name: name,
3847
- title: title,
3848
- isStarted: true,
3849
- isDone: true,
3850
- templateType: currentTemplate.templateType,
3851
- parameterName: currentTemplate.resultingParameterName,
3852
- parameterValue: resultString,
3853
- // <- [3]
3854
- };
3855
- if (isReturned) {
3856
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3857
- .split('\n')
3858
- .map(function (line) { return "> ".concat(line); })
3859
- .join('\n')), "\n\n "); }));
3860
- }
3861
- return [4 /*yield*/, onProgress(progress_2)];
3862
- case 8:
3863
- _h.sent();
3864
- _h.label = 9;
3865
- case 9:
3866
- parametersToPass = Object.freeze(__assign(__assign({}, parametersToPass), (_g = {}, _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _g)));
3867
- return [2 /*return*/];
3836
+ */
3837
+ //------------------------------------
3838
+ if (resultString === null) {
3839
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3868
3840
  }
3869
- });
3870
- });
3871
- }
3872
- function filterJustOutputParameters() {
3873
- var e_8, _a;
3874
- var outputParameters = {};
3875
- var _loop_6 = function (parameter) {
3876
- if (parametersToPass[parameter.name] === undefined) {
3877
- // [4]
3878
- warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3879
- return "continue";
3880
- }
3881
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3882
- };
3883
- try {
3884
- // Note: Filter ONLY output parameters
3885
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3886
- var isOutput = _a.isOutput;
3887
- return isOutput;
3888
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3889
- var parameter = _c.value;
3890
- _loop_6(parameter);
3891
- }
3892
- }
3893
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3894
- finally {
3895
- try {
3896
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3897
- }
3898
- finally { if (e_8) throw e_8.error; }
3841
+ return [4 /*yield*/, onProgress({
3842
+ name: name,
3843
+ title: title,
3844
+ isStarted: true,
3845
+ isDone: true,
3846
+ templateType: currentTemplate.templateType,
3847
+ parameterName: currentTemplate.resultingParameterName,
3848
+ parameterValue: resultString,
3849
+ // <- [🍸]
3850
+ })];
3851
+ case 7:
3852
+ _h.sent();
3853
+ return [2 /*return*/, Object.freeze((_g = {},
3854
+ _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */,
3855
+ _g))];
3899
3856
  }
3900
- return outputParameters;
3857
+ });
3858
+ });
3859
+ }
3860
+ /**
3861
+ * TODO: [🤹‍♂️]
3862
+ */
3863
+
3864
+ /**
3865
+ * @@@
3866
+ *
3867
+ * @private internal utility of `createPipelineExecutor`
3868
+ */
3869
+ function filterJustOutputParameters(options) {
3870
+ var e_1, _a;
3871
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
3872
+ var outputParameters = {};
3873
+ var _loop_1 = function (parameter) {
3874
+ if (parametersToPass[parameter.name] === undefined) {
3875
+ // [4]
3876
+ $warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3877
+ return "continue";
3878
+ }
3879
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3880
+ };
3881
+ try {
3882
+ // Note: Filter ONLY output parameters
3883
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3884
+ var isOutput = _a.isOutput;
3885
+ return isOutput;
3886
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
3887
+ var parameter = _c.value;
3888
+ _loop_1(parameter);
3889
+ }
3890
+ }
3891
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3892
+ finally {
3893
+ try {
3894
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3901
3895
  }
3902
- 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;
3896
+ finally { if (e_1) throw e_1.error; }
3897
+ }
3898
+ return outputParameters;
3899
+ }
3900
+
3901
+ /**
3902
+ * @@@
3903
+ *
3904
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
3905
+ *
3906
+ * @private internal utility of `createPipelineExecutor`
3907
+ */
3908
+ function executePipeline(options) {
3909
+ return __awaiter(this, void 0, void 0, function () {
3910
+ var inputParameters, tools, onProgress, pipeline, setPreparedPipeline, pipelineIdentification, settings, maxParallelCount, isVerbose, preparedPipeline, llmTools, errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
3903
3911
  var e_1, _e, e_2, _f;
3904
3912
  return __generator(this, function (_g) {
3905
3913
  switch (_g.label) {
3906
3914
  case 0:
3915
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3916
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
3917
+ preparedPipeline = options.preparedPipeline;
3918
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3907
3919
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3908
3920
  return [4 /*yield*/, preparePipeline(pipeline, {
3909
3921
  llmTools: llmTools,
@@ -3912,6 +3924,7 @@ function createPipelineExecutor(options) {
3912
3924
  })];
3913
3925
  case 1:
3914
3926
  preparedPipeline = _g.sent();
3927
+ setPreparedPipeline(preparedPipeline);
3915
3928
  _g.label = 2;
3916
3929
  case 2:
3917
3930
  errors = [];
@@ -3981,7 +3994,7 @@ function createPipelineExecutor(options) {
3981
3994
  return name === parameterName;
3982
3995
  });
3983
3996
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3984
- warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3997
+ warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3985
3998
  return [3 /*break*/, 4];
3986
3999
  case 1:
3987
4000
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3993,10 +4006,10 @@ function createPipelineExecutor(options) {
3993
4006
  // Note: Wait a short time to prevent race conditions
3994
4007
  _h.sent();
3995
4008
  _h.label = 3;
3996
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim$1(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4009
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim$1(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3997
4010
  isSuccessful: false,
3998
4011
  errors: __spreadArray([
3999
- new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4012
+ new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4000
4013
  ], __read(errors), false).map(serializeError),
4001
4014
  warnings: warnings.map(serializeError),
4002
4015
  executionReport: executionReport,
@@ -4060,7 +4073,7 @@ function createPipelineExecutor(options) {
4060
4073
  case 0:
4061
4074
  if (loopLimit-- < 0) {
4062
4075
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
4063
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4076
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4064
4077
  }
4065
4078
  currentTemplate = unresovedTemplates_1.find(function (template) {
4066
4079
  return template.dependentParameterNames.every(function (name) {
@@ -4070,24 +4083,45 @@ function createPipelineExecutor(options) {
4070
4083
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4071
4084
  throw new UnexpectedError(
4072
4085
  // TODO: [🐎] DRY
4073
- spaceTrim$1(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4086
+ spaceTrim$1(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4074
4087
  .map(function (_a) {
4075
4088
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4076
4089
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4077
4090
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4078
4091
  .join(' and '));
4079
4092
  })
4080
- .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 "); }));
4093
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
4081
4094
  case 1:
4082
4095
  if (!!currentTemplate) return [3 /*break*/, 3];
4083
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4096
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4084
4097
  case 2:
4085
- /* [5] */ _j.sent();
4098
+ /* [🤹‍♂️] */ _j.sent();
4086
4099
  return [3 /*break*/, 4];
4087
4100
  case 3:
4088
4101
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4089
- work_1 = executeSingleTemplate(currentTemplate)
4090
- .then(function () {
4102
+ work_1 = executeTemplate({
4103
+ currentTemplate: currentTemplate,
4104
+ preparedPipeline: preparedPipeline,
4105
+ parametersToPass: parametersToPass,
4106
+ tools: tools,
4107
+ llmTools: llmTools,
4108
+ onProgress: function (progress) {
4109
+ if (isReturned) {
4110
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4111
+ .split('\n')
4112
+ .map(function (line) { return "> ".concat(line); })
4113
+ .join('\n')), "\n "); }));
4114
+ }
4115
+ if (onProgress) {
4116
+ onProgress(progress);
4117
+ }
4118
+ },
4119
+ settings: settings,
4120
+ $executionReport: executionReport,
4121
+ pipelineIdentification: pipelineIdentification,
4122
+ })
4123
+ .then(function (newParametersToPass) {
4124
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4091
4125
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4092
4126
  })
4093
4127
  .then(function () {
@@ -4119,7 +4153,12 @@ function createPipelineExecutor(options) {
4119
4153
  var result = _a.result;
4120
4154
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4121
4155
  })), false));
4122
- outputParameters_1 = filterJustOutputParameters();
4156
+ outputParameters_1 = filterJustOutputParameters({
4157
+ preparedPipeline: preparedPipeline,
4158
+ parametersToPass: parametersToPass,
4159
+ $warnings: warnings,
4160
+ pipelineIdentification: pipelineIdentification,
4161
+ });
4123
4162
  isReturned = true;
4124
4163
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4125
4164
  // Note: Wait a short time to prevent race conditions
@@ -4142,7 +4181,12 @@ function createPipelineExecutor(options) {
4142
4181
  var result = _a.result;
4143
4182
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4144
4183
  })), false));
4145
- outputParameters = filterJustOutputParameters();
4184
+ outputParameters = filterJustOutputParameters({
4185
+ preparedPipeline: preparedPipeline,
4186
+ parametersToPass: parametersToPass,
4187
+ $warnings: warnings,
4188
+ pipelineIdentification: pipelineIdentification,
4189
+ });
4146
4190
  isReturned = true;
4147
4191
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4148
4192
  // Note: Wait a short time to prevent race conditions
@@ -4162,22 +4206,62 @@ function createPipelineExecutor(options) {
4162
4206
  })];
4163
4207
  }
4164
4208
  });
4165
- }); };
4166
- return pipelineExecutor;
4209
+ });
4167
4210
  }
4211
+
4168
4212
  /**
4169
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4170
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4171
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4172
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4173
- * TODO: [♈] Probbably move expectations from templates to parameters
4174
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4175
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4176
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4177
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4178
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4179
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4213
+ * Creates executor function from pipeline and execution tools.
4214
+ *
4215
+ * @returns The executor function
4216
+ * @throws {PipelineLogicError} on logical error in the pipeline
4217
+ * @public exported from `@promptbook/core`
4180
4218
  */
4219
+ function createPipelineExecutor(options) {
4220
+ var _this = this;
4221
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4222
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
4223
+ validatePipeline(pipeline);
4224
+ var pipelineIdentification = (function () {
4225
+ // Note: This is a 😐 implementation of [🚞]
4226
+ var _ = [];
4227
+ if (pipeline.sourceFile !== undefined) {
4228
+ _.push("File: ".concat(pipeline.sourceFile));
4229
+ }
4230
+ if (pipeline.pipelineUrl !== undefined) {
4231
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4232
+ }
4233
+ return _.join('\n');
4234
+ })();
4235
+ var preparedPipeline;
4236
+ if (isPipelinePrepared(pipeline)) {
4237
+ preparedPipeline = pipeline;
4238
+ }
4239
+ else if (isNotPreparedWarningSupressed !== true) {
4240
+ console.warn(spaceTrim$1(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4241
+ }
4242
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4243
+ return __generator(this, function (_a) {
4244
+ return [2 /*return*/, executePipeline({
4245
+ pipeline: pipeline,
4246
+ preparedPipeline: preparedPipeline,
4247
+ setPreparedPipeline: function (newPreparedPipeline) {
4248
+ preparedPipeline = newPreparedPipeline;
4249
+ },
4250
+ inputParameters: inputParameters,
4251
+ tools: tools,
4252
+ onProgress: onProgress,
4253
+ pipelineIdentification: pipelineIdentification,
4254
+ settings: {
4255
+ maxExecutionAttempts: maxExecutionAttempts,
4256
+ maxParallelCount: maxParallelCount,
4257
+ isVerbose: isVerbose,
4258
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4259
+ },
4260
+ })];
4261
+ });
4262
+ }); };
4263
+ return pipelineExecutor;
4264
+ }
4181
4265
 
4182
4266
  /**
4183
4267
  * @@@
@@ -5416,6 +5500,8 @@ var foreachCommandParser = {
5416
5500
  */
5417
5501
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5418
5502
  var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5503
+ // TODO: !!!!!! Detect double use
5504
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
5419
5505
  $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5420
5506
  keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
5421
5507
  // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase