@promptbook/cli 0.70.0-1 → 0.71.0-0

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 (76) hide show
  1. package/README.md +23 -60
  2. package/esm/index.es.js +2030 -1220
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/promptbook-collection/index.d.ts +0 -3
  5. package/esm/typings/src/_packages/core.index.d.ts +9 -1
  6. package/esm/typings/src/_packages/types.index.d.ts +12 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  8. package/esm/typings/src/cli/cli-commands/make.d.ts +1 -1
  9. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +1 -1
  10. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +3 -7
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +23 -0
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  14. package/esm/typings/src/config.d.ts +16 -3
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +10 -5
  19. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +9 -8
  20. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +45 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +40 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +19 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  31. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  32. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  33. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  34. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  35. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  36. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  37. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  38. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  39. package/esm/typings/src/formats/index.d.ts +1 -1
  40. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  41. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  42. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  43. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  44. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  45. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  48. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  50. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  51. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  52. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  53. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +9 -2
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  57. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  58. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  59. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  60. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  61. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  62. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  63. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  64. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  65. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  67. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  68. package/package.json +17 -12
  69. package/umd/index.umd.js +2033 -1224
  70. package/umd/index.umd.js.map +1 -1
  71. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  72. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  73. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  74. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  75. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  76. /package/esm/typings/src/{personas/preparePersona.test.d.ts → utils/validators/parameterName/validateParameterName.test.d.ts} +0 -0
package/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('path'), require('prettier'), require('prettier/parser-html'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv'), require('glob-promise'), require('socket.io-client'), require('@anthropic-ai/sdk'), require('@azure/openai'), require('openai')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'path', 'prettier', 'prettier/parser-html', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv', 'glob-promise', 'socket.io-client', '@anthropic-ai/sdk', '@azure/openai', 'openai'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.path, global.prettier, global.parserHtml, global.hexEncoder, global.sha256, global.posix, global.dotenv, global.glob, global.socket_ioClient, global.Anthropic, global.openai, global.OpenAI));
5
- })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, path, prettier, parserHtml, hexEncoder, sha256, posix, dotenv, glob, socket_ioClient, Anthropic, openai, OpenAI) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('path'), require('prettier'), require('prettier/parser-html'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv'), require('glob-promise'), require('socket.io-client'), require('@anthropic-ai/sdk'), require('@azure/openai'), require('openai')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'path', 'prettier', 'prettier/parser-html', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv', 'glob-promise', 'socket.io-client', '@anthropic-ai/sdk', '@azure/openai', 'openai'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.path, global.prettier, global.parserHtml, global.papaparse, global.hexEncoder, global.sha256, global.posix, global.dotenv, global.glob, global.socket_ioClient, global.Anthropic, global.openai, global.OpenAI));
5
+ })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, path, prettier, parserHtml, papaparse, hexEncoder, sha256, posix, dotenv, glob, socket_ioClient, Anthropic, openai, OpenAI) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -39,8 +39,8 @@
39
39
  /**
40
40
  * The version of the Promptbook library
41
41
  */
42
- var PROMPTBOOK_VERSION = '0.70.0-0';
43
- // TODO: !!!! List here all the versions and annotate + put into script
42
+ var PROMPTBOOK_VERSION = '0.70.0-1';
43
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
44
44
 
45
45
  /*! *****************************************************************************
46
46
  Copyright (c) Microsoft Corporation.
@@ -375,7 +375,7 @@
375
375
  }
376
376
  /**
377
377
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
378
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
378
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
379
379
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
380
380
  */
381
381
 
@@ -449,13 +449,13 @@
449
449
  *
450
450
  * @public exported from `@promptbook/core`
451
451
  */
452
- var MAX_PARALLEL_COUNT = 5;
452
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
453
453
  /**
454
454
  * The maximum number of attempts to execute LLM task before giving up
455
455
  *
456
456
  * @public exported from `@promptbook/core`
457
457
  */
458
- var MAX_EXECUTION_ATTEMPTS = 3;
458
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
459
459
  /**
460
460
  * The maximum length of the (generated) filename
461
461
  *
@@ -492,6 +492,7 @@
492
492
  'samples',
493
493
  'modelName',
494
494
  'currentDate',
495
+ // <- TODO: !!!!! list here all command names
495
496
  // <- TODO: Add more like 'date', 'modelName',...
496
497
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
497
498
  ]);
@@ -520,12 +521,32 @@
520
521
  */
521
522
  var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
522
523
  // <- TODO: [🧜‍♂️]
524
+ /**
525
+ * @@@
526
+ *
527
+ * @public exported from `@promptbook/core`
528
+ */
529
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
530
+ delimiter: ',',
531
+ quoteChar: '"',
532
+ newline: '\n',
533
+ skipEmptyLines: true,
534
+ });
523
535
  /**
524
536
  * @@@
525
537
  *
526
538
  * @public exported from `@promptbook/core`
527
539
  */
528
540
  var IS_VERBOSE = false;
541
+ /**
542
+ * @@@
543
+ *
544
+ * @private within the repository
545
+ */
546
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
547
+ /**/
548
+ // Note: In normal situations, we check the pipeline logic:
549
+ true);
529
550
  /**
530
551
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
531
552
  */
@@ -679,7 +700,7 @@
679
700
  commands.push("PIPELINE URL ".concat(pipelineUrl));
680
701
  }
681
702
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
682
- // TODO: !!! This increase size of the bundle and is probbably not necessary
703
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
683
704
  pipelineString = prettifyMarkdown(pipelineString);
684
705
  try {
685
706
  for (var _g = __values(parameters.filter(function (_a) {
@@ -827,12 +848,12 @@
827
848
  pipelineString += '```' + contentLanguage;
828
849
  pipelineString += '\n';
829
850
  pipelineString += spaceTrim__default["default"](content);
830
- // <- TODO: !!! Escape
851
+ // <- TODO:[main] !!! Escape
831
852
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
832
853
  pipelineString += '\n';
833
854
  pipelineString += '```';
834
855
  pipelineString += '\n\n';
835
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
856
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
836
857
  }
837
858
  }
838
859
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -1059,7 +1080,7 @@
1059
1080
  });
1060
1081
  }
1061
1082
 
1062
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.70.0-0",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.70.0-0",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.70.0-0",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.70.0-0",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"}];
1083
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",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",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",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",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"}];
1063
1084
 
1064
1085
  /**
1065
1086
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1134,7 +1155,7 @@
1134
1155
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
1135
1156
  return false;
1136
1157
  }
1137
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1158
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1138
1159
  return true;
1139
1160
  }
1140
1161
 
@@ -1266,6 +1287,26 @@
1266
1287
  * @public exported from `@promptbook/core`
1267
1288
  */
1268
1289
  function validatePipeline(pipeline) {
1290
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
1291
+ validatePipelineCore(pipeline);
1292
+ }
1293
+ else {
1294
+ try {
1295
+ validatePipelineCore(pipeline);
1296
+ }
1297
+ catch (error) {
1298
+ if (!(error instanceof PipelineLogicError)) {
1299
+ throw error;
1300
+ }
1301
+ console.error(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
1302
+ }
1303
+ }
1304
+ return pipeline;
1305
+ }
1306
+ /**
1307
+ * @private internal function for `validatePipeline`
1308
+ */
1309
+ function validatePipelineCore(pipeline) {
1269
1310
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1270
1311
  var e_1, _a, e_2, _b, e_3, _c;
1271
1312
  var pipelineIdentification = (function () {
@@ -1283,19 +1324,19 @@
1283
1324
  // <- Note: [🚲]
1284
1325
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1285
1326
  }
1286
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1327
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1287
1328
  // <- Note: [🚲]
1288
1329
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1289
1330
  }
1290
1331
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1291
1332
  if (!Array.isArray(pipeline.parameters)) {
1292
1333
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1293
- throw new ParseError(spaceTrim.spaceTrim(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 "); }));
1334
+ throw new ParseError(spaceTrim.spaceTrim(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 "); }));
1294
1335
  }
1295
1336
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1296
1337
  if (!Array.isArray(pipeline.templates)) {
1297
1338
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1298
- throw new ParseError(spaceTrim.spaceTrim(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 "); }));
1339
+ throw new ParseError(spaceTrim.spaceTrim(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 "); }));
1299
1340
  }
1300
1341
  var _loop_1 = function (parameter) {
1301
1342
  if (parameter.isInput && parameter.isOutput) {
@@ -1464,9 +1505,9 @@
1464
1505
  while (unresovedTemplates.length > 0) {
1465
1506
  _loop_3();
1466
1507
  }
1467
- return pipeline;
1468
1508
  }
1469
1509
  /**
1510
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1470
1511
  * TODO: [🧠] Work with promptbookVersion
1471
1512
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1472
1513
  * > /**
@@ -1478,11 +1519,11 @@
1478
1519
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1479
1520
  */
1480
1521
  /**
1481
- * TODO: [🐣] !!!! Validate that all samples match expectations
1482
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1483
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1484
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1485
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1522
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1523
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1524
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1525
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1526
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1486
1527
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1487
1528
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1488
1529
  */
@@ -2188,113 +2229,35 @@
2188
2229
  */
2189
2230
 
2190
2231
  /**
2191
- * Parses the given script and returns the list of all used variables that are not defined in the script
2192
- *
2193
- * @param script from which to extract the variables
2194
- * @returns the list of variable names
2195
- * @throws {ParseError} if the script is invalid
2196
- * @public exported from `@promptbook/utils`
2197
- */
2198
- function extractVariables(script) {
2199
- var variables = new Set();
2200
- script = "(()=>{".concat(script, "})()");
2201
- try {
2202
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2203
- try {
2204
- eval(script);
2205
- }
2206
- catch (error) {
2207
- if (!(error instanceof ReferenceError)) {
2208
- throw error;
2209
- }
2210
- var undefinedName = error.message.split(' ')[0];
2211
- /*
2212
- Note: Parsing the error
2213
- [PipelineUrlError: thing is not defined]
2214
- */
2215
- if (!undefinedName) {
2216
- throw error;
2217
- }
2218
- if (script.includes(undefinedName + '(')) {
2219
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2220
- }
2221
- else {
2222
- variables.add(undefinedName);
2223
- script = "const ".concat(undefinedName, " = '';") + script;
2224
- }
2225
- }
2226
- }
2227
- catch (error) {
2228
- if (!(error instanceof Error)) {
2229
- throw error;
2230
- }
2231
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2232
- }
2233
- return variables;
2234
- }
2235
- /**
2236
- * TODO: [🔣] Support for multiple languages - python, java,...
2237
- */
2238
-
2239
- /**
2240
- * Parses the template and returns the set of all used parameters
2232
+ * Determine if the pipeline is fully prepared
2241
2233
  *
2242
- * @param template the template with used parameters
2243
- * @returns the set of parameter names
2244
- * @throws {ParseError} if the script is invalid
2245
- * @public exported from `@promptbook/utils`
2234
+ * @public exported from `@promptbook/core`
2246
2235
  */
2247
- function extractParameterNamesFromTemplate(template) {
2248
- var e_1, _a, e_2, _b, e_3, _c;
2249
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2250
- var parameterNames = new Set();
2251
- try {
2252
- 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()) {
2253
- var parameterName = _e.value;
2254
- parameterNames.add(parameterName);
2255
- }
2256
- }
2257
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2258
- finally {
2259
- try {
2260
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2261
- }
2262
- finally { if (e_1) throw e_1.error; }
2263
- }
2264
- if (templateType === 'SCRIPT_TEMPLATE') {
2265
- try {
2266
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2267
- var parameterName = _g.value;
2268
- parameterNames.add(parameterName);
2269
- }
2270
- }
2271
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2272
- finally {
2273
- try {
2274
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2275
- }
2276
- finally { if (e_2) throw e_2.error; }
2277
- }
2278
- }
2279
- try {
2280
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2281
- var jokerName = _j.value;
2282
- parameterNames.add(jokerName);
2283
- }
2236
+ function isPipelinePrepared(pipeline) {
2237
+ // Note: Ignoring `pipeline.preparations` @@@
2238
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2239
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2240
+ return false;
2284
2241
  }
2285
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2286
- finally {
2287
- try {
2288
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2289
- }
2290
- finally { if (e_3) throw e_3.error; }
2242
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2243
+ return false;
2291
2244
  }
2292
- parameterNames.delete('content');
2293
- // <- Note {websiteContent} is used in `preparedContent`
2294
- return parameterNames;
2245
+ /*
2246
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2247
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2248
+ > return false;
2249
+ > }
2250
+ */
2251
+ return true;
2295
2252
  }
2296
2253
  /**
2297
- * TODO: [🔣] If script require contentLanguage
2254
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2255
+ * TODO: [🐠] Maybe base this on `makeValidator`
2256
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2257
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2258
+ * - [🏍] ? Is context in each template
2259
+ * - [♨] Are samples prepared
2260
+ * - [♨] Are templates prepared
2298
2261
  */
2299
2262
 
2300
2263
  /**
@@ -2314,27 +2277,6 @@
2314
2277
  };
2315
2278
  }
2316
2279
 
2317
- /**
2318
- * Function isValidJsonString will tell you if the string is valid JSON or not
2319
- *
2320
- * @public exported from `@promptbook/utils`
2321
- */
2322
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2323
- try {
2324
- JSON.parse(value);
2325
- return true;
2326
- }
2327
- catch (error) {
2328
- if (!(error instanceof Error)) {
2329
- throw error;
2330
- }
2331
- if (error.message.includes('Unexpected token')) {
2332
- return false;
2333
- }
2334
- return false;
2335
- }
2336
- }
2337
-
2338
2280
  /**
2339
2281
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2340
2282
  *
@@ -2361,9 +2303,10 @@
2361
2303
  });
2362
2304
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2363
2305
  get: function () {
2364
- return this.llmExecutionTools
2365
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2366
- .join('\n');
2306
+ return this.llmExecutionTools.map(function (_a, index) {
2307
+ var title = _a.title;
2308
+ return "".concat(index + 1, ") `").concat(title, "`");
2309
+ }).join('\n');
2367
2310
  },
2368
2311
  enumerable: false,
2369
2312
  configurable: true
@@ -2561,9 +2504,7 @@
2561
2504
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2562
2505
  }
2563
2506
  else {
2564
- throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.llmExecutionTools
2565
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2566
- .join('\n')), "\n\n "); }));
2507
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\"\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.description), "\n\n "); }));
2567
2508
  }
2568
2509
  }
2569
2510
  });
@@ -2629,288 +2570,153 @@
2629
2570
  */
2630
2571
 
2631
2572
  /**
2632
- * Extracts all code blocks from markdown.
2573
+ * Takes an item or an array of items and returns an array of items
2633
2574
  *
2634
- * Note: There are multiple simmilar function:
2635
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2636
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2637
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2638
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2575
+ * 1) Any item except array and undefined returns array with that one item (also null)
2576
+ * 2) Undefined returns empty array
2577
+ * 3) Array returns itself
2639
2578
  *
2640
- * @param markdown any valid markdown
2641
- * @returns code blocks with language and content
2642
- * @throws {ParseError} if block is not closed properly
2643
- * @public exported from `@promptbook/markdown-utils`
2579
+ * @private internal utility
2644
2580
  */
2645
- function extractAllBlocksFromMarkdown(markdown) {
2646
- var e_1, _a;
2647
- var codeBlocks = [];
2648
- var lines = markdown.split('\n');
2649
- // Note: [0] Ensure that the last block notated by gt > will be closed
2650
- lines.push('');
2651
- var currentCodeBlock = null;
2652
- try {
2653
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2654
- var line = lines_1_1.value;
2655
- if (line.startsWith('> ') || line === '>') {
2656
- if (currentCodeBlock === null) {
2657
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2658
- } /* not else */
2659
- if (currentCodeBlock.blockNotation === '>') {
2660
- if (currentCodeBlock.content !== '') {
2661
- currentCodeBlock.content += '\n';
2662
- }
2663
- currentCodeBlock.content += line.slice(2);
2664
- }
2665
- }
2666
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2667
- codeBlocks.push(currentCodeBlock);
2668
- currentCodeBlock = null;
2669
- }
2670
- /* not else */
2671
- if (line.startsWith('```')) {
2672
- var language = line.slice(3).trim() || null;
2673
- if (currentCodeBlock === null) {
2674
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2675
- }
2676
- else {
2677
- if (language !== null) {
2678
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2679
- }
2680
- codeBlocks.push(currentCodeBlock);
2681
- currentCodeBlock = null;
2682
- }
2683
- }
2684
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2685
- if (currentCodeBlock.content !== '') {
2686
- currentCodeBlock.content += '\n';
2687
- }
2688
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2689
- }
2690
- }
2691
- }
2692
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2693
- finally {
2694
- try {
2695
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2696
- }
2697
- finally { if (e_1) throw e_1.error; }
2581
+ function arrayableToArray(input) {
2582
+ if (input === undefined) {
2583
+ return [];
2698
2584
  }
2699
- if (currentCodeBlock !== null) {
2700
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2585
+ if (input instanceof Array) {
2586
+ return input;
2701
2587
  }
2702
- return codeBlocks;
2588
+ return [input];
2703
2589
  }
2704
- /**
2705
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2706
- */
2707
2590
 
2708
2591
  /**
2709
- * Extracts extracts exactly one valid JSON code block
2710
- *
2711
- * - When given string is a valid JSON as it is, it just returns it
2712
- * - When there is no JSON code block the function throws a `ParseError`
2713
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2714
- *
2715
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2716
- * Note: There are multiple simmilar function:
2717
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2718
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2719
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2720
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2592
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2721
2593
  *
2722
- * @public exported from `@promptbook/markdown-utils`
2723
- * @throws {ParseError} if there is no valid JSON block in the markdown
2724
- */
2725
- function extractJsonBlock(markdown) {
2726
- if (isValidJsonString(markdown)) {
2727
- return markdown;
2728
- }
2729
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2730
- var jsonBlocks = codeBlocks.filter(function (_a) {
2731
- var content = _a.content;
2732
- return isValidJsonString(content);
2733
- });
2734
- if (jsonBlocks.length === 0) {
2735
- throw new Error('There is no valid JSON block in the markdown');
2736
- }
2737
- if (jsonBlocks.length > 1) {
2738
- throw new Error('There are multiple JSON code blocks in the markdown');
2739
- }
2740
- return jsonBlocks[0].content;
2741
- }
2742
- /**
2743
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2744
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2745
- */
2746
-
2747
- /**
2748
- * Determine if the pipeline is fully prepared
2749
- *
2750
- * @public exported from `@promptbook/core`
2751
- */
2752
- function isPipelinePrepared(pipeline) {
2753
- // Note: Ignoring `pipeline.preparations` @@@
2754
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2755
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2756
- return false;
2757
- }
2758
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2759
- return false;
2760
- }
2761
- /*
2762
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2763
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2764
- > return false;
2765
- > }
2766
- */
2767
- return true;
2768
- }
2769
- /**
2770
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2771
- * TODO: [🐠] Maybe base this on `makeValidator`
2772
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2773
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2774
- * - [🏍] ? Is context in each template
2775
- * - [♨] Are samples prepared
2776
- * - [♨] Are templates prepared
2777
- */
2778
-
2779
- /**
2780
- * Takes an item or an array of items and returns an array of items
2781
- *
2782
- * 1) Any item except array and undefined returns array with that one item (also null)
2783
- * 2) Undefined returns empty array
2784
- * 3) Array returns itself
2785
- *
2786
- * @private internal utility
2594
+ * @param script from which to extract the variables
2595
+ * @returns the list of variable names
2596
+ * @throws {ParseError} if the script is invalid
2597
+ * @public exported from `@promptbook/utils`
2787
2598
  */
2788
- function arrayableToArray(input) {
2789
- if (input === undefined) {
2790
- return [];
2791
- }
2792
- if (input instanceof Array) {
2793
- return input;
2599
+ function extractVariables(script) {
2600
+ var variables = new Set();
2601
+ script = "(()=>{".concat(script, "})()");
2602
+ try {
2603
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2604
+ try {
2605
+ eval(script);
2606
+ }
2607
+ catch (error) {
2608
+ if (!(error instanceof ReferenceError)) {
2609
+ throw error;
2610
+ }
2611
+ var undefinedName = error.message.split(' ')[0];
2612
+ /*
2613
+ Note: Parsing the error
2614
+ [PipelineUrlError: thing is not defined]
2615
+ */
2616
+ if (!undefinedName) {
2617
+ throw error;
2618
+ }
2619
+ if (script.includes(undefinedName + '(')) {
2620
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2621
+ }
2622
+ else {
2623
+ variables.add(undefinedName);
2624
+ script = "const ".concat(undefinedName, " = '';") + script;
2625
+ }
2626
+ }
2794
2627
  }
2795
- return [input];
2796
- }
2797
-
2798
- /**
2799
- * Just says that the variable is not used but should be kept
2800
- * No side effects.
2801
- *
2802
- * Note: It can be usefull for:
2803
- *
2804
- * 1) Suppressing eager optimization of unused imports
2805
- * 2) Suppressing eslint errors of unused variables in the tests
2806
- * 3) Keeping the type of the variable for type testing
2807
- *
2808
- * @param value any values
2809
- * @returns void
2810
- * @private within the repository
2811
- */
2812
- function keepUnused() {
2813
- var valuesToKeep = [];
2814
- for (var _i = 0; _i < arguments.length; _i++) {
2815
- valuesToKeep[_i] = arguments[_i];
2628
+ catch (error) {
2629
+ if (!(error instanceof Error)) {
2630
+ throw error;
2631
+ }
2632
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2816
2633
  }
2634
+ return variables;
2817
2635
  }
2818
-
2819
2636
  /**
2820
- * Just marks a place of place where should be something implemented
2821
- * No side effects.
2822
- *
2823
- * Note: It can be usefull suppressing eslint errors of unused variables
2824
- *
2825
- * @param value any values
2826
- * @returns void
2827
- * @private within the repository
2637
+ * TODO: [🔣] Support for multiple languages - python, java,...
2828
2638
  */
2829
- function TODO_USE() {
2830
- var value = [];
2831
- for (var _i = 0; _i < arguments.length; _i++) {
2832
- value[_i] = arguments[_i];
2833
- }
2834
- }
2835
2639
 
2836
2640
  /**
2837
- * Replaces parameters in template with values from parameters object
2641
+ * Parses the template and returns the set of all used parameters
2838
2642
  *
2839
- * @param template the template with parameters in {curly} braces
2840
- * @param parameters the object with parameters
2841
- * @returns the template with replaced parameters
2842
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2643
+ * @param template the template with used parameters
2644
+ * @returns the set of parameter names
2645
+ * @throws {ParseError} if the script is invalid
2843
2646
  * @public exported from `@promptbook/utils`
2844
2647
  */
2845
- function replaceParameters(template, parameters) {
2846
- var e_1, _a;
2648
+ function extractParameterNamesFromTemplate(template) {
2649
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2650
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2651
+ var parameterNames = new Set();
2847
2652
  try {
2848
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2849
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2850
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2851
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2852
- }
2853
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2854
- // TODO: [🍵]
2855
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2856
- }
2653
+ for (var _e = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _f = _e.next(); !_f.done; _f = _e.next()) {
2654
+ var parameterName = _f.value;
2655
+ parameterNames.add(parameterName);
2857
2656
  }
2858
2657
  }
2859
2658
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2860
2659
  finally {
2861
2660
  try {
2862
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2661
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2863
2662
  }
2864
2663
  finally { if (e_1) throw e_1.error; }
2865
2664
  }
2866
- var replacedTemplate = template;
2867
- var match;
2868
- var loopLimit = LOOP_LIMIT;
2869
- var _loop_1 = function () {
2870
- if (loopLimit-- < 0) {
2871
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2665
+ if (templateType === 'SCRIPT_TEMPLATE') {
2666
+ try {
2667
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2668
+ var parameterName = _h.value;
2669
+ parameterNames.add(parameterName);
2670
+ }
2872
2671
  }
2873
- var precol = match.groups.precol;
2874
- var parameterName = match.groups.parameterName;
2875
- if (parameterName === '') {
2876
- return "continue";
2672
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2673
+ finally {
2674
+ try {
2675
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2676
+ }
2677
+ finally { if (e_2) throw e_2.error; }
2877
2678
  }
2878
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2879
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2679
+ }
2680
+ try {
2681
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2682
+ var jokerName = _k.value;
2683
+ parameterNames.add(jokerName);
2880
2684
  }
2881
- if (parameters[parameterName] === undefined) {
2882
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2685
+ }
2686
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2687
+ finally {
2688
+ try {
2689
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2883
2690
  }
2884
- var parameterValue = parameters[parameterName];
2885
- if (parameterValue === undefined) {
2886
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2691
+ finally { if (e_3) throw e_3.error; }
2692
+ }
2693
+ parameterNames.delete('content');
2694
+ // <- Note {websiteContent} is used in `preparedContent`
2695
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2696
+ if (foreach !== undefined) {
2697
+ try {
2698
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2699
+ var subparameterName = _m.value;
2700
+ if (parameterNames.has(subparameterName)) {
2701
+ parameterNames.delete(subparameterName);
2702
+ parameterNames.add(foreach.parameterName);
2703
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2704
+ }
2705
+ }
2887
2706
  }
2888
- parameterValue = parameterValue.toString();
2889
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2890
- parameterValue = parameterValue
2891
- .split('\n')
2892
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2893
- .join('\n');
2707
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2708
+ finally {
2709
+ try {
2710
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2711
+ }
2712
+ finally { if (e_4) throw e_4.error; }
2894
2713
  }
2895
- replacedTemplate =
2896
- replacedTemplate.substring(0, match.index + precol.length) +
2897
- parameterValue +
2898
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2899
- };
2900
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2901
- .exec(replacedTemplate))) {
2902
- _loop_1();
2903
- }
2904
- // [💫] Check if there are parameters that are not closed properly
2905
- if (/{\w+$/.test(replacedTemplate)) {
2906
- throw new PipelineExecutionError('Parameter is not closed');
2907
2714
  }
2908
- // [💫] Check if there are parameters that are not opened properly
2909
- if (/^\w+}/.test(replacedTemplate)) {
2910
- throw new PipelineExecutionError('Parameter is not opened');
2911
- }
2912
- return replacedTemplate;
2715
+ return parameterNames;
2913
2716
  }
2717
+ /**
2718
+ * TODO: [🔣] If script require contentLanguage
2719
+ */
2914
2720
 
2915
2721
  /**
2916
2722
  * Create difference set of two sets.
@@ -2988,16 +2794,613 @@
2988
2794
  }
2989
2795
 
2990
2796
  /**
2991
- * Counts number of characters in the text
2797
+ * Just marks a place of place where should be something implemented
2798
+ * No side effects.
2992
2799
  *
2993
- * @public exported from `@promptbook/utils`
2800
+ * Note: It can be usefull suppressing eslint errors of unused variables
2801
+ *
2802
+ * @param value any values
2803
+ * @returns void
2804
+ * @private within the repository
2994
2805
  */
2995
- function countCharacters(text) {
2996
- // Remove null characters
2997
- text = text.replace(/\0/g, '');
2998
- // Replace emojis (and also ZWJ sequence) with hyphens
2999
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3000
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2806
+ function TODO_USE() {
2807
+ var value = [];
2808
+ for (var _i = 0; _i < arguments.length; _i++) {
2809
+ value[_i] = arguments[_i];
2810
+ }
2811
+ }
2812
+
2813
+ /**
2814
+ * @@@
2815
+ *
2816
+ * @public exported from `@promptbook/core`
2817
+ */
2818
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2819
+ header: true,
2820
+ // encoding: 'utf8',
2821
+ });
2822
+
2823
+ /**
2824
+ * Definition for CSV spreadsheet
2825
+ *
2826
+ * @public exported from `@promptbook/core`
2827
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2828
+ */
2829
+ var CsvFormatDefinition = {
2830
+ formatName: 'CSV',
2831
+ aliases: ['SPREADSHEET', 'TABLE'],
2832
+ isValid: function (value, settings, schema) {
2833
+ // TODO: !!!!!! Implement CSV validation
2834
+ TODO_USE(value /* <- TODO: Use value here */);
2835
+ TODO_USE(settings /* <- TODO: Use settings here */);
2836
+ TODO_USE(schema /* <- TODO: Use schema here */);
2837
+ return true;
2838
+ },
2839
+ canBeValid: function (partialValue, settings, schema) {
2840
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2841
+ TODO_USE(settings /* <- TODO: Use settings here */);
2842
+ TODO_USE(schema /* <- TODO: Use schema here */);
2843
+ return true;
2844
+ },
2845
+ heal: function (value, settings, schema) {
2846
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2847
+ TODO_USE(settings /* <- TODO: Use settings here */);
2848
+ TODO_USE(schema /* <- TODO: Use schema here */);
2849
+ throw new Error('Not implemented');
2850
+ },
2851
+ subvalueDefinitions: [
2852
+ {
2853
+ subvalueName: 'ROW',
2854
+ mapValues: function (value, settings, mapCallback) {
2855
+ return __awaiter(this, void 0, void 0, function () {
2856
+ var csv, mappedData;
2857
+ var _this = this;
2858
+ return __generator(this, function (_a) {
2859
+ switch (_a.label) {
2860
+ case 0:
2861
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2862
+ if (csv.errors.length !== 0) {
2863
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2864
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2865
+ }
2866
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2867
+ var _a;
2868
+ var _b;
2869
+ return __generator(this, function (_c) {
2870
+ switch (_c.label) {
2871
+ case 0:
2872
+ _a = [__assign({}, row)];
2873
+ _b = {};
2874
+ // <- TODO: !!!!!! Dynamic new column name and position
2875
+ // <- TODO: !!!!!! Check name collisions
2876
+ return [4 /*yield*/, mapCallback(row, index)];
2877
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2878
+ // <- TODO: !!!!!! Dynamic new column name and position
2879
+ // <- TODO: !!!!!! Check name collisions
2880
+ _c.sent(), _b)])))];
2881
+ }
2882
+ });
2883
+ }); }))];
2884
+ case 1:
2885
+ mappedData = _a.sent();
2886
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2887
+ }
2888
+ });
2889
+ });
2890
+ },
2891
+ },
2892
+ {
2893
+ subvalueName: 'CELL',
2894
+ mapValues: function (value, settings, mapCallback) {
2895
+ return __awaiter(this, void 0, void 0, function () {
2896
+ var csv, mappedData;
2897
+ var _this = this;
2898
+ return __generator(this, function (_a) {
2899
+ switch (_a.label) {
2900
+ case 0:
2901
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2902
+ if (csv.errors.length !== 0) {
2903
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2904
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2905
+ }
2906
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2907
+ var _this = this;
2908
+ return __generator(this, function (_a) {
2909
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2910
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2911
+ return __awaiter(_this, void 0, void 0, function () {
2912
+ var index;
2913
+ var _c;
2914
+ return __generator(this, function (_d) {
2915
+ index = rowIndex * Object.keys(row).length + columnIndex;
2916
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2917
+ });
2918
+ });
2919
+ }))];
2920
+ });
2921
+ }); }))];
2922
+ case 1:
2923
+ mappedData = _a.sent();
2924
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2925
+ }
2926
+ });
2927
+ });
2928
+ },
2929
+ },
2930
+ ],
2931
+ };
2932
+ /**
2933
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2934
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2935
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2936
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2937
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2938
+ */
2939
+
2940
+ /**
2941
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2942
+ *
2943
+ * @public exported from `@promptbook/utils`
2944
+ */
2945
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2946
+ try {
2947
+ JSON.parse(value);
2948
+ return true;
2949
+ }
2950
+ catch (error) {
2951
+ if (!(error instanceof Error)) {
2952
+ throw error;
2953
+ }
2954
+ if (error.message.includes('Unexpected token')) {
2955
+ return false;
2956
+ }
2957
+ return false;
2958
+ }
2959
+ }
2960
+
2961
+ /**
2962
+ * Definition for JSON format
2963
+ *
2964
+ * @private still in development [🏢]
2965
+ */
2966
+ var JsonFormatDefinition = {
2967
+ formatName: 'JSON',
2968
+ mimeType: 'application/json',
2969
+ isValid: function (value, settings, schema) {
2970
+ TODO_USE(schema /* <- TODO: Use schema here */);
2971
+ TODO_USE(settings /* <- TODO: Use settings here */);
2972
+ return isValidJsonString(value);
2973
+ },
2974
+ canBeValid: function (partialValue, settings, schema) {
2975
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2976
+ TODO_USE(settings /* <- TODO: Use settings here */);
2977
+ TODO_USE(schema /* <- TODO: Use schema here */);
2978
+ return true;
2979
+ },
2980
+ heal: function (value, settings, schema) {
2981
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2982
+ TODO_USE(settings /* <- TODO: Use settings here */);
2983
+ TODO_USE(schema /* <- TODO: Use schema here */);
2984
+ throw new Error('Not implemented');
2985
+ },
2986
+ subvalueDefinitions: [],
2987
+ };
2988
+ /**
2989
+ * TODO: [🧠] Maybe propper instance of object
2990
+ * TODO: [0] Make string_serialized_json
2991
+ * TODO: [1] Make type for JSON Settings and Schema
2992
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2993
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2994
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2995
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2996
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2997
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2998
+ */
2999
+
3000
+ /**
3001
+ * Definition for any text - this will be always valid
3002
+ *
3003
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3004
+ *
3005
+ * @public exported from `@promptbook/core`
3006
+ */
3007
+ var TextFormatDefinition = {
3008
+ formatName: 'TEXT',
3009
+ isValid: function (value) {
3010
+ return typeof value === 'string';
3011
+ },
3012
+ canBeValid: function (partialValue) {
3013
+ return typeof partialValue === 'string';
3014
+ },
3015
+ heal: function () {
3016
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3017
+ },
3018
+ subvalueDefinitions: [
3019
+ {
3020
+ subvalueName: 'LINE',
3021
+ mapValues: function (value, settings, mapCallback) {
3022
+ return __awaiter(this, void 0, void 0, function () {
3023
+ var lines, mappedLines;
3024
+ return __generator(this, function (_a) {
3025
+ switch (_a.label) {
3026
+ case 0:
3027
+ lines = value.split('\n');
3028
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3029
+ // TODO: [🧠] Maybe option to skip empty line
3030
+ /* not await */ return mapCallback({
3031
+ lineContent: lineContent,
3032
+ // TODO: [🧠] Maybe also put here `lineNumber`
3033
+ }, lineNumber);
3034
+ }))];
3035
+ case 1:
3036
+ mappedLines = _a.sent();
3037
+ return [2 /*return*/, mappedLines.join('\n')];
3038
+ }
3039
+ });
3040
+ });
3041
+ },
3042
+ },
3043
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3044
+ ],
3045
+ };
3046
+ /**
3047
+ * TODO: [1] Make type for XML Text and Schema
3048
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3049
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3050
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3051
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3052
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3053
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3054
+ */
3055
+
3056
+ /**
3057
+ * Definition for XML format
3058
+ *
3059
+ * @private still in development [🏢]
3060
+ */
3061
+ var XmlFormatDefinition = {
3062
+ formatName: 'XML',
3063
+ mimeType: 'application/xml',
3064
+ isValid: function (value, settings, schema) {
3065
+ TODO_USE(value /* <- TODO: Use value here */);
3066
+ TODO_USE(settings /* <- TODO: Use settings here */);
3067
+ TODO_USE(schema /* <- TODO: Use schema here */);
3068
+ return true;
3069
+ },
3070
+ canBeValid: function (partialValue, settings, schema) {
3071
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3072
+ TODO_USE(settings /* <- TODO: Use settings here */);
3073
+ TODO_USE(schema /* <- TODO: Use schema here */);
3074
+ return true;
3075
+ },
3076
+ heal: function (value, settings, schema) {
3077
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3078
+ TODO_USE(settings /* <- TODO: Use settings here */);
3079
+ TODO_USE(schema /* <- TODO: Use schema here */);
3080
+ throw new Error('Not implemented');
3081
+ },
3082
+ subvalueDefinitions: [],
3083
+ };
3084
+ /**
3085
+ * TODO: [🧠] Maybe propper instance of object
3086
+ * TODO: [0] Make string_serialized_xml
3087
+ * TODO: [1] Make type for XML Settings and Schema
3088
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3089
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3090
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3091
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3092
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3093
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3094
+ */
3095
+
3096
+ /**
3097
+ * Definitions for all formats supported by Promptbook
3098
+ *
3099
+ * @private internal index of `...` <- TODO [🏢]
3100
+ */
3101
+ var FORMAT_DEFINITIONS = [
3102
+ JsonFormatDefinition,
3103
+ XmlFormatDefinition,
3104
+ TextFormatDefinition,
3105
+ CsvFormatDefinition,
3106
+ ];
3107
+
3108
+ /**
3109
+ * Maps available parameters to expected parameters
3110
+ *
3111
+ * The strategy is:
3112
+ * 1) @@@
3113
+ * 2) @@@
3114
+ *
3115
+ * @throws {PipelineExecutionError} @@@
3116
+ * @private within the repository used in `createPipelineExecutor`
3117
+ */
3118
+ function mapAvailableToExpectedParameters(options) {
3119
+ var e_1, _a;
3120
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3121
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3122
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3123
+ var mappedParameters = {};
3124
+ try {
3125
+ // Phase 1️⃣: Matching mapping
3126
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3127
+ var parameterName = _c.value;
3128
+ // Situation: Parameter is available and expected
3129
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3130
+ mappedParameters[parameterName] = availableParameters[parameterName];
3131
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3132
+ availableParametersNames.delete(parameterName);
3133
+ expectedParameterNames.delete(parameterName);
3134
+ }
3135
+ // Situation: Parameter is available but NOT expected
3136
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3137
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3138
+ }
3139
+ // Situation: Parameter is NOT available BUT expected
3140
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3141
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3142
+ }
3143
+ }
3144
+ }
3145
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3146
+ finally {
3147
+ try {
3148
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3149
+ }
3150
+ finally { if (e_1) throw e_1.error; }
3151
+ }
3152
+ if (expectedParameterNames.size === 0) {
3153
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3154
+ Object.freeze(mappedParameters);
3155
+ return mappedParameters;
3156
+ }
3157
+ // Phase 2️⃣: Non-matching mapping
3158
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3159
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3160
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3161
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3162
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3163
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3164
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3165
+ .join('\n')), "\n\n "); }));
3166
+ }
3167
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3168
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3169
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3170
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3171
+ }
3172
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3173
+ Object.freeze(mappedParameters);
3174
+ return mappedParameters;
3175
+ }
3176
+
3177
+ /**
3178
+ * Extracts all code blocks from markdown.
3179
+ *
3180
+ * Note: There are multiple simmilar function:
3181
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3182
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3183
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3184
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3185
+ *
3186
+ * @param markdown any valid markdown
3187
+ * @returns code blocks with language and content
3188
+ * @throws {ParseError} if block is not closed properly
3189
+ * @public exported from `@promptbook/markdown-utils`
3190
+ */
3191
+ function extractAllBlocksFromMarkdown(markdown) {
3192
+ var e_1, _a;
3193
+ var codeBlocks = [];
3194
+ var lines = markdown.split('\n');
3195
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3196
+ lines.push('');
3197
+ var currentCodeBlock = null;
3198
+ try {
3199
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3200
+ var line = lines_1_1.value;
3201
+ if (line.startsWith('> ') || line === '>') {
3202
+ if (currentCodeBlock === null) {
3203
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3204
+ } /* not else */
3205
+ if (currentCodeBlock.blockNotation === '>') {
3206
+ if (currentCodeBlock.content !== '') {
3207
+ currentCodeBlock.content += '\n';
3208
+ }
3209
+ currentCodeBlock.content += line.slice(2);
3210
+ }
3211
+ }
3212
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3213
+ codeBlocks.push(currentCodeBlock);
3214
+ currentCodeBlock = null;
3215
+ }
3216
+ /* not else */
3217
+ if (line.startsWith('```')) {
3218
+ var language = line.slice(3).trim() || null;
3219
+ if (currentCodeBlock === null) {
3220
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3221
+ }
3222
+ else {
3223
+ if (language !== null) {
3224
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3225
+ }
3226
+ codeBlocks.push(currentCodeBlock);
3227
+ currentCodeBlock = null;
3228
+ }
3229
+ }
3230
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3231
+ if (currentCodeBlock.content !== '') {
3232
+ currentCodeBlock.content += '\n';
3233
+ }
3234
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3235
+ }
3236
+ }
3237
+ }
3238
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3239
+ finally {
3240
+ try {
3241
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3242
+ }
3243
+ finally { if (e_1) throw e_1.error; }
3244
+ }
3245
+ if (currentCodeBlock !== null) {
3246
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3247
+ }
3248
+ return codeBlocks;
3249
+ }
3250
+ /**
3251
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3252
+ */
3253
+
3254
+ /**
3255
+ * Extracts extracts exactly one valid JSON code block
3256
+ *
3257
+ * - When given string is a valid JSON as it is, it just returns it
3258
+ * - When there is no JSON code block the function throws a `ParseError`
3259
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3260
+ *
3261
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3262
+ * Note: There are multiple simmilar function:
3263
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3264
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3265
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3266
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3267
+ *
3268
+ * @public exported from `@promptbook/markdown-utils`
3269
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3270
+ */
3271
+ function extractJsonBlock(markdown) {
3272
+ if (isValidJsonString(markdown)) {
3273
+ return markdown;
3274
+ }
3275
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3276
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3277
+ var content = _a.content;
3278
+ return isValidJsonString(content);
3279
+ });
3280
+ if (jsonBlocks.length === 0) {
3281
+ throw new Error('There is no valid JSON block in the markdown');
3282
+ }
3283
+ if (jsonBlocks.length > 1) {
3284
+ throw new Error('There are multiple JSON code blocks in the markdown');
3285
+ }
3286
+ return jsonBlocks[0].content;
3287
+ }
3288
+ /**
3289
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3290
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3291
+ */
3292
+
3293
+ /**
3294
+ * Just says that the variable is not used but should be kept
3295
+ * No side effects.
3296
+ *
3297
+ * Note: It can be usefull for:
3298
+ *
3299
+ * 1) Suppressing eager optimization of unused imports
3300
+ * 2) Suppressing eslint errors of unused variables in the tests
3301
+ * 3) Keeping the type of the variable for type testing
3302
+ *
3303
+ * @param value any values
3304
+ * @returns void
3305
+ * @private within the repository
3306
+ */
3307
+ function keepUnused() {
3308
+ var valuesToKeep = [];
3309
+ for (var _i = 0; _i < arguments.length; _i++) {
3310
+ valuesToKeep[_i] = arguments[_i];
3311
+ }
3312
+ }
3313
+
3314
+ /**
3315
+ * Replaces parameters in template with values from parameters object
3316
+ *
3317
+ * @param template the template with parameters in {curly} braces
3318
+ * @param parameters the object with parameters
3319
+ * @returns the template with replaced parameters
3320
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3321
+ * @public exported from `@promptbook/utils`
3322
+ */
3323
+ function replaceParameters(template, parameters) {
3324
+ var e_1, _a;
3325
+ try {
3326
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3327
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3328
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3329
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3330
+ }
3331
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3332
+ // TODO: [🍵]
3333
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3334
+ }
3335
+ }
3336
+ }
3337
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3338
+ finally {
3339
+ try {
3340
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3341
+ }
3342
+ finally { if (e_1) throw e_1.error; }
3343
+ }
3344
+ var replacedTemplate = template;
3345
+ var match;
3346
+ var loopLimit = LOOP_LIMIT;
3347
+ var _loop_1 = function () {
3348
+ if (loopLimit-- < 0) {
3349
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3350
+ }
3351
+ var precol = match.groups.precol;
3352
+ var parameterName = match.groups.parameterName;
3353
+ if (parameterName === '') {
3354
+ return "continue";
3355
+ }
3356
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3357
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3358
+ }
3359
+ if (parameters[parameterName] === undefined) {
3360
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3361
+ }
3362
+ var parameterValue = parameters[parameterName];
3363
+ if (parameterValue === undefined) {
3364
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3365
+ }
3366
+ parameterValue = parameterValue.toString();
3367
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3368
+ parameterValue = parameterValue
3369
+ .split('\n')
3370
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3371
+ .join('\n');
3372
+ }
3373
+ replacedTemplate =
3374
+ replacedTemplate.substring(0, match.index + precol.length) +
3375
+ parameterValue +
3376
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3377
+ };
3378
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3379
+ .exec(replacedTemplate))) {
3380
+ _loop_1();
3381
+ }
3382
+ // [💫] Check if there are parameters that are not closed properly
3383
+ if (/{\w+$/.test(replacedTemplate)) {
3384
+ throw new PipelineExecutionError('Parameter is not closed');
3385
+ }
3386
+ // [💫] Check if there are parameters that are not opened properly
3387
+ if (/^\w+}/.test(replacedTemplate)) {
3388
+ throw new PipelineExecutionError('Parameter is not opened');
3389
+ }
3390
+ return replacedTemplate;
3391
+ }
3392
+
3393
+ /**
3394
+ * Counts number of characters in the text
3395
+ *
3396
+ * @public exported from `@promptbook/utils`
3397
+ */
3398
+ function countCharacters(text) {
3399
+ // Remove null characters
3400
+ text = text.replace(/\0/g, '');
3401
+ // Replace emojis (and also ZWJ sequence) with hyphens
3402
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3403
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3001
3404
  text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3002
3405
  return text.length;
3003
3406
  }
@@ -3044,62 +3447,789 @@
3044
3447
  return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3045
3448
  }
3046
3449
  /**
3047
- * Counts number of sentences in the text
3450
+ * Counts number of sentences in the text
3451
+ *
3452
+ * @public exported from `@promptbook/utils`
3453
+ */
3454
+ function countSentences(text) {
3455
+ return splitIntoSentences(text).length;
3456
+ }
3457
+
3458
+ /**
3459
+ * Counts number of words in the text
3460
+ *
3461
+ * @public exported from `@promptbook/utils`
3462
+ */
3463
+ function countWords(text) {
3464
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3465
+ text = removeDiacritics(text);
3466
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3467
+ }
3468
+
3469
+ /**
3470
+ * Index of all counter functions
3471
+ *
3472
+ * @public exported from `@promptbook/utils`
3473
+ */
3474
+ var CountUtils = {
3475
+ CHARACTERS: countCharacters,
3476
+ WORDS: countWords,
3477
+ SENTENCES: countSentences,
3478
+ PARAGRAPHS: countParagraphs,
3479
+ LINES: countLines,
3480
+ PAGES: countPages,
3481
+ };
3482
+ /**
3483
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3484
+ */
3485
+
3486
+ /**
3487
+ * Function checkExpectations will check if the expectations on given value are met
3488
+ *
3489
+ * Note: There are two simmilar functions:
3490
+ * - `checkExpectations` which throws an error if the expectations are not met
3491
+ * - `isPassingExpectations` which returns a boolean
3492
+ *
3493
+ * @throws {ExpectError} if the expectations are not met
3494
+ * @returns {void} Nothing
3495
+ * @private internal function of `createPipelineExecutor`
3496
+ */
3497
+ function checkExpectations(expectations, value) {
3498
+ var e_1, _a;
3499
+ try {
3500
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3501
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3502
+ var amount = CountUtils[unit.toUpperCase()](value);
3503
+ if (min && amount < min) {
3504
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3505
+ } /* not else */
3506
+ if (max && amount > max) {
3507
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3508
+ }
3509
+ }
3510
+ }
3511
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3512
+ finally {
3513
+ try {
3514
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3515
+ }
3516
+ finally { if (e_1) throw e_1.error; }
3517
+ }
3518
+ }
3519
+ /**
3520
+ * TODO: [💝] Unite object for expecting amount and format
3521
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3522
+ * Note: [💝] and [🤠] are interconnected together
3523
+ */
3524
+
3525
+ /**
3526
+ * @@@
3527
+ *
3528
+ * @private internal utility of `createPipelineExecutor`
3529
+ */
3530
+ function executeAttempts(options) {
3531
+ return __awaiter(this, void 0, void 0, function () {
3532
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3533
+ return __generator(this, function (_a) {
3534
+ switch (_a.label) {
3535
+ case 0:
3536
+ jokerParameterNames = options.jokerParameterNames, priority = options.priority, maxAttempts = options.maxAttempts, preparedContent = options.preparedContent, parameters = options.parameters, template = options.template, preparedPipeline = options.preparedPipeline, tools = options.tools, llmTools = options.llmTools, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3537
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3538
+ $ongoingTemplateResult = {
3539
+ $result: null,
3540
+ $resultString: null,
3541
+ $expectError: null,
3542
+ $scriptPipelineExecutionErrors: [],
3543
+ };
3544
+ _loop_1 = function (attempt) {
3545
+ var isJokerAttempt, jokerParameterName, _b, modelRequirements, _c, _d, _e, _f, _g, scriptTools, _h, error_1, e_1_1, _j, _k, _l, functionName, postprocessingError, _m, _o, scriptTools, _p, error_2, e_2_1, e_3_1, error_3;
3546
+ var e_1, _q, e_3, _r, e_2, _s;
3547
+ return __generator(this, function (_t) {
3548
+ switch (_t.label) {
3549
+ case 0:
3550
+ isJokerAttempt = attempt < 0;
3551
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3552
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3553
+ if (isJokerAttempt && !jokerParameterName) {
3554
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3555
+ }
3556
+ $ongoingTemplateResult.$result = null;
3557
+ $ongoingTemplateResult.$resultString = null;
3558
+ $ongoingTemplateResult.$expectError = null;
3559
+ if (isJokerAttempt) {
3560
+ if (parameters[jokerParameterName] === undefined) {
3561
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3562
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3563
+ }
3564
+ else {
3565
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3566
+ }
3567
+ }
3568
+ _t.label = 1;
3569
+ case 1:
3570
+ _t.trys.push([1, 43, 44, 45]);
3571
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3572
+ _b = template.templateType;
3573
+ switch (_b) {
3574
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3575
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3576
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3577
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3578
+ }
3579
+ return [3 /*break*/, 24];
3580
+ case 2:
3581
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3582
+ return [3 /*break*/, 25];
3583
+ case 3:
3584
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3585
+ $ongoingTemplateResult.$prompt = {
3586
+ title: template.title,
3587
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3588
+ ? preparedPipeline.pipelineUrl
3589
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3590
+ parameters: parameters,
3591
+ content: preparedContent,
3592
+ modelRequirements: modelRequirements,
3593
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3594
+ var name = _a.name;
3595
+ return name === template.personaName;
3596
+ }) ||
3597
+ {})), template.expectations),
3598
+ format: template.format,
3599
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3600
+ }; // <- TODO: Not very good type guard
3601
+ _c = modelRequirements.modelVariant;
3602
+ switch (_c) {
3603
+ case 'CHAT': return [3 /*break*/, 4];
3604
+ case 'COMPLETION': return [3 /*break*/, 6];
3605
+ case 'EMBEDDING': return [3 /*break*/, 8];
3606
+ }
3607
+ return [3 /*break*/, 9];
3608
+ case 4:
3609
+ _d = $ongoingTemplateResult;
3610
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3611
+ case 5:
3612
+ _d.$chatResult = _t.sent();
3613
+ // TODO: [🍬] Destroy chatThread
3614
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3615
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3616
+ return [3 /*break*/, 10];
3617
+ case 6:
3618
+ _e = $ongoingTemplateResult;
3619
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3620
+ case 7:
3621
+ _e.$completionResult = _t.sent();
3622
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3623
+ $ongoingTemplateResult.$resultString =
3624
+ $ongoingTemplateResult.$completionResult.content;
3625
+ return [3 /*break*/, 10];
3626
+ case 8: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Embedding model can not be used in pipeline\n\n This should be catched during parsing\n\n ".concat(block(pipelineIdentification), "\n\n "); }));
3627
+ case 9: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3628
+ case 10: return [3 /*break*/, 25];
3629
+ case 11:
3630
+ if (arrayableToArray(tools.script).length === 0) {
3631
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3632
+ }
3633
+ if (!template.contentLanguage) {
3634
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3635
+ }
3636
+ _t.label = 12;
3637
+ case 12:
3638
+ _t.trys.push([12, 19, 20, 21]);
3639
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3640
+ _t.label = 13;
3641
+ case 13:
3642
+ if (!!_g.done) return [3 /*break*/, 18];
3643
+ scriptTools = _g.value;
3644
+ _t.label = 14;
3645
+ case 14:
3646
+ _t.trys.push([14, 16, , 17]);
3647
+ _h = $ongoingTemplateResult;
3648
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3649
+ scriptLanguage: template.contentLanguage,
3650
+ script: preparedContent,
3651
+ parameters: parameters,
3652
+ }))];
3653
+ case 15:
3654
+ _h.$resultString = _t.sent();
3655
+ return [3 /*break*/, 18];
3656
+ case 16:
3657
+ error_1 = _t.sent();
3658
+ if (!(error_1 instanceof Error)) {
3659
+ throw error_1;
3660
+ }
3661
+ if (error_1 instanceof UnexpectedError) {
3662
+ throw error_1;
3663
+ }
3664
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3665
+ return [3 /*break*/, 17];
3666
+ case 17:
3667
+ _g = _f.next();
3668
+ return [3 /*break*/, 13];
3669
+ case 18: return [3 /*break*/, 21];
3670
+ case 19:
3671
+ e_1_1 = _t.sent();
3672
+ e_1 = { error: e_1_1 };
3673
+ return [3 /*break*/, 21];
3674
+ case 20:
3675
+ try {
3676
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3677
+ }
3678
+ finally { if (e_1) throw e_1.error; }
3679
+ return [7 /*endfinally*/];
3680
+ case 21:
3681
+ if ($ongoingTemplateResult.$resultString !== null) {
3682
+ return [3 /*break*/, 25];
3683
+ }
3684
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3685
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3686
+ }
3687
+ else {
3688
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3689
+ .map(function (error) { return '- ' + error.message; })
3690
+ .join('\n\n')), "\n "); }));
3691
+ }
3692
+ case 22:
3693
+ if (tools.userInterface === undefined) {
3694
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3695
+ }
3696
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3697
+ _j = $ongoingTemplateResult;
3698
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3699
+ promptTitle: template.title,
3700
+ promptMessage: replaceParameters(template.description || '', parameters),
3701
+ defaultValue: replaceParameters(preparedContent, parameters),
3702
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3703
+ placeholder: undefined,
3704
+ priority: priority,
3705
+ }))];
3706
+ case 23:
3707
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3708
+ _j.$resultString = _t.sent();
3709
+ return [3 /*break*/, 25];
3710
+ case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3711
+ case 25:
3712
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3713
+ _t.label = 26;
3714
+ case 26:
3715
+ _t.trys.push([26, 40, 41, 42]);
3716
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3717
+ _t.label = 27;
3718
+ case 27:
3719
+ if (!!_l.done) return [3 /*break*/, 39];
3720
+ functionName = _l.value;
3721
+ postprocessingError = null;
3722
+ _t.label = 28;
3723
+ case 28:
3724
+ _t.trys.push([28, 35, 36, 37]);
3725
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3726
+ _t.label = 29;
3727
+ case 29:
3728
+ if (!!_o.done) return [3 /*break*/, 34];
3729
+ scriptTools = _o.value;
3730
+ _t.label = 30;
3731
+ case 30:
3732
+ _t.trys.push([30, 32, , 33]);
3733
+ _p = $ongoingTemplateResult;
3734
+ return [4 /*yield*/, scriptTools.execute({
3735
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3736
+ script: "".concat(functionName, "(resultString)"),
3737
+ parameters: {
3738
+ resultString: $ongoingTemplateResult.$resultString || '',
3739
+ // Note: No ...parametersForTemplate, because working with result only
3740
+ },
3741
+ })];
3742
+ case 31:
3743
+ _p.$resultString = _t.sent();
3744
+ postprocessingError = null;
3745
+ return [3 /*break*/, 34];
3746
+ case 32:
3747
+ error_2 = _t.sent();
3748
+ if (!(error_2 instanceof Error)) {
3749
+ throw error_2;
3750
+ }
3751
+ if (error_2 instanceof UnexpectedError) {
3752
+ throw error_2;
3753
+ }
3754
+ postprocessingError = error_2;
3755
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3756
+ return [3 /*break*/, 33];
3757
+ case 33:
3758
+ _o = _m.next();
3759
+ return [3 /*break*/, 29];
3760
+ case 34: return [3 /*break*/, 37];
3761
+ case 35:
3762
+ e_2_1 = _t.sent();
3763
+ e_2 = { error: e_2_1 };
3764
+ return [3 /*break*/, 37];
3765
+ case 36:
3766
+ try {
3767
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3768
+ }
3769
+ finally { if (e_2) throw e_2.error; }
3770
+ return [7 /*endfinally*/];
3771
+ case 37:
3772
+ if (postprocessingError) {
3773
+ throw postprocessingError;
3774
+ }
3775
+ _t.label = 38;
3776
+ case 38:
3777
+ _l = _k.next();
3778
+ return [3 /*break*/, 27];
3779
+ case 39: return [3 /*break*/, 42];
3780
+ case 40:
3781
+ e_3_1 = _t.sent();
3782
+ e_3 = { error: e_3_1 };
3783
+ return [3 /*break*/, 42];
3784
+ case 41:
3785
+ try {
3786
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3787
+ }
3788
+ finally { if (e_3) throw e_3.error; }
3789
+ return [7 /*endfinally*/];
3790
+ case 42:
3791
+ // TODO: [💝] Unite object for expecting amount and format
3792
+ if (template.format) {
3793
+ if (template.format === 'JSON') {
3794
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3795
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3796
+ try {
3797
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3798
+ }
3799
+ catch (error) {
3800
+ keepUnused(error);
3801
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3802
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3803
+ }
3804
+ }
3805
+ }
3806
+ else {
3807
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3808
+ }
3809
+ }
3810
+ // TODO: [💝] Unite object for expecting amount and format
3811
+ if (template.expectations) {
3812
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3813
+ }
3814
+ return [2 /*return*/, "break-attempts"];
3815
+ case 43:
3816
+ error_3 = _t.sent();
3817
+ if (!(error_3 instanceof ExpectError)) {
3818
+ throw error_3;
3819
+ }
3820
+ $ongoingTemplateResult.$expectError = error_3;
3821
+ return [3 /*break*/, 45];
3822
+ case 44:
3823
+ if (!isJokerAttempt &&
3824
+ template.templateType === 'PROMPT_TEMPLATE' &&
3825
+ $ongoingTemplateResult.$prompt
3826
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3827
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3828
+ ) {
3829
+ // TODO: [🧠] Maybe put other templateTypes into report
3830
+ $executionReport.promptExecutions.push({
3831
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3832
+ result: $ongoingTemplateResult.$result || undefined,
3833
+ error: $ongoingTemplateResult.$expectError === null
3834
+ ? undefined
3835
+ : serializeError($ongoingTemplateResult.$expectError),
3836
+ });
3837
+ }
3838
+ return [7 /*endfinally*/];
3839
+ case 45:
3840
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3841
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3842
+ var _a, _b, _c;
3843
+ return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block((((_a = $ongoingTemplateResult.$prompt) === null || _a === void 0 ? void 0 : _a.content) || '')
3844
+ .split('\n')
3845
+ .map(function (line) { return "> ".concat(line); })
3846
+ .join('\n')), "\n\n Last error ").concat(((_b = $ongoingTemplateResult.$expectError) === null || _b === void 0 ? void 0 : _b.name) || '', ":\n ").concat(block((((_c = $ongoingTemplateResult.$expectError) === null || _c === void 0 ? void 0 : _c.message) || '')
3847
+ .split('\n')
3848
+ .map(function (line) { return "> ".concat(line); })
3849
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3850
+ ? 'null'
3851
+ : $ongoingTemplateResult.$resultString
3852
+ .split('\n')
3853
+ .map(function (line) { return "> ".concat(line); })
3854
+ .join('\n')), "\n ---\n ");
3855
+ }));
3856
+ }
3857
+ return [2 /*return*/];
3858
+ }
3859
+ });
3860
+ };
3861
+ attempt = -jokerParameterNames.length;
3862
+ _a.label = 1;
3863
+ case 1:
3864
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3865
+ return [5 /*yield**/, _loop_1(attempt)];
3866
+ case 2:
3867
+ state_1 = _a.sent();
3868
+ switch (state_1) {
3869
+ case "break-attempts": return [3 /*break*/, 4];
3870
+ }
3871
+ _a.label = 3;
3872
+ case 3:
3873
+ attempt++;
3874
+ return [3 /*break*/, 1];
3875
+ case 4:
3876
+ if ($ongoingTemplateResult.$resultString === null) {
3877
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3878
+ }
3879
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3880
+ }
3881
+ });
3882
+ });
3883
+ }
3884
+ /**
3885
+ * TODO: Break into smaller functions
3886
+ */
3887
+
3888
+ /**
3889
+ * @@@
3890
+ *
3891
+ * @private internal utility of `createPipelineExecutor`
3892
+ */
3893
+ function executeFormatCells(options) {
3894
+ return __awaiter(this, void 0, void 0, function () {
3895
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
3896
+ var _this = this;
3897
+ return __generator(this, function (_a) {
3898
+ switch (_a.label) {
3899
+ case 0:
3900
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3901
+ if (template.foreach === undefined) {
3902
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3903
+ }
3904
+ if (jokerParameterNames.length !== 0) {
3905
+ throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n JOKER parameters are not supported together with FOREACH command\n\n [\uD83E\uDDDE\u200D\u2640\uFE0F] This should be prevented in `validatePipeline`\n\n ".concat(block(pipelineIdentification), "\n "); }));
3906
+ }
3907
+ parameterValue = parameters[template.foreach.parameterName] || '';
3908
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3909
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3910
+ });
3911
+ if (formatDefinition === undefined) {
3912
+ throw new UnexpectedError(
3913
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3914
+ spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(template.foreach.formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
3915
+ .map(function (formatName) { return "- ".concat(formatName); })
3916
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3917
+ }
3918
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3919
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
3920
+ });
3921
+ if (subvalueDefinition === undefined) {
3922
+ throw new UnexpectedError(
3923
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3924
+ spaceTrim__default["default"](function (block) { return "\n Unsupported subformat name \"".concat(template.foreach.subformatName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
3925
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3926
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3927
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3928
+ }
3929
+ if (formatDefinition.formatName === 'CSV') {
3930
+ formatSettings = settings.csvSettings;
3931
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
3932
+ }
3933
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3934
+ var mappedParameters, allSubparameters, subresultString;
3935
+ return __generator(this, function (_a) {
3936
+ switch (_a.label) {
3937
+ case 0:
3938
+ // TODO: !!!!!!! Limit to N concurrent executions
3939
+ // TODO: !!!!!!! Report progress
3940
+ try {
3941
+ mappedParameters = mapAvailableToExpectedParameters({
3942
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3943
+ availableParameters: subparameters,
3944
+ });
3945
+ }
3946
+ catch (error) {
3947
+ if (!(error instanceof PipelineExecutionError)) {
3948
+ throw error;
3949
+ }
3950
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n ".concat(error.message, "\n\n This is error in FOREACH command\n You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command\n\n ").concat(block(pipelineIdentification), "\n "); }));
3951
+ }
3952
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3953
+ // Note: [👨‍👨‍👧] Now we can freeze `subparameters` because we are sure that all and only used parameters are defined and are not going to be changed
3954
+ Object.freeze(allSubparameters);
3955
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3956
+ case 1:
3957
+ subresultString = _a.sent();
3958
+ return [2 /*return*/, subresultString];
3959
+ }
3960
+ });
3961
+ }); })];
3962
+ case 1:
3963
+ resultString = _a.sent();
3964
+ return [2 /*return*/, resultString];
3965
+ }
3966
+ });
3967
+ });
3968
+ }
3969
+ /**
3970
+ * TODO: !!!!!! Make pipelineIdentification more precise
3971
+ * TODO: !!!!!! How FOREACH execution looks in the report
3972
+ */
3973
+
3974
+ /**
3975
+ * @@@
3976
+ *
3977
+ * @private internal utility of `createPipelineExecutor`
3978
+ */
3979
+ function getContextForTemplate(template) {
3980
+ return __awaiter(this, void 0, void 0, function () {
3981
+ return __generator(this, function (_a) {
3982
+ TODO_USE(template);
3983
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3984
+ });
3985
+ });
3986
+ }
3987
+
3988
+ /**
3989
+ * @@@
3990
+ *
3991
+ * @private internal utility of `createPipelineExecutor`
3992
+ */
3993
+ function getKnowledgeForTemplate(options) {
3994
+ return __awaiter(this, void 0, void 0, function () {
3995
+ var preparedPipeline, template;
3996
+ return __generator(this, function (_a) {
3997
+ preparedPipeline = options.preparedPipeline, template = options.template;
3998
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3999
+ TODO_USE(template);
4000
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4001
+ var content = _a.content;
4002
+ return "- ".concat(content);
4003
+ }).join('\n')];
4004
+ });
4005
+ });
4006
+ }
4007
+
4008
+ /**
4009
+ * @@@
4010
+ *
4011
+ * @private internal utility of `createPipelineExecutor`
4012
+ */
4013
+ function getSamplesForTemplate(template) {
4014
+ return __awaiter(this, void 0, void 0, function () {
4015
+ return __generator(this, function (_a) {
4016
+ // TODO: [♨] Implement Better - use real index and keyword search
4017
+ TODO_USE(template);
4018
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4019
+ });
4020
+ });
4021
+ }
4022
+
4023
+ /**
4024
+ * @@@
3048
4025
  *
3049
- * @public exported from `@promptbook/utils`
4026
+ * @private internal utility of `createPipelineExecutor`
3050
4027
  */
3051
- function countSentences(text) {
3052
- return splitIntoSentences(text).length;
4028
+ function getReservedParametersForTemplate(options) {
4029
+ return __awaiter(this, void 0, void 0, function () {
4030
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4031
+ var e_1, _a;
4032
+ return __generator(this, function (_b) {
4033
+ switch (_b.label) {
4034
+ case 0:
4035
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4036
+ return [4 /*yield*/, getContextForTemplate(template)];
4037
+ case 1:
4038
+ context = _b.sent();
4039
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4040
+ case 2:
4041
+ knowledge = _b.sent();
4042
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4043
+ case 3:
4044
+ samples = _b.sent();
4045
+ currentDate = new Date().toISOString();
4046
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4047
+ reservedParameters = {
4048
+ content: RESERVED_PARAMETER_RESTRICTED,
4049
+ context: context,
4050
+ knowledge: knowledge,
4051
+ samples: samples,
4052
+ currentDate: currentDate,
4053
+ modelName: modelName,
4054
+ };
4055
+ _loop_1 = function (parameterName) {
4056
+ if (reservedParameters[parameterName] === undefined) {
4057
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4058
+ }
4059
+ };
4060
+ try {
4061
+ // Note: Doublecheck that ALL reserved parameters are defined:
4062
+ 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()) {
4063
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4064
+ _loop_1(parameterName);
4065
+ }
4066
+ }
4067
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4068
+ finally {
4069
+ try {
4070
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4071
+ }
4072
+ finally { if (e_1) throw e_1.error; }
4073
+ }
4074
+ return [2 /*return*/, reservedParameters];
4075
+ }
4076
+ });
4077
+ });
3053
4078
  }
3054
4079
 
3055
4080
  /**
3056
- * Counts number of words in the text
4081
+ * @@@
3057
4082
  *
3058
- * @public exported from `@promptbook/utils`
4083
+ * @private internal utility of `createPipelineExecutor`
3059
4084
  */
3060
- function countWords(text) {
3061
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3062
- text = removeDiacritics(text);
3063
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
4085
+ function executeTemplate(options) {
4086
+ return __awaiter(this, void 0, void 0, function () {
4087
+ 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, maxAttempts, jokerParameterNames, preparedContent, resultString;
4088
+ var e_1, _f, _g;
4089
+ return __generator(this, function (_h) {
4090
+ switch (_h.label) {
4091
+ case 0:
4092
+ 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;
4093
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4094
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4095
+ title = currentTemplate.title;
4096
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4097
+ return [4 /*yield*/, onProgress({
4098
+ name: name,
4099
+ title: title,
4100
+ isStarted: false,
4101
+ isDone: false,
4102
+ templateType: currentTemplate.templateType,
4103
+ parameterName: currentTemplate.resultingParameterName,
4104
+ parameterValue: null,
4105
+ // <- [🍸]
4106
+ })];
4107
+ case 1:
4108
+ _h.sent();
4109
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4110
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4111
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4112
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4113
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
4114
+ .map(function (name) { return "{".concat(name, "}"); })
4115
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4116
+ .map(function (name) { return "{".concat(name, "}"); })
4117
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4118
+ }
4119
+ _b = (_a = Object).freeze;
4120
+ _c = [{}];
4121
+ return [4 /*yield*/, getReservedParametersForTemplate({
4122
+ preparedPipeline: preparedPipeline,
4123
+ template: currentTemplate,
4124
+ pipelineIdentification: pipelineIdentification,
4125
+ })];
4126
+ case 2:
4127
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4128
+ definedParameterNames = new Set(Object.keys(definedParameters));
4129
+ parameters = {};
4130
+ _loop_1 = function (parameterName) {
4131
+ // Situation: Parameter is defined and used
4132
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4133
+ parameters[parameterName] = definedParameters[parameterName];
4134
+ }
4135
+ // Situation: Parameter is defined but NOT used
4136
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4137
+ // Situation: Parameter is NOT defined BUT used
4138
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4139
+ // Houston, we have a problem
4140
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4141
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4142
+ }
4143
+ };
4144
+ try {
4145
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4146
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4147
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4148
+ parameterName = _e.value;
4149
+ _loop_1(parameterName);
4150
+ }
4151
+ }
4152
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4153
+ finally {
4154
+ try {
4155
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4156
+ }
4157
+ finally { if (e_1) throw e_1.error; }
4158
+ }
4159
+ // Note: [👨‍👨‍👧] Now we can freeze `parameters` because we are sure that all and only used parameters are defined and are not going to be changed
4160
+ Object.freeze(parameters);
4161
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4162
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4163
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4164
+ .split('{content}')
4165
+ .join(currentTemplate.content);
4166
+ return [4 /*yield*/, executeFormatCells({
4167
+ jokerParameterNames: jokerParameterNames,
4168
+ priority: priority,
4169
+ maxAttempts: maxAttempts,
4170
+ preparedContent: preparedContent,
4171
+ parameters: parameters,
4172
+ template: currentTemplate,
4173
+ preparedPipeline: preparedPipeline,
4174
+ tools: tools,
4175
+ llmTools: llmTools,
4176
+ settings: settings,
4177
+ $executionReport: $executionReport,
4178
+ pipelineIdentification: pipelineIdentification,
4179
+ })];
4180
+ case 3:
4181
+ resultString = _h.sent();
4182
+ return [4 /*yield*/, onProgress({
4183
+ name: name,
4184
+ title: title,
4185
+ isStarted: true,
4186
+ isDone: true,
4187
+ templateType: currentTemplate.templateType,
4188
+ parameterName: currentTemplate.resultingParameterName,
4189
+ parameterValue: resultString,
4190
+ // <- [🍸]
4191
+ })];
4192
+ case 4:
4193
+ _h.sent();
4194
+ return [2 /*return*/, Object.freeze((_g = {},
4195
+ _g[currentTemplate.resultingParameterName] =
4196
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4197
+ resultString,
4198
+ _g))];
4199
+ }
4200
+ });
4201
+ });
3064
4202
  }
3065
-
3066
4203
  /**
3067
- * Index of all counter functions
3068
- *
3069
- * @public exported from `@promptbook/utils`
4204
+ * TODO: [🤹‍♂️]
3070
4205
  */
3071
- var CountUtils = {
3072
- CHARACTERS: countCharacters,
3073
- WORDS: countWords,
3074
- SENTENCES: countSentences,
3075
- PARAGRAPHS: countParagraphs,
3076
- LINES: countLines,
3077
- PAGES: countPages,
3078
- };
3079
4206
 
3080
4207
  /**
3081
- * Function checkExpectations will check if the expectations on given value are met
3082
- *
3083
- * Note: There are two simmilar functions:
3084
- * - `checkExpectations` which throws an error if the expectations are not met
3085
- * - `isPassingExpectations` which returns a boolean
4208
+ * @@@
3086
4209
  *
3087
- * @throws {ExpectError} if the expectations are not met
3088
- * @returns {void} Nothing
3089
- * @private internal function of `createPipelineExecutor`
4210
+ * @private internal utility of `createPipelineExecutor`
3090
4211
  */
3091
- function checkExpectations(expectations, value) {
4212
+ function filterJustOutputParameters(options) {
3092
4213
  var e_1, _a;
4214
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4215
+ var outputParameters = {};
4216
+ var _loop_1 = function (parameter) {
4217
+ if (parametersToPass[parameter.name] === undefined) {
4218
+ // [4]
4219
+ $warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
4220
+ return "continue";
4221
+ }
4222
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4223
+ };
3093
4224
  try {
3094
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3095
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3096
- var amount = CountUtils[unit.toUpperCase()](value);
3097
- if (min && amount < min) {
3098
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3099
- } /* not else */
3100
- if (max && amount > max) {
3101
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3102
- }
4225
+ // Note: Filter ONLY output parameters
4226
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4227
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4228
+ var isOutput = _a.isOutput;
4229
+ return isOutput;
4230
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4231
+ var parameter = _c.value;
4232
+ _loop_1(parameter);
3103
4233
  }
3104
4234
  }
3105
4235
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3109,600 +4239,27 @@
3109
4239
  }
3110
4240
  finally { if (e_1) throw e_1.error; }
3111
4241
  }
4242
+ return outputParameters;
3112
4243
  }
3113
- /**
3114
- * TODO: [💝] Unite object for expecting amount and format
3115
- */
3116
4244
 
3117
4245
  /**
3118
- * Creates executor function from pipeline and execution tools.
4246
+ * @@@
3119
4247
  *
3120
- * @returns The executor function
3121
- * @throws {PipelineLogicError} on logical error in the pipeline
3122
- * @public exported from `@promptbook/core`
4248
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4249
+ *
4250
+ * @private internal utility of `createPipelineExecutor`
3123
4251
  */
3124
- function createPipelineExecutor(options) {
3125
- var _this = this;
3126
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3127
- 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;
3128
- validatePipeline(pipeline);
3129
- var pipelineIdentification = (function () {
3130
- // Note: This is a 😐 implementation of [🚞]
3131
- var _ = [];
3132
- if (pipeline.sourceFile !== undefined) {
3133
- _.push("File: ".concat(pipeline.sourceFile));
3134
- }
3135
- if (pipeline.pipelineUrl !== undefined) {
3136
- _.push("Url: ".concat(pipeline.pipelineUrl));
3137
- }
3138
- return _.join('\n');
3139
- })();
3140
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3141
- var preparedPipeline;
3142
- if (isPipelinePrepared(pipeline)) {
3143
- preparedPipeline = pipeline;
3144
- }
3145
- else if (isNotPreparedWarningSupressed !== true) {
3146
- console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3147
- }
3148
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3149
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3150
- function getContextForTemplate(template) {
3151
- return __awaiter(this, void 0, void 0, function () {
3152
- return __generator(this, function (_a) {
3153
- TODO_USE(template);
3154
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3155
- });
3156
- });
3157
- }
3158
- function getKnowledgeForTemplate(template) {
3159
- return __awaiter(this, void 0, void 0, function () {
3160
- return __generator(this, function (_a) {
3161
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3162
- TODO_USE(template);
3163
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3164
- var content = _a.content;
3165
- return "- ".concat(content);
3166
- }).join('\n')];
3167
- });
3168
- });
3169
- }
3170
- function getSamplesForTemplate(template) {
3171
- return __awaiter(this, void 0, void 0, function () {
3172
- return __generator(this, function (_a) {
3173
- // TODO: [♨] Implement Better - use real index and keyword search
3174
- TODO_USE(template);
3175
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3176
- });
3177
- });
3178
- }
3179
- function getReservedParametersForTemplate(template) {
3180
- return __awaiter(this, void 0, void 0, function () {
3181
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3182
- var e_3, _a;
3183
- return __generator(this, function (_b) {
3184
- switch (_b.label) {
3185
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3186
- case 1:
3187
- context = _b.sent();
3188
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3189
- case 2:
3190
- knowledge = _b.sent();
3191
- return [4 /*yield*/, getSamplesForTemplate(template)];
3192
- case 3:
3193
- samples = _b.sent();
3194
- currentDate = new Date().toISOString();
3195
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3196
- reservedParameters = {
3197
- content: RESERVED_PARAMETER_RESTRICTED,
3198
- context: context,
3199
- knowledge: knowledge,
3200
- samples: samples,
3201
- currentDate: currentDate,
3202
- modelName: modelName,
3203
- };
3204
- _loop_3 = function (parameterName) {
3205
- if (reservedParameters[parameterName] === undefined) {
3206
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3207
- }
3208
- };
3209
- try {
3210
- // Note: Doublecheck that ALL reserved parameters are defined:
3211
- for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3212
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3213
- _loop_3(parameterName);
3214
- }
3215
- }
3216
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3217
- finally {
3218
- try {
3219
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3220
- }
3221
- finally { if (e_3) throw e_3.error; }
3222
- }
3223
- return [2 /*return*/, reservedParameters];
3224
- }
3225
- });
3226
- });
3227
- }
3228
- function executeSingleTemplate(currentTemplate) {
3229
- return __awaiter(this, void 0, void 0, function () {
3230
- 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;
3231
- var e_4, _f, _g;
3232
- return __generator(this, function (_h) {
3233
- switch (_h.label) {
3234
- case 0:
3235
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3236
- title = currentTemplate.title;
3237
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3238
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3239
- progress_1 = {
3240
- name: name,
3241
- title: title,
3242
- isStarted: false,
3243
- isDone: false,
3244
- templateType: currentTemplate.templateType,
3245
- parameterName: currentTemplate.resultingParameterName,
3246
- parameterValue: null,
3247
- // <- [3]
3248
- };
3249
- if (isReturned) {
3250
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3251
- .split('\n')
3252
- .map(function (line) { return "> ".concat(line); })
3253
- .join('\n')), "\n "); }));
3254
- }
3255
- return [4 /*yield*/, onProgress(progress_1)];
3256
- case 1:
3257
- _h.sent();
3258
- _h.label = 2;
3259
- case 2:
3260
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3261
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3262
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3263
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3264
- .map(function (name) { return "{".concat(name, "}"); })
3265
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3266
- .map(function (name) { return "{".concat(name, "}"); })
3267
- .join(', '), "\n\n "); }));
3268
- }
3269
- _b = (_a = Object).freeze;
3270
- _c = [{}];
3271
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3272
- case 3:
3273
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3274
- definedParameterNames = new Set(Object.keys(definedParameters));
3275
- parameters = {};
3276
- _loop_4 = function (parameterName) {
3277
- // Situation: Parameter is defined and used
3278
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3279
- parameters[parameterName] = definedParameters[parameterName];
3280
- }
3281
- // Situation: Parameter is defined but NOT used
3282
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3283
- // Situation: Parameter is NOT defined BUT used
3284
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3285
- // Houston, we have a problem
3286
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3287
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3288
- }
3289
- };
3290
- try {
3291
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3292
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3293
- parameterName = _e.value;
3294
- _loop_4(parameterName);
3295
- }
3296
- }
3297
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3298
- finally {
3299
- try {
3300
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3301
- }
3302
- finally { if (e_4) throw e_4.error; }
3303
- }
3304
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3305
- Object.freeze(parameters);
3306
- result = null;
3307
- resultString = null;
3308
- expectError = null;
3309
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3310
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3311
- preparedContent = (currentTemplate.preparedContent || '{content}')
3312
- .split('{content}')
3313
- .join(currentTemplate.content);
3314
- _loop_5 = function (attempt) {
3315
- 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;
3316
- var e_5, _s, e_7, _t, e_6, _u;
3317
- return __generator(this, function (_v) {
3318
- switch (_v.label) {
3319
- case 0:
3320
- isJokerAttempt = attempt < 0;
3321
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3322
- if (isJokerAttempt && !jokerParameterName) {
3323
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3324
- }
3325
- result = null;
3326
- resultString = null;
3327
- expectError = null;
3328
- if (isJokerAttempt) {
3329
- if (parameters[jokerParameterName] === undefined) {
3330
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3331
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3332
- }
3333
- else {
3334
- resultString = parameters[jokerParameterName];
3335
- }
3336
- }
3337
- _v.label = 1;
3338
- case 1:
3339
- _v.trys.push([1, 44, 45, 46]);
3340
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3341
- _j = currentTemplate.templateType;
3342
- switch (_j) {
3343
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3344
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3345
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3346
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3347
- }
3348
- return [3 /*break*/, 25];
3349
- case 2:
3350
- resultString = replaceParameters(preparedContent, parameters);
3351
- return [3 /*break*/, 26];
3352
- case 3:
3353
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3354
- prompt = {
3355
- title: currentTemplate.title,
3356
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3357
- ? preparedPipeline.pipelineUrl
3358
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3359
- parameters: parameters,
3360
- content: preparedContent,
3361
- modelRequirements: modelRequirements,
3362
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3363
- var name = _a.name;
3364
- return name === currentTemplate.personaName;
3365
- }) || {})), currentTemplate.expectations),
3366
- format: currentTemplate.format,
3367
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3368
- }; // <- TODO: Not very good type guard
3369
- _k = modelRequirements.modelVariant;
3370
- switch (_k) {
3371
- case 'CHAT': return [3 /*break*/, 4];
3372
- case 'COMPLETION': return [3 /*break*/, 6];
3373
- case 'EMBEDDING': return [3 /*break*/, 8];
3374
- }
3375
- return [3 /*break*/, 10];
3376
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3377
- case 5:
3378
- chatResult = _v.sent();
3379
- // TODO: [🍬] Destroy chatThread
3380
- result = chatResult;
3381
- resultString = chatResult.content;
3382
- return [3 /*break*/, 11];
3383
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3384
- case 7:
3385
- completionResult = _v.sent();
3386
- result = completionResult;
3387
- resultString = completionResult.content;
3388
- return [3 /*break*/, 11];
3389
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3390
- case 9:
3391
- embeddingResult = _v.sent();
3392
- result = embeddingResult;
3393
- resultString = embeddingResult.content.join(',');
3394
- return [3 /*break*/, 11];
3395
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3396
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3397
- case 11: return [3 /*break*/, 26];
3398
- case 12:
3399
- if (arrayableToArray(tools.script).length === 0) {
3400
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3401
- }
3402
- if (!currentTemplate.contentLanguage) {
3403
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3404
- }
3405
- // TODO: DRY [1]
3406
- scriptPipelineExecutionErrors = [];
3407
- _v.label = 13;
3408
- case 13:
3409
- _v.trys.push([13, 20, 21, 22]);
3410
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3411
- _v.label = 14;
3412
- case 14:
3413
- if (!!_m.done) return [3 /*break*/, 19];
3414
- scriptTools = _m.value;
3415
- _v.label = 15;
3416
- case 15:
3417
- _v.trys.push([15, 17, , 18]);
3418
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3419
- scriptLanguage: currentTemplate.contentLanguage,
3420
- script: preparedContent,
3421
- parameters: parameters,
3422
- }))];
3423
- case 16:
3424
- resultString = _v.sent();
3425
- return [3 /*break*/, 19];
3426
- case 17:
3427
- error_2 = _v.sent();
3428
- if (!(error_2 instanceof Error)) {
3429
- throw error_2;
3430
- }
3431
- if (error_2 instanceof UnexpectedError) {
3432
- throw error_2;
3433
- }
3434
- scriptPipelineExecutionErrors.push(error_2);
3435
- return [3 /*break*/, 18];
3436
- case 18:
3437
- _m = _l.next();
3438
- return [3 /*break*/, 14];
3439
- case 19: return [3 /*break*/, 22];
3440
- case 20:
3441
- e_5_1 = _v.sent();
3442
- e_5 = { error: e_5_1 };
3443
- return [3 /*break*/, 22];
3444
- case 21:
3445
- try {
3446
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3447
- }
3448
- finally { if (e_5) throw e_5.error; }
3449
- return [7 /*endfinally*/];
3450
- case 22:
3451
- if (resultString !== null) {
3452
- return [3 /*break*/, 26];
3453
- }
3454
- if (scriptPipelineExecutionErrors.length === 1) {
3455
- throw scriptPipelineExecutionErrors[0];
3456
- }
3457
- else {
3458
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3459
- .map(function (error) { return '- ' + error.message; })
3460
- .join('\n\n')), "\n "); }));
3461
- }
3462
- case 23:
3463
- if (tools.userInterface === undefined) {
3464
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3465
- }
3466
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3467
- promptTitle: currentTemplate.title,
3468
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3469
- defaultValue: replaceParameters(preparedContent, parameters),
3470
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3471
- placeholder: undefined,
3472
- priority: priority,
3473
- }))];
3474
- case 24:
3475
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3476
- resultString = _v.sent();
3477
- return [3 /*break*/, 26];
3478
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3479
- case 26:
3480
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3481
- _v.label = 27;
3482
- case 27:
3483
- _v.trys.push([27, 41, 42, 43]);
3484
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3485
- _v.label = 28;
3486
- case 28:
3487
- if (!!_p.done) return [3 /*break*/, 40];
3488
- functionName = _p.value;
3489
- // TODO: DRY [1]
3490
- scriptPipelineExecutionErrors = [];
3491
- postprocessingError = null;
3492
- _v.label = 29;
3493
- case 29:
3494
- _v.trys.push([29, 36, 37, 38]);
3495
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3496
- _v.label = 30;
3497
- case 30:
3498
- if (!!_r.done) return [3 /*break*/, 35];
3499
- scriptTools = _r.value;
3500
- _v.label = 31;
3501
- case 31:
3502
- _v.trys.push([31, 33, , 34]);
3503
- return [4 /*yield*/, scriptTools.execute({
3504
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3505
- script: "".concat(functionName, "(resultString)"),
3506
- parameters: {
3507
- resultString: resultString || '',
3508
- // Note: No ...parametersForTemplate, because working with result only
3509
- },
3510
- })];
3511
- case 32:
3512
- resultString = _v.sent();
3513
- postprocessingError = null;
3514
- return [3 /*break*/, 35];
3515
- case 33:
3516
- error_3 = _v.sent();
3517
- if (!(error_3 instanceof Error)) {
3518
- throw error_3;
3519
- }
3520
- if (error_3 instanceof UnexpectedError) {
3521
- throw error_3;
3522
- }
3523
- postprocessingError = error_3;
3524
- scriptPipelineExecutionErrors.push(error_3);
3525
- return [3 /*break*/, 34];
3526
- case 34:
3527
- _r = _q.next();
3528
- return [3 /*break*/, 30];
3529
- case 35: return [3 /*break*/, 38];
3530
- case 36:
3531
- e_6_1 = _v.sent();
3532
- e_6 = { error: e_6_1 };
3533
- return [3 /*break*/, 38];
3534
- case 37:
3535
- try {
3536
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3537
- }
3538
- finally { if (e_6) throw e_6.error; }
3539
- return [7 /*endfinally*/];
3540
- case 38:
3541
- if (postprocessingError) {
3542
- throw postprocessingError;
3543
- }
3544
- _v.label = 39;
3545
- case 39:
3546
- _p = _o.next();
3547
- return [3 /*break*/, 28];
3548
- case 40: return [3 /*break*/, 43];
3549
- case 41:
3550
- e_7_1 = _v.sent();
3551
- e_7 = { error: e_7_1 };
3552
- return [3 /*break*/, 43];
3553
- case 42:
3554
- try {
3555
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3556
- }
3557
- finally { if (e_7) throw e_7.error; }
3558
- return [7 /*endfinally*/];
3559
- case 43:
3560
- // TODO: [💝] Unite object for expecting amount and format
3561
- if (currentTemplate.format) {
3562
- if (currentTemplate.format === 'JSON') {
3563
- if (!isValidJsonString(resultString || '')) {
3564
- // TODO: [🏢] Do more universally via `FormatDefinition`
3565
- try {
3566
- resultString = extractJsonBlock(resultString || '');
3567
- }
3568
- catch (error) {
3569
- keepUnused(error);
3570
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3571
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3572
- }
3573
- }
3574
- }
3575
- else {
3576
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3577
- }
3578
- }
3579
- // TODO: [💝] Unite object for expecting amount and format
3580
- if (currentTemplate.expectations) {
3581
- checkExpectations(currentTemplate.expectations, resultString || '');
3582
- }
3583
- return [2 /*return*/, "break-attempts"];
3584
- case 44:
3585
- error_4 = _v.sent();
3586
- if (!(error_4 instanceof ExpectError)) {
3587
- throw error_4;
3588
- }
3589
- expectError = error_4;
3590
- return [3 /*break*/, 46];
3591
- case 45:
3592
- if (!isJokerAttempt &&
3593
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3594
- prompt
3595
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3596
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3597
- ) {
3598
- // TODO: [🧠] Maybe put other templateTypes into report
3599
- executionReport.promptExecutions.push({
3600
- prompt: __assign({}, prompt),
3601
- result: result || undefined,
3602
- error: expectError === null ? undefined : serializeError(expectError),
3603
- });
3604
- }
3605
- return [7 /*endfinally*/];
3606
- case 46:
3607
- if (expectError !== null && attempt === maxAttempts - 1) {
3608
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3609
- .split('\n')
3610
- .map(function (line) { return "> ".concat(line); })
3611
- .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) || '')
3612
- .split('\n')
3613
- .map(function (line) { return "> ".concat(line); })
3614
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3615
- ? 'null'
3616
- : resultString
3617
- .split('\n')
3618
- .map(function (line) { return "> ".concat(line); })
3619
- .join('\n')), "\n ---\n "); }));
3620
- }
3621
- return [2 /*return*/];
3622
- }
3623
- });
3624
- };
3625
- attempt = -jokerParameterNames.length;
3626
- _h.label = 4;
3627
- case 4:
3628
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3629
- return [5 /*yield**/, _loop_5(attempt)];
3630
- case 5:
3631
- state_2 = _h.sent();
3632
- switch (state_2) {
3633
- case "break-attempts": return [3 /*break*/, 7];
3634
- }
3635
- _h.label = 6;
3636
- case 6:
3637
- attempt++;
3638
- return [3 /*break*/, 4];
3639
- case 7:
3640
- if (resultString === null) {
3641
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3642
- }
3643
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3644
- progress_2 = {
3645
- name: name,
3646
- title: title,
3647
- isStarted: true,
3648
- isDone: true,
3649
- templateType: currentTemplate.templateType,
3650
- parameterName: currentTemplate.resultingParameterName,
3651
- parameterValue: resultString,
3652
- // <- [3]
3653
- };
3654
- if (isReturned) {
3655
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3656
- .split('\n')
3657
- .map(function (line) { return "> ".concat(line); })
3658
- .join('\n')), "\n\n "); }));
3659
- }
3660
- return [4 /*yield*/, onProgress(progress_2)];
3661
- case 8:
3662
- _h.sent();
3663
- _h.label = 9;
3664
- case 9:
3665
- 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)));
3666
- return [2 /*return*/];
3667
- }
3668
- });
3669
- });
3670
- }
3671
- function filterJustOutputParameters() {
3672
- var e_8, _a;
3673
- var outputParameters = {};
3674
- var _loop_6 = function (parameter) {
3675
- if (parametersToPass[parameter.name] === undefined) {
3676
- // [4]
3677
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3678
- return "continue";
3679
- }
3680
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3681
- };
3682
- try {
3683
- // Note: Filter ONLY output parameters
3684
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3685
- var isOutput = _a.isOutput;
3686
- return isOutput;
3687
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3688
- var parameter = _c.value;
3689
- _loop_6(parameter);
3690
- }
3691
- }
3692
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3693
- finally {
3694
- try {
3695
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3696
- }
3697
- finally { if (e_8) throw e_8.error; }
3698
- }
3699
- return outputParameters;
3700
- }
3701
- 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;
4252
+ function executePipeline(options) {
4253
+ return __awaiter(this, void 0, void 0, function () {
4254
+ 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;
3702
4255
  var e_1, _e, e_2, _f;
3703
4256
  return __generator(this, function (_g) {
3704
4257
  switch (_g.label) {
3705
4258
  case 0:
4259
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4260
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4261
+ preparedPipeline = options.preparedPipeline;
4262
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3706
4263
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3707
4264
  return [4 /*yield*/, preparePipeline(pipeline, {
3708
4265
  llmTools: llmTools,
@@ -3711,6 +4268,7 @@
3711
4268
  })];
3712
4269
  case 1:
3713
4270
  preparedPipeline = _g.sent();
4271
+ setPreparedPipeline(preparedPipeline);
3714
4272
  _g.label = 2;
3715
4273
  case 2:
3716
4274
  errors = [];
@@ -3780,7 +4338,7 @@
3780
4338
  return name === parameterName;
3781
4339
  });
3782
4340
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3783
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4341
+ warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3784
4342
  return [3 /*break*/, 4];
3785
4343
  case 1:
3786
4344
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3792,10 +4350,10 @@
3792
4350
  // Note: Wait a short time to prevent race conditions
3793
4351
  _h.sent();
3794
4352
  _h.label = 3;
3795
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4353
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3796
4354
  isSuccessful: false,
3797
4355
  errors: __spreadArray([
3798
- new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4356
+ new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3799
4357
  ], __read(errors), false).map(serializeError),
3800
4358
  warnings: warnings.map(serializeError),
3801
4359
  executionReport: executionReport,
@@ -3859,7 +4417,7 @@
3859
4417
  case 0:
3860
4418
  if (loopLimit-- < 0) {
3861
4419
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3862
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4420
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3863
4421
  }
3864
4422
  currentTemplate = unresovedTemplates_1.find(function (template) {
3865
4423
  return template.dependentParameterNames.every(function (name) {
@@ -3869,29 +4427,52 @@
3869
4427
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3870
4428
  throw new UnexpectedError(
3871
4429
  // TODO: [🐎] DRY
3872
- spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4430
+ spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3873
4431
  .map(function (_a) {
3874
4432
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3875
4433
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3876
4434
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3877
4435
  .join(' and '));
3878
4436
  })
3879
- .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 "); }));
4437
+ .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 "); }));
3880
4438
  case 1:
3881
4439
  if (!!currentTemplate) return [3 /*break*/, 3];
3882
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4440
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3883
4441
  case 2:
3884
- /* [5] */ _j.sent();
4442
+ /* [🤹‍♂️] */ _j.sent();
3885
4443
  return [3 /*break*/, 4];
3886
4444
  case 3:
3887
4445
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3888
- work_1 = executeSingleTemplate(currentTemplate)
3889
- .then(function () {
4446
+ work_1 = executeTemplate({
4447
+ currentTemplate: currentTemplate,
4448
+ preparedPipeline: preparedPipeline,
4449
+ parametersToPass: parametersToPass,
4450
+ tools: tools,
4451
+ llmTools: llmTools,
4452
+ onProgress: function (progress) {
4453
+ if (isReturned) {
4454
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4455
+ .split('\n')
4456
+ .map(function (line) { return "> ".concat(line); })
4457
+ .join('\n')), "\n "); }));
4458
+ }
4459
+ if (onProgress) {
4460
+ onProgress(progress);
4461
+ }
4462
+ },
4463
+ settings: settings,
4464
+ $executionReport: executionReport,
4465
+ pipelineIdentification: pipelineIdentification,
4466
+ })
4467
+ .then(function (newParametersToPass) {
4468
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3890
4469
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3891
4470
  })
3892
4471
  .then(function () {
3893
4472
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3894
4473
  });
4474
+ // <- Note: Errors are catched here [3]
4475
+ // TODO: BUT if in multiple templates are errors, only the first one is catched so maybe we should catch errors here and save them to errors array here
3895
4476
  resolving_1.push(work_1);
3896
4477
  _j.label = 4;
3897
4478
  case 4: return [2 /*return*/];
@@ -3918,7 +4499,12 @@
3918
4499
  var result = _a.result;
3919
4500
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3920
4501
  })), false));
3921
- outputParameters_1 = filterJustOutputParameters();
4502
+ outputParameters_1 = filterJustOutputParameters({
4503
+ preparedPipeline: preparedPipeline,
4504
+ parametersToPass: parametersToPass,
4505
+ $warnings: warnings,
4506
+ pipelineIdentification: pipelineIdentification,
4507
+ });
3922
4508
  isReturned = true;
3923
4509
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3924
4510
  // Note: Wait a short time to prevent race conditions
@@ -3941,7 +4527,12 @@
3941
4527
  var result = _a.result;
3942
4528
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3943
4529
  })), false));
3944
- outputParameters = filterJustOutputParameters();
4530
+ outputParameters = filterJustOutputParameters({
4531
+ preparedPipeline: preparedPipeline,
4532
+ parametersToPass: parametersToPass,
4533
+ $warnings: warnings,
4534
+ pipelineIdentification: pipelineIdentification,
4535
+ });
3945
4536
  isReturned = true;
3946
4537
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3947
4538
  // Note: Wait a short time to prevent race conditions
@@ -3961,22 +4552,63 @@
3961
4552
  })];
3962
4553
  }
3963
4554
  });
4555
+ });
4556
+ }
4557
+
4558
+ /**
4559
+ * Creates executor function from pipeline and execution tools.
4560
+ *
4561
+ * @returns The executor function
4562
+ * @throws {PipelineLogicError} on logical error in the pipeline
4563
+ * @public exported from `@promptbook/core`
4564
+ */
4565
+ function createPipelineExecutor(options) {
4566
+ var _this = this;
4567
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4568
+ 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.csvSettings, csvSettings = _d === void 0 ? DEFAULT_CSV_SETTINGS : _d, _e = settings.isVerbose, isVerbose = _e === void 0 ? IS_VERBOSE : _e, _f = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _f === void 0 ? false : _f;
4569
+ validatePipeline(pipeline);
4570
+ var pipelineIdentification = (function () {
4571
+ // Note: This is a 😐 implementation of [🚞]
4572
+ var _ = [];
4573
+ if (pipeline.sourceFile !== undefined) {
4574
+ _.push("File: ".concat(pipeline.sourceFile));
4575
+ }
4576
+ if (pipeline.pipelineUrl !== undefined) {
4577
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4578
+ }
4579
+ return _.join('\n');
4580
+ })();
4581
+ var preparedPipeline;
4582
+ if (isPipelinePrepared(pipeline)) {
4583
+ preparedPipeline = pipeline;
4584
+ }
4585
+ else if (isNotPreparedWarningSupressed !== true) {
4586
+ console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4587
+ }
4588
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4589
+ return __generator(this, function (_a) {
4590
+ return [2 /*return*/, executePipeline({
4591
+ pipeline: pipeline,
4592
+ preparedPipeline: preparedPipeline,
4593
+ setPreparedPipeline: function (newPreparedPipeline) {
4594
+ preparedPipeline = newPreparedPipeline;
4595
+ },
4596
+ inputParameters: inputParameters,
4597
+ tools: tools,
4598
+ onProgress: onProgress,
4599
+ pipelineIdentification: pipelineIdentification,
4600
+ settings: {
4601
+ maxExecutionAttempts: maxExecutionAttempts,
4602
+ maxParallelCount: maxParallelCount,
4603
+ csvSettings: csvSettings,
4604
+ isVerbose: isVerbose,
4605
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4606
+ },
4607
+ })];
4608
+ });
3964
4609
  }); };
3965
4610
  return pipelineExecutor;
3966
4611
  }
3967
- /**
3968
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3969
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3970
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3971
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3972
- * TODO: [♈] Probbably move expectations from templates to parameters
3973
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3974
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3975
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3976
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3977
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3978
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
3979
- */
3980
4612
 
3981
4613
  /**
3982
4614
  * @@@
@@ -4028,7 +4660,7 @@
4028
4660
  outputParameters = result.outputParameters;
4029
4661
  knowledgePiecesRaw = outputParameters.knowledgePieces;
4030
4662
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4031
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4663
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4032
4664
  if (isVerbose) {
4033
4665
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
4034
4666
  }
@@ -4086,8 +4718,13 @@
4086
4718
  case 6: return [3 /*break*/, 8];
4087
4719
  case 7:
4088
4720
  error_1 = _c.sent();
4721
+ // Note: Here is expected error:
4722
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4723
+ if (!(error_1 instanceof PipelineExecutionError)) {
4724
+ throw error_1;
4725
+ }
4089
4726
  // TODO: [🟥] Detect browser / node and make it colorfull
4090
- console.error(error_1);
4727
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4091
4728
  return [3 /*break*/, 8];
4092
4729
  case 8: return [2 /*return*/, {
4093
4730
  name: name,
@@ -4108,7 +4745,7 @@
4108
4745
  });
4109
4746
  }
4110
4747
  /**
4111
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4748
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4112
4749
  * TODO: [🪂] Do it in parallel 11:11
4113
4750
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4114
4751
  */
@@ -4132,7 +4769,7 @@
4132
4769
  var partialPieces, pieces;
4133
4770
  return __generator(this, function (_a) {
4134
4771
  switch (_a.label) {
4135
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4772
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4136
4773
  options)];
4137
4774
  case 1:
4138
4775
  partialPieces = _a.sent();
@@ -4324,7 +4961,7 @@
4324
4961
  });
4325
4962
  }
4326
4963
  /**
4327
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4964
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4328
4965
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4329
4966
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4330
4967
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4373,7 +5010,7 @@
4373
5010
  case 0:
4374
5011
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4375
5012
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4376
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
5013
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4377
5014
  TODO_USE(parameters);
4378
5015
  templatesPrepared = new Array(
4379
5016
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4405,7 +5042,7 @@
4405
5042
  /**
4406
5043
  * TODO: [🧠] Add context to each template (if missing)
4407
5044
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4408
- * TODO: [♨] !!! Prepare index the samples and maybe templates
5045
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4409
5046
  * TODO: Write tests for `preparePipeline`
4410
5047
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4411
5048
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4577,7 +5214,7 @@
4577
5214
  if (sourceContent === '') {
4578
5215
  throw new ParseError("Source is not defined");
4579
5216
  }
4580
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5217
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4581
5218
  if (sourceContent.startsWith('http://')) {
4582
5219
  throw new ParseError("Source is not secure");
4583
5220
  }
@@ -4780,7 +5417,7 @@
4780
5417
  if (command.templateType === 'KNOWLEDGE') {
4781
5418
  knowledgeCommandParser.$applyToPipelineJson({
4782
5419
  type: 'KNOWLEDGE',
4783
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5420
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4784
5421
  }, $pipelineJson);
4785
5422
  $templateJson.isTemplate = false;
4786
5423
  return;
@@ -5130,6 +5767,171 @@
5130
5767
  * TODO: [🌺] Use some intermediate util splitWords
5131
5768
  */
5132
5769
 
5770
+ /**
5771
+ * @@@
5772
+ *
5773
+ * @param text @@@
5774
+ * @param _isFirstLetterCapital @@@
5775
+ * @returns @@@
5776
+ * @example 'helloWorld'
5777
+ * @example 'iLovePromptbook'
5778
+ * @public exported from `@promptbook/utils`
5779
+ */
5780
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5781
+ var e_1, _a;
5782
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5783
+ var charType;
5784
+ var lastCharType = null;
5785
+ var normalizedName = '';
5786
+ try {
5787
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5788
+ var char = text_1_1.value;
5789
+ var normalizedChar = void 0;
5790
+ if (/^[a-z]$/.test(char)) {
5791
+ charType = 'LOWERCASE';
5792
+ normalizedChar = char;
5793
+ }
5794
+ else if (/^[A-Z]$/.test(char)) {
5795
+ charType = 'UPPERCASE';
5796
+ normalizedChar = char.toLowerCase();
5797
+ }
5798
+ else if (/^[0-9]$/.test(char)) {
5799
+ charType = 'NUMBER';
5800
+ normalizedChar = char;
5801
+ }
5802
+ else {
5803
+ charType = 'OTHER';
5804
+ normalizedChar = '';
5805
+ }
5806
+ if (!lastCharType) {
5807
+ if (_isFirstLetterCapital) {
5808
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5809
+ }
5810
+ }
5811
+ else if (charType !== lastCharType &&
5812
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5813
+ !(lastCharType === 'NUMBER') &&
5814
+ !(charType === 'NUMBER')) {
5815
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5816
+ }
5817
+ normalizedName += normalizedChar;
5818
+ lastCharType = charType;
5819
+ }
5820
+ }
5821
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5822
+ finally {
5823
+ try {
5824
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5825
+ }
5826
+ finally { if (e_1) throw e_1.error; }
5827
+ }
5828
+ return normalizedName;
5829
+ }
5830
+ /**
5831
+ * TODO: [🌺] Use some intermediate util splitWords
5832
+ */
5833
+
5834
+ /**
5835
+ * Removes quotes from a string
5836
+ *
5837
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5838
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5839
+ * Note: There are two simmilar functions:
5840
+ * - `removeQuotes` which removes only bounding quotes
5841
+ * - `unwrapResult` which removes whole introduce sentence
5842
+ *
5843
+ * @param text optionally quoted text
5844
+ * @returns text without quotes
5845
+ * @public exported from `@promptbook/utils`
5846
+ */
5847
+ function removeQuotes(text) {
5848
+ if (text.startsWith('"') && text.endsWith('"')) {
5849
+ return text.slice(1, -1);
5850
+ }
5851
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5852
+ return text.slice(1, -1);
5853
+ }
5854
+ return text;
5855
+ }
5856
+
5857
+ /**
5858
+ * Function `validateParameterName` will @@@
5859
+ *
5860
+ * @param parameterName @@@
5861
+ * @returns @@@
5862
+ * @throws {ParseError} @@@
5863
+ * @private within the repository
5864
+ */
5865
+ function validateParameterName(parameterName) {
5866
+ var e_1, _a;
5867
+ var rawParameterName = parameterName;
5868
+ try {
5869
+ for (var _b = __values([
5870
+ ['`', '`'],
5871
+ ['{', '}'],
5872
+ ['[', ']'],
5873
+ ['(', ')'],
5874
+ ['<', '>'],
5875
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5876
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5877
+ if (parameterName.substring(0, 1) === start &&
5878
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5879
+ // <- TODO: More universal that 1 character
5880
+ ) {
5881
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5882
+ // <- TODO: More universal that 1 character
5883
+ }
5884
+ }
5885
+ }
5886
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5887
+ finally {
5888
+ try {
5889
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5890
+ }
5891
+ finally { if (e_1) throw e_1.error; }
5892
+ }
5893
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5894
+ try {
5895
+ /*
5896
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5897
+ if (parameterName.includes(' ')) {
5898
+ throw new ParseError(`Parameter name cannot contain spaces`);
5899
+ }
5900
+ */
5901
+ if (parameterName.includes('.')) {
5902
+ throw new ParseError("Parameter name cannot contain dots");
5903
+ }
5904
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5905
+ throw new ParseError("Parameter name cannot contain slashes");
5906
+ }
5907
+ if (parameterName.includes('(') ||
5908
+ parameterName.includes(')') ||
5909
+ parameterName.includes('{') ||
5910
+ parameterName.includes('}') ||
5911
+ parameterName.includes('[') ||
5912
+ parameterName.includes(']')) {
5913
+ throw new ParseError("Parameter name cannot contain braces");
5914
+ }
5915
+ parameterName = removeDiacritics(parameterName);
5916
+ parameterName = removeEmojis(parameterName);
5917
+ parameterName = removeQuotes(parameterName);
5918
+ parameterName = normalizeTo_camelCase(parameterName);
5919
+ if (parameterName === '') {
5920
+ throw new ParseError("Parameter name cannot be empty");
5921
+ }
5922
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5923
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5924
+ }
5925
+ }
5926
+ catch (error) {
5927
+ if (!(error instanceof ParseError)) {
5928
+ throw error;
5929
+ }
5930
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
5931
+ }
5932
+ return parameterName;
5933
+ }
5934
+
5133
5935
  /**
5134
5936
  * Parses the foreach command
5135
5937
  *
@@ -5159,67 +5961,61 @@
5159
5961
  /**
5160
5962
  * Link to discussion
5161
5963
  */
5162
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5964
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5163
5965
  /**
5164
5966
  * Example usages of the FOREACH command
5165
5967
  */
5166
5968
  examples: [
5167
- 'FOREACH List Line -> `{customer}`',
5168
- 'FOR List Line -> `{customer}`',
5169
- 'EACH List Line -> `{customer}`',
5170
- // <- TODO: [🍭] !!!!!! More
5969
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5970
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5971
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
5171
5972
  ],
5172
5973
  /**
5173
5974
  * Parses the FOREACH command
5174
5975
  */
5175
5976
  parse: function (input) {
5176
- var args = input.args, rawArgs = input.rawArgs;
5977
+ var args = input.args;
5177
5978
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5178
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5179
- var assignSign = args[2];
5180
- var parameter = args[3];
5181
- if (![
5182
- 'LIST',
5183
- 'CSV',
5184
- // <- TODO: [🏢] Unhardcode formats
5185
- ].includes(formatName)) {
5186
- console.info({ args: args, formatName: formatName });
5187
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5979
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5980
+ var parameterNameArg = args[2] || '';
5981
+ var assignSign = args[3];
5982
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5983
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5984
+ });
5985
+ if (formatDefinition === undefined) {
5986
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
5987
+ .map(function (formatName) { return "- ".concat(formatName); })
5988
+ .join('\n')), "\n "); }));
5188
5989
  // <- TODO: [🏢] List all supported format names
5189
5990
  }
5190
- if (![
5191
- 'LINE',
5192
- 'ROW',
5193
- 'COLUMN',
5194
- 'CELL',
5195
- // <- TODO: [🏢] Unhardcode format cekks
5196
- ].includes(cellName)) {
5197
- console.info({ args: args, cellName: cellName });
5198
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5199
- // <- TODO: [🏢] List all supported cell names for the format
5991
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5992
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5993
+ });
5994
+ if (subvalueDefinition === undefined) {
5995
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported subformat name \"".concat(subformatName, "\" for format \"").concat(formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
5996
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5997
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
5998
+ .join('\n')), "\n "); }));
5999
+ // <- TODO: [🏢] List all supported subformat names for the format
5200
6000
  }
5201
6001
  if (assignSign !== '->') {
5202
- console.info({ args: args, assignSign: assignSign });
5203
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5204
- }
5205
- var parameterNames = extractParameterNames(parameter || rawArgs);
5206
- if (parameterNames.size !== 1) {
5207
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5208
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5209
- }
5210
- var parameterName = parameterNames.values().next().value;
5211
- if (typeof parameterName !== 'string'
5212
- // <- TODO: !!!!!! Replace with propper parameter name validation
5213
- ) {
5214
- console.info({ args: args, parameterName: parameterName });
5215
- throw new Error("Invalid parameter name");
5216
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
6002
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6003
+ }
6004
+ var parameterName = validateParameterName(parameterNameArg);
6005
+ var subparameterNames = args
6006
+ .slice(4)
6007
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6008
+ .filter(function (parameterName) { return parameterName !== ''; })
6009
+ .map(validateParameterName);
6010
+ if (subparameterNames.length === 0) {
6011
+ throw new ParseError("FOREACH command must have at least one subparameter");
5217
6012
  }
5218
6013
  return {
5219
6014
  type: 'FOREACH',
5220
6015
  formatName: formatName,
5221
- cellName: cellName,
6016
+ subformatName: subformatName,
5222
6017
  parameterName: parameterName,
6018
+ subparameterNames: subparameterNames,
5223
6019
  };
5224
6020
  },
5225
6021
  /**
@@ -5228,8 +6024,12 @@
5228
6024
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5229
6025
  */
5230
6026
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5231
- keepUnused(command, $templateJson, $pipelineJson);
5232
- // <- TODO: [🍭] !!!!!! Implement
6027
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6028
+ // TODO: [🍭] Detect double use
6029
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6030
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
6031
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
6032
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5233
6033
  },
5234
6034
  /**
5235
6035
  * Converts the FOREACH command back to string
@@ -5238,8 +6038,7 @@
5238
6038
  */
5239
6039
  stringify: function (command) {
5240
6040
  keepUnused(command);
5241
- return "";
5242
- // <- TODO: [🍭] !!!!!! Implement
6041
+ return "---"; // <- TODO: [🛋] Implement
5243
6042
  },
5244
6043
  /**
5245
6044
  * Reads the FOREACH command from the `TemplateJson`
@@ -5248,13 +6047,11 @@
5248
6047
  */
5249
6048
  takeFromTemplateJson: function ($templateJson) {
5250
6049
  keepUnused($templateJson);
5251
- return [];
5252
- // <- TODO: [🍭] !!!!!! Implement
6050
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5253
6051
  },
5254
6052
  };
5255
6053
  /**
5256
- * TODO: !!!!!! Comment console logs
5257
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6054
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5258
6055
  */
5259
6056
 
5260
6057
  /**
@@ -5364,11 +6161,11 @@
5364
6161
  */
5365
6162
  parse: function (input) {
5366
6163
  var args = input.args;
5367
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5368
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5369
- throw new ParseError("Invalid joker");
6164
+ if (args.length !== 1) {
6165
+ throw new ParseError("JOKE command expects exactly one parameter name");
5370
6166
  }
5371
- var parameterName = parametersMatch.groups.parameterName;
6167
+ var parameterNameArg = args[0] || '';
6168
+ var parameterName = validateParameterName(parameterNameArg);
5372
6169
  return {
5373
6170
  type: 'JOKER',
5374
6171
  parameterName: parameterName,
@@ -5443,6 +6240,9 @@
5443
6240
  */
5444
6241
  parse: function (input) {
5445
6242
  var args = input.args, normalized = input.normalized;
6243
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6244
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6245
+ }).join('\n')), "\n "); });
5446
6246
  // TODO: Make this more elegant and dynamically
5447
6247
  if (normalized.startsWith('MODEL_VARIANT')) {
5448
6248
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5458,17 +6258,13 @@
5458
6258
  key: 'modelVariant',
5459
6259
  value: 'COMPLETION',
5460
6260
  };
6261
+ // <- Note: [🤖]
5461
6262
  }
5462
6263
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5463
- return {
5464
- type: 'MODEL',
5465
- key: 'modelVariant',
5466
- value: 'EMBEDDING',
5467
- };
5468
- // <- Note: [🤖]
6264
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5469
6265
  }
5470
6266
  else {
5471
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n Supported variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) { return "- ".concat(variantName); }).join('\n')), "\n "); }));
6267
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5472
6268
  }
5473
6269
  }
5474
6270
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5493,6 +6289,7 @@
5493
6289
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5494
6290
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5495
6291
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6292
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5496
6293
  }
5497
6294
  else {
5498
6295
  throw new ParseError(spaceTrim__default["default"]("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -5592,14 +6389,13 @@
5592
6389
  * Parses the PARAMETER command
5593
6390
  */
5594
6391
  parse: function (input) {
5595
- var normalized = input.normalized, raw = input.raw;
5596
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5597
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5598
- throw new ParseError("Invalid parameter");
5599
- }
5600
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5601
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5602
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6392
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6393
+ var parameterNameRaw = args.shift() || '';
6394
+ var parameterDescriptionRaw = args.join(' ');
6395
+ // <- TODO: When [🥶] fixed, change to:
6396
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6397
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6398
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Parameter {".concat(parameterNameRaw, "} can not contain another parameter in description\n\n The description:\n ").concat(block(parameterDescriptionRaw), "\n "); }));
5603
6399
  }
5604
6400
  var isInput = normalized.startsWith('INPUT');
5605
6401
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5607,11 +6403,12 @@
5607
6403
  isInput = false;
5608
6404
  isOutput = false;
5609
6405
  }
5610
- // TODO: !!!!!! Add parameter name validation
6406
+ var parameterName = validateParameterName(parameterNameRaw);
6407
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5611
6408
  return {
5612
6409
  type: 'PARAMETER',
5613
6410
  parameterName: parameterName,
5614
- parameterDescription: parameterDescription.trim() || null,
6411
+ parameterDescription: parameterDescription,
5615
6412
  isInput: isInput,
5616
6413
  isOutput: isOutput,
5617
6414
  };
@@ -5936,6 +6733,7 @@
5936
6733
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
5937
6734
  */
5938
6735
  $applyToPipelineJson: function (command, $pipelineJson) {
6736
+ // TODO: Warn if the version is overridden
5939
6737
  $pipelineJson.promptbookVersion = command.promptbookVersion;
5940
6738
  },
5941
6739
  /**
@@ -6418,7 +7216,9 @@
6418
7216
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6419
7217
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6420
7218
  var args = items.slice(commandNameSegmentsCount + 1);
6421
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7219
+ var rawArgs = raw
7220
+ .substring(commandNameRaw.length)
7221
+ .trim();
6422
7222
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6423
7223
  if (command !== null) {
6424
7224
  return command;
@@ -6429,7 +7229,9 @@
6429
7229
  {
6430
7230
  var commandNameRaw = items.slice(-1).join('_');
6431
7231
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6432
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7232
+ var rawArgs = raw
7233
+ .substring(0, raw.length - commandNameRaw.length)
7234
+ .trim();
6433
7235
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6434
7236
  if (command !== null) {
6435
7237
  return command;
@@ -6569,7 +7371,7 @@
6569
7371
  function extractOneBlockFromMarkdown(markdown) {
6570
7372
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6571
7373
  if (codeBlocks.length !== 1) {
6572
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7374
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6573
7375
  }
6574
7376
  return codeBlocks[0];
6575
7377
  }
@@ -6756,7 +7558,7 @@
6756
7558
  var $pipelineJson = {
6757
7559
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6758
7560
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6759
- promptbookVersion: PROMPTBOOK_VERSION,
7561
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6760
7562
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6761
7563
  parameters: [],
6762
7564
  templates: [],
@@ -7047,7 +7849,7 @@
7047
7849
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7048
7850
  }
7049
7851
  /**
7050
- * TODO: !!!! Warn if used only sync version
7852
+ * TODO:[main] !!!! Warn if used only sync version
7051
7853
  * TODO: [🚞] Report here line/column of error
7052
7854
  * TODO: Use spaceTrim more effectively
7053
7855
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7552,7 +8354,7 @@
7552
8354
  }
7553
8355
  }
7554
8356
  /**
7555
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8357
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7556
8358
  * TODO: [🧠][💺] Can be done this on type-level?
7557
8359
  */
7558
8360
 
@@ -7609,21 +8411,41 @@
7609
8411
  * @public exported from `@promptbook/core`
7610
8412
  */
7611
8413
  function usageToHuman(usage) {
7612
- var report = 'Usage:';
8414
+ var reportItems = [];
7613
8415
  var uncertainNumberToHuman = function (_a) {
7614
8416
  var value = _a.value, isUncertain = _a.isUncertain;
7615
8417
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7616
8418
  };
7617
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7618
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7619
- return spaceTrim__default["default"](report);
8419
+ if (usage.price.value > 0.01
8420
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8421
+ ) {
8422
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8423
+ }
8424
+ else {
8425
+ reportItems.push("Negligible cost");
8426
+ }
8427
+ var worktime = usageToWorktime(usage);
8428
+ if (worktime.value >
8429
+ 1 / 60
8430
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8431
+ ) {
8432
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8433
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8434
+ }
8435
+ if (usage.output.charactersCount.value > 0) {
8436
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8437
+ }
8438
+ if (reportItems.length === 0) {
8439
+ // Note: For negligible usage, we report at least something
8440
+ reportItems.push('Negligible');
8441
+ }
8442
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7620
8443
  }
7621
8444
  /**
7622
- * TODO: Use "$1" not "1 USD"
7623
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7624
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8445
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8446
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8447
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7625
8448
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7626
- * TODO: When negligible usage, report "Negligible" or just don't report it
7627
8449
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7628
8450
  * TODO: [🏛] Maybe make some markdown builder
7629
8451
  */
@@ -8393,7 +9215,7 @@
8393
9215
  });
8394
9216
  }
8395
9217
  /**
8396
- * TODO: [🥃] !!! Allow `ptbk make` without configuring any llm tools
9218
+ * TODO: [🥃][main] !!! Allow `ptbk make` without configuring any llm tools
8397
9219
  * TODO: Maybe remove this command - "about" command should be enough?
8398
9220
  * TODO: [0] DRY Javascript and typescript - Maybe make ONLY typescript and for javascript just remove types
8399
9221
  * Note: [🟡] This code should never be published outside of `@promptbook/cli`
@@ -8427,70 +9249,6 @@
8427
9249
  * TODO: [🏛] This can be part of markdown builder
8428
9250
  */
8429
9251
 
8430
- /**
8431
- * @@@
8432
- *
8433
- * @param text @@@
8434
- * @param _isFirstLetterCapital @@@
8435
- * @returns @@@
8436
- * @example 'helloWorld'
8437
- * @example 'iLovePromptbook'
8438
- * @public exported from `@promptbook/utils`
8439
- */
8440
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
8441
- var e_1, _a;
8442
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
8443
- var charType;
8444
- var lastCharType = null;
8445
- var normalizedName = '';
8446
- try {
8447
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
8448
- var char = text_1_1.value;
8449
- var normalizedChar = void 0;
8450
- if (/^[a-z]$/.test(char)) {
8451
- charType = 'LOWERCASE';
8452
- normalizedChar = char;
8453
- }
8454
- else if (/^[A-Z]$/.test(char)) {
8455
- charType = 'UPPERCASE';
8456
- normalizedChar = char.toLowerCase();
8457
- }
8458
- else if (/^[0-9]$/.test(char)) {
8459
- charType = 'NUMBER';
8460
- normalizedChar = char;
8461
- }
8462
- else {
8463
- charType = 'OTHER';
8464
- normalizedChar = '';
8465
- }
8466
- if (!lastCharType) {
8467
- if (_isFirstLetterCapital) {
8468
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
8469
- }
8470
- }
8471
- else if (charType !== lastCharType &&
8472
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
8473
- !(lastCharType === 'NUMBER') &&
8474
- !(charType === 'NUMBER')) {
8475
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
8476
- }
8477
- normalizedName += normalizedChar;
8478
- lastCharType = charType;
8479
- }
8480
- }
8481
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
8482
- finally {
8483
- try {
8484
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
8485
- }
8486
- finally { if (e_1) throw e_1.error; }
8487
- }
8488
- return normalizedName;
8489
- }
8490
- /**
8491
- * TODO: [🌺] Use some intermediate util splitWords
8492
- */
8493
-
8494
9252
  /**
8495
9253
  * Creates a Mermaid graph based on the promptbook
8496
9254
  *
@@ -8547,6 +9305,9 @@
8547
9305
  return promptbookMermaid;
8548
9306
  }
8549
9307
  /**
9308
+ * TODO: !!!!! FOREACH in mermaid graph
9309
+ * TODO: !!!!! Knowledge in mermaid graph
9310
+ * TODO: !!!!! Personas in mermaid graph
8550
9311
  * TODO: Maybe use some Mermaid package instead of string templating
8551
9312
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8552
9313
  */
@@ -8872,7 +9633,7 @@
8872
9633
  socket.on('connect', function () {
8873
9634
  resolve(socket);
8874
9635
  });
8875
- // TODO: !!!! Better timeout handling
9636
+ // TODO:[main] !!!! Better timeout handling
8876
9637
  setTimeout(function () {
8877
9638
  reject(new Error("Timeout while connecting to ".concat(_this.options.remoteUrl)));
8878
9639
  }, CONNECTION_TIMEOUT_MS);
@@ -9052,11 +9813,11 @@
9052
9813
  output: computeUsage("$2.40 / 1M tokens"),
9053
9814
  },
9054
9815
  },
9055
- // TODO: !!! Claude 1 and 2 has also completion versions - ask Hoagy
9816
+ // TODO:[main] !!! Claude 1 and 2 has also completion versions - ask Hoagy
9056
9817
  ]);
9057
9818
  /**
9058
9819
  * Note: [🤖] Add models of new variant
9059
- * TODO: [🧠] !!! Add embedding models OR Anthropic has only chat+completion models?
9820
+ * TODO: [🧠][main] !!! Add embedding models OR Anthropic has only chat+completion models?
9060
9821
  * TODO: [🧠] Some mechanism to propagate unsureness
9061
9822
  * TODO: [🧠][👮‍♀️] Put here more info like description, isVision, trainingDateCutoff, languages, strengths ( Top-level performance, intelligence, fluency, and understanding), contextWindow,...
9062
9823
  * TODO: [🎰] Some mechanism to auto-update available models
@@ -9265,7 +10026,7 @@
9265
10026
  resultContent = contentBlock.text;
9266
10027
  // eslint-disable-next-line prefer-const
9267
10028
  complete = getCurrentIsoDate();
9268
- usage = computeAnthropicClaudeUsage(content, '', rawResponse);
10029
+ usage = computeAnthropicClaudeUsage(rawPromptContent || '', resultContent || '', rawResponse);
9269
10030
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('AnthropicClaudeExecutionTools ChatPromptResult', {
9270
10031
  content: resultContent,
9271
10032
  modelName: rawResponse.model,
@@ -9412,8 +10173,8 @@
9412
10173
  className: 'AnthropicClaudeExecutionTools',
9413
10174
  });
9414
10175
  /**
9415
- * TODO: [🧠] !!!! Make anonymous this with all LLM providers
9416
- * TODO: [🧠][🧱] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
10176
+ * TODO: [🧠][main] !!!! Make anonymous this with all LLM providers
10177
+ * TODO: [🧠][🧱][main] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
9417
10178
  * TODO: [🧠] Maybe auto-detect usage in browser and determine default value of `isProxied`
9418
10179
  * TODO: [🦺] Is there some way how to put `packageName` and `className` on top and function definition on bottom?
9419
10180
  * TODO: [🎶] Naming "constructor" vs "creator" vs "factory"
@@ -9791,6 +10552,7 @@
9791
10552
  prompt: computeUsage("$5.00 / 1M tokens"),
9792
10553
  output: computeUsage("$15.00 / 1M tokens"),
9793
10554
  },
10555
+ //TODO:[main] !!!!!! Add gpt-4o-mini-2024-07-18 and all others to be up to date
9794
10556
  },
9795
10557
  /**/
9796
10558
  /**/
@@ -9805,6 +10567,51 @@
9805
10567
  },
9806
10568
  /**/
9807
10569
  /**/
10570
+ {
10571
+ modelVariant: 'CHAT',
10572
+ modelTitle: 'o1-preview',
10573
+ modelName: 'o1-preview',
10574
+ pricing: {
10575
+ prompt: computeUsage("$15.00 / 1M tokens"),
10576
+ output: computeUsage("$60.00 / 1M tokens"),
10577
+ },
10578
+ },
10579
+ /**/
10580
+ /**/
10581
+ {
10582
+ modelVariant: 'CHAT',
10583
+ modelTitle: 'o1-preview-2024-09-12',
10584
+ modelName: 'o1-preview-2024-09-12',
10585
+ // <- TODO:[main] !!!!!! Some better system to organize theese date suffixes and versions
10586
+ pricing: {
10587
+ prompt: computeUsage("$15.00 / 1M tokens"),
10588
+ output: computeUsage("$60.00 / 1M tokens"),
10589
+ },
10590
+ },
10591
+ /**/
10592
+ /**/
10593
+ {
10594
+ modelVariant: 'CHAT',
10595
+ modelTitle: 'o1-mini',
10596
+ modelName: 'o1-mini',
10597
+ pricing: {
10598
+ prompt: computeUsage("$3.00 / 1M tokens"),
10599
+ output: computeUsage("$12.00 / 1M tokens"),
10600
+ },
10601
+ },
10602
+ /**/
10603
+ /**/
10604
+ {
10605
+ modelVariant: 'CHAT',
10606
+ modelTitle: 'o1-mini-2024-09-12',
10607
+ modelName: 'o1-mini-2024-09-12',
10608
+ pricing: {
10609
+ prompt: computeUsage("$3.00 / 1M tokens"),
10610
+ output: computeUsage("$12.00 / 1M tokens"),
10611
+ },
10612
+ },
10613
+ /**/
10614
+ /**/
9808
10615
  {
9809
10616
  modelVariant: 'CHAT',
9810
10617
  modelTitle: 'gpt-3.5-turbo-16k-0613',
@@ -9893,7 +10700,7 @@
9893
10700
  AzureOpenAiExecutionTools.prototype.listModels = function () {
9894
10701
  return __awaiter(this, void 0, void 0, function () {
9895
10702
  return __generator(this, function (_a) {
9896
- // TODO: !!! Do here some filtering which models are really available as deployment
10703
+ // TODO:[main] !!! Do here some filtering which models are really available as deployment
9897
10704
  // @see https://management.azure.com/subscriptions/subscriptionId/resourceGroups/resourceGroupName/providers/Microsoft.CognitiveServices/accounts/accountName/deployments?api-version=2023-05-01
9898
10705
  return [2 /*return*/, OPENAI_MODELS.map(function (_a) {
9899
10706
  var modelTitle = _a.modelTitle, modelName = _a.modelName, modelVariant = _a.modelVariant;
@@ -10379,7 +11186,7 @@
10379
11186
  resultContent = rawResponse.choices[0].message.content;
10380
11187
  // eslint-disable-next-line prefer-const
10381
11188
  complete = getCurrentIsoDate();
10382
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11189
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10383
11190
  if (resultContent === null) {
10384
11191
  throw new PipelineExecutionError('No response message from OpenAI');
10385
11192
  }
@@ -10451,7 +11258,7 @@
10451
11258
  resultContent = rawResponse.choices[0].text;
10452
11259
  // eslint-disable-next-line prefer-const
10453
11260
  complete = getCurrentIsoDate();
10454
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11261
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10455
11262
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools CompletionPromptResult', {
10456
11263
  content: resultContent,
10457
11264
  modelName: rawResponse.model || modelName,
@@ -10511,7 +11318,9 @@
10511
11318
  resultContent = rawResponse.data[0].embedding;
10512
11319
  // eslint-disable-next-line prefer-const
10513
11320
  complete = getCurrentIsoDate();
10514
- usage = computeOpenAiUsage(content, '', rawResponse);
11321
+ usage = computeOpenAiUsage(content || '', '',
11322
+ // <- Note: Embedding does not have result content
11323
+ rawResponse);
10515
11324
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools EmbeddingPromptResult', {
10516
11325
  content: resultContent,
10517
11326
  modelName: rawResponse.model || modelName,
@@ -10582,7 +11391,7 @@
10582
11391
  * @public exported from `@promptbook/openai`
10583
11392
  */
10584
11393
  var createOpenAiExecutionTools = Object.assign(function (options) {
10585
- // TODO: [🧠] !!!! If browser, auto add `dangerouslyAllowBrowser`
11394
+ // TODO: [🧠][main] !!!! If browser, auto add `dangerouslyAllowBrowser`
10586
11395
  if (($isRunningInBrowser() || $isRunningInWebWorker()) && !options.dangerouslyAllowBrowser) {
10587
11396
  options = __assign(__assign({}, options), { dangerouslyAllowBrowser: true });
10588
11397
  }